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
155 lines
6.8 KiB
TypeScript
155 lines
6.8 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { getIssuePlan, issueOrder, type IssuePlanLine, type IssueResult } from "@/app/lib/services/adminDeliveryOrders";
|
|
|
|
type BulkOrder = { uuid: string; documentNo: string; transactionDateTime: string };
|
|
type Plan = { order: BulkOrder; lines: IssuePlanLine[]; loadError: string | null };
|
|
type Outcome = { result?: IssueResult; error?: string };
|
|
|
|
// Stock goes to the oldest paid order first; each line takes what is left of its warehouse and variant.
|
|
// ponytail: bundle components share stock only by line variant; the server guard rejects the rest
|
|
function allocate(plans: Plan[]): Record<string, Record<number, number>> {
|
|
const left = new Map<string, number>();
|
|
const out: Record<string, Record<number, number>> = {};
|
|
for (const { order, lines } of plans) {
|
|
const qty: Record<number, number> = {};
|
|
for (const l of lines) {
|
|
const key = `${l.warehouseId}|${l.variationId}`;
|
|
const remaining = left.get(key) ?? l.onHand;
|
|
const take = Math.max(0, Math.min(l.outstanding, remaining));
|
|
left.set(key, remaining - take);
|
|
if (take > 0) qty[l.orderLineIndex] = take;
|
|
}
|
|
out[order.uuid] = qty;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
const units = (q: Record<number, number> | undefined) => Object.values(q ?? {}).reduce((a, b) => a + b, 0);
|
|
|
|
/** Bulk issue preview (manual-do-issue §6.3): allocate oldest first, then issue the ticked orders one at a time. */
|
|
export function BulkIssueDialog({ orders, onClose }: { orders: BulkOrder[]; onClose: (issuedDoUuids: string[]) => void }) {
|
|
const t = useT();
|
|
const [plans, setPlans] = useState<Plan[] | null>(null);
|
|
const [ticked, setTicked] = useState<Set<string>>(new Set());
|
|
const [outcomes, setOutcomes] = useState<Record<string, Outcome>>({});
|
|
const [phase, setPhase] = useState<"preview" | "running" | "done">("preview");
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
const sorted = [...orders].sort((a, b) => a.transactionDateTime.localeCompare(b.transactionDateTime));
|
|
Promise.all(sorted.map(order => getIssuePlan(order.uuid).then(
|
|
lines => ({ order, lines, loadError: null }),
|
|
(err: unknown) => ({ order, lines: [], loadError: err instanceof Error ? err.message : String(err) }),
|
|
))).then(loaded => {
|
|
if (cancelled) return;
|
|
const alloc = allocate(loaded);
|
|
setPlans(loaded);
|
|
setTicked(new Set(loaded.filter(p => units(alloc[p.order.uuid]) > 0).map(p => p.order.uuid)));
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, [orders]);
|
|
|
|
const alloc = useMemo(() => allocate(plans ?? []), [plans]);
|
|
const toIssue = (plans ?? []).filter(p => ticked.has(p.order.uuid));
|
|
|
|
async function run() {
|
|
setPhase("running");
|
|
for (const { order } of toIssue) {
|
|
let outcome: Outcome;
|
|
try {
|
|
outcome = { result: await issueOrder(order.uuid, crypto.randomUUID(), alloc[order.uuid]) };
|
|
} catch (err) {
|
|
outcome = { error: err instanceof Error ? err.message : t("FulIssueFailed") };
|
|
}
|
|
setOutcomes(prev => ({ ...prev, [order.uuid]: outcome }));
|
|
}
|
|
setPhase("done");
|
|
}
|
|
|
|
const results = Object.values(outcomes).flatMap(o => (o.result ? [o.result] : []));
|
|
const issued = results.filter(r => r.outstandingUnits === 0).length;
|
|
const partial = results.length - issued;
|
|
const close = () => onClose(results.flatMap(r => r.deliveryOrderUuids));
|
|
|
|
function planLabel(p: Plan) {
|
|
const outstanding = p.lines.reduce((a, l) => a + l.outstanding, 0);
|
|
const allocated = units(alloc[p.order.uuid]);
|
|
if (allocated === 0) return t("FulPlanNone");
|
|
return allocated >= outstanding ? t("FulPlanFull") : t("FulPlanPartial", { allocated, outstanding });
|
|
}
|
|
|
|
return (
|
|
<Dialog open onOpenChange={open => { if (!open && phase !== "running") close(); }}>
|
|
<DialogContent className="max-w-3xl" showCloseButton={false}>
|
|
<DialogHeader>
|
|
<DialogTitle>{t("FulBulkIssueTitle")}</DialogTitle>
|
|
</DialogHeader>
|
|
{plans === null ? (
|
|
<p className="text-sm text-muted-foreground">{t("Loading")}</p>
|
|
) : (
|
|
<table className="w-full text-sm">
|
|
<thead>
|
|
<tr className="border-b text-left">
|
|
<th className="py-2 pr-2"><span className="sr-only">{t("FulColSelect")}</span></th>
|
|
<th className="py-2 pr-2">{t("FulColInvoice")}</th>
|
|
<th className="py-2 pr-2">{t("FulColIssueNow")}</th>
|
|
<th className="py-2 pr-2"><span className="sr-only">{t("FulColResult")}</span></th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{plans.map(p => {
|
|
const error = p.loadError ?? outcomes[p.order.uuid]?.error;
|
|
return (
|
|
<tr key={p.order.uuid} className="border-b last:border-0">
|
|
<td className="py-2 pr-2">
|
|
<input
|
|
type="checkbox"
|
|
aria-label={t("FulSelectRow", { ref: p.order.documentNo })}
|
|
checked={ticked.has(p.order.uuid)}
|
|
disabled={phase !== "preview" || units(alloc[p.order.uuid]) === 0}
|
|
onChange={() => setTicked(prev => {
|
|
const next = new Set(prev);
|
|
if (!next.delete(p.order.uuid)) next.add(p.order.uuid);
|
|
return next;
|
|
})}
|
|
/>
|
|
</td>
|
|
<td className="py-2 pr-2">{p.order.documentNo}</td>
|
|
<td className="py-2 pr-2">{planLabel(p)}</td>
|
|
<td className="py-2 pr-2 text-destructive">{error}</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
)}
|
|
{phase === "running" && (
|
|
<p role="status" className="text-sm text-muted-foreground">
|
|
{t("FulBulkProgress", { done: Object.keys(outcomes).length, total: toIssue.length })}
|
|
</p>
|
|
)}
|
|
{phase === "done" && (
|
|
<p role="status" className="text-sm font-medium">
|
|
{t("FulBulkIssueSummary", { issued, partial, skipped: (plans?.length ?? 0) - results.length })}
|
|
</p>
|
|
)}
|
|
<DialogFooter>
|
|
{phase === "done" ? (
|
|
<Button variant="secondary" onClick={close}>{t("FulClose")}</Button>
|
|
) : (
|
|
<>
|
|
<Button variant="outline" disabled={phase === "running"} onClick={() => onClose([])}>{t("Cancel")}</Button>
|
|
<Button variant="secondary" disabled={phase === "running" || toIssue.length === 0} onClick={run}>{t("FulIssueDo")}</Button>
|
|
</>
|
|
)}
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|