Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
396 lines
14 KiB
TypeScript
396 lines
14 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import Link from "next/link";
|
|
import { Search } from "lucide-react";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { PageHeader } from "@/app/components/ui/page-header";
|
|
import { Skeleton } from "@/app/components/ui/skeleton";
|
|
import type { SortingState } from "@tanstack/react-table";
|
|
import { SortableHead, sortRows } from "@/app/components/ui/sortable-head";
|
|
import { formatDateTime } from "@/app/lib/format";
|
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/app/components/ui/tabs";
|
|
import {
|
|
Table,
|
|
TableBody,
|
|
TableCell,
|
|
TableHead,
|
|
TableHeader,
|
|
TableRow,
|
|
} from "@/app/components/ui/table";
|
|
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
|
import { RequireModule } from "@/app/lib/RequireModule";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { MEMBER_STATUS_LABEL_CODES } from "@/app/lib/memberLabels";
|
|
import { MemberSearchCombobox } from "@/app/components/members/MemberSearchCombobox";
|
|
import { MemberCell } from "@/app/components/members/MemberCell";
|
|
import type {
|
|
AdminMember,
|
|
AdminSponsorHistoryRow,
|
|
AdminTreeNode,
|
|
AdminTreeNodeMember,
|
|
} from "@/app/lib/types";
|
|
import {
|
|
getMemberUpline,
|
|
getNetworkTree,
|
|
getPlacementHistory,
|
|
} from "@/app/lib/services/network";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import type { MessageParams } from "@/app/lib/i18n/t";
|
|
import { TreeView } from "@/app/components/genealogy/tree-view";
|
|
import { OrgChart } from "@/app/components/genealogy/org-chart";
|
|
import { useQueryState } from "@/app/lib/useQueryState";
|
|
import { useRouter } from "next/navigation";
|
|
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
|
import NetworkTabs from "./NetworkTabs";
|
|
|
|
/**
|
|
* Collects nodes whose name matches `term`, plus every ancestor on the path to a
|
|
* match, so the caller can expand exactly enough of the tree to reveal it.
|
|
*/
|
|
function collectMatches(
|
|
node: AdminTreeNode,
|
|
term: string,
|
|
ancestors: string[],
|
|
matched: Set<string>,
|
|
ancestorIds: Set<string>,
|
|
) {
|
|
if ((node.member?.name ?? node.mbid).toLowerCase().includes(term)) {
|
|
matched.add(node.mbid);
|
|
ancestors.forEach(id => ancestorIds.add(id));
|
|
}
|
|
const path = [...ancestors, node.mbid];
|
|
(node.children ?? []).forEach(child => collectMatches(child, term, path, matched, ancestorIds));
|
|
}
|
|
|
|
function UplineEntry({ node, index }: { node: AdminTreeNode; index: number }) {
|
|
const t = useT();
|
|
const member = node.member;
|
|
return (
|
|
<li className="flex items-center gap-2 text-sm">
|
|
<span className="tabular text-muted-foreground">{t("NtwUplineLevel", { level: index })}</span>
|
|
<Link
|
|
href={`/members/${node.mbid}`}
|
|
className="font-medium hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
|
|
>
|
|
{member?.name ?? node.mbid}
|
|
</Link>
|
|
<span className="tabular text-xs text-muted-foreground">{node.mbid}</span>
|
|
</li>
|
|
);
|
|
}
|
|
|
|
export default function NetworkPage() {
|
|
return (
|
|
<RequireModule pathname="/network">
|
|
<Network />
|
|
</RequireModule>
|
|
);
|
|
}
|
|
|
|
function Network() {
|
|
const t = useT();
|
|
const router = useRouter();
|
|
const { hasModule } = useAdminAuth();
|
|
const [params, setParams] = useQueryState();
|
|
const rootCode = params.get("root") ?? "";
|
|
|
|
const [tree, setTree] = useState<AdminTreeNode | null>(null);
|
|
const [upline, setUpline] = useState<AdminTreeNode[]>([]);
|
|
const [history, setHistory] = useState<AdminSponsorHistoryRow[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<{ code: string; params?: MessageParams } | null>(null);
|
|
const [search, setSearch] = useState("");
|
|
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
|
|
const [reloadKey, setReloadKey] = useState(0);
|
|
const [view, setView] = useState("tree");
|
|
|
|
const retry = useCallback(() => setReloadKey(k => k + 1), []);
|
|
|
|
useEffect(() => {
|
|
if (!rootCode) return;
|
|
let cancelled = false;
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the rootCode/reloadKey-triggered load below, which is the actual synchronization.
|
|
setLoading(true);
|
|
setError(null);
|
|
Promise.all([getNetworkTree(rootCode), getMemberUpline(rootCode), getPlacementHistory(rootCode)])
|
|
.then(([root, chain, historyPage]) => {
|
|
if (cancelled) return;
|
|
setTree(root);
|
|
setUpline(chain);
|
|
setHistory(historyPage.content ?? []);
|
|
setExpandedIds(new Set([root.mbid]));
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) {
|
|
if (err instanceof ApiError && err.status === 404) {
|
|
setTree(null);
|
|
setUpline([]);
|
|
setHistory([]);
|
|
setError({ code: "NetworkRootNotFound", params: { memberCode: rootCode } });
|
|
} else {
|
|
setError({ code: err instanceof Error ? err.message : "NtwLoadFailed" });
|
|
}
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [rootCode, reloadKey]);
|
|
|
|
const term = search.trim().toLowerCase();
|
|
|
|
const { matched, ancestorIds } = useMemo(() => {
|
|
const matched = new Set<string>();
|
|
const ancestorIds = new Set<string>();
|
|
if (tree && term) collectMatches(tree, term, [], matched, ancestorIds);
|
|
return { matched, ancestorIds };
|
|
}, [tree, term]);
|
|
|
|
// Searching expands just the paths to matches; clearing restores the default of
|
|
// root expanded with level 1 visible.
|
|
useEffect(() => {
|
|
if (!tree) return;
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- synchronizes expansion with the search term/tree changing (expand paths to matches, or restore the default).
|
|
setExpandedIds(term ? new Set(ancestorIds) : new Set([tree.mbid]));
|
|
}, [tree, term, ancestorIds]);
|
|
|
|
const toggle = useCallback((id: string) => {
|
|
setExpandedIds(prev => {
|
|
const next = new Set(prev);
|
|
if (next.has(id)) next.delete(id);
|
|
else next.add(id);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
// Shared by the root picker and a node's "Set as tree root" inline action
|
|
// (Task 10) — both just need the `root` query param set to reload the tree.
|
|
const setRootParam = useCallback(
|
|
(memberCode: string) => {
|
|
const value = memberCode.trim().toUpperCase();
|
|
if (!value) return;
|
|
setParams(prev => {
|
|
const next = new URLSearchParams(prev);
|
|
next.set("root", value);
|
|
return next;
|
|
});
|
|
},
|
|
[setParams],
|
|
);
|
|
|
|
const handleRootSelect = useCallback(
|
|
(member: AdminMember) => setRootParam(member.memberCode),
|
|
[setRootParam],
|
|
);
|
|
|
|
// Task 10 — "Set as tree root" inline action on a chart node.
|
|
const handleSetRoot = useCallback((memberCode: string) => setRootParam(memberCode), [setRootParam]);
|
|
|
|
// Task 10 / BABYBOO-43 — "Correct placement" inline action on a chart node: opens the referral
|
|
// tab of Rank & referral with that member prefilled. Offered only with BO_RANK_REFERRAL.
|
|
const handleCorrectPlacement = useCallback(
|
|
(memberCode: string) =>
|
|
router.push(`/rank-referral?tab=referral&member=${encodeURIComponent(memberCode)}`),
|
|
[router],
|
|
);
|
|
|
|
const noMatches = Boolean(term) && matched.size === 0;
|
|
|
|
const noMatchEmpty = (
|
|
<EmptyState
|
|
title={t("NoMemberMatches", { term: search.trim() })}
|
|
className="rounded-lg border bg-card"
|
|
/>
|
|
);
|
|
|
|
return (
|
|
<>
|
|
<PageHeader title={t("NetworkTitle")}>
|
|
<NetworkTabs />
|
|
</PageHeader>
|
|
|
|
<div className="mb-4 flex flex-wrap items-end gap-3 rounded-lg border bg-card p-4">
|
|
<div className="w-64 space-y-1.5">
|
|
<Label className="text-xs text-muted-foreground">{t("NetworkRoot")}</Label>
|
|
<MemberSearchCombobox
|
|
placeholder={t("NetworkRoot")}
|
|
initialQuery={rootCode}
|
|
onSelect={handleRootSelect}
|
|
aria-label={t("NetworkRoot")}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{error && <ErrorState message={t(error.code, error.params)} onRetry={retry} className="mb-4" />}
|
|
|
|
{loading ? (
|
|
<div className="space-y-2">
|
|
{Array.from({ length: 8 }).map((_, i) => (
|
|
<Skeleton key={i} className="h-9 w-full" />
|
|
))}
|
|
</div>
|
|
) : !tree ? (
|
|
<EmptyState
|
|
title={t("NetworkNoRoot")}
|
|
className="rounded-lg border bg-card"
|
|
/>
|
|
) : (
|
|
<Tabs value={view} onValueChange={setView}>
|
|
<div className="mb-4 flex flex-wrap items-center gap-3">
|
|
<TabsList>
|
|
<TabsTrigger value="tree">{t("Tree")}</TabsTrigger>
|
|
<TabsTrigger value="chart">{t("Chart")}</TabsTrigger>
|
|
<TabsTrigger value="upline">{t("Upline")}</TabsTrigger>
|
|
<TabsTrigger value="history">{t("PlacementHistory")}</TabsTrigger>
|
|
</TabsList>
|
|
|
|
<div className="relative">
|
|
<Search
|
|
aria-hidden="true"
|
|
className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground"
|
|
/>
|
|
<Input
|
|
aria-label={t("SearchMembers")}
|
|
placeholder={t("SearchByName")}
|
|
value={search}
|
|
onChange={e => setSearch(e.target.value)}
|
|
className="h-9 w-72 pl-8"
|
|
/>
|
|
</div>
|
|
|
|
{term && !noMatches && (
|
|
<p className="text-sm text-muted-foreground">
|
|
<span className="tabular">{matched.size}</span>{" "}
|
|
{matched.size === 1 ? t("Match") : t("Matches")}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<TabsContent value="tree">
|
|
{noMatches ? (
|
|
noMatchEmpty
|
|
) : (
|
|
<TreeView
|
|
root={tree}
|
|
expandedIds={expandedIds}
|
|
onToggle={toggle}
|
|
searchTerm={search.trim()}
|
|
/>
|
|
)}
|
|
</TabsContent>
|
|
{/* Chart shares expansion state with the tree, so switching views keeps
|
|
the same branch open instead of blowing the chart wide open. */}
|
|
<TabsContent value="chart">
|
|
{noMatches ? (
|
|
noMatchEmpty
|
|
) : (
|
|
<OrgChart
|
|
root={tree}
|
|
expandedIds={expandedIds}
|
|
onToggle={toggle}
|
|
searchMatches={matched}
|
|
onSetRoot={handleSetRoot}
|
|
onCorrectPlacement={hasModule("BO_RANK_REFERRAL") ? handleCorrectPlacement : undefined}
|
|
/>
|
|
)}
|
|
</TabsContent>
|
|
<TabsContent value="upline">
|
|
{noMatches ? (
|
|
noMatchEmpty
|
|
) : upline.length === 0 ? (
|
|
<EmptyState title={t("NoUpline")} className="rounded-lg border bg-card" />
|
|
) : (
|
|
<ol className="space-y-1 rounded-lg border bg-card p-4">
|
|
{upline.map((node, i) => (
|
|
<UplineEntry key={node.mbid} node={node} index={i + 1} />
|
|
))}
|
|
</ol>
|
|
)}
|
|
</TabsContent>
|
|
<TabsContent value="history">
|
|
{noMatches ? noMatchEmpty : <PlacementHistoryTable rows={history} t={t} />}
|
|
</TabsContent>
|
|
</Tabs>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function PlacementHistoryTable({
|
|
rows,
|
|
t,
|
|
}: {
|
|
rows: AdminSponsorHistoryRow[];
|
|
t: (code: string, params?: Record<string, string | number>) => string;
|
|
}) {
|
|
const [sorting, setSorting] = useState<SortingState>([]);
|
|
const sorted = useMemo(
|
|
() =>
|
|
sortRows(rows, sorting, {
|
|
date: (r) => r.createDateTime,
|
|
member: (r) => r.memberCode,
|
|
oldSponsor: (r) => r.oldSponsorCode,
|
|
newSponsor: (r) => r.newSponsorCode,
|
|
by: (r) => r.doneBy,
|
|
reason: (r) => { const p = placementReason(r.remarks); return p === "—" ? null : p; }, // blanks sort last
|
|
}),
|
|
[rows, sorting],
|
|
);
|
|
return (
|
|
<div className="overflow-hidden rounded-table border bg-card">
|
|
<Table aria-label={t("PlacementHistory")}>
|
|
<TableHeader className="sticky top-0 z-10 bg-card">
|
|
<TableRow>
|
|
<SortableHead label={t("PlacementDate")} sortKey="date" sorting={sorting} onSortingChange={setSorting} />
|
|
<SortableHead label={t("PlacementMember")} sortKey="member" sorting={sorting} onSortingChange={setSorting} />
|
|
<SortableHead label={t("PlacementOldSponsor")} sortKey="oldSponsor" sorting={sorting} onSortingChange={setSorting} />
|
|
<SortableHead label={t("PlacementNewSponsor")} sortKey="newSponsor" sorting={sorting} onSortingChange={setSorting} />
|
|
<SortableHead label={t("PlacementBy")} sortKey="by" sorting={sorting} onSortingChange={setSorting} />
|
|
<SortableHead label={t("PlacementReason")} sortKey="reason" sorting={sorting} onSortingChange={setSorting} />
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{rows.length === 0 ? (
|
|
<TableRow>
|
|
<TableCell colSpan={6} className="h-24 text-center">
|
|
<EmptyState title={t("NoPlacementHistory")} />
|
|
</TableCell>
|
|
</TableRow>
|
|
) : (
|
|
sorted.map((row, i) => (
|
|
<TableRow key={row.id ?? i} className="h-9 hover:bg-muted">
|
|
<TableCell className="tabular">{formatDateTime(row.createDateTime)}</TableCell>
|
|
<TableCell>
|
|
<MemberCell code={row.memberCode} name={row.memberName} />
|
|
</TableCell>
|
|
<TableCell>
|
|
<MemberCell code={row.oldSponsorCode} name={row.oldSponsorName} />
|
|
</TableCell>
|
|
<TableCell>
|
|
<MemberCell code={row.newSponsorCode} name={row.newSponsorName} />
|
|
</TableCell>
|
|
<TableCell className="tabular">{row.doneBy ?? "—"}</TableCell>
|
|
<TableCell className="min-w-48 whitespace-normal">{placementReason(row.remarks)}</TableCell>
|
|
</TableRow>
|
|
))
|
|
)}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** The recorded reason for a move; blank or the "-" placeholder (admin correction has no remarks field) shows "—". */
|
|
function placementReason(remarks?: string): string {
|
|
const text = remarks?.trim();
|
|
return !text || text === "-" ? "—" : text;
|
|
}
|
|
|
|
export type { AdminTreeNode, AdminTreeNodeMember };
|