Files
co-lite/solvway-admin-portal/app/lib/inventory/transferWorkbook.ts
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

148 lines
5.7 KiB
TypeScript

/**
* Pure helpers for the Stock Transfer Excel template / import (in-browser only, no upload).
* Mirrors stockInWorkbook.ts; DOM work lives in the component.
*/
import * as XLSX from "xlsx";
import type { StockOnHandRow, TransferLineInput } from "@/app/lib/types";
import type { Translate } from "@/app/lib/i18n/t";
export const TRANSFER_HEADERS = [
"SKU Code",
"SKU Name",
"Variation",
"On Hand",
"Quantity",
"Batch Number",
"Expiry (YYYY-MM-DD)",
"skuVariationId",
] as const;
/** 0-based column index of the hidden skuVariationId column. */
const SKU_VARIATION_ID_COL = 7;
const EXPIRY_COL = 6;
/** A parsed line plus the readable fields the review table shows. */
export interface TransferImportLine extends TransferLineInput {
skuCode: string;
skuName: string;
variation: string;
}
/** Template of the source warehouse's stock: only rows with stockOnHand > 0. */
export function buildTransferWorkbook(rows: StockOnHandRow[]): Uint8Array<ArrayBuffer> {
const wb = XLSX.utils.book_new();
// skuVariationId is a string to avoid Snowflake precision loss.
const ws = XLSX.utils.aoa_to_sheet([
[...TRANSFER_HEADERS],
...rows
.filter(r => r.stockOnHand > 0)
.map(r => [r.skuCode, r.skuName, r.variation ?? null, r.stockOnHand, null, null, null, String(r.skuVariationId)]),
]);
// Text format on Expiry so a typed 2027-12-31 stays text where Excel honours it. Every data row
// gets a cell (aoa_to_sheet skips nulls), so typing into an empty row is formatted too.
const lastRow = rows.filter(r => r.stockOnHand > 0).length + 1;
for (let r = 1; r < lastRow; r++) ws[XLSX.utils.encode_cell({ r, c: EXPIRY_COL })] = { t: "s", v: "", z: "@" };
// BABYBOO-50: a `{}` col opens at zero width in Excel, so every visible column gets a width.
ws["!cols"] = TRANSFER_HEADERS.map((header, i) =>
i === SKU_VARIATION_ID_COL ? { hidden: true } : { wch: Math.max(14, header.length + 4) },
);
XLSX.utils.book_append_sheet(wb, ws, "Stock Transfer");
const instructions = [
["Stock Transfer Import Instructions"],
[""],
["1. Fill in Quantity (whole units) for the rows you are transferring. Leave other rows blank or set Quantity to 0."],
["2. Do not edit SKU Code, SKU Name, Variation, On Hand, or skuVariationId. On Hand is the source stock when this file was downloaded."],
["3. Batch Number is optional."],
["4. Expiry date must be in YYYY-MM-DD format (e.g. 2027-12-31). Leave blank if not applicable."],
["5. Pick the source and destination warehouses on the Transfer page before importing."],
["6. Click 'Import' to load the filled rows into the form for review, then click Submit."],
["7. Do NOT unhide or edit the hidden skuVariationId column - editing it will cause the row to be rejected on import."],
["8. Do NOT round-trip this file through Google Sheets - it can corrupt the long internal IDs. Use Excel or LibreOffice instead."],
];
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(instructions), "Instructions");
// SheetJS may return an ArrayBuffer or a Uint8Array; always wrap into a fresh Uint8Array.
const out = XLSX.write(wb, { type: "array", bookType: "xlsx" });
return out instanceof Uint8Array ? new Uint8Array(out) : new Uint8Array(out as ArrayBuffer);
}
const EXPIRY_RE = /^\d{4}-\d{2}-\d{2}$/;
const text = (v: unknown): string => (v === undefined || v === null ? "" : String(v).trim());
const EXPIRY_HEADER = "Expiry (YYYY-MM-DD)";
/**
* Parse sheet_to_json rows of the "Stock Transfer" sheet. Blank/zero/negative quantity is skipped;
* a non-numeric or fractional quantity, missing id or bad expiry is an error naming the xlsx row
* (header = 1, first data row = 2). Nothing is silently dropped.
*/
export function parseTransferWorkbook(rows: Record<string, unknown>[], t: Translate): {
lines: TransferImportLine[];
errors: string[];
} {
const lines: TransferImportLine[] = [];
const errors: string[] = [];
rows.forEach((row, i) => {
const xlsxRow = i + 2;
const rawQty = row["Quantity"];
if (rawQty === undefined || rawQty === null || rawQty === "" || rawQty === 0) return;
if (typeof rawQty !== "number" || !Number.isFinite(rawQty)) {
errors.push(t("StockInRowQuantity", { row: xlsxRow }));
return;
}
if (rawQty < 0) return;
if (!Number.isInteger(rawQty)) {
errors.push(t("StockXferRowQuantityWhole", { row: xlsxRow }));
return;
}
const skuVariationId = text(row["skuVariationId"]);
if (!skuVariationId) {
errors.push(t("StockInRowMissingSku", { row: xlsxRow }));
return;
}
const expiry = text(row[EXPIRY_HEADER]);
if (expiry && !EXPIRY_RE.test(expiry)) {
errors.push(t("StockInRowExpiry", { row: xlsxRow, value: expiry }));
return;
}
const batchNumber = text(row["Batch Number"]);
lines.push({
skuVariationId,
quantity: rawQty,
...(batchNumber ? { batchNumber } : {}),
...(expiry ? { expiryDate: expiry } : {}),
skuCode: text(row["SKU Code"]),
skuName: text(row["SKU Name"]),
variation: text(row["Variation"]),
});
});
return { lines, errors };
}
/**
* Per skuVariationId, how many units the summed lines exceed raw on-hand by (missing id = 0 on hand).
* Mirrors the StockTransferService check; ids that fit are absent from the result.
*/
export function transferShortfalls(
lines: { skuVariationId: string; quantity: number }[],
onHandById: Map<string, number>,
): Map<string, number> {
const totals = new Map<string, number>();
for (const l of lines) totals.set(l.skuVariationId, (totals.get(l.skuVariationId) ?? 0) + l.quantity);
const short = new Map<string, number>();
for (const [id, total] of totals) {
const gap = total - (onHandById.get(id) ?? 0);
if (gap > 0) short.set(id, gap);
}
return short;
}