@aglyn/plugins-commerce 1.24.0 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/returns.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { PluginApiHandler, PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport {\n findUserByUidAcrossPools,\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { hostConsoleUrl } from '@aglyn/tenant-data-admin/server/host-console-link'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport * as CommerceModel from '../model'\nimport {\n RETURN_APPROVED_EVENT,\n RETURN_DECLINED_EVENT,\n RETURN_RECEIVED_EVENT,\n RETURN_REFUNDED_EVENT,\n RETURN_REQUESTED_EVENT,\n} from '../model/order-events'\nimport { raiseOrderEvent, stageOrderEvent } from './order-events'\nimport { orderStatusUrl, verifyOrderStatusToken } from './order-status-token'\nimport { readActiveMemberSession } from './membership'\nimport { resolveTrackedRestockLines } from './restock-flag'\nimport { refundHandler } from './refund'\nimport { dropStorefrontPages, soldOutMoved } from './sold-out-drop'\n\n/**\n * Returns (RMA, AGL-3611): the buyer's door, the merchant's door, and the\n * writes behind both. The rules — what is returnable, the window, the state\n * machine, what a refund is worth — are the model's (`commerce-returns.ts`);\n * this is where they are re-asked under the write.\n *\n * EVERY WRITE IS A TRANSACTION that reads the return, the order and, when it\n * opens one, every return already on the order — so two requests for the last\n * unit cannot both be granted, and a stale console cannot approve a return a\n * colleague declined a moment ago.\n *\n * THE MONEY MOVES THROUGH THE ORDER'S REFUND ROUTE, never here. A return's\n * refund calls `refund.ts` with the merchant's own credentials and a key\n * derived from the return, so its gates (an admin of the whole workspace,\n * the over-refund cap, the open-dispute block, Stripe's idempotency) are the\n * ones every refund passes, and asking twice refunds once.\n *\n * STOCK COMES BACK WHEN THE PARCEL DOES. Receiving a return puts the units\n * the merchant chose back on the shelf, at the location they chose, with an\n * inventory adjustment row — the products hub's history shows it beside the\n * sale. A refund then answers the order's restock question with what the\n * return already did, so nobody is asked to restock the same units twice.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst hostRefFor = (firestore: Firestore, hostId: string) => firestore.collection('hosts').doc(hostId)\n\nconst isId = (value: string) => Boolean(value) && value.length <= 200 && !/^__.*__$/.test(value) && !value.includes('/')\n\n/** The store's settings document and what the return emails need from the host. */\nasync function readStore(firestore: Firestore, hostId: string) {\n const hostRef = hostRefFor(firestore, hostId)\n const [host, store] = await Promise.all([\n hostRef.get().catch(() => null),\n hostRef.collection('settings').doc('store').get().catch(() => null),\n ])\n const settings = (store?.data() ?? {}) as Record<string, unknown>\n return {\n host: (host?.data() ?? {}) as Record<string, unknown>,\n returnSettings: CommerceModel.readReturnSettings(settings['returns']),\n currency: String(settings['currency'] ?? 'USD').toUpperCase(),\n }\n}\n\nfunction money(cents: number, currency: string): string {\n try {\n return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100)\n } catch {\n return `$${(cents / 100).toFixed(2)}`\n }\n}\n\n/** The return as an event carries it. */\nfunction returnEventView(id: string, entry: CommerceModel.HostReturn) {\n return {\n id,\n status: entry.status,\n lines: entry.lines.map((line) => ({ ...line })),\n refundCents: entry.refundCents ?? null,\n restock: entry.restock ? entry.restock.lines.map((line) => ({ ...line })) : null,\n }\n}\n\n/** \"1× House Blend — Arrived damaged\", one per line. */\nfunction returnItemsText(order: CommerceModel.HostOrder, entry: Pick<CommerceModel.HostReturn, 'lines'>): string {\n return entry.lines\n .map(\n (line) =>\n `${line.quantity}× ${order.lineItems?.[line.lineItemId]?.name ?? `line ${line.lineItemId}`} — ${\n CommerceModel.RETURN_REASON_LABELS[line.reason] ?? line.reason\n }`,\n )\n .join('\\n')\n}\n\nexport type OpenReturnOutcome =\n | { outcome: 'created'; returnId: string; entry: CommerceModel.HostReturn; order: CommerceModel.HostOrder }\n | { outcome: 'refused'; message: string }\n | { outcome: 'no_such_order' }\n\n/**\n * Opens a return. A buyer's starts `requested`; a merchant's starts\n * `approved`, since the merchant asking is the approval.\n */\nexport async function openReturn(request: {\n hostId: string\n orderId: string\n lines: ReadonlyArray<{ lineItemId: unknown; quantity: unknown; reason: unknown }>\n note?: string\n by: 'buyer' | 'merchant'\n now?: number\n}): Promise<OpenReturnOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const orderRef = hostRef.collection('orders').doc(request.orderId)\n const { returnSettings } = await readStore(firestore, request.hostId)\n const now = request.now ?? Date.now()\n const note = String(request.note ?? '').trim().slice(0, CommerceModel.RETURN_NOTE_MAX)\n return firestore.runTransaction(async (transaction): Promise<OpenReturnOutcome> => {\n const orderSnapshot = await transaction.get(orderRef)\n if (!orderSnapshot.exists) return { outcome: 'no_such_order' }\n const existing = await transaction.get(\n hostRef.collection('returns').where('orderId', '==', request.orderId),\n )\n const order = CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never)\n const verdict = CommerceModel.validateReturnRequest({\n order,\n existing: existing.docs.map((entry) => entry.data() as CommerceModel.HostReturn),\n settings: returnSettings,\n lines: request.lines,\n by: request.by,\n now,\n })\n if (!('lines' in verdict)) {\n return { outcome: 'refused', message: CommerceModel.describeReturnRequestProblem(verdict) }\n }\n const status: CommerceModel.ReturnStatus = request.by === 'merchant' ? 'approved' : 'requested'\n const entry: CommerceModel.HostReturn = {\n orderId: request.orderId,\n orderNumber: CommerceModel.returnOrderNumber(order, request.orderId),\n customerEmail: order.customerEmail ?? null,\n customerName: order.customerName ?? null,\n lines: verdict.lines.map((line) => ({\n ...line,\n name: String(order.lineItems?.[line.lineItemId]?.name ?? '').slice(0, 200),\n })),\n status,\n requestedBy: request.by,\n ...(note ? (request.by === 'buyer' ? { customerNote: note } : { merchantNote: note }) : {}),\n timeline: [\n {\n atMs: now,\n event: status,\n detail: `${request.by === 'buyer' ? 'Requested by the buyer' : 'Opened by the store'}: ${CommerceModel.describeReturnLines(order, verdict.lines)}`,\n },\n ],\n createdAtMs: now,\n updatedAtMs: now,\n }\n const returnRef = hostRef.collection('returns').doc(createResourceUid())\n transaction.create(returnRef, entry)\n const orderPatch = {\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'return-requested',\n CommerceModel.describeReturnLines(order, verdict.lines),\n now,\n ),\n }\n transaction.update(orderRef, orderPatch)\n stageOrderEvent(transaction, RETURN_REQUESTED_EVENT, {\n hostId: request.hostId,\n orderId: request.orderId,\n key: `return:${returnRef.id}`,\n order: { ...orderSnapshot.data(), ...orderPatch },\n extra: { return: returnEventView(returnRef.id, entry) },\n })\n // The store opening a return is its approval.\n if (status === 'approved') {\n stageOrderEvent(transaction, RETURN_APPROVED_EVENT, {\n hostId: request.hostId,\n orderId: request.orderId,\n key: `return-approved:${returnRef.id}`,\n order: { ...orderSnapshot.data(), ...orderPatch },\n extra: { return: returnEventView(returnRef.id, entry) },\n })\n }\n return { outcome: 'created', returnId: returnRef.id, entry, order }\n })\n}\n\nexport type ReturnAction = 'approve' | 'decline' | 'close' | 'note' | 'attach-label'\n\nexport type ChangeReturnOutcome =\n | { outcome: 'changed'; entry: CommerceModel.HostReturn; order: CommerceModel.HostOrder | null }\n | { outcome: 'already'; entry: CommerceModel.HostReturn }\n | { outcome: 'refused'; message: string }\n | { outcome: 'no_such_return' }\n\nconst ACTION_TARGET: Partial<Record<ReturnAction, CommerceModel.ReturnStatus>> = {\n approve: 'approved',\n decline: 'declined',\n close: 'closed',\n}\n\n/**\n * Approve, decline, close, a note, or a return label — the writes that move\n * no stock and no money. The transition is re-asked under the write.\n */\nexport async function changeReturn(request: {\n hostId: string\n returnId: string\n action: ReturnAction\n merchantNote?: string\n label?: { carrier: string; trackingNumber: string; labelUrl: string; trackingUrl?: string }\n now?: number\n}): Promise<ChangeReturnOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const returnRef = hostRef.collection('returns').doc(request.returnId)\n const now = request.now ?? Date.now()\n const note = request.merchantNote === undefined ? undefined : String(request.merchantNote).trim().slice(0, CommerceModel.RETURN_NOTE_MAX)\n return firestore.runTransaction(async (transaction): Promise<ChangeReturnOutcome> => {\n const snapshot = await transaction.get(returnRef)\n if (!snapshot.exists) return { outcome: 'no_such_return' }\n const entry = snapshot.data() as CommerceModel.HostReturn\n const orderSnapshot = await transaction.get(hostRef.collection('orders').doc(entry.orderId))\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n const target = ACTION_TARGET[request.action]\n let patch: Partial<CommerceModel.HostReturn>\n if (target) {\n if (entry.status === target) return { outcome: 'already', entry }\n if (!CommerceModel.canTransitionReturn(entry.status, target)) {\n return {\n outcome: 'refused',\n message: `A return that is ${CommerceModel.RETURN_STATUS_LABELS[entry.status].toLowerCase()} cannot be ${CommerceModel.RETURN_STATUS_LABELS[target].toLowerCase()}`,\n }\n }\n patch = {\n status: target,\n ...(note !== undefined && note ? { merchantNote: note } : {}),\n timeline: CommerceModel.appendReturnEvent(entry, target, note || undefined, now),\n }\n } else if (request.action === 'attach-label') {\n const label = request.label\n if (!label?.labelUrl || !/^https:\\/\\//i.test(label.labelUrl)) {\n return { outcome: 'refused', message: 'A return label needs an https link' }\n }\n if (!CommerceModel.returnIsOpen(entry) || entry.status === 'refunded') {\n return { outcome: 'refused', message: 'This return is finished; a label can no longer be attached' }\n }\n const carrier = String(label.carrier ?? '').trim().slice(0, 40)\n const trackingNumber = String(label.trackingNumber ?? '').trim().slice(0, 60)\n const trackingUrl =\n (label.trackingUrl && /^https:\\/\\//i.test(label.trackingUrl) ? label.trackingUrl : null) ??\n CommerceModel.trackingUrlFor(carrier, trackingNumber)\n patch = {\n returnLabel: {\n carrier,\n trackingNumber,\n labelUrl: String(label.labelUrl).slice(0, 2048),\n ...(trackingUrl ? { trackingUrl } : {}),\n attachedAtMs: now,\n },\n timeline: CommerceModel.appendReturnEvent(entry, 'label', `${carrier} ${trackingNumber}`.trim() || 'Return label attached', now),\n }\n } else {\n patch = {\n merchantNote: note ?? '',\n timeline: CommerceModel.appendReturnEvent(entry, 'note', note || 'Note cleared', now),\n }\n }\n transaction.update(returnRef, { ...patch, updatedAtMs: now })\n const changed = { ...entry, ...patch, updatedAtMs: now }\n const event = target === 'approved' ? RETURN_APPROVED_EVENT : target === 'declined' ? RETURN_DECLINED_EVENT : null\n if (event && orderSnapshot.exists) {\n stageOrderEvent(transaction, event, {\n hostId: request.hostId,\n orderId: entry.orderId,\n key: `return-${target}:${request.returnId}`,\n order: orderSnapshot.data() ?? {},\n extra: { return: returnEventView(request.returnId, changed) },\n })\n }\n return { outcome: 'changed', entry: changed, order }\n })\n}\n\n/**\n * The parcel arrived: the return is `received`, and the units the merchant\n * chose go back on the shelf, at the location they chose. A unit the sale\n * never took off a tracked count (an untracked variant, a deleted product)\n * has nothing to go back to and is left out, as a cancellation leaves it.\n */\nexport async function receiveReturn(request: {\n hostId: string\n returnId: string\n restock: ReadonlyArray<{ lineItemId: unknown; quantity: unknown }>\n locationId?: string\n now?: number\n}): Promise<ChangeReturnOutcome & { units?: number }> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const returnRef = hostRef.collection('returns').doc(request.returnId)\n const now = request.now ?? Date.now()\n const locationId = String(request.locationId ?? '').trim().slice(0, 100)\n // Whether the restock flipped a sold-out verdict the storefront shows\n // (AGL-4121); a retried attempt can only make the drop spurious.\n let soldOutFlipped = false\n const outcome = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(returnRef)\n if (!snapshot.exists) return { outcome: 'no_such_return' as const }\n const entry = snapshot.data() as CommerceModel.HostReturn\n if (entry.status === 'received' || entry.restock) return { outcome: 'already' as const, entry }\n if (!CommerceModel.canTransitionReturn(entry.status, 'received')) {\n return {\n outcome: 'refused' as const,\n message: `A return that is ${CommerceModel.RETURN_STATUS_LABELS[entry.status].toLowerCase()} cannot be received`,\n }\n }\n // What may go back: at most what the return covers, per line.\n const covered = new Map(entry.lines.map((line) => [line.lineItemId, line.quantity]))\n const wanted = new Map<number, number>()\n for (const line of request.restock) {\n const lineItemId = Number(line?.lineItemId)\n const quantity = Number(line?.quantity)\n if (!covered.has(lineItemId)) {\n return { outcome: 'refused' as const, message: `Line ${lineItemId} is not part of this return` }\n }\n if (!Number.isInteger(quantity) || quantity < 0) {\n return { outcome: 'refused' as const, message: 'Restock quantities must be whole numbers' }\n }\n const total = (wanted.get(lineItemId) ?? 0) + quantity\n if (total > (covered.get(lineItemId) ?? 0)) {\n return { outcome: 'refused' as const, message: `Only ${covered.get(lineItemId)} of line ${lineItemId} came back` }\n }\n if (quantity > 0) wanted.set(lineItemId, total)\n }\n if (locationId && wanted.size > 0) {\n const location = await transaction.get(hostRef.collection('locations').doc(locationId))\n if (!location.exists) return { outcome: 'refused' as const, message: 'That stock location no longer exists' }\n }\n const orderRef = hostRef.collection('orders').doc(entry.orderId)\n const orderSnapshot = await transaction.get(orderRef)\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n // Every read before any write, as a transaction requires.\n const tracked =\n order && wanted.size > 0\n ? await resolveTrackedRestockLines(hostRef, order, (ref) => transaction.get(ref))\n : { lines: [], products: new Map<string, CommerceModel.HostProduct>() }\n const byProduct = new Map<string, Array<{ variantId: string; quantity: number }>>()\n for (const line of tracked.lines) {\n const quantity = Math.min(line.quantity, wanted.get(line.lineIndex ?? -1) ?? 0)\n if (quantity <= 0) continue\n byProduct.set(line.productId, [...(byProduct.get(line.productId) ?? []), { variantId: line.variantId, quantity }])\n }\n let units = 0\n for (const [productId, lines] of byProduct) {\n const product = tracked.products.get(productId)\n if (!product) continue\n let variants = product.variants\n for (const line of lines) {\n variants = CommerceModel.adjustVariantInventory({ variants }, line.variantId, line.quantity, locationId || undefined)\n }\n transaction.update(hostRef.collection('products').doc(productId), {\n variants,\n ...CommerceModel.productStockFields({ ...product, variants }),\n updatedAtMs: now,\n })\n soldOutFlipped ||= soldOutMoved(product, { ...product, variants })\n for (const line of lines) {\n units += line.quantity\n transaction.create(hostRef.collection('inventoryAdjustments').doc(createResourceUid()), {\n productId,\n variantId: line.variantId,\n delta: line.quantity,\n reason: 'restock',\n orderId: entry.orderId,\n ...(locationId ? { locationId } : {}),\n atMs: now,\n } satisfies CommerceModel.InventoryAdjustment)\n }\n }\n const restock: CommerceModel.ReturnRestock = {\n lines: [...wanted.entries()].map(([lineItemId, quantity]) => ({ lineItemId, quantity })),\n ...(locationId ? { locationId } : {}),\n atMs: now,\n }\n const patch = {\n status: 'received' as const,\n restock,\n timeline: CommerceModel.appendReturnEvent(\n entry,\n 'received',\n units > 0 ? `${units} ${units === 1 ? 'unit' : 'units'} back in stock` : 'Nothing restocked',\n now,\n ),\n updatedAtMs: now,\n }\n transaction.update(returnRef, patch)\n const received = { ...entry, ...patch }\n if (order) {\n const orderPatch = {\n timeline: CommerceModel.appendOrderEvent(order, 'return-received', units > 0 ? `${units} restocked` : undefined, now),\n }\n transaction.update(orderRef, orderPatch)\n stageOrderEvent(transaction, RETURN_RECEIVED_EVENT, {\n hostId: request.hostId,\n orderId: entry.orderId,\n key: `return-received:${request.returnId}`,\n order: { ...orderSnapshot.data(), ...orderPatch },\n extra: { return: returnEventView(request.returnId, received) },\n })\n }\n return { outcome: 'changed' as const, entry: received, order, units }\n })\n if (soldOutFlipped && outcome.outcome === 'changed') {\n await dropStorefrontPages({\n hostId: request.hostId,\n reason: 'a received return restocked a product',\n })\n }\n return outcome\n}\n\n/**\n * Records a refund that went through the order's refund route against the\n * return, and answers the order's restock question with what the return\n * already did, so the merchant is not asked to restock the same units again.\n */\nexport async function markReturnRefunded(request: {\n hostId: string\n returnId: string\n refundCents: number\n uid: string\n now?: number\n}): Promise<ChangeReturnOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const returnRef = hostRef.collection('returns').doc(request.returnId)\n const now = request.now ?? Date.now()\n return firestore.runTransaction(async (transaction): Promise<ChangeReturnOutcome> => {\n const snapshot = await transaction.get(returnRef)\n if (!snapshot.exists) return { outcome: 'no_such_return' }\n const entry = snapshot.data() as CommerceModel.HostReturn\n if (entry.status === 'refunded' || entry.refundedAtMs) return { outcome: 'already', entry }\n const orderRef = hostRef.collection('orders').doc(entry.orderId)\n const orderSnapshot = await transaction.get(orderRef)\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n const patch = {\n status: 'refunded' as const,\n refundedAtMs: now,\n refundCents: Math.max(0, Math.round(request.refundCents)),\n timeline: CommerceModel.appendReturnEvent(entry, 'refunded', undefined, now),\n updatedAtMs: now,\n }\n transaction.update(returnRef, patch)\n const check = order?.restockCheck\n if (order && check && !check.resolution && entry.restock) {\n const restocked = entry.restock.lines.some((line) => line.quantity > 0)\n transaction.update(orderRef, {\n restockCheck: {\n ...check,\n resolution: restocked ? 'restocked' : 'dismissed',\n resolvedAtMs: now,\n ...(request.uid ? { resolvedBy: request.uid } : {}),\n } satisfies CommerceModel.OrderRestockCheck,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'restock-check',\n restocked ? 'answered by the return — restocked' : 'answered by the return — no restock',\n now,\n ),\n })\n }\n return { outcome: 'changed', entry: { ...entry, ...patch }, order }\n })\n}\n\n/** Calls the order's own refund route in-process, with the caller's credentials. */\nasync function callRefundRoute(\n req: PluginApiRequest,\n body: Record<string, unknown>,\n idempotencyKey: string,\n): Promise<{ status: number; body: Record<string, any> }> {\n let status = 200\n let payload: Record<string, any> = {}\n const res = {\n status(code: number) {\n status = code\n return res\n },\n json(value: unknown) {\n payload = (value ?? {}) as Record<string, any>\n return res\n },\n send(value: unknown) {\n payload = { error: String(value ?? '') }\n return res\n },\n setHeader() {\n return res\n },\n end() {\n return res\n },\n } as unknown as PluginApiResponse\n await refundHandler(\n {\n ...req,\n method: 'POST',\n headers: { authorization: String(req.headers.authorization ?? ''), 'idempotency-key': idempotencyKey },\n body,\n } as PluginApiRequest,\n res,\n )\n return { status, body: payload }\n}\n\n// ---------------------------------------------------------------------------\n// Emails\n// ---------------------------------------------------------------------------\n\ntype ReturnEmailKey = 'return-requested' | 'return-approved' | 'return-declined' | 'return-refunded'\n\nasync function sendReturnEmail(\n hostId: string,\n key: ReturnEmailKey,\n to: string,\n tokens: Record<string, string>,\n fallback: { subject: string; text: string },\n): Promise<void> {\n if (!to || !isEmailConfigured()) return\n try {\n const firestore = firebaseAdmin.app().firestore()\n const designed = await renderHostEmailWithTokens(firestore, hostId, key, tokens)\n const org = await getOrgForHost(hostId).catch(() => null)\n await sendEmail({\n to,\n subject: designed?.subject ?? fallback.subject,\n text: designed?.text || fallback.text,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: Aglyn.resolveBrandingProfile(org?.org as never).fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: key,\n // Owed to the recipient by their own order (AGL-3356).\n owedFor: 'order',\n })\n await meterHostEmail(hostId)\n } catch (error) {\n // A return that is recorded is not undone because its email failed.\n console.error(`[returns] ${key} not sent`, hostId, error)\n }\n}\n\n/** Tells the store a buyer asked, in the console and by email to the owner. */\nasync function tellStoreOfRequest(hostId: string, returnId: string, entry: CommerceModel.HostReturn, order: CommerceModel.HostOrder) {\n const items = returnItemsText(order, entry)\n await notifyHostManagers(\n hostId,\n {\n type: 'content.order',\n title: `Return requested for order ${entry.orderNumber}`,\n body: `${entry.customerEmail ?? 'A buyer'} wants to return ${CommerceModel.describeReturnLines(order, entry.lines)} from order ${entry.orderNumber} on {site}.`,\n link: `/${hostId}/products/returns?return=${encodeURIComponent(returnId)}`,\n },\n { skipOwnerEmail: true },\n ).catch(() => undefined)\n const ownerUid = (await getOrgForHost(hostId).catch(() => null))?.org?.ownerUid\n const owner = ownerUid ? (await findUserByUidAcrossPools(ownerUid).catch(() => null))?.record : null\n if (!owner?.email) return\n await sendReturnEmail(\n hostId,\n 'return-requested',\n owner.email,\n {\n 'order.number': entry.orderNumber,\n 'return.items': items,\n 'buyer.email': String(entry.customerEmail ?? ''),\n 'return.customerNote': String(entry.customerNote ?? ''),\n 'return.url': await hostConsoleUrl(\n hostId,\n `/${hostId}/products/returns?return=${encodeURIComponent(returnId)}`,\n ),\n },\n {\n subject: `Return requested for order ${entry.orderNumber}`,\n text:\n `${entry.customerEmail ?? 'A buyer'} wants to return items from order ${entry.orderNumber}.\\n\\n${items}` +\n (entry.customerNote ? `\\n\\n\"${entry.customerNote}\"` : '') +\n `\\n\\nApprove or decline it under Products → Returns.`,\n },\n )\n}\n\n/** Tells the buyer what happened to their return. */\nasync function tellBuyer(\n hostId: string,\n key: Exclude<ReturnEmailKey, 'return-requested'>,\n entry: CommerceModel.HostReturn,\n order: CommerceModel.HostOrder | null,\n): Promise<void> {\n const to = String(entry.customerEmail ?? order?.customerEmail ?? '').trim()\n if (!to || !order) return\n const firestore = firebaseAdmin.app().firestore()\n const store = await readStore(firestore, hostId)\n const statusUrl = orderStatusUrl(store.host as never, hostId, entry.orderId) ?? ''\n const items = returnItemsText(order, entry)\n const label = entry.returnLabel\n ? `Print your return label: ${entry.returnLabel.labelUrl}` +\n (entry.returnLabel.trackingNumber ? ` (${[entry.returnLabel.carrier, entry.returnLabel.trackingNumber].filter(Boolean).join(' ')})` : '')\n : ''\n const refundTotal = money(entry.refundCents ?? 0, store.currency)\n const tokens: Record<string, string> = {\n 'order.number': entry.orderNumber,\n 'return.items': items,\n 'return.note': String(entry.merchantNote ?? ''),\n 'return.label': label,\n 'return.refundTotal': refundTotal,\n 'order.statusUrl': statusUrl,\n }\n const fallback =\n key === 'return-approved'\n ? {\n subject: `Your return for order ${entry.orderNumber} is approved`,\n text: `Your return is approved:\\n\\n${items}` + (entry.merchantNote ? `\\n\\n${entry.merchantNote}` : '') + (label ? `\\n\\n${label}` : ''),\n }\n : key === 'return-declined'\n ? {\n subject: `About your return for order ${entry.orderNumber}`,\n text: `We could not accept the return of:\\n\\n${items}` + (entry.merchantNote ? `\\n\\n${entry.merchantNote}` : ''),\n }\n : {\n subject: `Your refund for order ${entry.orderNumber}`,\n text: `We received your return and refunded ${refundTotal}.\\n\\n${items}`,\n }\n if (statusUrl) fallback.text += `\\n\\nView your order: ${statusUrl}`\n await sendReturnEmail(hostId, key, to, tokens, fallback)\n}\n\n// ---------------------------------------------------------------------------\n// The buyer's door (tenant)\n// ---------------------------------------------------------------------------\n\n/**\n * Whether this request may act for the buyer of this order: the signed-in\n * site member whose email the order carries, or the holder of the order's\n * signed status link. Neither reveals whether the order exists to anyone\n * else — both refusals read the same.\n */\nasync function buyerMayActFor(\n req: PluginApiRequest,\n hostId: string,\n orderId: string,\n token: string,\n order: CommerceModel.HostOrder,\n): Promise<boolean> {\n if (token && verifyOrderStatusToken(hostId, orderId, token)) return true\n const session = await readActiveMemberSession(req, hostId)\n if (session.status !== 'active') return false\n const memberEmail = String(session.member.get('email') ?? '').trim().toLowerCase()\n return Boolean(memberEmail) && memberEmail === String(order.customerEmail ?? '').trim().toLowerCase()\n}\n\n/**\n * `GET /api/commerce/return-request?hostId&orderId&t` — what the buyer may\n * send back and until when, and the returns already open.\n * `POST` with `{ hostId, orderId, t?, lines: [{ lineItemId, quantity, reason }], note? }`\n * opens a return.\n */\nexport const returnRequestHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET' && req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const input = (req.method === 'GET' ? req.query : typeof req.body === 'string' ? JSON.parse(req.body) : req.body) ?? {}\n const hostId = String(input.hostId ?? '')\n const orderId = String(input.orderId ?? input.o ?? '')\n const token = String(input.t ?? input.token ?? '').slice(0, 100)\n if (!isId(hostId) || !isId(orderId)) return res.status(400).json({ error: 'Missing hostId or orderId' })\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, hostId)\n const orderSnapshot = await hostRef.collection('orders').doc(orderId).get()\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n if (!order || !(await buyerMayActFor(req, hostId, orderId, token, order))) {\n return res.status(404).json({ error: 'We could not find that order' })\n }\n if (req.method === 'GET') {\n const [{ returnSettings }, existing] = await Promise.all([\n readStore(firestore, hostId),\n hostRef.collection('returns').where('orderId', '==', orderId).get(),\n ])\n const returns = existing.docs.map((entry) => ({ id: entry.id, ...(entry.data() as CommerceModel.HostReturn) }))\n const endsAt = CommerceModel.returnWindowEndsAtMs(order, returnSettings)\n return res.status(200).json({\n enabled: returnSettings.enabled,\n windowEndsAtMs: endsAt,\n windowOpen: endsAt === null || Date.now() <= endsAt,\n lines: CommerceModel.returnableLines(order, returns, returnSettings),\n reasons: CommerceModel.RETURN_REASONS.map((reason) => ({ value: reason, label: CommerceModel.RETURN_REASON_LABELS[reason] })),\n returns: returns.map((entry) => ({\n id: entry.id,\n status: entry.status,\n lines: entry.lines,\n createdAtMs: entry.createdAtMs,\n ...(entry.returnLabel ? { returnLabel: { labelUrl: entry.returnLabel.labelUrl, carrier: entry.returnLabel.carrier, trackingNumber: entry.returnLabel.trackingNumber } } : {}),\n ...(entry.status === 'declined' && entry.merchantNote ? { merchantNote: entry.merchantNote } : {}),\n })),\n })\n }\n const outcome = await openReturn({\n hostId,\n orderId,\n lines: Array.isArray(input.lines) ? (input.lines as unknown[]).slice(0, 100) as never : [],\n note: String(input.note ?? ''),\n by: 'buyer',\n })\n if (outcome.outcome === 'no_such_order') return res.status(404).json({ error: 'We could not find that order' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n await tellStoreOfRequest(hostId, outcome.returnId, outcome.entry, outcome.order)\n return res.status(200).json({ ok: true, returnId: outcome.returnId, status: outcome.entry.status })\n } catch (error) {\n console.error('return request failed', error)\n return res.status(500).json({ error: 'Your return could not be requested. Please try again.' })\n }\n}\n\n// ---------------------------------------------------------------------------\n// The merchant's door (console)\n// ---------------------------------------------------------------------------\n\nconst MERCHANT_ACTIONS = ['create', 'approve', 'decline', 'close', 'note', 'attach-label', 'receive', 'refund'] as const\ntype MerchantAction = (typeof MERCHANT_ACTIONS)[number]\n\n/**\n * `POST /api/commerce/returns` with `{ hostId, action, … }`. Admins and\n * editors run the return; the refund goes through the order's refund route,\n * which asks for an admin of the whole workspace on its own.\n */\nexport const returnsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body = (typeof req.body === 'string' ? JSON.parse(req.body) : req.body) ?? {}\n const hostId = String(body.hostId ?? '')\n const action = String(body.action ?? '') as MerchantAction\n const returnId = String(body.returnId ?? '')\n if (!isId(hostId)) return res.status(400).json({ error: 'Missing hostId' })\n if (!MERCHANT_ACTIONS.includes(action)) return res.status(400).json({ error: 'Unknown action' })\n if (action !== 'create' && !isId(returnId)) return res.status(400).json({ error: 'Missing returnId' })\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostSnapshot = await hostRefFor(firestore, hostId).get()\n if (!hostSnapshot.exists) return res.status(404).json({ error: 'Unknown site' })\n // \"Manage orders\" (`commerce.orders`, AGL-4047).\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n\n if (action === 'create') {\n const orderId = String(body.orderId ?? '')\n if (!isId(orderId)) return res.status(400).json({ error: 'Missing orderId' })\n const outcome = await openReturn({\n hostId,\n orderId,\n lines: Array.isArray(body.lines) ? (body.lines as unknown[]).slice(0, 100) as never : [],\n note: String(body.note ?? ''),\n by: 'merchant',\n })\n if (outcome.outcome === 'no_such_order') return res.status(404).json({ error: 'Unknown order' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n if (body.notify !== false) await tellBuyer(hostId, 'return-approved', outcome.entry, outcome.order)\n return res.status(200).json({ ok: true, returnId: outcome.returnId, status: outcome.entry.status })\n }\n\n if (action === 'receive') {\n const outcome = await receiveReturn({\n hostId,\n returnId,\n restock: Array.isArray(body.restock) ? (body.restock as unknown[]).slice(0, 100) as never : [],\n locationId: body.locationId ? String(body.locationId) : undefined,\n })\n if (outcome.outcome === 'no_such_return') return res.status(404).json({ error: 'Unknown return' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n return res.status(200).json({\n ok: true,\n ...(outcome.outcome === 'already' ? { already: true } : { units: outcome.units ?? 0 }),\n status: outcome.entry.status,\n })\n }\n\n if (action === 'refund') {\n const returnSnapshot = await hostRefFor(firestore, hostId).collection('returns').doc(returnId).get()\n if (!returnSnapshot.exists) return res.status(404).json({ error: 'Unknown return' })\n const entry = returnSnapshot.data() as CommerceModel.HostReturn\n if (entry.status === 'refunded' || entry.refundedAtMs) {\n return res.status(200).json({ ok: true, already: true, status: entry.status })\n }\n if (!CommerceModel.canTransitionReturn(entry.status, 'refunded')) {\n return res.status(409).json({ error: `A return that is ${CommerceModel.RETURN_STATUS_LABELS[entry.status].toLowerCase()} cannot be refunded` })\n }\n const orderSnapshot = await hostRefFor(firestore, hostId).collection('orders').doc(entry.orderId).get()\n if (!orderSnapshot.exists) return res.status(404).json({ error: 'The order for this return is gone' })\n const order = CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never)\n const suggested = CommerceModel.returnRefundCents(order, entry.lines)\n const amountCents = body.amountCents == null ? suggested : Math.round(Number(body.amountCents))\n if (!Number.isFinite(amountCents) || amountCents <= 0) {\n return res.status(400).json({ error: 'The refund amount must be above zero' })\n }\n const wholeLines = CommerceModel.returnWholeLineIds(order, entry.lines).filter(\n (index) => !CommerceModel.orderLineRefunded(order, index),\n )\n const namedWorth = CommerceModel.orderLineRefundCents(order, wholeLines)\n // Lines are named only when the amount covers them in full, which is\n // what the refund route requires before it withdraws a line's\n // entitlements; a smaller amount refunds by amount alone.\n const refund = await callRefundRoute(\n req,\n {\n hostId,\n orderId: entry.orderId,\n amountCents,\n ...(wholeLines.length > 0 && amountCents >= namedWorth ? { lineItemIds: wholeLines } : {}),\n },\n // One refund per return: asking again replays rather than pays twice.\n `return:${hostId}:${returnId}`,\n )\n if (refund.status !== 200) {\n return res.status(refund.status).json({ error: refund.body?.error ?? 'Refund failed' })\n }\n const marked = await markReturnRefunded({ hostId, returnId, refundCents: amountCents, uid: decoded.uid })\n if (marked.outcome === 'changed') {\n await raiseOrderEvent(RETURN_REFUNDED_EVENT, {\n hostId,\n orderId: entry.orderId,\n key: `return-refunded:${returnId}`,\n extra: { return: returnEventView(returnId, marked.entry) },\n })\n await tellBuyer(hostId, 'return-refunded', marked.entry, marked.order)\n }\n return res.status(200).json({ ok: true, refundCents: amountCents, status: 'refunded' })\n }\n\n const outcome = await changeReturn({\n hostId,\n returnId,\n action: action as ReturnAction,\n ...(body.merchantNote !== undefined ? { merchantNote: String(body.merchantNote) } : {}),\n ...(action === 'attach-label' ? { label: body.label } : {}),\n })\n if (outcome.outcome === 'no_such_return') return res.status(404).json({ error: 'Unknown return' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n if (outcome.outcome === 'changed' && body.notify !== false) {\n if (action === 'approve') await tellBuyer(hostId, 'return-approved', outcome.entry, outcome.order)\n if (action === 'decline') await tellBuyer(hostId, 'return-declined', outcome.entry, outcome.order)\n // A label attached after the approval reaches the buyer the same way,\n // in the approval email, which carries it.\n if (action === 'attach-label' && outcome.entry.status === 'approved') {\n await tellBuyer(hostId, 'return-approved', outcome.entry, outcome.order)\n }\n }\n return res.status(200).json({\n ok: true,\n ...(outcome.outcome === 'already' ? { already: true } : {}),\n status: outcome.entry.status,\n })\n } catch (error) {\n console.error('returns action failed', action, error)\n // Every write here is a transaction or keyed (the refund), so asking\n // again lands once.\n return res.status(500).json({ error: 'The return could not be updated. Retrying is safe.' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","Aglyn","createResourceUid","findUserByUidAcrossPools","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","renderHostEmailWithTokens","hostConsoleUrl","isEmailConfigured","sendEmail","CommerceModel","RETURN_APPROVED_EVENT","RETURN_DECLINED_EVENT","RETURN_RECEIVED_EVENT","RETURN_REFUNDED_EVENT","RETURN_REQUESTED_EVENT","raiseOrderEvent","stageOrderEvent","orderStatusUrl","verifyOrderStatusToken","readActiveMemberSession","resolveTrackedRestockLines","refundHandler","dropStorefrontPages","soldOutMoved","hostRefFor","firestore","hostId","collection","doc","isId","value","Boolean","length","test","includes","readStore","settings","hostRef","host","store","Promise","all","get","catch","data","returnSettings","readReturnSettings","currency","String","toUpperCase","money","cents","Intl","NumberFormat","style","format","toFixed","returnEventView","id","entry","status","lines","map","line","refundCents","restock","returnItemsText","order","quantity","lineItems","lineItemId","name","RETURN_REASON_LABELS","reason","join","openReturn","request","app","orderRef","orderId","now","Date","note","trim","slice","RETURN_NOTE_MAX","runTransaction","transaction","orderSnapshot","exists","outcome","existing","where","liftLegacyOrder","verdict","validateReturnRequest","docs","by","message","describeReturnRequestProblem","orderNumber","returnOrderNumber","customerEmail","customerName","requestedBy","customerNote","merchantNote","timeline","atMs","event","detail","describeReturnLines","createdAtMs","updatedAtMs","returnRef","create","orderPatch","appendOrderEvent","update","key","extra","return","returnId","ACTION_TARGET","approve","decline","close","changeReturn","undefined","snapshot","target","action","patch","canTransitionReturn","RETURN_STATUS_LABELS","toLowerCase","appendReturnEvent","label","labelUrl","returnIsOpen","carrier","trackingNumber","trackingUrl","trackingUrlFor","returnLabel","attachedAtMs","changed","receiveReturn","locationId","soldOutFlipped","covered","Map","wanted","Number","has","isInteger","total","set","size","location","tracked","ref","products","byProduct","Math","min","lineIndex","productId","variantId","units","product","variants","adjustVariantInventory","productStockFields","delta","entries","received","markReturnRefunded","refundedAtMs","max","round","check","restockCheck","resolution","restocked","some","resolvedAtMs","uid","resolvedBy","callRefundRoute","req","body","idempotencyKey","payload","res","code","json","send","error","setHeader","end","method","headers","authorization","sendReturnEmail","to","tokens","fallback","designed","org","subject","text","html","fromName","resolveBrandingProfile","sendingIdentity","audience","context","owedFor","console","tellStoreOfRequest","items","type","title","link","encodeURIComponent","skipOwnerEmail","ownerUid","owner","record","email","tellBuyer","statusUrl","filter","refundTotal","buyerMayActFor","token","session","memberEmail","member","returnRequestHandler","input","query","JSON","parse","o","t","returns","endsAt","returnWindowEndsAtMs","enabled","windowEndsAtMs","windowOpen","returnableLines","reasons","RETURN_REASONS","Array","isArray","ok","MERCHANT_ACTIONS","returnsHandler","idToken","startsWith","decoded","auth","verifyIdToken","hostSnapshot","notify","already","returnSnapshot","suggested","returnRefundCents","amountCents","isFinite","wholeLines","returnWholeLineIds","index","orderLineRefunded","namedWorth","orderLineRefundCents","refund","lineItemIds","marked"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,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,mBAAmBgE,QAAQ/B,KAAK,EAAE+B,QAAQvB,KAAK;YACzE;QACF;QACA,OAAO+H,IAAItI,MAAM,CAAC,KAAKwI,IAAI,CAAC;YAC1B8D,IAAI;WACAxK,QAAQA,OAAO,KAAK,YAAY;YAAEkL,SAAS;QAAK,IAAI,CAAC;YACzDhN,QAAQ8B,QAAQ/B,KAAK,CAACC,MAAM;;IAEhC,EAAE,OAAO0I,OAAO;QACdqB,QAAQrB,KAAK,CAAC,yBAAyBnE,QAAQmE;QAC/C,qEAAqE;QACrE,oBAAoB;QACpB,OAAOJ,IAAItI,MAAM,CAAC,KAAKwI,IAAI,CAAC;YAAEE,OAAO;QAAqD;IAC5F;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/returns.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { PluginApiHandler, PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport {\n findUserByUidAcrossPools,\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { hostConsoleUrl } from '@aglyn/tenant-data-admin/server/host-console-link'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport * as CommerceModel from '../model'\nimport {\n RETURN_APPROVED_EVENT,\n RETURN_DECLINED_EVENT,\n RETURN_RECEIVED_EVENT,\n RETURN_REFUNDED_EVENT,\n RETURN_REQUESTED_EVENT,\n} from '../model/order-events'\nimport { raiseOrderEvent, stageOrderEvent } from './order-events'\nimport { orderStatusUrl, verifyOrderStatusToken } from './order-status-token'\nimport { readActiveMemberSession } from './membership'\nimport { resolveTrackedRestockLines } from './restock-flag'\nimport { refundHandler } from './refund'\nimport { dropStorefrontPages, soldOutMoved } from './sold-out-drop'\n\n/**\n * Returns (RMA, AGL-3611): the buyer's door, the merchant's door, and the\n * writes behind both. The rules — what is returnable, the window, the state\n * machine, what a refund is worth — are the model's (`commerce-returns.ts`);\n * this is where they are re-asked under the write.\n *\n * EVERY WRITE IS A TRANSACTION that reads the return, the order and, when it\n * opens one, every return already on the order — so two requests for the last\n * unit cannot both be granted, and a stale console cannot approve a return a\n * colleague declined a moment ago.\n *\n * THE MONEY MOVES THROUGH THE ORDER'S REFUND ROUTE, never here. A return's\n * refund calls `refund.ts` with the merchant's own credentials and a key\n * derived from the return, so its gates (an admin of the whole workspace,\n * the over-refund cap, the open-dispute block, Stripe's idempotency) are the\n * ones every refund passes, and asking twice refunds once.\n *\n * STOCK COMES BACK WHEN THE PARCEL DOES. Receiving a return puts the units\n * the merchant chose back on the shelf, at the location they chose, with an\n * inventory adjustment row — the products hub's history shows it beside the\n * sale. A refund then answers the order's restock question with what the\n * return already did, so nobody is asked to restock the same units twice.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst hostRefFor = (firestore: Firestore, hostId: string) => firestore.collection('hosts').doc(hostId)\n\nconst isId = (value: string) => Boolean(value) && value.length <= 200 && !/^__.*__$/.test(value) && !value.includes('/')\n\n/** The store's settings document and what the return emails need from the host. */\nasync function readStore(firestore: Firestore, hostId: string) {\n const hostRef = hostRefFor(firestore, hostId)\n const [host, store] = await Promise.all([\n hostRef.get().catch(() => null),\n hostRef.collection('settings').doc('store').get().catch(() => null),\n ])\n const settings = (store?.data() ?? {}) as Record<string, unknown>\n return {\n host: (host?.data() ?? {}) as Record<string, unknown>,\n returnSettings: CommerceModel.readReturnSettings(settings['returns']),\n currency: String(settings['currency'] ?? 'USD').toUpperCase(),\n }\n}\n\nfunction money(cents: number, currency: string): string {\n try {\n return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100)\n } catch {\n return `$${(cents / 100).toFixed(2)}`\n }\n}\n\n/** The return as an event carries it. */\nfunction returnEventView(id: string, entry: CommerceModel.HostReturn) {\n return {\n id,\n status: entry.status,\n lines: entry.lines.map((line) => ({ ...line })),\n refundCents: entry.refundCents ?? null,\n restock: entry.restock ? entry.restock.lines.map((line) => ({ ...line })) : null,\n }\n}\n\n/** \"1× House Blend — Arrived damaged\", one per line. */\nfunction returnItemsText(order: CommerceModel.HostOrder, entry: Pick<CommerceModel.HostReturn, 'lines'>): string {\n return entry.lines\n .map(\n (line) =>\n `${line.quantity}× ${order.lineItems?.[line.lineItemId]?.name ?? `line ${line.lineItemId}`} — ${\n CommerceModel.RETURN_REASON_LABELS[line.reason] ?? line.reason\n }`,\n )\n .join('\\n')\n}\n\nexport type OpenReturnOutcome =\n | { outcome: 'created'; returnId: string; entry: CommerceModel.HostReturn; order: CommerceModel.HostOrder }\n | { outcome: 'refused'; message: string }\n | { outcome: 'no_such_order' }\n\n/**\n * Opens a return. A buyer's starts `requested`; a merchant's starts\n * `approved`, since the merchant asking is the approval.\n */\nexport async function openReturn(request: {\n hostId: string\n orderId: string\n lines: ReadonlyArray<{ lineItemId: unknown; quantity: unknown; reason: unknown }>\n note?: string\n by: 'buyer' | 'merchant'\n now?: number\n}): Promise<OpenReturnOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const orderRef = hostRef.collection('orders').doc(request.orderId)\n const { returnSettings } = await readStore(firestore, request.hostId)\n const now = request.now ?? Date.now()\n const note = String(request.note ?? '').trim().slice(0, CommerceModel.RETURN_NOTE_MAX)\n return firestore.runTransaction(async (transaction): Promise<OpenReturnOutcome> => {\n const orderSnapshot = await transaction.get(orderRef)\n if (!orderSnapshot.exists) return { outcome: 'no_such_order' }\n const existing = await transaction.get(\n hostRef.collection('returns').where('orderId', '==', request.orderId),\n )\n const order = CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never)\n const verdict = CommerceModel.validateReturnRequest({\n order,\n existing: existing.docs.map((entry) => entry.data() as CommerceModel.HostReturn),\n settings: returnSettings,\n lines: request.lines,\n by: request.by,\n now,\n })\n if (!('lines' in verdict)) {\n return { outcome: 'refused', message: CommerceModel.describeReturnRequestProblem(verdict) }\n }\n const status: CommerceModel.ReturnStatus = request.by === 'merchant' ? 'approved' : 'requested'\n const entry: CommerceModel.HostReturn = {\n orderId: request.orderId,\n orderNumber: CommerceModel.returnOrderNumber(order, request.orderId),\n customerEmail: order.customerEmail ?? null,\n customerName: order.customerName ?? null,\n lines: verdict.lines.map((line) => ({\n ...line,\n name: String(order.lineItems?.[line.lineItemId]?.name ?? '').slice(0, 200),\n })),\n status,\n requestedBy: request.by,\n ...(note ? (request.by === 'buyer' ? { customerNote: note } : { merchantNote: note }) : {}),\n timeline: [\n {\n atMs: now,\n event: status,\n detail: `${request.by === 'buyer' ? 'Requested by the buyer' : 'Opened by the store'}: ${CommerceModel.describeReturnLines(order, verdict.lines)}`,\n },\n ],\n createdAtMs: now,\n updatedAtMs: now,\n }\n const returnRef = hostRef.collection('returns').doc(createResourceUid())\n transaction.create(returnRef, entry)\n const orderPatch = {\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'return-requested',\n CommerceModel.describeReturnLines(order, verdict.lines),\n now,\n ),\n }\n transaction.update(orderRef, orderPatch)\n stageOrderEvent(transaction, RETURN_REQUESTED_EVENT, {\n hostId: request.hostId,\n orderId: request.orderId,\n key: `return:${returnRef.id}`,\n order: { ...orderSnapshot.data(), ...orderPatch },\n extra: { return: returnEventView(returnRef.id, entry) },\n })\n // The store opening a return is its approval.\n if (status === 'approved') {\n stageOrderEvent(transaction, RETURN_APPROVED_EVENT, {\n hostId: request.hostId,\n orderId: request.orderId,\n key: `return-approved:${returnRef.id}`,\n order: { ...orderSnapshot.data(), ...orderPatch },\n extra: { return: returnEventView(returnRef.id, entry) },\n })\n }\n return { outcome: 'created', returnId: returnRef.id, entry, order }\n })\n}\n\nexport type ReturnAction = 'approve' | 'decline' | 'close' | 'note' | 'attach-label'\n\nexport type ChangeReturnOutcome =\n | { outcome: 'changed'; entry: CommerceModel.HostReturn; order: CommerceModel.HostOrder | null }\n | { outcome: 'already'; entry: CommerceModel.HostReturn }\n | { outcome: 'refused'; message: string }\n | { outcome: 'no_such_return' }\n\nconst ACTION_TARGET: Partial<Record<ReturnAction, CommerceModel.ReturnStatus>> = {\n approve: 'approved',\n decline: 'declined',\n close: 'closed',\n}\n\n/**\n * Approve, decline, close, a note, or a return label — the writes that move\n * no stock and no money. The transition is re-asked under the write.\n */\nexport async function changeReturn(request: {\n hostId: string\n returnId: string\n action: ReturnAction\n merchantNote?: string\n label?: { carrier: string; trackingNumber: string; labelUrl: string; trackingUrl?: string }\n now?: number\n}): Promise<ChangeReturnOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const returnRef = hostRef.collection('returns').doc(request.returnId)\n const now = request.now ?? Date.now()\n const note = request.merchantNote === undefined ? undefined : String(request.merchantNote).trim().slice(0, CommerceModel.RETURN_NOTE_MAX)\n return firestore.runTransaction(async (transaction): Promise<ChangeReturnOutcome> => {\n const snapshot = await transaction.get(returnRef)\n if (!snapshot.exists) return { outcome: 'no_such_return' }\n const entry = snapshot.data() as CommerceModel.HostReturn\n const orderSnapshot = await transaction.get(hostRef.collection('orders').doc(entry.orderId))\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n const target = ACTION_TARGET[request.action]\n let patch: Partial<CommerceModel.HostReturn>\n if (target) {\n if (entry.status === target) return { outcome: 'already', entry }\n if (!CommerceModel.canTransitionReturn(entry.status, target)) {\n return {\n outcome: 'refused',\n message: `A return that is ${CommerceModel.RETURN_STATUS_LABELS[entry.status].toLowerCase()} cannot be ${CommerceModel.RETURN_STATUS_LABELS[target].toLowerCase()}`,\n }\n }\n patch = {\n status: target,\n ...(note !== undefined && note ? { merchantNote: note } : {}),\n timeline: CommerceModel.appendReturnEvent(entry, target, note || undefined, now),\n }\n } else if (request.action === 'attach-label') {\n const label = request.label\n if (!label?.labelUrl || !/^https:\\/\\//i.test(label.labelUrl)) {\n return { outcome: 'refused', message: 'A return label needs an https link' }\n }\n if (!CommerceModel.returnIsOpen(entry) || entry.status === 'refunded') {\n return { outcome: 'refused', message: 'This return is finished; a label can no longer be attached' }\n }\n const carrier = String(label.carrier ?? '').trim().slice(0, 40)\n const trackingNumber = String(label.trackingNumber ?? '').trim().slice(0, 60)\n const trackingUrl =\n (label.trackingUrl && /^https:\\/\\//i.test(label.trackingUrl) ? label.trackingUrl : null) ??\n CommerceModel.trackingUrlFor(carrier, trackingNumber)\n patch = {\n returnLabel: {\n carrier,\n trackingNumber,\n labelUrl: String(label.labelUrl).slice(0, 2048),\n ...(trackingUrl ? { trackingUrl } : {}),\n attachedAtMs: now,\n },\n timeline: CommerceModel.appendReturnEvent(entry, 'label', `${carrier} ${trackingNumber}`.trim() || 'Return label attached', now),\n }\n } else {\n patch = {\n merchantNote: note ?? '',\n timeline: CommerceModel.appendReturnEvent(entry, 'note', note || 'Note cleared', now),\n }\n }\n transaction.update(returnRef, { ...patch, updatedAtMs: now })\n const changed = { ...entry, ...patch, updatedAtMs: now }\n const event = target === 'approved' ? RETURN_APPROVED_EVENT : target === 'declined' ? RETURN_DECLINED_EVENT : null\n if (event && orderSnapshot.exists) {\n stageOrderEvent(transaction, event, {\n hostId: request.hostId,\n orderId: entry.orderId,\n key: `return-${target}:${request.returnId}`,\n order: orderSnapshot.data() ?? {},\n extra: { return: returnEventView(request.returnId, changed) },\n })\n }\n return { outcome: 'changed', entry: changed, order }\n })\n}\n\n/**\n * The parcel arrived: the return is `received`, and the units the merchant\n * chose go back on the shelf, at the location they chose. A unit the sale\n * never took off a tracked count (an untracked variant, a deleted product)\n * has nothing to go back to and is left out, as a cancellation leaves it.\n */\nexport async function receiveReturn(request: {\n hostId: string\n returnId: string\n restock: ReadonlyArray<{ lineItemId: unknown; quantity: unknown }>\n locationId?: string\n now?: number\n}): Promise<ChangeReturnOutcome & { units?: number }> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const returnRef = hostRef.collection('returns').doc(request.returnId)\n const now = request.now ?? Date.now()\n const locationId = String(request.locationId ?? '').trim().slice(0, 100)\n // Whether the restock flipped a sold-out verdict the storefront shows\n // (AGL-4121); a retried attempt can only make the drop spurious.\n let soldOutFlipped = false\n const outcome = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(returnRef)\n if (!snapshot.exists) return { outcome: 'no_such_return' as const }\n const entry = snapshot.data() as CommerceModel.HostReturn\n if (entry.status === 'received' || entry.restock) return { outcome: 'already' as const, entry }\n if (!CommerceModel.canTransitionReturn(entry.status, 'received')) {\n return {\n outcome: 'refused' as const,\n message: `A return that is ${CommerceModel.RETURN_STATUS_LABELS[entry.status].toLowerCase()} cannot be received`,\n }\n }\n // What may go back: at most what the return covers, per line.\n const covered = new Map(entry.lines.map((line) => [line.lineItemId, line.quantity]))\n const wanted = new Map<number, number>()\n for (const line of request.restock) {\n const lineItemId = Number(line?.lineItemId)\n const quantity = Number(line?.quantity)\n if (!covered.has(lineItemId)) {\n return { outcome: 'refused' as const, message: `Line ${lineItemId} is not part of this return` }\n }\n if (!Number.isInteger(quantity) || quantity < 0) {\n return { outcome: 'refused' as const, message: 'Restock quantities must be whole numbers' }\n }\n const total = (wanted.get(lineItemId) ?? 0) + quantity\n if (total > (covered.get(lineItemId) ?? 0)) {\n return { outcome: 'refused' as const, message: `Only ${covered.get(lineItemId)} of line ${lineItemId} came back` }\n }\n if (quantity > 0) wanted.set(lineItemId, total)\n }\n if (locationId && wanted.size > 0) {\n const location = await transaction.get(hostRef.collection('locations').doc(locationId))\n if (!location.exists) return { outcome: 'refused' as const, message: 'That stock location no longer exists' }\n }\n const orderRef = hostRef.collection('orders').doc(entry.orderId)\n const orderSnapshot = await transaction.get(orderRef)\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n // Every read before any write, as a transaction requires.\n const tracked =\n order && wanted.size > 0\n ? await resolveTrackedRestockLines(hostRef, order, (ref) => transaction.get(ref))\n : { lines: [], products: new Map<string, CommerceModel.HostProduct>() }\n const byProduct = new Map<string, Array<{ variantId: string; quantity: number }>>()\n for (const line of tracked.lines) {\n const quantity = Math.min(line.quantity, wanted.get(line.lineIndex ?? -1) ?? 0)\n if (quantity <= 0) continue\n byProduct.set(line.productId, [...(byProduct.get(line.productId) ?? []), { variantId: line.variantId, quantity }])\n }\n let units = 0\n for (const [productId, lines] of byProduct) {\n const product = tracked.products.get(productId)\n if (!product) continue\n let variants = product.variants\n for (const line of lines) {\n variants = CommerceModel.adjustVariantInventory({ variants }, line.variantId, line.quantity, locationId || undefined)\n }\n transaction.update(hostRef.collection('products').doc(productId), {\n variants,\n ...CommerceModel.productStockFields({ ...product, variants }),\n updatedAtMs: now,\n })\n soldOutFlipped ||= soldOutMoved(product, { ...product, variants })\n for (const line of lines) {\n units += line.quantity\n transaction.create(hostRef.collection('inventoryAdjustments').doc(createResourceUid()), {\n productId,\n variantId: line.variantId,\n delta: line.quantity,\n reason: 'restock',\n orderId: entry.orderId,\n ...(locationId ? { locationId } : {}),\n atMs: now,\n } satisfies CommerceModel.InventoryAdjustment)\n }\n }\n const restock: CommerceModel.ReturnRestock = {\n lines: [...wanted.entries()].map(([lineItemId, quantity]) => ({ lineItemId, quantity })),\n ...(locationId ? { locationId } : {}),\n atMs: now,\n }\n const patch = {\n status: 'received' as const,\n restock,\n timeline: CommerceModel.appendReturnEvent(\n entry,\n 'received',\n units > 0 ? `${units} ${units === 1 ? 'unit' : 'units'} back in stock` : 'Nothing restocked',\n now,\n ),\n updatedAtMs: now,\n }\n transaction.update(returnRef, patch)\n const received = { ...entry, ...patch }\n if (order) {\n const orderPatch = {\n timeline: CommerceModel.appendOrderEvent(order, 'return-received', units > 0 ? `${units} restocked` : undefined, now),\n }\n transaction.update(orderRef, orderPatch)\n stageOrderEvent(transaction, RETURN_RECEIVED_EVENT, {\n hostId: request.hostId,\n orderId: entry.orderId,\n key: `return-received:${request.returnId}`,\n order: { ...orderSnapshot.data(), ...orderPatch },\n extra: { return: returnEventView(request.returnId, received) },\n })\n }\n return { outcome: 'changed' as const, entry: received, order, units }\n })\n if (soldOutFlipped && outcome.outcome === 'changed') {\n await dropStorefrontPages({\n hostId: request.hostId,\n reason: 'a received return restocked a product',\n })\n }\n return outcome\n}\n\n/**\n * Records a refund that went through the order's refund route against the\n * return, and answers the order's restock question with what the return\n * already did, so the merchant is not asked to restock the same units again.\n */\nexport async function markReturnRefunded(request: {\n hostId: string\n returnId: string\n refundCents: number\n uid: string\n now?: number\n}): Promise<ChangeReturnOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, request.hostId)\n const returnRef = hostRef.collection('returns').doc(request.returnId)\n const now = request.now ?? Date.now()\n return firestore.runTransaction(async (transaction): Promise<ChangeReturnOutcome> => {\n const snapshot = await transaction.get(returnRef)\n if (!snapshot.exists) return { outcome: 'no_such_return' }\n const entry = snapshot.data() as CommerceModel.HostReturn\n if (entry.status === 'refunded' || entry.refundedAtMs) return { outcome: 'already', entry }\n const orderRef = hostRef.collection('orders').doc(entry.orderId)\n const orderSnapshot = await transaction.get(orderRef)\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n const patch = {\n status: 'refunded' as const,\n refundedAtMs: now,\n refundCents: Math.max(0, Math.round(request.refundCents)),\n timeline: CommerceModel.appendReturnEvent(entry, 'refunded', undefined, now),\n updatedAtMs: now,\n }\n transaction.update(returnRef, patch)\n const check = order?.restockCheck\n if (order && check && !check.resolution && entry.restock) {\n const restocked = entry.restock.lines.some((line) => line.quantity > 0)\n transaction.update(orderRef, {\n restockCheck: {\n ...check,\n resolution: restocked ? 'restocked' : 'dismissed',\n resolvedAtMs: now,\n ...(request.uid ? { resolvedBy: request.uid } : {}),\n } satisfies CommerceModel.OrderRestockCheck,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'restock-check',\n restocked ? 'answered by the return — restocked' : 'answered by the return — no restock',\n now,\n ),\n })\n }\n return { outcome: 'changed', entry: { ...entry, ...patch }, order }\n })\n}\n\n/** Calls the order's own refund route in-process, with the caller's credentials. */\nasync function callRefundRoute(\n req: PluginApiRequest,\n body: Record<string, unknown>,\n idempotencyKey: string,\n): Promise<{ status: number; body: Record<string, any> }> {\n let status = 200\n let payload: Record<string, any> = {}\n const res = {\n status(code: number) {\n status = code\n return res\n },\n json(value: unknown) {\n payload = (value ?? {}) as Record<string, any>\n return res\n },\n send(value: unknown) {\n payload = { error: String(value ?? '') }\n return res\n },\n setHeader() {\n return res\n },\n end() {\n return res\n },\n } as unknown as PluginApiResponse\n await refundHandler(\n {\n ...req,\n method: 'POST',\n headers: { authorization: String(req.headers.authorization ?? ''), 'idempotency-key': idempotencyKey },\n body,\n } as PluginApiRequest,\n res,\n )\n return { status, body: payload }\n}\n\n// ---------------------------------------------------------------------------\n// Emails\n// ---------------------------------------------------------------------------\n\ntype ReturnEmailKey = 'return-requested' | 'return-approved' | 'return-declined' | 'return-refunded'\n\nasync function sendReturnEmail(\n hostId: string,\n key: ReturnEmailKey,\n to: string,\n tokens: Record<string, string>,\n fallback: { subject: string; text: string },\n): Promise<void> {\n if (!to || !isEmailConfigured()) return\n try {\n const firestore = firebaseAdmin.app().firestore()\n const designed = await renderHostEmailWithTokens(firestore, hostId, key, tokens)\n const org = await getOrgForHost(hostId).catch(() => null)\n const emailOutcome = await sendEmail({\n to,\n subject: designed?.subject ?? fallback.subject,\n text: designed?.text || fallback.text,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: Aglyn.resolveBrandingProfile(org?.org as never).fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: key,\n // Owed to the recipient by their own order (AGL-3356).\n owedFor: 'order',\n })\n // Only a sent email is metered (AGL-4227).\n if (emailOutcome?.sent) await meterHostEmail(hostId)\n } catch (error) {\n // A return that is recorded is not undone because its email failed.\n console.error(`[returns] ${key} not sent`, hostId, error)\n }\n}\n\n/** Tells the store a buyer asked, in the console and by email to the owner. */\nasync function tellStoreOfRequest(hostId: string, returnId: string, entry: CommerceModel.HostReturn, order: CommerceModel.HostOrder) {\n const items = returnItemsText(order, entry)\n await notifyHostManagers(\n hostId,\n {\n type: 'content.order',\n title: `Return requested for order ${entry.orderNumber}`,\n body: `${entry.customerEmail ?? 'A buyer'} wants to return ${CommerceModel.describeReturnLines(order, entry.lines)} from order ${entry.orderNumber} on {site}.`,\n link: `/${hostId}/products/returns?return=${encodeURIComponent(returnId)}`,\n },\n { skipOwnerEmail: true },\n ).catch(() => undefined)\n const ownerUid = (await getOrgForHost(hostId).catch(() => null))?.org?.ownerUid\n const owner = ownerUid ? (await findUserByUidAcrossPools(ownerUid).catch(() => null))?.record : null\n if (!owner?.email) return\n await sendReturnEmail(\n hostId,\n 'return-requested',\n owner.email,\n {\n 'order.number': entry.orderNumber,\n 'return.items': items,\n 'buyer.email': String(entry.customerEmail ?? ''),\n 'return.customerNote': String(entry.customerNote ?? ''),\n 'return.url': await hostConsoleUrl(\n hostId,\n `/${hostId}/products/returns?return=${encodeURIComponent(returnId)}`,\n ),\n },\n {\n subject: `Return requested for order ${entry.orderNumber}`,\n text:\n `${entry.customerEmail ?? 'A buyer'} wants to return items from order ${entry.orderNumber}.\\n\\n${items}` +\n (entry.customerNote ? `\\n\\n\"${entry.customerNote}\"` : '') +\n `\\n\\nApprove or decline it under Products → Returns.`,\n },\n )\n}\n\n/** Tells the buyer what happened to their return. */\nasync function tellBuyer(\n hostId: string,\n key: Exclude<ReturnEmailKey, 'return-requested'>,\n entry: CommerceModel.HostReturn,\n order: CommerceModel.HostOrder | null,\n): Promise<void> {\n const to = String(entry.customerEmail ?? order?.customerEmail ?? '').trim()\n if (!to || !order) return\n const firestore = firebaseAdmin.app().firestore()\n const store = await readStore(firestore, hostId)\n const statusUrl = orderStatusUrl(store.host as never, hostId, entry.orderId) ?? ''\n const items = returnItemsText(order, entry)\n const label = entry.returnLabel\n ? `Print your return label: ${entry.returnLabel.labelUrl}` +\n (entry.returnLabel.trackingNumber ? ` (${[entry.returnLabel.carrier, entry.returnLabel.trackingNumber].filter(Boolean).join(' ')})` : '')\n : ''\n const refundTotal = money(entry.refundCents ?? 0, store.currency)\n const tokens: Record<string, string> = {\n 'order.number': entry.orderNumber,\n 'return.items': items,\n 'return.note': String(entry.merchantNote ?? ''),\n 'return.label': label,\n 'return.refundTotal': refundTotal,\n 'order.statusUrl': statusUrl,\n }\n const fallback =\n key === 'return-approved'\n ? {\n subject: `Your return for order ${entry.orderNumber} is approved`,\n text: `Your return is approved:\\n\\n${items}` + (entry.merchantNote ? `\\n\\n${entry.merchantNote}` : '') + (label ? `\\n\\n${label}` : ''),\n }\n : key === 'return-declined'\n ? {\n subject: `About your return for order ${entry.orderNumber}`,\n text: `We could not accept the return of:\\n\\n${items}` + (entry.merchantNote ? `\\n\\n${entry.merchantNote}` : ''),\n }\n : {\n subject: `Your refund for order ${entry.orderNumber}`,\n text: `We received your return and refunded ${refundTotal}.\\n\\n${items}`,\n }\n if (statusUrl) fallback.text += `\\n\\nView your order: ${statusUrl}`\n await sendReturnEmail(hostId, key, to, tokens, fallback)\n}\n\n// ---------------------------------------------------------------------------\n// The buyer's door (tenant)\n// ---------------------------------------------------------------------------\n\n/**\n * Whether this request may act for the buyer of this order: the signed-in\n * site member whose email the order carries, or the holder of the order's\n * signed status link. Neither reveals whether the order exists to anyone\n * else — both refusals read the same.\n */\nasync function buyerMayActFor(\n req: PluginApiRequest,\n hostId: string,\n orderId: string,\n token: string,\n order: CommerceModel.HostOrder,\n): Promise<boolean> {\n if (token && verifyOrderStatusToken(hostId, orderId, token)) return true\n const session = await readActiveMemberSession(req, hostId)\n if (session.status !== 'active') return false\n const memberEmail = String(session.member.get('email') ?? '').trim().toLowerCase()\n return Boolean(memberEmail) && memberEmail === String(order.customerEmail ?? '').trim().toLowerCase()\n}\n\n/**\n * `GET /api/commerce/return-request?hostId&orderId&t` — what the buyer may\n * send back and until when, and the returns already open.\n * `POST` with `{ hostId, orderId, t?, lines: [{ lineItemId, quantity, reason }], note? }`\n * opens a return.\n */\nexport const returnRequestHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET' && req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const input = (req.method === 'GET' ? req.query : typeof req.body === 'string' ? JSON.parse(req.body) : req.body) ?? {}\n const hostId = String(input.hostId ?? '')\n const orderId = String(input.orderId ?? input.o ?? '')\n const token = String(input.t ?? input.token ?? '').slice(0, 100)\n if (!isId(hostId) || !isId(orderId)) return res.status(400).json({ error: 'Missing hostId or orderId' })\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = hostRefFor(firestore, hostId)\n const orderSnapshot = await hostRef.collection('orders').doc(orderId).get()\n const order = orderSnapshot.exists ? CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never) : null\n if (!order || !(await buyerMayActFor(req, hostId, orderId, token, order))) {\n return res.status(404).json({ error: 'We could not find that order' })\n }\n if (req.method === 'GET') {\n const [{ returnSettings }, existing] = await Promise.all([\n readStore(firestore, hostId),\n hostRef.collection('returns').where('orderId', '==', orderId).get(),\n ])\n const returns = existing.docs.map((entry) => ({ id: entry.id, ...(entry.data() as CommerceModel.HostReturn) }))\n const endsAt = CommerceModel.returnWindowEndsAtMs(order, returnSettings)\n return res.status(200).json({\n enabled: returnSettings.enabled,\n windowEndsAtMs: endsAt,\n windowOpen: endsAt === null || Date.now() <= endsAt,\n lines: CommerceModel.returnableLines(order, returns, returnSettings),\n reasons: CommerceModel.RETURN_REASONS.map((reason) => ({ value: reason, label: CommerceModel.RETURN_REASON_LABELS[reason] })),\n returns: returns.map((entry) => ({\n id: entry.id,\n status: entry.status,\n lines: entry.lines,\n createdAtMs: entry.createdAtMs,\n ...(entry.returnLabel ? { returnLabel: { labelUrl: entry.returnLabel.labelUrl, carrier: entry.returnLabel.carrier, trackingNumber: entry.returnLabel.trackingNumber } } : {}),\n ...(entry.status === 'declined' && entry.merchantNote ? { merchantNote: entry.merchantNote } : {}),\n })),\n })\n }\n const outcome = await openReturn({\n hostId,\n orderId,\n lines: Array.isArray(input.lines) ? (input.lines as unknown[]).slice(0, 100) as never : [],\n note: String(input.note ?? ''),\n by: 'buyer',\n })\n if (outcome.outcome === 'no_such_order') return res.status(404).json({ error: 'We could not find that order' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n await tellStoreOfRequest(hostId, outcome.returnId, outcome.entry, outcome.order)\n return res.status(200).json({ ok: true, returnId: outcome.returnId, status: outcome.entry.status })\n } catch (error) {\n console.error('return request failed', error)\n return res.status(500).json({ error: 'Your return could not be requested. Please try again.' })\n }\n}\n\n// ---------------------------------------------------------------------------\n// The merchant's door (console)\n// ---------------------------------------------------------------------------\n\nconst MERCHANT_ACTIONS = ['create', 'approve', 'decline', 'close', 'note', 'attach-label', 'receive', 'refund'] as const\ntype MerchantAction = (typeof MERCHANT_ACTIONS)[number]\n\n/**\n * `POST /api/commerce/returns` with `{ hostId, action, … }`. Admins and\n * editors run the return; the refund goes through the order's refund route,\n * which asks for an admin of the whole workspace on its own.\n */\nexport const returnsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body = (typeof req.body === 'string' ? JSON.parse(req.body) : req.body) ?? {}\n const hostId = String(body.hostId ?? '')\n const action = String(body.action ?? '') as MerchantAction\n const returnId = String(body.returnId ?? '')\n if (!isId(hostId)) return res.status(400).json({ error: 'Missing hostId' })\n if (!MERCHANT_ACTIONS.includes(action)) return res.status(400).json({ error: 'Unknown action' })\n if (action !== 'create' && !isId(returnId)) return res.status(400).json({ error: 'Missing returnId' })\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostSnapshot = await hostRefFor(firestore, hostId).get()\n if (!hostSnapshot.exists) return res.status(404).json({ error: 'Unknown site' })\n // \"Manage orders\" (`commerce.orders`, AGL-4047).\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n\n if (action === 'create') {\n const orderId = String(body.orderId ?? '')\n if (!isId(orderId)) return res.status(400).json({ error: 'Missing orderId' })\n const outcome = await openReturn({\n hostId,\n orderId,\n lines: Array.isArray(body.lines) ? (body.lines as unknown[]).slice(0, 100) as never : [],\n note: String(body.note ?? ''),\n by: 'merchant',\n })\n if (outcome.outcome === 'no_such_order') return res.status(404).json({ error: 'Unknown order' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n if (body.notify !== false) await tellBuyer(hostId, 'return-approved', outcome.entry, outcome.order)\n return res.status(200).json({ ok: true, returnId: outcome.returnId, status: outcome.entry.status })\n }\n\n if (action === 'receive') {\n const outcome = await receiveReturn({\n hostId,\n returnId,\n restock: Array.isArray(body.restock) ? (body.restock as unknown[]).slice(0, 100) as never : [],\n locationId: body.locationId ? String(body.locationId) : undefined,\n })\n if (outcome.outcome === 'no_such_return') return res.status(404).json({ error: 'Unknown return' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n return res.status(200).json({\n ok: true,\n ...(outcome.outcome === 'already' ? { already: true } : { units: outcome.units ?? 0 }),\n status: outcome.entry.status,\n })\n }\n\n if (action === 'refund') {\n const returnSnapshot = await hostRefFor(firestore, hostId).collection('returns').doc(returnId).get()\n if (!returnSnapshot.exists) return res.status(404).json({ error: 'Unknown return' })\n const entry = returnSnapshot.data() as CommerceModel.HostReturn\n if (entry.status === 'refunded' || entry.refundedAtMs) {\n return res.status(200).json({ ok: true, already: true, status: entry.status })\n }\n if (!CommerceModel.canTransitionReturn(entry.status, 'refunded')) {\n return res.status(409).json({ error: `A return that is ${CommerceModel.RETURN_STATUS_LABELS[entry.status].toLowerCase()} cannot be refunded` })\n }\n const orderSnapshot = await hostRefFor(firestore, hostId).collection('orders').doc(entry.orderId).get()\n if (!orderSnapshot.exists) return res.status(404).json({ error: 'The order for this return is gone' })\n const order = CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never)\n const suggested = CommerceModel.returnRefundCents(order, entry.lines)\n const amountCents = body.amountCents == null ? suggested : Math.round(Number(body.amountCents))\n if (!Number.isFinite(amountCents) || amountCents <= 0) {\n return res.status(400).json({ error: 'The refund amount must be above zero' })\n }\n const wholeLines = CommerceModel.returnWholeLineIds(order, entry.lines).filter(\n (index) => !CommerceModel.orderLineRefunded(order, index),\n )\n const namedWorth = CommerceModel.orderLineRefundCents(order, wholeLines)\n // Lines are named only when the amount covers them in full, which is\n // what the refund route requires before it withdraws a line's\n // entitlements; a smaller amount refunds by amount alone.\n const refund = await callRefundRoute(\n req,\n {\n hostId,\n orderId: entry.orderId,\n amountCents,\n ...(wholeLines.length > 0 && amountCents >= namedWorth ? { lineItemIds: wholeLines } : {}),\n },\n // One refund per return: asking again replays rather than pays twice.\n `return:${hostId}:${returnId}`,\n )\n if (refund.status !== 200) {\n return res.status(refund.status).json({ error: refund.body?.error ?? 'Refund failed' })\n }\n const marked = await markReturnRefunded({ hostId, returnId, refundCents: amountCents, uid: decoded.uid })\n if (marked.outcome === 'changed') {\n await raiseOrderEvent(RETURN_REFUNDED_EVENT, {\n hostId,\n orderId: entry.orderId,\n key: `return-refunded:${returnId}`,\n extra: { return: returnEventView(returnId, marked.entry) },\n })\n await tellBuyer(hostId, 'return-refunded', marked.entry, marked.order)\n }\n return res.status(200).json({ ok: true, refundCents: amountCents, status: 'refunded' })\n }\n\n const outcome = await changeReturn({\n hostId,\n returnId,\n action: action as ReturnAction,\n ...(body.merchantNote !== undefined ? { merchantNote: String(body.merchantNote) } : {}),\n ...(action === 'attach-label' ? { label: body.label } : {}),\n })\n if (outcome.outcome === 'no_such_return') return res.status(404).json({ error: 'Unknown return' })\n if (outcome.outcome === 'refused') return res.status(409).json({ error: outcome.message })\n if (outcome.outcome === 'changed' && body.notify !== false) {\n if (action === 'approve') await tellBuyer(hostId, 'return-approved', outcome.entry, outcome.order)\n if (action === 'decline') await tellBuyer(hostId, 'return-declined', outcome.entry, outcome.order)\n // A label attached after the approval reaches the buyer the same way,\n // in the approval email, which carries it.\n if (action === 'attach-label' && outcome.entry.status === 'approved') {\n await tellBuyer(hostId, 'return-approved', outcome.entry, outcome.order)\n }\n }\n return res.status(200).json({\n ok: true,\n ...(outcome.outcome === 'already' ? { already: true } : {}),\n status: outcome.entry.status,\n })\n } catch (error) {\n console.error('returns action failed', action, error)\n // Every write here is a transaction or keyed (the refund), so asking\n // again lands once.\n return res.status(500).json({ error: 'The return could not be updated. Retrying is safe.' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","Aglyn","createResourceUid","findUserByUidAcrossPools","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","renderHostEmailWithTokens","hostConsoleUrl","isEmailConfigured","sendEmail","CommerceModel","RETURN_APPROVED_EVENT","RETURN_DECLINED_EVENT","RETURN_RECEIVED_EVENT","RETURN_REFUNDED_EVENT","RETURN_REQUESTED_EVENT","raiseOrderEvent","stageOrderEvent","orderStatusUrl","verifyOrderStatusToken","readActiveMemberSession","resolveTrackedRestockLines","refundHandler","dropStorefrontPages","soldOutMoved","hostRefFor","firestore","hostId","collection","doc","isId","value","Boolean","length","test","includes","readStore","settings","hostRef","host","store","Promise","all","get","catch","data","returnSettings","readReturnSettings","currency","String","toUpperCase","money","cents","Intl","NumberFormat","style","format","toFixed","returnEventView","id","entry","status","lines","map","line","refundCents","restock","returnItemsText","order","quantity","lineItems","lineItemId","name","RETURN_REASON_LABELS","reason","join","openReturn","request","app","orderRef","orderId","now","Date","note","trim","slice","RETURN_NOTE_MAX","runTransaction","transaction","orderSnapshot","exists","outcome","existing","where","liftLegacyOrder","verdict","validateReturnRequest","docs","by","message","describeReturnRequestProblem","orderNumber","returnOrderNumber","customerEmail","customerName","requestedBy","customerNote","merchantNote","timeline","atMs","event","detail","describeReturnLines","createdAtMs","updatedAtMs","returnRef","create","orderPatch","appendOrderEvent","update","key","extra","return","returnId","ACTION_TARGET","approve","decline","close","changeReturn","undefined","snapshot","target","action","patch","canTransitionReturn","RETURN_STATUS_LABELS","toLowerCase","appendReturnEvent","label","labelUrl","returnIsOpen","carrier","trackingNumber","trackingUrl","trackingUrlFor","returnLabel","attachedAtMs","changed","receiveReturn","locationId","soldOutFlipped","covered","Map","wanted","Number","has","isInteger","total","set","size","location","tracked","ref","products","byProduct","Math","min","lineIndex","productId","variantId","units","product","variants","adjustVariantInventory","productStockFields","delta","entries","received","markReturnRefunded","refundedAtMs","max","round","check","restockCheck","resolution","restocked","some","resolvedAtMs","uid","resolvedBy","callRefundRoute","req","body","idempotencyKey","payload","res","code","json","send","error","setHeader","end","method","headers","authorization","sendReturnEmail","to","tokens","fallback","designed","org","emailOutcome","subject","text","html","fromName","resolveBrandingProfile","sendingIdentity","audience","context","owedFor","sent","console","tellStoreOfRequest","items","type","title","link","encodeURIComponent","skipOwnerEmail","ownerUid","owner","record","email","tellBuyer","statusUrl","filter","refundTotal","buyerMayActFor","token","session","memberEmail","member","returnRequestHandler","input","query","JSON","parse","o","t","returns","endsAt","returnWindowEndsAtMs","enabled","windowEndsAtMs","windowOpen","returnableLines","reasons","RETURN_REASONS","Array","isArray","ok","MERCHANT_ACTIONS","returnsHandler","idToken","startsWith","decoded","auth","verifyIdToken","hostSnapshot","notify","already","returnSnapshot","suggested","returnRefundCents","amountCents","isFinite","wholeLines","returnWholeLineIds","index","orderLineRefunded","namedWorth","orderLineRefundCents","refund","lineItemIds","marked"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SACEC,wBAAwB,EACxBC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,qBAAqB,EACrBC,qBAAqB,EACrBC,qBAAqB,EACrBC,qBAAqB,EACrBC,sBAAsB,QACjB,2BAAuB;AAC9B,SAASC,eAAe,EAAEC,eAAe,QAAQ,oBAAgB;AACjE,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,0BAAsB;AAC7E,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,0BAA0B,QAAQ,oBAAgB;AAC3D,SAASC,aAAa,QAAQ,cAAU;AACxC,SAASC,mBAAmB,EAAEC,YAAY,QAAQ,qBAAiB;AA4BnE,MAAMC,aAAa,CAACC,WAAsBC,SAAmBD,UAAUE,UAAU,CAAC,SAASC,GAAG,CAACF;AAE/F,MAAMG,OAAO,CAACC,QAAkBC,QAAQD,UAAUA,MAAME,MAAM,IAAI,OAAO,CAAC,WAAWC,IAAI,CAACH,UAAU,CAACA,MAAMI,QAAQ,CAAC;AAEpH,iFAAiF,GACjF,eAAeC,UAAUV,SAAo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,OAAO5G,QAAQQ,OAAO;QAAC;QACxF,IAAIR,QAAQA,OAAO,KAAK,aAAaqG,KAAK8E,MAAM,KAAK,OAAO;YAC1D,IAAI1I,WAAW,WAAW,MAAMsG,UAAU/M,QAAQ,mBAAmBgE,QAAQ/B,KAAK,EAAE+B,QAAQvB,KAAK;YACjG,IAAIgE,WAAW,WAAW,MAAMsG,UAAU/M,QAAQ,mBAAmBgE,QAAQ/B,KAAK,EAAE+B,QAAQvB,KAAK;YACjG,sEAAsE;YACtE,2CAA2C;YAC3C,IAAIgE,WAAW,kBAAkBzC,QAAQ/B,KAAK,CAACC,MAAM,KAAK,YAAY;gBACpE,MAAM6K,UAAU/M,QAAQ,mBAAmBgE,QAAQ/B,KAAK,EAAE+B,QAAQvB,KAAK;YACzE;QACF;QACA,OAAO+H,IAAItI,MAAM,CAAC,KAAKwI,IAAI,CAAC;YAC1BgE,IAAI;WACA1K,QAAQA,OAAO,KAAK,YAAY;YAAEoL,SAAS;QAAK,IAAI,CAAC;YACzDlN,QAAQ8B,QAAQ/B,KAAK,CAACC,MAAM;;IAEhC,EAAE,OAAO0I,OAAO;QACduB,QAAQvB,KAAK,CAAC,yBAAyBnE,QAAQmE;QAC/C,qEAAqE;QACrE,oBAAoB;QACpB,OAAOJ,IAAItI,MAAM,CAAC,KAAKwI,IAAI,CAAC;YAAEE,OAAO;QAAqD;IAC5F;AACF,EAAC"}
@@ -137,7 +137,7 @@ function describeLine(line) {
137
137
  shippingAddress.country
138
138
  ].filter(Boolean).join(', ') : '';
139
139
  const subject = lines.length === 1 ? `New order to fulfill for ${store}: ${lines[0].name}` : `New order to fulfill for ${store}: ${lines.length} items`;
140
- await sendEmail({
140
+ const emailOutcome = await sendEmail({
141
141
  to: supplier.email,
142
142
  subject,
143
143
  text: `${store} has a new order for you to ship (order ${orderLabel}):\n` + lines.map((line)=>`- ${describeLine(line)}`).join('\n') + '\n\n' + (address ? `Ship to: ${recipient}, ${address}\n\n` : `Ship to: ${recipient}. No shipping address was ` + `collected at checkout; ask ${store} for it.\n\n`) + 'When it ships, open this link to enter the carrier and ' + `tracking number:\n${updateUrl}`,
@@ -149,8 +149,12 @@ function describeLine(line) {
149
149
  owedFor: 'order'
150
150
  });
151
151
  // Cost meter (AGL-1438): transactional, the order needs it.
152
- await meterHostEmail(hostId);
153
- told = true;
152
+ // A refused send is not a supplier told (AGL-4227): no meter, no
153
+ // "Sent to supplier" on the timeline unless a webhook carried it.
154
+ if (emailOutcome == null ? void 0 : emailOutcome.sent) {
155
+ await meterHostEmail(hostId);
156
+ told = true;
157
+ }
154
158
  }
155
159
  if (!told) continue;
156
160
  await orderRef.set({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/supplier-routing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n} from '@aglyn/tenant-data-admin'\nimport {\n resolveHostToken,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { createHmac } from 'crypto'\nimport * as CommerceModel from '../model'\nimport { tokenSigningSecret } from './download'\nimport { enqueueSupplierDelivery } from './supplier-outbox'\n\n/**\n * Dropship routing for a multi-line CART order (AGL-3773).\n *\n * The Buy-button path has routed a paid order to its product's supplier since\n * AGL-289; the cart path recorded each line's `supplierId` and told nobody, so\n * a supplier assigned to a product never heard about an order placed through\n * the cart. This sends one notice per supplier on the order, naming only that\n * supplier's lines.\n *\n * - **Token.** Each supplier gets `HMAC(hostId:orderId:supplierId)`, the token\n * `supplier-update.ts` re-derives for every supplier on the order, so the\n * link it posts tracking through marks only its own lines shipped (AGL-2455).\n * Nothing is stored for it.\n * - **Webhook.** Queued, never posted from the webhook, through the same\n * outbox as the Buy-button path (AGL-2473): a deterministic id and\n * `create()`, so a second pass cannot queue it twice or reset its retries.\n * - **Email.** Sent inline through Aglyn's own provider, like the receipt.\n *\n * The caller runs this once, behind the AGL-498 `created` guard, and it never\n * throws: a supplier that cannot be told is logged and stamped on the order's\n * timeline as routed only when the notice went out, and the paid order\n * stands.\n */\n\n/** What the supplier is told about one line. */\nexport interface SupplierRoutedLine {\n productId: string\n name: string\n variantLabel?: string\n sku?: string\n quantity: number\n}\n\n/** The session fields the notice is built from. */\nexport interface SupplierRoutingSession {\n customer_details?: { email?: string | null; name?: string | null } | null\n shipping_details?: {\n name?: string | null\n address?: {\n line1?: string | null\n line2?: string | null\n city?: string | null\n state?: string | null\n postal_code?: string | null\n country?: string | null\n } | null\n } | null\n}\n\nexport interface RouteCartOrderOptions {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n orderId: string\n /** The number the merchant and supplier know the order by, e.g. `#12`. */\n orderLabel: string\n lineItems: readonly CommerceModel.OrderLineItem[]\n session: SupplierRoutingSession\n /** The host this request came in on; the tracking link is built on it. */\n requestHost: string\n}\n\n/** The callback token for one supplier on one order. */\nexport function supplierRoutingToken(\n hostId: string,\n orderId: string,\n supplierId: string,\n): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`${hostId}:${orderId}:${supplierId}`)\n .digest('hex')\n .slice(0, 32)\n}\n\n/** The order's lines, grouped by the supplier that fulfills them. */\nexport function linesBySupplier(\n lineItems: readonly CommerceModel.OrderLineItem[],\n): Map<string, SupplierRoutedLine[]> {\n const grouped = new Map<string, SupplierRoutedLine[]>()\n for (const line of lineItems) {\n const supplierId = String(line.supplierId ?? '')\n if (!supplierId) continue\n const lines = grouped.get(supplierId) ?? []\n lines.push({\n productId: String(line.productId ?? ''),\n name: String(line.name ?? 'Product'),\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n quantity: Number(line.quantity ?? 1),\n })\n grouped.set(supplierId, lines)\n }\n return grouped\n}\n\nfunction describeLine(line: SupplierRoutedLine): string {\n return (\n `${line.quantity}× ${line.name}` +\n (line.variantLabel ? ` (${line.variantLabel})` : '') +\n (line.sku ? `, SKU ${line.sku}` : '')\n )\n}\n\n/**\n * Notifies every supplier with lines on a paid cart order. Resolves once each\n * notice is queued or sent; never rejects.\n */\nexport async function routeCartOrderToSuppliers(\n options: RouteCartOrderOptions,\n): Promise<void> {\n const { firestore, hostId, orderId, orderLabel, session, requestHost } =\n options\n const grouped = linesBySupplier(options.lineItems)\n if (grouped.size === 0) return\n try {\n const routedOrg = await getOrgForHost(hostId)\n if (!Aglyn.checkEntitlement(routedOrg?.org as any, 'dropshipRouting')) {\n return\n }\n const hostRef = firestore.collection('hosts').doc(hostId)\n const orderRef = hostRef.collection('orders').doc(orderId)\n const shipTo = session?.shipping_details?.address\n ? session.shipping_details\n : null\n const shippingName =\n shipTo?.name ?? session?.customer_details?.name ?? null\n const customerEmail = session?.customer_details?.email ?? null\n const shippingAddress = shipTo?.address\n ? {\n line1: shipTo.address.line1 ?? null,\n line2: shipTo.address.line2 ?? null,\n city: shipTo.address.city ?? null,\n state: shipTo.address.state ?? null,\n postalCode: shipTo.address.postal_code ?? null,\n country: shipTo.address.country ?? null,\n }\n : null\n let storeName: string | null = null\n const storeNameOnce = async () => {\n if (storeName !== null) return storeName\n storeName =\n resolveHostToken(\n 'businessName',\n (await hostRef\n .get()\n .then((snapshot) => snapshot.data())\n .catch(() => undefined)) as HostTokenSource | undefined,\n ) ?? 'A store'\n return storeName\n }\n\n for (const [supplierId, lines] of grouped) {\n try {\n const supplier = (\n await hostRef.collection('suppliers').doc(supplierId).get()\n ).data() as CommerceModel.HostSupplier | undefined\n if (!supplier) continue\n const token = supplierRoutingToken(hostId, orderId, supplierId)\n const updateUrl =\n `https://${requestHost}/api/commerce/supplier-update` +\n `?hostId=${hostId}&orderId=${orderId}&token=${token}`\n const payload = {\n hostId,\n orderId,\n lines: lines.map((line) => ({\n productId: line.productId,\n productName: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n quantity: line.quantity,\n })),\n customerEmail,\n shippingName,\n shippingAddress,\n updateUrl,\n }\n let told = false\n if (supplier.webhookUrl) {\n const queued = await enqueueSupplierDelivery({\n firestore,\n hostId,\n orderId,\n supplierId,\n supplierName: String(supplier.name ?? ''),\n url: String(supplier.webhookUrl),\n body: JSON.stringify(payload),\n })\n told = told || queued !== 'skipped'\n }\n if (supplier.email) {\n const store = await storeNameOnce()\n const recipient = shippingName ?? customerEmail ?? 'the buyer'\n const address = shippingAddress\n ? [\n shippingAddress.line1,\n shippingAddress.line2,\n [\n shippingAddress.city,\n [shippingAddress.state, shippingAddress.postalCode]\n .filter(Boolean)\n .join(' '),\n ]\n .filter(Boolean)\n .join(', '),\n shippingAddress.country,\n ]\n .filter(Boolean)\n .join(', ')\n : ''\n const subject =\n lines.length === 1\n ? `New order to fulfill for ${store}: ${lines[0].name}`\n : `New order to fulfill for ${store}: ${lines.length} items`\n await sendEmail({\n to: supplier.email,\n subject,\n text:\n `${store} has a new order for you to ship (order ${orderLabel}):\\n` +\n lines.map((line) => `- ${describeLine(line)}`).join('\\n') +\n '\\n\\n' +\n (address\n ? `Ship to: ${recipient}, ${address}\\n\\n`\n : `Ship to: ${recipient}. No shipping address was ` +\n `collected at checkout; ask ${store} for it.\\n\\n`) +\n 'When it ships, open this link to enter the carrier and ' +\n `tracking number:\\n${updateUrl}`,\n fromName: Aglyn.resolveBrandingProfile(routedOrg?.org as never)\n .fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'dropship supplier notice',\n // Owed to the recipient by their own order (AGL-3356).\n owedFor: 'order',\n })\n // Cost meter (AGL-1438): transactional, the order needs it.\n await meterHostEmail(hostId)\n told = true\n }\n if (!told) continue\n await orderRef.set(\n {\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: Date.now(),\n event: 'routed',\n detail:\n `Sent ${lines.length} line${lines.length === 1 ? '' : 's'} ` +\n `to supplier ${supplier.name}`,\n }),\n },\n { merge: true },\n )\n } catch (supplierError) {\n // One supplier failing never keeps the others from being told.\n console.error('Dropship routing failed', supplierId, supplierError)\n }\n }\n } catch (routingError) {\n console.error('Dropship routing failed', routingError)\n }\n}\n"],"names":["Aglyn","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","resolveHostToken","sendEmail","createHmac","tokenSigningSecret","enqueueSupplierDelivery","supplierRoutingToken","hostId","orderId","supplierId","update","digest","slice","linesBySupplier","lineItems","grouped","Map","line","String","lines","get","push","productId","name","variantLabel","sku","quantity","Number","set","describeLine","routeCartOrderToSuppliers","options","firestore","orderLabel","session","requestHost","size","shipTo","routedOrg","checkEntitlement","org","hostRef","collection","doc","orderRef","shipping_details","address","shippingName","customer_details","customerEmail","email","shippingAddress","line1","line2","city","state","postalCode","postal_code","country","storeName","storeNameOnce","then","snapshot","data","catch","undefined","supplier","token","updateUrl","payload","map","productName","told","webhookUrl","queued","supplierName","url","body","JSON","stringify","store","recipient","filter","Boolean","join","subject","length","to","text","fromName","resolveBrandingProfile","sendingIdentity","audience","context","owedFor","timeline","FieldValue","arrayUnion","atMs","Date","now","event","detail","merge","supplierError","console","error","routingError"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,QACT,2BAA0B;AACjC,SACEC,gBAAgB,QAEX,qCAAoC;AAC3C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,UAAU,QAAQ,SAAQ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ACCtC,CAAAA,UACG,CAAC,SAAS,EAAEmC,UAAU,EAAE,EAAEnC,QAAQ,IAAI,CAAC,GACvC,CAAC,SAAS,EAAEmC,UAAU,0BAA0B,CAAC,GACjD,CAAC,2BAA2B,EAAED,MAAM,YAAY,CAAC,AAAD,IACpD,4DACA,CAAC,kBAAkB,EAAEZ,WAAW;wBAClCqB,UAAU7F,MAAM8F,sBAAsB,CAACpD,6BAAAA,UAAWE,GAAG,EAClDiD,QAAQ;wBACXE,iBAAiB,MAAM5F,oBAAoBQ;wBAC3CqF,UAAU;wBACVC,SAAS;wBACT,uDAAuD;wBACvDC,SAAS;oBACX;oBACA,4DAA4D;oBAC5D,MAAM9F,eAAeO;oBACrBiE,OAAO;gBACT;gBACA,IAAI,CAACA,MAAM;gBACX,MAAM5B,SAAShB,GAAG,CAChB;oBACEmE,UAAUlG,cAAcmC,SAAS,CAACgE,UAAU,CAACC,UAAU,CAAC;wBACtDC,MAAMC,KAAKC,GAAG;wBACdC,OAAO;wBACPC,QACE,CAAC,KAAK,EAAEnF,MAAMmE,MAAM,CAAC,KAAK,EAAEnE,MAAMmE,MAAM,KAAK,IAAI,KAAK,IAAI,CAAC,CAAC,GAC5D,CAAC,YAAY,EAAEpB,SAAS3C,IAAI,EAAE;oBAClC;gBACF,GACA;oBAAEgF,OAAO;gBAAK;YAElB,EAAE,OAAOC,eAAe;gBACtB,+DAA+D;gBAC/DC,QAAQC,KAAK,CAAC,2BAA2BjG,YAAY+F;YACvD;QACF;IACF,EAAE,OAAOG,cAAc;QACrBF,QAAQC,KAAK,CAAC,2BAA2BC;IAC3C;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/supplier-routing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n} from '@aglyn/tenant-data-admin'\nimport {\n resolveHostToken,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { createHmac } from 'crypto'\nimport * as CommerceModel from '../model'\nimport { tokenSigningSecret } from './download'\nimport { enqueueSupplierDelivery } from './supplier-outbox'\n\n/**\n * Dropship routing for a multi-line CART order (AGL-3773).\n *\n * The Buy-button path has routed a paid order to its product's supplier since\n * AGL-289; the cart path recorded each line's `supplierId` and told nobody, so\n * a supplier assigned to a product never heard about an order placed through\n * the cart. This sends one notice per supplier on the order, naming only that\n * supplier's lines.\n *\n * - **Token.** Each supplier gets `HMAC(hostId:orderId:supplierId)`, the token\n * `supplier-update.ts` re-derives for every supplier on the order, so the\n * link it posts tracking through marks only its own lines shipped (AGL-2455).\n * Nothing is stored for it.\n * - **Webhook.** Queued, never posted from the webhook, through the same\n * outbox as the Buy-button path (AGL-2473): a deterministic id and\n * `create()`, so a second pass cannot queue it twice or reset its retries.\n * - **Email.** Sent inline through Aglyn's own provider, like the receipt.\n *\n * The caller runs this once, behind the AGL-498 `created` guard, and it never\n * throws: a supplier that cannot be told is logged and stamped on the order's\n * timeline as routed only when the notice went out, and the paid order\n * stands.\n */\n\n/** What the supplier is told about one line. */\nexport interface SupplierRoutedLine {\n productId: string\n name: string\n variantLabel?: string\n sku?: string\n quantity: number\n}\n\n/** The session fields the notice is built from. */\nexport interface SupplierRoutingSession {\n customer_details?: { email?: string | null; name?: string | null } | null\n shipping_details?: {\n name?: string | null\n address?: {\n line1?: string | null\n line2?: string | null\n city?: string | null\n state?: string | null\n postal_code?: string | null\n country?: string | null\n } | null\n } | null\n}\n\nexport interface RouteCartOrderOptions {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n orderId: string\n /** The number the merchant and supplier know the order by, e.g. `#12`. */\n orderLabel: string\n lineItems: readonly CommerceModel.OrderLineItem[]\n session: SupplierRoutingSession\n /** The host this request came in on; the tracking link is built on it. */\n requestHost: string\n}\n\n/** The callback token for one supplier on one order. */\nexport function supplierRoutingToken(\n hostId: string,\n orderId: string,\n supplierId: string,\n): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`${hostId}:${orderId}:${supplierId}`)\n .digest('hex')\n .slice(0, 32)\n}\n\n/** The order's lines, grouped by the supplier that fulfills them. */\nexport function linesBySupplier(\n lineItems: readonly CommerceModel.OrderLineItem[],\n): Map<string, SupplierRoutedLine[]> {\n const grouped = new Map<string, SupplierRoutedLine[]>()\n for (const line of lineItems) {\n const supplierId = String(line.supplierId ?? '')\n if (!supplierId) continue\n const lines = grouped.get(supplierId) ?? []\n lines.push({\n productId: String(line.productId ?? ''),\n name: String(line.name ?? 'Product'),\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n quantity: Number(line.quantity ?? 1),\n })\n grouped.set(supplierId, lines)\n }\n return grouped\n}\n\nfunction describeLine(line: SupplierRoutedLine): string {\n return (\n `${line.quantity}× ${line.name}` +\n (line.variantLabel ? ` (${line.variantLabel})` : '') +\n (line.sku ? `, SKU ${line.sku}` : '')\n )\n}\n\n/**\n * Notifies every supplier with lines on a paid cart order. Resolves once each\n * notice is queued or sent; never rejects.\n */\nexport async function routeCartOrderToSuppliers(\n options: RouteCartOrderOptions,\n): Promise<void> {\n const { firestore, hostId, orderId, orderLabel, session, requestHost } =\n options\n const grouped = linesBySupplier(options.lineItems)\n if (grouped.size === 0) return\n try {\n const routedOrg = await getOrgForHost(hostId)\n if (!Aglyn.checkEntitlement(routedOrg?.org as any, 'dropshipRouting')) {\n return\n }\n const hostRef = firestore.collection('hosts').doc(hostId)\n const orderRef = hostRef.collection('orders').doc(orderId)\n const shipTo = session?.shipping_details?.address\n ? session.shipping_details\n : null\n const shippingName =\n shipTo?.name ?? session?.customer_details?.name ?? null\n const customerEmail = session?.customer_details?.email ?? null\n const shippingAddress = shipTo?.address\n ? {\n line1: shipTo.address.line1 ?? null,\n line2: shipTo.address.line2 ?? null,\n city: shipTo.address.city ?? null,\n state: shipTo.address.state ?? null,\n postalCode: shipTo.address.postal_code ?? null,\n country: shipTo.address.country ?? null,\n }\n : null\n let storeName: string | null = null\n const storeNameOnce = async () => {\n if (storeName !== null) return storeName\n storeName =\n resolveHostToken(\n 'businessName',\n (await hostRef\n .get()\n .then((snapshot) => snapshot.data())\n .catch(() => undefined)) as HostTokenSource | undefined,\n ) ?? 'A store'\n return storeName\n }\n\n for (const [supplierId, lines] of grouped) {\n try {\n const supplier = (\n await hostRef.collection('suppliers').doc(supplierId).get()\n ).data() as CommerceModel.HostSupplier | undefined\n if (!supplier) continue\n const token = supplierRoutingToken(hostId, orderId, supplierId)\n const updateUrl =\n `https://${requestHost}/api/commerce/supplier-update` +\n `?hostId=${hostId}&orderId=${orderId}&token=${token}`\n const payload = {\n hostId,\n orderId,\n lines: lines.map((line) => ({\n productId: line.productId,\n productName: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n quantity: line.quantity,\n })),\n customerEmail,\n shippingName,\n shippingAddress,\n updateUrl,\n }\n let told = false\n if (supplier.webhookUrl) {\n const queued = await enqueueSupplierDelivery({\n firestore,\n hostId,\n orderId,\n supplierId,\n supplierName: String(supplier.name ?? ''),\n url: String(supplier.webhookUrl),\n body: JSON.stringify(payload),\n })\n told = told || queued !== 'skipped'\n }\n if (supplier.email) {\n const store = await storeNameOnce()\n const recipient = shippingName ?? customerEmail ?? 'the buyer'\n const address = shippingAddress\n ? [\n shippingAddress.line1,\n shippingAddress.line2,\n [\n shippingAddress.city,\n [shippingAddress.state, shippingAddress.postalCode]\n .filter(Boolean)\n .join(' '),\n ]\n .filter(Boolean)\n .join(', '),\n shippingAddress.country,\n ]\n .filter(Boolean)\n .join(', ')\n : ''\n const subject =\n lines.length === 1\n ? `New order to fulfill for ${store}: ${lines[0].name}`\n : `New order to fulfill for ${store}: ${lines.length} items`\n const emailOutcome = await sendEmail({\n to: supplier.email,\n subject,\n text:\n `${store} has a new order for you to ship (order ${orderLabel}):\\n` +\n lines.map((line) => `- ${describeLine(line)}`).join('\\n') +\n '\\n\\n' +\n (address\n ? `Ship to: ${recipient}, ${address}\\n\\n`\n : `Ship to: ${recipient}. No shipping address was ` +\n `collected at checkout; ask ${store} for it.\\n\\n`) +\n 'When it ships, open this link to enter the carrier and ' +\n `tracking number:\\n${updateUrl}`,\n fromName: Aglyn.resolveBrandingProfile(routedOrg?.org as never)\n .fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'dropship supplier notice',\n // Owed to the recipient by their own order (AGL-3356).\n owedFor: 'order',\n })\n // Cost meter (AGL-1438): transactional, the order needs it.\n // A refused send is not a supplier told (AGL-4227): no meter, no\n // \"Sent to supplier\" on the timeline unless a webhook carried it.\n if (emailOutcome?.sent) {\n await meterHostEmail(hostId)\n told = true\n }\n }\n if (!told) continue\n await orderRef.set(\n {\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: Date.now(),\n event: 'routed',\n detail:\n `Sent ${lines.length} line${lines.length === 1 ? '' : 's'} ` +\n `to supplier ${supplier.name}`,\n }),\n },\n { merge: true },\n )\n } catch (supplierError) {\n // One supplier failing never keeps the others from being told.\n console.error('Dropship routing failed', supplierId, supplierError)\n }\n }\n } catch (routingError) {\n console.error('Dropship routing failed', routingError)\n }\n}\n"],"names":["Aglyn","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","resolveHostToken","sendEmail","createHmac","tokenSigningSecret","enqueueSupplierDelivery","supplierRoutingToken","hostId","orderId","supplierId","update","digest","slice","linesBySupplier","lineItems","grouped","Map","line","String","lines","get","push","productId","name","variantLabel","sku","quantity","Number","set","describeLine","routeCartOrderToSuppliers","options","firestore","orderLabel","session","requestHost","size","shipTo","routedOrg","checkEntitlement","org","hostRef","collection","doc","orderRef","shipping_details","address","shippingName","customer_details","customerEmail","email","shippingAddress","line1","line2","city","state","postalCode","postal_code","country","storeName","storeNameOnce","then","snapshot","data","catch","undefined","supplier","token","updateUrl","payload","map","productName","told","webhookUrl","queued","supplierName","url","body","JSON","stringify","store","recipient","filter","Boolean","join","subject","length","emailOutcome","to","text","fromName","resolveBrandingProfile","sendingIdentity","audience","context","owedFor","sent","timeline","FieldValue","arrayUnion","atMs","Date","now","event","detail","merge","supplierError","console","error","routingError"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,QACT,2BAA0B;AACjC,SACEC,gBAAgB,QAEX,qCAAoC;AAC3C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,UAAU,QAAQ,SAAQ;AAEnC,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,uBAAuB,QAAQ,uBAAmB;AA+D3D,sDAAsD,GACtD,OAAO,SAASC,qBACdC,MAAc,EACdC,OAAe,EACfC,UAAkB;IAElB,OAAON,WAAW,UAAUC,sBACzBM,MAAM,CAAC,GAAGH,OAAO,CAAC,EAAEC,QAAQ,CAAC,EAAEC,YAAY,EAC3CE,MAAM,CAAC,OACPC,KAAK,CAAC,GAAG;AACd;AAEA,mEAAmE,GACnE,OAAO,SAASC,gBACdC,SAAiD;IAEjD,MAAMC,UAAU,IAAIC;IACpB,KAAK,MAAMC,QAAQH,UAAW;YACFG,kBAEZF,cAEME,iBACLA,YAGIA;QARnB,MAAMR,aAAaS,QAAOD,mBAAAA,KAAKR,UAAU,YAAfQ,mBAAmB;QAC7C,IAAI,CAACR,YAAY;QACj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