Files
co-lite/solvway-admin-portal/app/inventory/delivery-orders/IssueDrawer.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

223 lines
8.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { Fragment, useEffect, useMemo, useState } from "react";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/app/components/ui/sheet";
import { Button } from "@/app/components/ui/button";
import { Alert, AlertDescription } from "@/app/components/ui/alert";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import {
getIssuePlan,
issueOrder,
type IssuePlanLine,
type IssueResult,
} from "@/app/lib/services/adminDeliveryOrders";
import { listAdminWarehouses } from "@/app/lib/services/adminWarehouses";
import type { AdminWarehouse } from "@/app/lib/types";
interface IssueDrawerProps {
orderUuid: string | null;
invoice: string;
onClose: () => void;
onIssued: (r: IssueResult) => void;
}
/** Drawer that opens per-row on the "To issue" tab, showing an issue plan and a submit. */
export function IssueDrawer({ orderUuid, invoice, onClose, onIssued }: IssueDrawerProps) {
// Inner component mounts per open, so each open gets a fresh plan and issueRequestId.
if (orderUuid === null) return null;
return (
<IssueDrawerInner
orderUuid={orderUuid}
invoice={invoice}
onClose={onClose}
onIssued={onIssued}
/>
);
}
function IssueDrawerInner({ orderUuid, invoice, onClose, onIssued }: Omit<IssueDrawerProps, "orderUuid"> & { orderUuid: string }) {
const t = useT();
const [plan, setPlan] = useState<IssuePlanLine[]>([]);
const [loaded, setLoaded] = useState(false);
const [planError, setPlanError] = useState<string | null>(null);
const [submitError, setSubmitError] = useState<string | null>(null);
const [warehouses, setWarehouses] = useState<AdminWarehouse[]>([]);
const [submitting, setSubmitting] = useState(false);
// One request id per open, reused on retry so the server can deduplicate a repeated submit.
const [issueRequestId] = useState(() => crypto.randomUUID());
// Quantities keyed by orderLineIndex.
const [quantities, setQuantities] = useState<Record<number, number>>({});
// Load plan + warehouses on mount.
useEffect(() => {
let cancelled = false;
getIssuePlan(orderUuid)
.then(p => {
if (!cancelled) {
setPlan(p);
setLoaded(true);
const defaults: Record<number, number> = {};
for (const line of p) {
defaults[line.orderLineIndex] = Math.max(0, Math.min(line.outstanding, line.onHand));
}
setQuantities(defaults);
}
})
.catch(err => {
if (!cancelled) setPlanError(err instanceof Error ? err.message : String(err));
});
listAdminWarehouses()
.then(w => { if (!cancelled) setWarehouses(w); })
.catch(() => {});
return () => { cancelled = true; };
}, [orderUuid]);
const warehouseById = useMemo(
() => new Map(warehouses.map(w => [String(w.id), w])),
[warehouses],
);
// Computed summary.
const { issuing, left } = useMemo(() => {
let totalIssuing = 0;
let totalOutstanding = 0;
for (const line of plan) {
totalOutstanding += line.outstanding;
totalIssuing += quantities[line.orderLineIndex] ?? 0;
}
return { issuing: totalIssuing, left: totalOutstanding - totalIssuing };
}, [plan, quantities]);
async function handleIssue() {
setSubmitting(true);
setSubmitError(null);
const quantitiesToIssue: Record<number, number> = {};
for (const line of plan) {
const qty = quantities[line.orderLineIndex] ?? 0;
if (qty > 0) {
quantitiesToIssue[line.orderLineIndex] = qty;
}
}
try {
const result = await issueOrder(orderUuid, issueRequestId, quantitiesToIssue);
onIssued(result);
} catch (err) {
setSubmitError((err instanceof Error && err.message) || t("FulIssueFailed"));
} finally {
setSubmitting(false);
}
}
function setQuantity(line: IssuePlanLine, value: number) {
setQuantities(prev => ({ ...prev, [line.orderLineIndex]: Math.max(0, Math.min(Math.trunc(value), line.outstanding)) }));
}
return (
<Sheet open onOpenChange={open => { if (!open) onClose(); }}>
<SheetContent side="right" className="w-full sm:max-w-2xl overflow-y-auto">
<SheetHeader>
<SheetTitle>{t("FulIssueDrawerTitle", { invoice })}</SheetTitle>
</SheetHeader>
<div className="mt-4 space-y-4">
{planError && (
<Alert variant="destructive">
<AlertDescription>{planError}</AlertDescription>
</Alert>
)}
{!loaded && !planError && <p className="text-sm text-muted-foreground">{t("Loading")}</p>}
{/* Plan table */}
{plan.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b">
<th className="text-left py-2 pr-2">{t("FulColItem")}</th>
<th className="text-left py-2 pr-2">{t("FulColSku")}</th>
<th className="text-right py-2 pr-2">{t("FulColOrdered")}</th>
<th className="text-right py-2 pr-2">{t("FulColIssued")}</th>
<th className="text-right py-2 pr-2">{t("FulColOnHand")}</th>
<th className="text-right py-2 pr-2">{t("FulColIssueNow")}</th>
</tr>
</thead>
<tbody>
{plan.map(line => {
const qty = quantities[line.orderLineIndex] ?? 0;
const isQianyi = warehouseById.get(line.warehouseId)?.fulfilmentMode === "QIANYI";
return (
<Fragment key={line.orderLineIndex}>
<tr className="border-b">
<td className="py-2 pr-2">{line.skuName ?? line.productName ?? line.productCode}</td>
<td className="py-2 pr-2">{line.skuCode || line.sku || "—"}</td>
<td className="py-2 pr-2 text-right tabular">{line.ordered}</td>
<td className="py-2 pr-2 text-right tabular">{line.issued}</td>
<td className="py-2 pr-2 text-right tabular">{line.onHand}</td>
<td className="py-2 pr-2 text-right">
<input
type="number"
min={0}
max={line.outstanding}
value={qty}
aria-label={t("FulIssueNowFor", { sku: line.skuCode || line.sku || line.productCode })}
className="w-16 rounded border px-1 py-0.5 text-right tabular"
onChange={e => setQuantity(line, Number(e.target.value) || 0)}
/>
{line.onHand <= 0 && (
<div className="text-xs text-muted-foreground">{t("FulAwaitingStock")}</div>
)}
{isQianyi && (
<div className="text-xs text-muted-foreground mt-1">{t("FulSentToQianyi")}</div>
)}
</td>
</tr>
{line.components?.map(c => (
<tr key={c.skuVariationId} className="border-b text-xs text-muted-foreground">
<td className="py-1 pr-2 pl-4">
<span>{c.skuName ?? c.skuCode}</span> <span>×{c.unitsPerLine}</span>
</td>
<td className="py-1 pr-2">{c.skuCode}</td>
<td />
<td />
<td className="py-1 pr-2 text-right tabular">{c.onHand}</td>
<td />
</tr>
))}
</Fragment>
);
})}
</tbody>
</table>
</div>
)}
{/* Summary + submit */}
{plan.length > 0 && <div className="flex items-center justify-between border-t pt-3">
<span className="text-sm text-muted-foreground">{t("FulIssueSummary", { issuing, left })}</span>
<Button
onClick={handleIssue}
disabled={issuing === 0 || submitting}
>
{t("FulIssueDo")}
</Button>
</div>}
{submitError && (
<Alert variant="destructive">
<AlertDescription>{submitError}</AlertDescription>
</Alert>
)}
</div>
</SheetContent>
</Sheet>
);
}