/** * order-assistant-save — the save-time merge the order Process page uses * so a rep's save of an AI-filled line records the review. * * The order-side twin of `quote-assistant-save.ts`. Client-safe (types + * `order-assistant-review` only), so it can be unit-tested. */ import { buildOrderAiReviewPatch, isOrderAiFillPending, nextOrderPricingSourceOnSave, } from "@/lib/order-assistant-review"; import type { OrderItem } from "@/lib/types"; /** The bits of a line the save merge reads. */ export type OrderAiLine = Pick; /** * Returns `patch` plus the AI-review bookkeeping for `item`: * * - `pricing_source`: only touched when the patch already carries one. * "ai_quote" / "quote" / "catalogue" survive the save (the line is * still priced from the quote); anything else becomes "manual". * The value the operator committed wins over the one the page was * loaded with, so the one-click "use this cost" copy — which sets * "quote" — really does end the AI's provenance. * - `ai_fill`: the reviewed copy, only for a pending AI line. * * Never removes keys from `patch` and never mutates it. */ export function withOrderAiReview( item: OrderAiLine | undefined, patch: Record, saved: { cost_price: number; selling_price: number; supplier: string | null }, reviewer: { id?: string; name: string }, now: Date, ): Record { const out: Record = { ...patch }; const committedSource = typeof patch.pricing_source === "string" ? patch.pricing_source : item?.pricing_source; if ("pricing_source" in patch && committedSource !== "catalogue") { out.pricing_source = nextOrderPricingSourceOnSave(committedSource); } if (!item || !isOrderAiFillPending(item)) return out; Object.assign(out, buildOrderAiReviewPatch(item, saved, reviewer, now)); return out; } /** `{ id, name }` for the signed-in PB user (`authStore.record`). */ export function orderReviewerFromAuthRecord( record: { id?: string; name?: unknown; email?: unknown } | null | undefined, ): { id?: string; name: string } { const name = typeof record?.name === "string" ? record.name : ""; const email = typeof record?.email === "string" ? record.email : ""; return { id: record?.id, name: name || email || "" }; }