@aglyn/plugins-commerce 1.15.0 → 1.15.1
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.
- package/package.json +13 -13
- package/src/lib/components/cart.js +8 -3
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +4 -2
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/product-detail.js +7 -3
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +26 -39
- package/src/lib/model/commerce-payment-methods.js +11 -118
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/server/billing-webhook.d.ts +23 -0
- package/src/lib/server/billing-webhook.js +162 -30
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +61 -14
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +42 -12
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +37 -12
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +112 -32
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
|
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { directSellerAccountForHost, fetchOnSellerThenPlatform } from "./seller-stripe-account.js";
|
|
18
|
+
import { holdsCommerceSiteKey } from "./commerce-site-keys.js";
|
|
18
19
|
import { commerceSitePermissionRefusal } from "../model/plugin-permissions.js";
|
|
19
20
|
import * as CommerceModel from "../model/index.js";
|
|
20
21
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
@@ -355,13 +356,13 @@ import { capRestockLines, resolveTrackedRestockLines, saleReleaseCaps } from "./
|
|
|
355
356
|
// both are states this has nothing to add to.
|
|
356
357
|
const expireSessionId = outcome.expireSessionId;
|
|
357
358
|
if (expireSessionId && process.env.STRIPE_SECRET_KEY) {
|
|
358
|
-
const expiry = await
|
|
359
|
+
const expiry = await fetchOnSellerThenPlatform(`https://api.stripe.com/v1/checkout/sessions/${expireSessionId}/expire`, {
|
|
359
360
|
method: 'POST',
|
|
360
361
|
headers: {
|
|
361
362
|
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
362
363
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
363
364
|
}
|
|
364
|
-
}).catch(()=>null);
|
|
365
|
+
}, await directSellerAccountForHost(hostId)).catch(()=>null);
|
|
365
366
|
if (!(expiry == null ? void 0 : expiry.ok)) {
|
|
366
367
|
console.error('Cancelled order: Stripe session not expired, the payment link may still be payable', {
|
|
367
368
|
hostId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cancel-order.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 CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_CANCELLED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport {\n capRestockLines,\n resolveTrackedRestockLines,\n saleReleaseCaps,\n} from './restock-flag'\n\n/**\n * Cancelling an order RELEASES its stock (AGL-1808) — the opposite of what the\n * reversal doors do, and for a structural reason rather than a preference.\n *\n * AGL-1797 refused to increment on a refund or a chargeback because the goods\n * may well be gone: a refund with no return, or a shopper who kept the item and\n * took the money, leaves stock that incrementing would INVENT. It flags and\n * lets the merchant answer. Cancellation carries no such question, and the\n * guarantee is `ORDER_TRANSITIONS`:\n *\n * pending: ['paid', 'cancelled'],\n * paid: ['partially_fulfilled', 'fulfilled', 'cancelled', 'refunded'],\n * partially_fulfilled | fulfilled | delivered: no 'cancelled'\n *\n * so a cancelled order was never fulfilled and nothing ever shipped. The units\n * are still on the shelf; the only wrong number is ours.\n *\n * THE GUARANTEE HAD TO BE ENFORCED BEFORE IT COULD BE RELIED ON, and that is\n * why this is a handler rather than a few lines in the console. The transition\n * table said the right thing but nothing consulted it on the way IN: the order\n * dialog cancelled with a client `updateDoc`, and `canTransitionOrder` only\n * decided whether to render the button. The Firestore rules impose no status\n * machine — an order update is allowed to any admin or editor — so a dialog\n * held open while the order shipped in another tab (or any other client) could\n * write `cancelled` straight onto a `fulfilled` order, and an automatic\n * increment behind that would restock goods already in the post. Re-asking the\n * transition INSIDE the transaction that writes the status is what turns the\n * comment into a guarantee, and it is what makes the release safe.\n *\n * `pending` RELEASES NOTHING, which is the other half the issue's premise\n * missed. Stock is decremented when the money lands, not when the order is\n * written: `draft-order.ts` and the POS card path both open a `pending` order\n * and decrement only in the webhook that pays it. Incrementing on a cancelled\n * `pending` order would invent inventory exactly the way AGL-1797 refused to —\n * so only a `paid` order, the one status reachable here whose sale provably\n * decremented, releases anything.\n *\n * ONE LEDGER, NOT A SECOND STOCK WRITER. The increment goes through\n * `adjustVariantInventory` and logs an `InventoryAdjustment` per line, the same\n * pair the sale paths and the products hub's \"Adjust stock\" write, with the new\n * `cancellation` reason and the `orderId`. An increment with no ledger row\n * would leave the hub's stock history unable to explain a count that moved on\n * its own — the mirror of AGL-1797's argument against writing a row for stock\n * that had NOT moved.\n *\n * ONLY WHAT THE SALE DECREMENTED comes back: `resolveTrackedRestockLines`, the\n * helper AGL-1797 already built, applies the sale path's own\n * `variant.inventory != null` test to the products as they stand now. A store\n * that tracks no stock gets a plain cancellation and no adjustment rows.\n *\n * IT FAILS THE CANCEL RATHER THAN LOSING THE RELEASE. `flagOrderRestock`\n * swallows its errors because the money had already moved and the flag was a\n * postscript; here the status flip and the stock write are one act, so they\n * share a transaction and a failure leaves the order uncancelled for the\n * merchant to retry. A cancelled order whose stock never came back is the\n * original bug.\n *\n * ONCE. The transaction's own read is the guard: a second cancel — a retried\n * request, two admins clicking together — finds `cancelled`, which\n * `canTransitionOrder` cannot leave, and returns without touching stock. Two\n * increments of the same units is the failure mode this shape exists to\n * prevent, and it is measured rather than asserted (`cancel-order.spec.ts`).\n *\n * REACHED FROM THE CONSOLE since AGL-1818: `order-detail-dialog`'s\n * `handleCancel` POSTs here with the console id token, and the client\n * `updateDoc` cancel it replaced is gone. (The wiring landed separately from\n * the route because the dialog belonged to a concurrent agent, AGL-1806,\n * when the route was written.)\n */\nexport const cancelOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n // Firestore reserves `__…__` ids and `.doc()` throws SYNCHRONOUSLY on one,\n // which would surface as a 500 on a caller's typo rather than the 400 it is.\n if (/^__.*__$/.test(hostId) || /^__.*__$/.test(orderId)) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // The role the CLIENT write already had, not a stricter one. Order updates\n // fall through the rules' host catch-all, which admits `admin` and\n // `editor` — narrowing to admin here would take the cancel button away\n // from editors who have always had it, and widening it past what the rules\n // allow would make this endpoint the way around them.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n\n const outcome = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) {\n return { status: 404, body: { error: 'Unknown order' } }\n }\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n // A redelivered click, or the second of two admins. Answered as success\n // because it IS the state the caller asked for — reporting 409 here\n // teaches an admin that the cancel failed and invites a third attempt —\n // but nothing is written, so the units are released exactly once.\n if (order.status === 'cancelled') {\n return {\n status: 200,\n body: { ok: true, alreadyCancelled: true, released: 0, units: 0 },\n }\n }\n if (!CommerceModel.canTransitionOrder(order.status, 'cancelled')) {\n return {\n status: 409,\n body: { error: `Orders in \"${order.status}\" cannot cancel` },\n }\n }\n // An OPEN register sale that has taken money (AGL-3607) is voided at\n // the register, which hands each payment back first. Cancelling it here\n // would mark it cancelled with a card charge, a gift card debit or a\n // room charge still standing.\n if (\n order.status === 'pending' &&\n CommerceModel.orderPayments(order).some(\n (payment) => payment.status === 'succeeded' || payment.status === 'pending',\n ) &&\n Array.isArray(order.payments)\n ) {\n return {\n status: 409,\n body: {\n error:\n 'This register sale has payments on it. Void it at the register, ' +\n 'which hands each payment back first.',\n },\n }\n }\n\n // A POS CARD order's decrement happens in the webhook that pays it —\n // and before AGL-1825 it did not happen AT ALL: the paying branch's\n // decrement was gated on `productId` metadata the register's session\n // never carried. Releasing such an order restocks units that were never\n // taken, turning the silent under-count into a silent over-count. The\n // sale's own ledger is the discriminator: every decrement pairs with a\n // `reason: 'sale'` row (AGL-1807 closed the last hole, and the AGL-1825\n // decrement writes them from day one), so a paid card order with no\n // sale row is one whose sale took nothing — and nothing is released.\n //\n // Scoped to card orders (the `pos-card-pending` timeline event) rather\n // than applied to every order, because one historical path decremented\n // WITHOUT rows — draft links paid before AGL-1807 — and asking the\n // ledger to vouch for those would wrongly strand their stock. The\n // residual is stated plainly: the sibling-shaped decrement/ledger pair\n // is two swallowed sequential writes, so a card order whose ledger add\n // alone failed will not release — a bounded under-count on that one\n // order, visible as a sale missing from the hub's history, against the\n // alternative of inflating stock on every pre-fix cancel.\n //\n // One equality filter, so the automatic single-field index answers it;\n // the reason test runs here, over the handful of rows one order has.\n //\n // THE SAME READ NOW ALSO BOUNDS HOW MUCH COMES BACK (AGL-2149), so it is\n // no longer scoped to card orders. `adjustVariantInventory` floors at\n // zero, and that floor silently absorbs the overshoot on a BACKORDER\n // product: stock 0, `canPurchase` admits the sale because the policy says\n // to, three units sell, `Math.max(0, 0 + -3)` leaves the count at 0 —\n // and a `+3` here would hand the merchant three units nobody has and a\n // stock badge offering them. The sale rows carry `appliedDelta` for\n // exactly this: `delta` stays the units sold (the merchant's history),\n // `appliedDelta` says how many the count could actually give up.\n //\n // Only lines the ledger DESCRIBES are capped. A pair the ledger says\n // nothing about restores as before, which is what keeps the pre-AGL-1807\n // draft links — decremented with no row at all — from having their stock\n // stranded, and what keeps a single swallowed ledger write from turning\n // into a lost restock on an unrelated line of the same order.\n let saleDecremented = true\n // The cap rule itself lives beside the restock flag, which now bounds\n // the question it ASKS by the same ledger this bounds the stock it\n // RETURNS (AGL-2325). One implementation, so a prompt naming more units\n // than a cancellation would put back is not expressible.\n let releaseCap: ReadonlyMap<string, number> = new Map<string, number>()\n if (order.status === 'paid') {\n const orderAdjustments = await transaction.get(\n hostRef\n .collection('inventoryAdjustments')\n .where('orderId', '==', orderId),\n )\n const saleRows = orderAdjustments.docs.filter(\n (row) => row.get('reason') === 'sale',\n )\n if (\n order.channel === 'pos' &&\n (order.timeline ?? []).some(\n (event) => event.event === 'pos-card-pending',\n )\n ) {\n saleDecremented = saleRows.length > 0\n }\n releaseCap = saleReleaseCaps(saleRows)\n }\n\n // `paid` is the only status reachable here whose sale decremented; see\n // the header. Reads happen before any write, as a transaction requires.\n const { lines, products } =\n order.status === 'paid' && saleDecremented\n ? await resolveTrackedRestockLines(hostRef, order, (ref) =>\n transaction.get(ref),\n )\n : {\n lines: [],\n products: new Map<string, CommerceModel.HostProduct>(),\n }\n\n const atMs = Date.now()\n // Grouped by product, because two lines of one product (two variants, or\n // the same variant twice) are two deltas against ONE document: writing\n // them separately would compute both from the same read and land only\n // the last, silently dropping units.\n const byProduct = new Map<string, CommerceModel.OrderRestockLine[]>()\n // Never more than the sale actually took off the shelf (AGL-2149).\n for (const line of capRestockLines(lines, releaseCap)) {\n byProduct.set(line.productId, [\n ...(byProduct.get(line.productId) ?? []),\n line,\n ])\n }\n for (const [productId, productLines] of byProduct) {\n const product = products.get(productId)\n if (!product) continue\n let variants = product.variants\n for (const line of productLines) {\n variants = CommerceModel.adjustVariantInventory(\n { variants },\n line.variantId,\n line.quantity,\n // The bucket the sale came out of, for a location-tracked store\n // (AGL-286). Absent on every path that decremented the flat count,\n // where `adjustVariantInventory` puts it back the same way.\n order.locationId || undefined,\n )\n }\n // `update()`, not `set(…, { merge: true })` as the sale paths use: the\n // transaction has just read this product, so it exists, and a product\n // deleted under us must not be conjured back as a stub holding nothing\n // but a variants array.\n transaction.update(hostRef.collection('products').doc(productId), {\n variants,\n // The total and the storefront's In stock verdict (AGL-3321).\n ...CommerceModel.productStockFields({ ...product, variants }),\n updatedAtMs: atMs,\n })\n for (const line of productLines) {\n transaction.create(hostRef.collection('inventoryAdjustments').doc(), {\n productId,\n variantId: line.variantId,\n delta: line.quantity,\n reason: 'cancellation',\n orderId,\n ...(order.locationId ? { locationId: order.locationId } : {}),\n atMs,\n } satisfies CommerceModel.InventoryAdjustment)\n }\n }\n\n // From the CAPPED lines, not the order's, so the timeline reports what\n // was actually put back (AGL-2149).\n const releasedLines = [...byProduct.values()].flat()\n const units = releasedLines.reduce((sum, line) => sum + line.quantity, 0)\n const patch: Record<string, unknown> = {\n status: 'cancelled',\n // What a shipping tool's feed asks to learn of the cancel (AGL-3613).\n updatedAtMs: atMs,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'cancelled',\n units > 0\n ? `${units} ${units === 1 ? 'unit' : 'units'} returned to stock`\n : undefined,\n atMs,\n ),\n }\n // An open restock question about THIS order's stock, raised by a partial\n // refund before the cancellation (AGL-1797). The units it asked about are\n // the ones just put back, so leaving it open would invite the merchant to\n // restock them a second time from the order dialog — the double-count\n // that flag exists to avoid. Answered with what actually happened.\n if (units > 0 && order.restockCheck && !order.restockCheck.resolution) {\n patch.restockCheck = {\n ...order.restockCheck,\n resolution: 'restocked',\n resolvedAtMs: atMs,\n resolvedBy: decoded.uid,\n } satisfies CommerceModel.OrderRestockCheck\n }\n transaction.update(orderRef, patch)\n return {\n status: 200,\n body: { ok: true, released: releasedLines.length, units },\n // The live Stripe page this cancellation orphans, if any (AGL-2244).\n // Read inside the transaction that flips the status so the expiry\n // below cannot act on an order some other writer paid meanwhile.\n expireSessionId:\n order.status === 'pending' ? (order.checkoutSessionId ?? '') : '',\n }\n })\n // EXPIRE THE PAYMENT LINK (AGL-2244). Cancelling a `pending` draft order or\n // POS card sale left its Checkout Session live: the URL is on the\n // customer's phone or in the email the merchant sent, and Stripe keeps it\n // payable for 24 hours. Paying it captured real money on the merchant's\n // account and the completing webhook then discarded the event — its\n // `status !== 'pending'` guard cannot tell a redelivery from a cancelled\n // order — so the sale existed in Stripe and nowhere in the product: no\n // order, no stock move, no contact, no notification, not even a timeline\n // line. The webhook now says so when it happens; this is the half that\n // stops it happening.\n //\n // OUTSIDE the transaction, because it is a network call, and best-effort\n // by design: the cancellation itself already landed and is what the\n // merchant asked for. A failure here leaves the pre-existing behaviour\n // (a payable link) plus the webhook's new record of it, which is strictly\n // better than failing a cancel that has already released stock. Stripe\n // answers 400 for a session that is already expired or already paid, and\n // both are states this has nothing to add to.\n const expireSessionId = (outcome as { expireSessionId?: string })\n .expireSessionId\n if (expireSessionId && process.env.STRIPE_SECRET_KEY) {\n const expiry = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${expireSessionId}/expire`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n },\n ).catch(() => null)\n if (!expiry?.ok) {\n console.error(\n 'Cancelled order: Stripe session not expired, the payment link may still be payable',\n { hostId, orderId, sessionId: expireSessionId },\n )\n }\n }\n // The buyer is told (AGL-3610) — only by the request that cancelled it.\n if (outcome.status === 200 && !(outcome.body as { alreadyCancelled?: boolean }).alreadyCancelled) {\n await notifyOrderBuyer({ hostId, orderId }, 'cancelled')\n await raiseOrderEvent(ORDER_CANCELLED_EVENT, { hostId, orderId, key: 'cancelled' })\n }\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n // Nothing landed — the transaction is all-or-nothing — so the order is\n // still open and the merchant can try again. Deliberately NOT the swallow\n // `flagOrderRestock` uses: there the money had already moved and only a\n // postscript was at risk; here a swallowed failure is a cancelled order\n // whose stock never came back, which is the bug this closes.\n console.error('cancelOrder failed', error)\n return res.status(500).json({ error: 'Cancel failed' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","CommerceModel","firebaseAdmin","notifyOrderBuyer","ORDER_CANCELLED_EVENT","raiseOrderEvent","capRestockLines","resolveTrackedRestockLines","saleReleaseCaps","cancelOrderHandler","req","res","body","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","orderId","test","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","orderRef","outcome","runTransaction","transaction","snapshot","order","liftLegacyOrder","data","ok","alreadyCancelled","released","units","canTransitionOrder","orderPayments","some","payment","Array","isArray","payments","saleDecremented","releaseCap","Map","orderAdjustments","where","saleRows","docs","filter","row","channel","timeline","event","lines","products","ref","atMs","Date","now","byProduct","line","set","productId","productLines","product","variants","adjustVariantInventory","variantId","quantity","locationId","update","productStockFields","updatedAtMs","create","delta","reason","releasedLines","values","flat","reduce","sum","patch","appendOrderEvent","restockCheck","resolution","resolvedAtMs","resolvedBy","expireSessionId","checkoutSessionId","process","env","STRIPE_SECRET_KEY","expiry","fetch","Authorization","catch","console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AAAA,OAAQ9D,EAAE,GAAE;gBACfkE,QAAQpG,KAAK,CACX,sFACA;oBAAEW;oBAAQC;oBAASyF,WAAWV;gBAAgB;YAElD;QACF;QACA,wEAAwE;QACxE,IAAIhE,QAAQ7B,MAAM,KAAK,OAAO,CAAC,AAAC6B,QAAQ/B,IAAI,CAAoCuC,gBAAgB,EAAE;YAChG,MAAMhD,iBAAiB;gBAAEwB;gBAAQC;YAAQ,GAAG;YAC5C,MAAMvB,gBAAgBD,uBAAuB;gBAAEuB;gBAAQC;gBAAS0F,KAAK;YAAY;QACnF;QACA,OAAO3G,IAAIG,MAAM,CAAC6B,QAAQ7B,MAAM,EAAEC,IAAI,CAAC4B,QAAQ/B,IAAI;IACrD,EAAE,OAAOI,OAAO;QACd,uEAAuE;QACvE,0EAA0E;QAC1E,wEAAwE;QACxE,wEAAwE;QACxE,6DAA6D;QAC7DoG,QAAQpG,KAAK,CAAC,sBAAsBA;QACpC,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cancel-order.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 { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_CANCELLED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport {\n capRestockLines,\n resolveTrackedRestockLines,\n saleReleaseCaps,\n} from './restock-flag'\n\n/**\n * Cancelling an order RELEASES its stock (AGL-1808) — the opposite of what the\n * reversal doors do, and for a structural reason rather than a preference.\n *\n * AGL-1797 refused to increment on a refund or a chargeback because the goods\n * may well be gone: a refund with no return, or a shopper who kept the item and\n * took the money, leaves stock that incrementing would INVENT. It flags and\n * lets the merchant answer. Cancellation carries no such question, and the\n * guarantee is `ORDER_TRANSITIONS`:\n *\n * pending: ['paid', 'cancelled'],\n * paid: ['partially_fulfilled', 'fulfilled', 'cancelled', 'refunded'],\n * partially_fulfilled | fulfilled | delivered: no 'cancelled'\n *\n * so a cancelled order was never fulfilled and nothing ever shipped. The units\n * are still on the shelf; the only wrong number is ours.\n *\n * THE GUARANTEE HAD TO BE ENFORCED BEFORE IT COULD BE RELIED ON, and that is\n * why this is a handler rather than a few lines in the console. The transition\n * table said the right thing but nothing consulted it on the way IN: the order\n * dialog cancelled with a client `updateDoc`, and `canTransitionOrder` only\n * decided whether to render the button. The Firestore rules impose no status\n * machine — an order update is allowed to any admin or editor — so a dialog\n * held open while the order shipped in another tab (or any other client) could\n * write `cancelled` straight onto a `fulfilled` order, and an automatic\n * increment behind that would restock goods already in the post. Re-asking the\n * transition INSIDE the transaction that writes the status is what turns the\n * comment into a guarantee, and it is what makes the release safe.\n *\n * `pending` RELEASES NOTHING, which is the other half the issue's premise\n * missed. Stock is decremented when the money lands, not when the order is\n * written: `draft-order.ts` and the POS card path both open a `pending` order\n * and decrement only in the webhook that pays it. Incrementing on a cancelled\n * `pending` order would invent inventory exactly the way AGL-1797 refused to —\n * so only a `paid` order, the one status reachable here whose sale provably\n * decremented, releases anything.\n *\n * ONE LEDGER, NOT A SECOND STOCK WRITER. The increment goes through\n * `adjustVariantInventory` and logs an `InventoryAdjustment` per line, the same\n * pair the sale paths and the products hub's \"Adjust stock\" write, with the new\n * `cancellation` reason and the `orderId`. An increment with no ledger row\n * would leave the hub's stock history unable to explain a count that moved on\n * its own — the mirror of AGL-1797's argument against writing a row for stock\n * that had NOT moved.\n *\n * ONLY WHAT THE SALE DECREMENTED comes back: `resolveTrackedRestockLines`, the\n * helper AGL-1797 already built, applies the sale path's own\n * `variant.inventory != null` test to the products as they stand now. A store\n * that tracks no stock gets a plain cancellation and no adjustment rows.\n *\n * IT FAILS THE CANCEL RATHER THAN LOSING THE RELEASE. `flagOrderRestock`\n * swallows its errors because the money had already moved and the flag was a\n * postscript; here the status flip and the stock write are one act, so they\n * share a transaction and a failure leaves the order uncancelled for the\n * merchant to retry. A cancelled order whose stock never came back is the\n * original bug.\n *\n * ONCE. The transaction's own read is the guard: a second cancel — a retried\n * request, two admins clicking together — finds `cancelled`, which\n * `canTransitionOrder` cannot leave, and returns without touching stock. Two\n * increments of the same units is the failure mode this shape exists to\n * prevent, and it is measured rather than asserted (`cancel-order.spec.ts`).\n *\n * REACHED FROM THE CONSOLE since AGL-1818: `order-detail-dialog`'s\n * `handleCancel` POSTs here with the console id token, and the client\n * `updateDoc` cancel it replaced is gone. (The wiring landed separately from\n * the route because the dialog belonged to a concurrent agent, AGL-1806,\n * when the route was written.)\n */\nexport const cancelOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n // Firestore reserves `__…__` ids and `.doc()` throws SYNCHRONOUSLY on one,\n // which would surface as a 500 on a caller's typo rather than the 400 it is.\n if (/^__.*__$/.test(hostId) || /^__.*__$/.test(orderId)) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // The role the CLIENT write already had, not a stricter one. Order updates\n // fall through the rules' host catch-all, which admits `admin` and\n // `editor` — narrowing to admin here would take the cancel button away\n // from editors who have always had it, and widening it past what the rules\n // allow would make this endpoint the way around them.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n\n const outcome = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) {\n return { status: 404, body: { error: 'Unknown order' } }\n }\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n // A redelivered click, or the second of two admins. Answered as success\n // because it IS the state the caller asked for — reporting 409 here\n // teaches an admin that the cancel failed and invites a third attempt —\n // but nothing is written, so the units are released exactly once.\n if (order.status === 'cancelled') {\n return {\n status: 200,\n body: { ok: true, alreadyCancelled: true, released: 0, units: 0 },\n }\n }\n if (!CommerceModel.canTransitionOrder(order.status, 'cancelled')) {\n return {\n status: 409,\n body: { error: `Orders in \"${order.status}\" cannot cancel` },\n }\n }\n // An OPEN register sale that has taken money (AGL-3607) is voided at\n // the register, which hands each payment back first. Cancelling it here\n // would mark it cancelled with a card charge, a gift card debit or a\n // room charge still standing.\n if (\n order.status === 'pending' &&\n CommerceModel.orderPayments(order).some(\n (payment) => payment.status === 'succeeded' || payment.status === 'pending',\n ) &&\n Array.isArray(order.payments)\n ) {\n return {\n status: 409,\n body: {\n error:\n 'This register sale has payments on it. Void it at the register, ' +\n 'which hands each payment back first.',\n },\n }\n }\n\n // A POS CARD order's decrement happens in the webhook that pays it —\n // and before AGL-1825 it did not happen AT ALL: the paying branch's\n // decrement was gated on `productId` metadata the register's session\n // never carried. Releasing such an order restocks units that were never\n // taken, turning the silent under-count into a silent over-count. The\n // sale's own ledger is the discriminator: every decrement pairs with a\n // `reason: 'sale'` row (AGL-1807 closed the last hole, and the AGL-1825\n // decrement writes them from day one), so a paid card order with no\n // sale row is one whose sale took nothing — and nothing is released.\n //\n // Scoped to card orders (the `pos-card-pending` timeline event) rather\n // than applied to every order, because one historical path decremented\n // WITHOUT rows — draft links paid before AGL-1807 — and asking the\n // ledger to vouch for those would wrongly strand their stock. The\n // residual is stated plainly: the sibling-shaped decrement/ledger pair\n // is two swallowed sequential writes, so a card order whose ledger add\n // alone failed will not release — a bounded under-count on that one\n // order, visible as a sale missing from the hub's history, against the\n // alternative of inflating stock on every pre-fix cancel.\n //\n // One equality filter, so the automatic single-field index answers it;\n // the reason test runs here, over the handful of rows one order has.\n //\n // THE SAME READ NOW ALSO BOUNDS HOW MUCH COMES BACK (AGL-2149), so it is\n // no longer scoped to card orders. `adjustVariantInventory` floors at\n // zero, and that floor silently absorbs the overshoot on a BACKORDER\n // product: stock 0, `canPurchase` admits the sale because the policy says\n // to, three units sell, `Math.max(0, 0 + -3)` leaves the count at 0 —\n // and a `+3` here would hand the merchant three units nobody has and a\n // stock badge offering them. The sale rows carry `appliedDelta` for\n // exactly this: `delta` stays the units sold (the merchant's history),\n // `appliedDelta` says how many the count could actually give up.\n //\n // Only lines the ledger DESCRIBES are capped. A pair the ledger says\n // nothing about restores as before, which is what keeps the pre-AGL-1807\n // draft links — decremented with no row at all — from having their stock\n // stranded, and what keeps a single swallowed ledger write from turning\n // into a lost restock on an unrelated line of the same order.\n let saleDecremented = true\n // The cap rule itself lives beside the restock flag, which now bounds\n // the question it ASKS by the same ledger this bounds the stock it\n // RETURNS (AGL-2325). One implementation, so a prompt naming more units\n // than a cancellation would put back is not expressible.\n let releaseCap: ReadonlyMap<string, number> = new Map<string, number>()\n if (order.status === 'paid') {\n const orderAdjustments = await transaction.get(\n hostRef\n .collection('inventoryAdjustments')\n .where('orderId', '==', orderId),\n )\n const saleRows = orderAdjustments.docs.filter(\n (row) => row.get('reason') === 'sale',\n )\n if (\n order.channel === 'pos' &&\n (order.timeline ?? []).some(\n (event) => event.event === 'pos-card-pending',\n )\n ) {\n saleDecremented = saleRows.length > 0\n }\n releaseCap = saleReleaseCaps(saleRows)\n }\n\n // `paid` is the only status reachable here whose sale decremented; see\n // the header. Reads happen before any write, as a transaction requires.\n const { lines, products } =\n order.status === 'paid' && saleDecremented\n ? await resolveTrackedRestockLines(hostRef, order, (ref) =>\n transaction.get(ref),\n )\n : {\n lines: [],\n products: new Map<string, CommerceModel.HostProduct>(),\n }\n\n const atMs = Date.now()\n // Grouped by product, because two lines of one product (two variants, or\n // the same variant twice) are two deltas against ONE document: writing\n // them separately would compute both from the same read and land only\n // the last, silently dropping units.\n const byProduct = new Map<string, CommerceModel.OrderRestockLine[]>()\n // Never more than the sale actually took off the shelf (AGL-2149).\n for (const line of capRestockLines(lines, releaseCap)) {\n byProduct.set(line.productId, [\n ...(byProduct.get(line.productId) ?? []),\n line,\n ])\n }\n for (const [productId, productLines] of byProduct) {\n const product = products.get(productId)\n if (!product) continue\n let variants = product.variants\n for (const line of productLines) {\n variants = CommerceModel.adjustVariantInventory(\n { variants },\n line.variantId,\n line.quantity,\n // The bucket the sale came out of, for a location-tracked store\n // (AGL-286). Absent on every path that decremented the flat count,\n // where `adjustVariantInventory` puts it back the same way.\n order.locationId || undefined,\n )\n }\n // `update()`, not `set(…, { merge: true })` as the sale paths use: the\n // transaction has just read this product, so it exists, and a product\n // deleted under us must not be conjured back as a stub holding nothing\n // but a variants array.\n transaction.update(hostRef.collection('products').doc(productId), {\n variants,\n // The total and the storefront's In stock verdict (AGL-3321).\n ...CommerceModel.productStockFields({ ...product, variants }),\n updatedAtMs: atMs,\n })\n for (const line of productLines) {\n transaction.create(hostRef.collection('inventoryAdjustments').doc(), {\n productId,\n variantId: line.variantId,\n delta: line.quantity,\n reason: 'cancellation',\n orderId,\n ...(order.locationId ? { locationId: order.locationId } : {}),\n atMs,\n } satisfies CommerceModel.InventoryAdjustment)\n }\n }\n\n // From the CAPPED lines, not the order's, so the timeline reports what\n // was actually put back (AGL-2149).\n const releasedLines = [...byProduct.values()].flat()\n const units = releasedLines.reduce((sum, line) => sum + line.quantity, 0)\n const patch: Record<string, unknown> = {\n status: 'cancelled',\n // What a shipping tool's feed asks to learn of the cancel (AGL-3613).\n updatedAtMs: atMs,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'cancelled',\n units > 0\n ? `${units} ${units === 1 ? 'unit' : 'units'} returned to stock`\n : undefined,\n atMs,\n ),\n }\n // An open restock question about THIS order's stock, raised by a partial\n // refund before the cancellation (AGL-1797). The units it asked about are\n // the ones just put back, so leaving it open would invite the merchant to\n // restock them a second time from the order dialog — the double-count\n // that flag exists to avoid. Answered with what actually happened.\n if (units > 0 && order.restockCheck && !order.restockCheck.resolution) {\n patch.restockCheck = {\n ...order.restockCheck,\n resolution: 'restocked',\n resolvedAtMs: atMs,\n resolvedBy: decoded.uid,\n } satisfies CommerceModel.OrderRestockCheck\n }\n transaction.update(orderRef, patch)\n return {\n status: 200,\n body: { ok: true, released: releasedLines.length, units },\n // The live Stripe page this cancellation orphans, if any (AGL-2244).\n // Read inside the transaction that flips the status so the expiry\n // below cannot act on an order some other writer paid meanwhile.\n expireSessionId:\n order.status === 'pending' ? (order.checkoutSessionId ?? '') : '',\n }\n })\n // EXPIRE THE PAYMENT LINK (AGL-2244). Cancelling a `pending` draft order or\n // POS card sale left its Checkout Session live: the URL is on the\n // customer's phone or in the email the merchant sent, and Stripe keeps it\n // payable for 24 hours. Paying it captured real money on the merchant's\n // account and the completing webhook then discarded the event — its\n // `status !== 'pending'` guard cannot tell a redelivery from a cancelled\n // order — so the sale existed in Stripe and nowhere in the product: no\n // order, no stock move, no contact, no notification, not even a timeline\n // line. The webhook now says so when it happens; this is the half that\n // stops it happening.\n //\n // OUTSIDE the transaction, because it is a network call, and best-effort\n // by design: the cancellation itself already landed and is what the\n // merchant asked for. A failure here leaves the pre-existing behaviour\n // (a payable link) plus the webhook's new record of it, which is strictly\n // better than failing a cancel that has already released stock. Stripe\n // answers 400 for a session that is already expired or already paid, and\n // both are states this has nothing to add to.\n const expireSessionId = (outcome as { expireSessionId?: string })\n .expireSessionId\n if (expireSessionId && process.env.STRIPE_SECRET_KEY) {\n const expiry = await fetchOnSellerThenPlatform(\n `https://api.stripe.com/v1/checkout/sessions/${expireSessionId}/expire`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n },\n await directSellerAccountForHost(hostId),\n ).catch(() => null)\n if (!expiry?.ok) {\n console.error(\n 'Cancelled order: Stripe session not expired, the payment link may still be payable',\n { hostId, orderId, sessionId: expireSessionId },\n )\n }\n }\n // The buyer is told (AGL-3610) — only by the request that cancelled it.\n if (outcome.status === 200 && !(outcome.body as { alreadyCancelled?: boolean }).alreadyCancelled) {\n await notifyOrderBuyer({ hostId, orderId }, 'cancelled')\n await raiseOrderEvent(ORDER_CANCELLED_EVENT, { hostId, orderId, key: 'cancelled' })\n }\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n // Nothing landed — the transaction is all-or-nothing — so the order is\n // still open and the merchant can try again. Deliberately NOT the swallow\n // `flagOrderRestock` uses: there the money had already moved and only a\n // postscript was at risk; here a swallowed failure is a cancelled order\n // whose stock never came back, which is the bug this closes.\n console.error('cancelOrder failed', error)\n return res.status(500).json({ error: 'Cancel failed' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","holdsCommerceSiteKey","commerceSitePermissionRefusal","CommerceModel","firebaseAdmin","notifyOrderBuyer","ORDER_CANCELLED_EVENT","raiseOrderEvent","capRestockLines","resolveTrackedRestockLines","saleReleaseCaps","cancelOrderHandler","req","res","body","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","orderId","test","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","orderRef","outcome","runTransaction","transaction","snapshot","order","liftLegacyOrder","data","ok","alreadyCancelled","released","units","canTransitionOrder","orderPayments","some","payment","Array","isArray","payments","saleDecremented","releaseCap","Map","orderAdjustments","where","saleRows","docs","filter","row","channel","timeline","event","lines","products","ref","atMs","Date","now","byProduct","line","set","productId","productLines","product","variants","adjustVariantInventory","variantId","quantity","locationId","update","productStockFields","updatedAtMs","create","delta","reason","releasedLines","values","flat","reduce","sum","patch","appendOrderEvent","restockCheck","resolution","resolvedAtMs","resolvedBy","expireSessionId","checkoutSessionId","process","env","STRIPE_SECRET_KEY","expiry","Authorization","catch","console","sessionId","key"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,eAAe,QAAQ,oBAAgB;AAEhD,SACEC,eAAe,EACfC,0BAA0B,EAC1BC,eAAe,QACV,oBAAgB;AAEvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoEC,GACD,OAAO,MAAMC,qBAAuC,OAAOC,KAAKC;QAIjCD,4BAM4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d,uEAAuE;QACvE,0EAA0E;QAC1E,wEAAwE;QACxE,wEAAwE;QACxE,6DAA6D;QAC7DmG,QAAQnG,KAAK,CAAC,sBAAsBA;QACpC,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
|
|
@@ -15,7 +15,8 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
|
|
|
15
15
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
16
|
* See the License for the specific language governing permissions and
|
|
17
17
|
* limitations under the License.
|
|
18
|
-
*/ import {
|
|
18
|
+
*/ import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
|
|
19
|
+
import { randomUUID } from "crypto";
|
|
19
20
|
import { readSiteReturnHost, siteReturnUrl } from "@aglyn/aglyn/app-utils/site-return-url";
|
|
20
21
|
import { advertisingRequestFacts, recordAdvertisingOrderConsent } from "@aglyn/aglyn/plugin-manager/plugin-advertising-conversions";
|
|
21
22
|
import * as Aglyn from "@aglyn/aglyn/server";
|
|
@@ -23,7 +24,7 @@ import * as CommerceModel from "../model/index.js";
|
|
|
23
24
|
import { checkoutRecoveryState } from "../model/checkout-recovery.js";
|
|
24
25
|
import { claimAttempt, deriveStripeObjectKey } from "@aglyn/aglyn/server";
|
|
25
26
|
import { consumeRateLimit, firebaseAdmin, getOrgForHost, isYoungWorkspace } from "@aglyn/tenant-data-admin";
|
|
26
|
-
import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
27
|
+
import { connectedAccountHeader, directChargeParams, merchantAccountIsReady, saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
27
28
|
import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
|
|
28
29
|
import { CARRIER_POSTAL_CODE_MESSAGE, planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
|
|
29
30
|
import { readCartId } from "./cart-cookie.js";
|
|
@@ -150,6 +151,19 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
150
151
|
error: 'This site has not enabled payments yet'
|
|
151
152
|
});
|
|
152
153
|
}
|
|
154
|
+
// DIRECT OR DESTINATION, decided by the seller's account as the profile
|
|
155
|
+
// records it, never by the request. A direct sale is created ON the
|
|
156
|
+
// seller's own Stripe account: every object this handler mints for it
|
|
157
|
+
// (the coupon, the tax rates, the session) carries `Stripe-Account`,
|
|
158
|
+
// because an id from the platform account does not resolve there. A
|
|
159
|
+
// destination seller gets an empty header and today's requests unchanged.
|
|
160
|
+
const chargeModel = saleChargeModel(ownerProfile.get('stripeChargeModel'));
|
|
161
|
+
const direct = chargeModel === 'direct';
|
|
162
|
+
const sellerAccountHeader = connectedAccountHeader(chargeModel, accountId);
|
|
163
|
+
// For the helpers that take the account and add the header themselves.
|
|
164
|
+
const sellerStripeAccount = direct ? {
|
|
165
|
+
stripeAccount: String(accountId)
|
|
166
|
+
} : {};
|
|
153
167
|
// Re-price every line from its doc; any unavailable line blocks.
|
|
154
168
|
const productSnapshots = await Promise.all([
|
|
155
169
|
...new Set(cart.lines.map((line)=>line.productId))
|
|
@@ -972,7 +986,7 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
972
986
|
headers: _extends({
|
|
973
987
|
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
974
988
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
975
|
-
}, stripeKeyHeader(creditHeldCents > 0 ? `coupon-c${creditHeldCents}` : 'coupon')),
|
|
989
|
+
}, stripeKeyHeader(creditHeldCents > 0 ? `coupon-c${creditHeldCents}` : 'coupon'), sellerAccountHeader),
|
|
976
990
|
body: new URLSearchParams({
|
|
977
991
|
amount_off: String(Math.min(totalOffCents, itemsCents)),
|
|
978
992
|
currency: 'usd',
|
|
@@ -1075,7 +1089,18 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1075
1089
|
const chargeCents = chargedItemsCents + // Stripe's cost on the extras is a real cost of this charge, passed
|
|
1076
1090
|
// through at cost like the rest; no take is added on them (AGL-3635).
|
|
1077
1091
|
extrasCents + (engineTax.quote ? engineTax.quote.taxCents : Math.round(chargedItemsCents * manualTaxPct / 100)) + shippingCeilingCents;
|
|
1078
|
-
|
|
1092
|
+
// The take plus the card's 2.9% + 30¢, never below what Stripe charges
|
|
1093
|
+
// the platform for the sale: the payout, and Stripe Tax where it
|
|
1094
|
+
// calculates the tax, come out of the take first (AGL-4198).
|
|
1095
|
+
// A direct sale is the take alone: Stripe bills the seller its card fee
|
|
1096
|
+
// and charges the platform nothing for the sale.
|
|
1097
|
+
feeCents = Aglyn.saleApplicationFeeCents(feeCents, chargeCents, _extends({
|
|
1098
|
+
stripeTax: CommerceModel.storefrontTaxDecision({
|
|
1099
|
+
settings: cartTaxSettings
|
|
1100
|
+
}).kind === 'stripe-automatic'
|
|
1101
|
+
}, direct ? {
|
|
1102
|
+
direct: true
|
|
1103
|
+
} : {}));
|
|
1079
1104
|
}
|
|
1080
1105
|
// THE CONNECT SPLIT IS EMITTED BELOW, NOT HERE (AGL-1956). It used to be
|
|
1081
1106
|
// written at this point, which is ABOVE the tax decision — and the shape
|
|
@@ -1152,6 +1177,18 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1152
1177
|
error: taxMisconfigured
|
|
1153
1178
|
});
|
|
1154
1179
|
}
|
|
1180
|
+
// A direct-charge store's Stripe Tax runs on ITS account, against its
|
|
1181
|
+
// registrations, and Stripe refuses the session where it is not set up.
|
|
1182
|
+
if (direct && taxDecision.kind === 'stripe-automatic' && !await sellerStripeTaxActive(String(accountId))) {
|
|
1183
|
+
await releaseGiftCardHold();
|
|
1184
|
+
await releaseCreditHold();
|
|
1185
|
+
await releasePromotionHolds();
|
|
1186
|
+
await releaseStock();
|
|
1187
|
+
await claim.release();
|
|
1188
|
+
return res.status(409).json({
|
|
1189
|
+
error: SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1155
1192
|
if (taxDecision.kind === 'stripe-automatic') {
|
|
1156
1193
|
params.set('automatic_tax[enabled]', 'true');
|
|
1157
1194
|
} else if (engineTax.quote) {
|
|
@@ -1173,12 +1210,12 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1173
1210
|
for(let position = 0; position < cartEngineLines.length; position++){
|
|
1174
1211
|
const pct = percentages[position];
|
|
1175
1212
|
if (pct === null) continue;
|
|
1176
|
-
const taxRateId = await resolveManualTaxRateId({
|
|
1213
|
+
const taxRateId = await resolveManualTaxRateId(_extends({
|
|
1177
1214
|
hostRef,
|
|
1178
1215
|
taxPct: pct,
|
|
1179
1216
|
taxLabel: 'Sales tax',
|
|
1180
1217
|
headers: stripeKeyHeader(`tax-rate-engine-${Math.round(pct * 10000)}`)
|
|
1181
|
-
});
|
|
1218
|
+
}, sellerStripeAccount));
|
|
1182
1219
|
if (!taxRateId) {
|
|
1183
1220
|
// The same visible refusal as the store's own rate: never an
|
|
1184
1221
|
// untaxed session.
|
|
@@ -1215,12 +1252,12 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1215
1252
|
return !((_productsById_get = productsById.get(line.productId)) == null ? void 0 : _productsById_get.taxExempt);
|
|
1216
1253
|
}).map(({ index })=>index);
|
|
1217
1254
|
if (rate && rate.pct > 0 && taxableIndexes.length > 0) {
|
|
1218
|
-
const taxRateId = await resolveManualTaxRateId({
|
|
1255
|
+
const taxRateId = await resolveManualTaxRateId(_extends({
|
|
1219
1256
|
hostRef,
|
|
1220
1257
|
taxPct: rate.pct,
|
|
1221
1258
|
taxLabel: rate.label || `Tax (${rate.pct}%)`,
|
|
1222
1259
|
headers: stripeKeyHeader('tax-rate')
|
|
1223
|
-
});
|
|
1260
|
+
}, sellerStripeAccount));
|
|
1224
1261
|
if (!taxRateId) {
|
|
1225
1262
|
// A VISIBLE refusal, never a fallback to an untaxed session — that
|
|
1226
1263
|
// silent under-collection is this issue. Nothing was sold, so the
|
|
@@ -1272,9 +1309,14 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1272
1309
|
// merchant. A manual-rate or untaxed cart keeps the fee form byte for
|
|
1273
1310
|
// byte. See `commerce-connect-transfer.ts` for why only one of the two
|
|
1274
1311
|
// knobs may ever be present.
|
|
1275
|
-
|
|
1312
|
+
//
|
|
1313
|
+
// A DIRECT sale has none of that: Stripe Tax computes against the SELLER's
|
|
1314
|
+
// registrations and the seller owns the tax, the money is already in the
|
|
1315
|
+
// seller's balance, so there is nothing to transfer and no tax for Aglyn
|
|
1316
|
+
// to hold back. The split is the take as `application_fee_amount`.
|
|
1317
|
+
const cartTaxOwner = !direct && taxDecision.kind === 'stripe-automatic' ? 'platform' : 'merchant';
|
|
1276
1318
|
const cartShippingFloorCents = CommerceModel.shippingFloorCents(shippingOptions);
|
|
1277
|
-
Object.entries(CommerceModel.destinationChargeParams({
|
|
1319
|
+
Object.entries(direct ? directChargeParams(feeCents) : CommerceModel.destinationChargeParams({
|
|
1278
1320
|
accountId: String(accountId),
|
|
1279
1321
|
feeCents,
|
|
1280
1322
|
taxOwner: cartTaxOwner,
|
|
@@ -1282,6 +1324,8 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1282
1324
|
merchantGoodsCents: chargedItemsCents + extrasCents,
|
|
1283
1325
|
shippingFloorCents: cartShippingFloorCents
|
|
1284
1326
|
})).forEach(([key, value])=>params.set(key, value));
|
|
1327
|
+
// So the webhook, refunds and reports read the sale on the right account.
|
|
1328
|
+
if (direct) params.set('metadata[chargeModel]', 'direct');
|
|
1285
1329
|
params.set('metadata[type]', 'commerce-cart');
|
|
1286
1330
|
// How the order reaches the buyer (AGL-3624): the webhook routes it.
|
|
1287
1331
|
if (localPlan.kind === 'pickup' || localPlan.kind === 'local_delivery') {
|
|
@@ -1339,17 +1383,19 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1339
1383
|
}
|
|
1340
1384
|
// Apple Pay shows on a registered domain only (AGL-3629): registered
|
|
1341
1385
|
// beside the session create, inside a budget, never failing the sale.
|
|
1342
|
-
|
|
1386
|
+
// A direct sale's wallets answer to the seller's account, so the domain is
|
|
1387
|
+
// registered there.
|
|
1388
|
+
const domainRegistration = nativeMode.native ? ensureCheckoutDomain(_extends({
|
|
1343
1389
|
pageUrl: backUrl,
|
|
1344
1390
|
site: returnSite,
|
|
1345
1391
|
hostId
|
|
1346
|
-
}).catch(()=>null) : Promise.resolve(null);
|
|
1392
|
+
}, sellerStripeAccount)).catch(()=>null) : Promise.resolve(null);
|
|
1347
1393
|
const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {
|
|
1348
1394
|
method: 'POST',
|
|
1349
1395
|
headers: _extends({
|
|
1350
1396
|
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
1351
1397
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
1352
|
-
}, stripeKeyHeader(`${engineTax.stamp ? `session-tax-${(_ref6 = (_engineTax_quote = engineTax.quote) == null ? void 0 : _engineTax_quote.taxCents) != null ? _ref6 : 'own'}-${engineTax.stamp.status}` : 'session'}${extrasCents > 0 ? `-x${extrasCents}` : ''}${creditHeldCents > 0 ? `-c${creditHeldCents}` : ''}`), nativeCheckoutStripeHeaders(nativeMode)),
|
|
1398
|
+
}, stripeKeyHeader(`${engineTax.stamp ? `session-tax-${(_ref6 = (_engineTax_quote = engineTax.quote) == null ? void 0 : _engineTax_quote.taxCents) != null ? _ref6 : 'own'}-${engineTax.stamp.status}` : 'session'}${extrasCents > 0 ? `-x${extrasCents}` : ''}${creditHeldCents > 0 ? `-c${creditHeldCents}` : ''}`), nativeCheckoutStripeHeaders(nativeMode), sellerAccountHeader),
|
|
1353
1399
|
body: params.toString()
|
|
1354
1400
|
});
|
|
1355
1401
|
const session = await response.json();
|
|
@@ -1358,7 +1404,8 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
|
|
|
1358
1404
|
// session reads as a Stripe failure: a 502 at the shopper, a released claim,
|
|
1359
1405
|
// and a real Checkout Session left open on the merchant's account.
|
|
1360
1406
|
await domainRegistration;
|
|
1361
|
-
const payload = response.ok ? readCheckoutSessionPayload(session, nativeMode, paymentMethodControls.wallets
|
|
1407
|
+
const payload = response.ok ? readCheckoutSessionPayload(session, nativeMode, paymentMethodControls.wallets, // The in-page form mounts a direct sale's session on that account.
|
|
1408
|
+
direct ? String(accountId) : undefined) : null;
|
|
1362
1409
|
if (!payload) {
|
|
1363
1410
|
console.error('Stripe cart checkout error', session.error);
|
|
1364
1411
|
// The checkout did not happen — hand the key back so one flaky moment
|