@tokenoftrust/storefront-runner 7.3.1 → 7.5.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.
Files changed (414) hide show
  1. package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
  2. package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
  3. package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
  4. package/apps/storefront/astro.config.mjs +8 -2
  5. package/apps/storefront/package.json +1 -2
  6. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
  7. package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
  8. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
  9. package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
  10. package/apps/storefront/src/layouts/Layout.astro +17 -0
  11. package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
  12. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +147 -0
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +67 -1
  14. package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
  15. package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
  16. package/apps/storefront/src/lib/access/auth/session.ts +79 -0
  17. package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
  18. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  19. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  20. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  21. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  22. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  23. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  24. package/apps/storefront/src/lib/activity/store.ts +9 -3
  25. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  26. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  27. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  28. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  29. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  30. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  31. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
  32. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  33. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  34. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  35. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  36. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  37. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  38. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  39. package/apps/storefront/src/middleware/index.ts +40 -1
  40. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  41. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  42. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  43. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  44. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  45. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  46. package/apps/storefront/tsconfig.astro.json +11 -0
  47. package/package.json +1 -1
  48. package/packages/public-runtime/src/activity/README.md +12 -0
  49. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  50. package/packages/public-runtime/src/activity/event.ts +19 -0
  51. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  52. package/packages/public-runtime/src/catalog-files.ts +3 -2
  53. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  54. package/packages/public-runtime/src/checkout.ts +70 -0
  55. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  56. package/packages/public-runtime/src/compliance/index.ts +1 -1
  57. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  58. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  59. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  60. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  61. package/packages/public-runtime/src/product.ts +9 -1
  62. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  63. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  64. package/pnpm-lock.runner.yaml +0 -15
  65. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  66. package/scripts/tenant/validate.mjs +128 -0
  67. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  68. package/apps/storefront/drizzle.config.apps.ts +0 -13
  69. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  70. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  71. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  72. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  73. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  74. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  75. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  76. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  77. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  78. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  79. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  80. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  81. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  82. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  83. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  84. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  85. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  86. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  87. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  88. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  89. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  90. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  91. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  92. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  93. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  94. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  95. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  96. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  97. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  98. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  99. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  100. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  101. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  102. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  103. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  104. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  105. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  106. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  107. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  108. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  109. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  110. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  111. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  112. package/apps/storefront/perf/README.md +0 -64
  113. package/apps/storefront/perf/assert-budgets.ts +0 -159
  114. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  115. package/apps/storefront/playwright.config.ts +0 -23
  116. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  117. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  118. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  119. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  120. package/apps/storefront/public/js/dashboard-team.js +0 -356
  121. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  122. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  123. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  124. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  125. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  126. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  127. package/apps/storefront/src/config/storeName.ts +0 -34
  128. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  129. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  130. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  131. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  132. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  133. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  134. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  135. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  136. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  137. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -150
  138. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -452
  139. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  140. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  141. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  142. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  143. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  144. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  145. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  146. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  147. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  148. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  149. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  150. package/apps/storefront/src/lib/activity/query.ts +0 -403
  151. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  152. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  153. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  154. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  155. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  156. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  157. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  158. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  159. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  160. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  161. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  162. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  163. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  164. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  165. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  166. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  167. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  168. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  169. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  172. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  173. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  174. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  175. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  176. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  177. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  178. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  179. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  180. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  181. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  182. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  183. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  184. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  185. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  186. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  187. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  188. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  189. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  190. package/apps/storefront/src/lib/content/index.ts +0 -27
  191. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  192. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  193. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  194. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  195. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  196. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  197. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  198. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  199. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  200. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  201. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  202. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  203. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  204. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  205. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  206. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  207. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  208. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  209. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  210. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  211. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  212. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  213. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  214. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  215. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  216. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  221. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  222. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  223. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  224. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  225. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  226. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  227. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  228. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  229. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  230. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  231. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  232. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  233. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  234. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  235. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  236. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  237. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  238. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  239. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  240. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  241. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  242. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  243. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  244. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  245. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  246. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  247. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  248. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  249. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  250. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  251. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  252. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  253. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  254. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  255. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  256. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  257. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  258. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  259. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  260. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  261. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  262. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  263. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  264. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  265. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  266. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  267. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  268. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  269. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  270. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  271. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  272. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  273. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  274. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  275. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  276. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  277. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  278. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  279. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  280. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  281. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  282. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  283. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  284. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  285. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  286. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  287. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  288. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  289. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  290. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  291. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  292. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  293. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  294. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  295. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  296. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  297. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  298. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  299. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  300. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  301. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  302. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  303. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  304. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  305. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  306. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  307. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  308. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  309. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  310. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  311. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  312. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  313. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  314. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  315. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  316. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  317. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  318. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  319. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  320. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  321. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  322. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  323. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  324. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  325. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  326. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  327. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  328. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  329. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  330. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  331. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  332. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  333. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  334. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  335. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  336. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  337. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  338. package/apps/storefront/src/pages/api/contact.ts +0 -144
  339. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  340. package/apps/storefront/src/styles/admin.css +0 -1161
  341. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  342. package/apps/storefront/test/pipeline/harness.ts +0 -209
  343. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  344. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  345. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  346. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  347. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  348. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  349. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  350. package/apps/storefront/vitest.config.cts +0 -44
  351. package/apps/storefront/vitest.faults.config.cts +0 -13
  352. package/apps/storefront/vitest.workers.config.cts +0 -7
  353. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  354. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  355. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  356. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  357. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  358. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  359. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  360. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  361. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  362. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  363. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  364. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  365. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  366. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  367. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  368. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  369. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  370. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  371. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  372. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  373. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  374. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  375. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  376. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  377. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  378. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  379. package/packages/feedback/package.json +0 -35
  380. package/packages/feedback/scripts/build-player.mjs +0 -28
  381. package/packages/feedback/src/index.ts +0 -1
  382. package/packages/feedback/src/primitives/composer.ts +0 -639
  383. package/packages/feedback/src/primitives/dialog.ts +0 -263
  384. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  385. package/packages/feedback/src/primitives/index.ts +0 -10
  386. package/packages/feedback/src/primitives/launcher.ts +0 -200
  387. package/packages/feedback/src/primitives/picker.ts +0 -663
  388. package/packages/feedback/src/primitives/redaction.ts +0 -204
  389. package/packages/feedback/src/primitives/selection.ts +0 -49
  390. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  391. package/packages/feedback/src/primitives/styles.ts +0 -77
  392. package/packages/feedback/src/primitives/surface.ts +0 -124
  393. package/packages/feedback/src/primitives/target.ts +0 -293
  394. package/packages/feedback/src/tour/canonical.ts +0 -27
  395. package/packages/feedback/src/tour/index.ts +0 -3
  396. package/packages/feedback/src/tour/player/browser.ts +0 -5
  397. package/packages/feedback/src/tour/player/host.ts +0 -12
  398. package/packages/feedback/src/tour/player/index.ts +0 -205
  399. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  400. package/packages/feedback/src/tour/player/player.css +0 -130
  401. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  402. package/packages/feedback/src/tour/player/surface.ts +0 -295
  403. package/packages/feedback/src/tour/player/types.ts +0 -8
  404. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  405. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  406. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  407. package/packages/feedback/src/tour/sanitize.ts +0 -76
  408. package/packages/feedback/src/tour/schema.ts +0 -362
  409. package/packages/feedback/src/v1/guards.ts +0 -335
  410. package/packages/feedback/src/v1/index.ts +0 -3
  411. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  412. package/packages/feedback/src/v1/types.ts +0 -177
  413. package/packages/feedback/tsconfig.json +0 -9
  414. package/packages/feedback/vitest.config.cts +0 -21
@@ -1,2842 +0,0 @@
1
- /**
2
- * Whole-order fulfillment commands.
3
- *
4
- * `decideCommerceCommand` is the commerce decision core. This service stores the
5
- * result. It does not call a carrier, does not select a vendor, and does not
6
- * read the admin fulfillment mock. Label purchase stays an intent row for a
7
- * separate adapter. UI fields are not source truth.
8
- */
9
- import { authorityHolds, authorityFence, type AuthorityRow, type SourceReadiness } from "../orders/data/sourceAuthorityStore.js";
10
- import type { APIContext } from "astro";
11
- import {
12
- COMPLIANCE_STATES,
13
- EVIDENCE_STATES,
14
- FULFILLMENT_STATES,
15
- LABEL_STATES,
16
- PAYMENT_STATES,
17
- STOCK_STATES,
18
- actorMayCommand,
19
- decideCommerceCommand,
20
- publicCommerceEvent,
21
- totalsMatch,
22
- type CommerceActor,
23
- type CommerceEvidence,
24
- type CommerceStage,
25
- type ComplianceState,
26
- type FulfillmentState,
27
- type LabelState,
28
- type MinorTotals,
29
- type PaymentState,
30
- type ProviderOutcome,
31
- type StockState,
32
- type OrderContactState,
33
- } from "@tot/public-runtime";
34
- import { readD1 } from "@/lib/publication/shared/env";
35
- import { readOrderContactAvailability, terminalTransitionExpiryStatement } from "@/lib/orders/vault/orderContactVault.js";
36
- import { decideAdminApiAccess } from "@/lib/access/auth/adminApiGuard";
37
- import { readViewerSession } from "@/lib/access/auth/route";
38
- import type { SessionRecord } from "@/lib/access/auth/session";
39
- import {
40
- canRelease,
41
- carrierEvidenceRefusal,
42
- carrierPolicyForTenant,
43
- carrierSelectionRefusal,
44
- handoffRefusal,
45
- releaseHolds,
46
- type CarrierPolicy,
47
- type ReadinessInput,
48
- type ReleaseHold,
49
- } from "./readiness.js";
50
- import {
51
- fulfillmentDbFromD1,
52
- type FulfillmentDatabase,
53
- type SqlStatement,
54
- } from "./store.js";
55
- import {
56
- DEFAULT_LOCATION,
57
- PROCESSOR_SCOPE,
58
- assignmentAtGate,
59
- insertAssignmentLinesStatements,
60
- insertAssignmentStatement,
61
- moveAssignmentStatement,
62
- processorGuard,
63
- readOpenAssignment,
64
- resolveProcessor,
65
- routeOrderLines,
66
- type AssignmentState,
67
- type OpenAssignment,
68
- type ProcessorConfig,
69
- type RoutedLine,
70
- } from "./assignmentStore.js";
71
- import {
72
- CommercePayloadRefused,
73
- commerceEventStatements,
74
- commerceTargetsQuery,
75
- } from "../integrations/webhooks/deliveryStore.js";
76
- import { dispatchCommerceDeliveries } from "./commerceRuntime.js";
77
- import type { CommerceTopic } from "../integrations/webhooks/commercePayloads.js";
78
- import { claimedByEventGate, handoffClaimStatement } from "../integrations/webhooks/orderFulfilledClaim.js";
79
- import { checkIdempotency, computeBodyHash } from "../integrations/apps/orders/idempotency.js";
80
- import type { Queryable } from "../catalog/d1/catalog.js";
81
- import {
82
- IDEMPOTENCY_KEY,
83
- appRefusal,
84
- appWritePredicate,
85
- idempotencyInsertStatement,
86
- labelOutcomeRecord,
87
- labelVoidedRecord,
88
- parseStoredLabelFacts,
89
- replayedResponse,
90
- sameLabelFacts,
91
- type AppAssignmentBinding,
92
- type AppEvidenceResponse,
93
- type AppShipmentView,
94
- type AppWriteView,
95
- type HandoffEvidence,
96
- type LabelOutcomeEvidence,
97
- type LabelVoidedEvidence,
98
- type StoredLabelFacts,
99
- } from "./appShipmentEvidence.js";
100
- import {
101
- allowedCarriers,
102
- completesLines,
103
- consumeLinesStatements,
104
- insertExceptionStatement,
105
- insertShipmentStatement,
106
- lineRefusal,
107
- orderCommittedAt,
108
- readAssignmentLines,
109
- readOpenExceptions,
110
- remainingLines,
111
- remainingQuantity,
112
- shipmentCarrierRefusal,
113
- shipmentCommittedGate,
114
- type AssignmentExceptionEvidence,
115
- type AssignmentExceptionRecord,
116
- type AssignmentShipmentEvidence,
117
- } from "./splitShipments.js";
118
-
119
- export const OPAQUE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
120
-
121
- export function isOpaqueId(value: string): boolean {
122
- return OPAQUE_ID.test(value) && !value.includes("@");
123
- }
124
-
125
- export interface FulfillmentActor extends CommerceActor {
126
- actorId: string;
127
- }
128
-
129
- export interface SourceOrderSnapshot {
130
- sourceVersion?: number;
131
- evidenceExpiresAt?: string;
132
- tenantId: string;
133
- stage: CommerceStage;
134
- orderId: string;
135
- source: string;
136
- sourceOrderId: string;
137
- currency: string;
138
- placedAt: string;
139
- payment: PaymentState;
140
- compliance: ComplianceState;
141
- stock: StockState;
142
- fulfillment: FulfillmentState;
143
- label: LabelState;
144
- amountMinor: number;
145
- totals: MinorTotals;
146
- evidence: CommerceEvidence;
147
- lines: readonly { sku: string; quantity: number }[];
148
- }
149
-
150
- export interface PackingSlip {
151
- orderId: string;
152
- currency: string;
153
- lines: { sku: string; quantity: number }[];
154
- adultSignatureRequired: boolean;
155
- prohibitedCarriers: string[];
156
- }
157
-
158
- export type BatchPhase = "claimed" | "picked" | "packed";
159
-
160
- export interface ShipmentIntentView {
161
- scope: "whole-order";
162
- purchaseId: string | null;
163
- labelPurchaseState: string;
164
- handoffState: string;
165
- vendorSelected: false;
166
- carrierAccountId: string | null;
167
- adultSignatureRequired: boolean;
168
- prohibitedCarriers: string[];
169
- /** The recorded label's carrier, service and tracking, as the processor reported them. */
170
- carrier: string | null;
171
- service: string | null;
172
- trackingNumber: string | null;
173
- trackingUrl: string | null;
174
- }
175
-
176
- export interface FulfillmentView {
177
- orderId: string;
178
- tenantId: string;
179
- stage: CommerceStage;
180
- eventVersion: number;
181
- payment: PaymentState;
182
- compliance: ComplianceState;
183
- stock: StockState;
184
- fulfillment: FulfillmentState;
185
- label: LabelState;
186
- holds: ReleaseHold[];
187
- canRelease: boolean;
188
- canHandOff: boolean;
189
- batch: { batchId: string; phase: BatchPhase } | null;
190
- shipment: ShipmentIntentView | null;
191
- packingSlip: PackingSlip | null;
192
- lines: {sku:string;quantity:number}[];
193
- evidence: CommerceEvidence;
194
- placedAt: string;
195
- currency: string;
196
- /** The processor install the order routes to (its location's, else the catch-all), when one is configured. */
197
- processor: { installId: string; locationId: string; notifiable: boolean } | null;
198
- /** The order's open assignment and the install that owns it. */
199
- assignment: { assignmentId: string; installId: string; state: "active" | "held" } | null;
200
- /** Lines the processor reported it cannot ship, awaiting the operator, oldest first. */
201
- exceptions: AssignmentExceptionRecord[];
202
- }
203
-
204
- export interface FulfillmentBatch {
205
- batchId: string;
206
- orders: { orderId: string; phase: BatchPhase }[];
207
- }
208
-
209
- export interface FulfillmentCommandOptions {
210
- expectedVersion?: number;
211
- scope?: string;
212
- carrier?: string;
213
- lines?: unknown;
214
- }
215
-
216
- export interface LabelOutcomeInput {
217
- outcome: "purchased" | "unknown" | "voided";
218
- adultSignature: "accepted" | "refused" | "absent";
219
- carrier?: string;
220
- expectedVersion?: number;
221
- }
222
-
223
- export type FulfillmentResult<T> =
224
- | { ok: true; value: T }
225
- | { ok: false; code: string; holds?: readonly ReleaseHold[] };
226
-
227
- interface LoadedOrder {
228
- shipTo: OrderContactState;
229
- sourceAuthority: AuthorityRow|null;
230
- sourceHolds: SourceReadiness[];
231
- order: {
232
- tenantId: string;
233
- stage: CommerceStage;
234
- orderId: string;
235
- source: string;
236
- sourceOrderId: string;
237
- currency: string;
238
- placedAt: string;
239
- payment: PaymentState;
240
- compliance: ComplianceState;
241
- stock: StockState;
242
- fulfillment: FulfillmentState;
243
- label: LabelState;
244
- amountMinor: number;
245
- eventVersion: number;
246
- };
247
- evidence: CommerceEvidence;
248
- lines: { sku: string; quantity: number }[];
249
- totals: MinorTotals | null;
250
- batch: { batchId: string; phase: BatchPhase } | null;
251
- operatorHold: boolean;
252
- cancelPending: boolean;
253
- packingSlip: PackingSlip | null;
254
- shipment: { labelPurchaseState: string; handoffState: string } | null;
255
- /** The open label_purchase operation (intent, accepted or unknown), or null when none is open. */
256
- provider: { purchaseId: string; outcome: ProviderOutcome } | null;
257
- /** The latest settled label_purchase operation, read only by the desk's label outcome and view. */
258
- settledProvider: { purchaseId: string; outcome: ProviderOutcome } | null;
259
- /** The number of voided label_purchase operations: the purchase attempt the next id belongs to. */
260
- labelGeneration: number;
261
- labelOutcome: StoredLabelFacts | null;
262
- carrierAccountId: string | null;
263
- prohibitedCarriers: string[];
264
- adultSignatureRequired: boolean;
265
- auditCount: number;
266
- /** The order's lines by sku with their inventory locations, and the location it routes through. */
267
- routing: { locationId: string; lines: RoutedLine[] };
268
- processor: ProcessorConfig | null;
269
- assignment: OpenAssignment | null;
270
- view: FulfillmentView;
271
- }
272
-
273
- interface PlannedDelivery {
274
- index: number;
275
- deliveryId: string;
276
- }
277
-
278
- type CommitPlan =
279
- | { type: "done"; view: FulfillmentView }
280
- | { type: "refuse"; code: string; holds?: readonly ReleaseHold[] }
281
- | {
282
- type: "write";
283
- statements: SqlStatement[];
284
- minimumChanges: number;
285
- sourceAdvance?: boolean;
286
- /** Delivery rows the batch writes; the committed ones are handed to `notify`. */
287
- deliveries?: readonly PlannedDelivery[];
288
- /** An assignment plan: a CAS miss re-runs build (bound to its install) even with expectedVersion. */
289
- assignment?: boolean;
290
- };
291
-
292
- /** One app write: the install actor (built only by the route), the order, the key, the raw and parsed body. */
293
- export interface AppEvidenceRequest<T> {
294
- actor: FulfillmentActor;
295
- orderId: string;
296
- idempotencyKey: string;
297
- body: unknown;
298
- evidence: T;
299
- }
300
-
301
- /** One assignment-scoped app write: the order is the one the bound assignment names. */
302
- export interface AssignmentWriteRequest<T> {
303
- actor: FulfillmentActor;
304
- idempotencyKey: string;
305
- body: unknown;
306
- evidence: T;
307
- }
308
-
309
- /** Label states a split shipment proceeds under: no whole-order label is in flight. */
310
- const SPLIT_LABEL_STATES: readonly LabelState[] = ["none", "voided"];
311
-
312
- type AppPlan =
313
- | { type: "done"; view: AppWriteView }
314
- | { type: "refuse"; code: string; holds?: readonly string[] }
315
- | {
316
- type: "write";
317
- statements: SqlStatement[];
318
- sourceAdvance: boolean;
319
- deliveries: readonly PlannedDelivery[];
320
- /** The planned post-state: the response and the idempotency record. */
321
- view: AppWriteView;
322
- };
323
-
324
- /** Statement and delivery accumulator for a plan that may carry commerce events. */
325
- interface PlanStatements {
326
- statements: SqlStatement[];
327
- deliveries: PlannedDelivery[];
328
- }
329
-
330
- /** Statuses an open assignment reports in its lifecycle event. */
331
- type ReportedAssignmentState = Exclude<AssignmentState, "released">;
332
-
333
- const FAIL_CLOSED_EVIDENCE: CommerceEvidence = {
334
- verification: "unreadable",
335
- tax: "unreadable",
336
- risk: "unreadable",
337
- stock: "unreadable",
338
- };
339
-
340
- const LABEL_RANK: Record<LabelState, number> = {
341
- UNKNOWN: 0,
342
- none: 1,
343
- voided: 1,
344
- intent: 2,
345
- void_requested: 3,
346
- purchased: 4,
347
- printed: 5,
348
- };
349
-
350
- const FORBIDDEN_BODY_KEYS = new Set([
351
- "address",
352
- "email",
353
- "phone",
354
- "line1",
355
- "line2",
356
- "postalCode",
357
- "name",
358
- "customer",
359
- ]);
360
-
361
- function refuse(code: string, holds?: readonly ReleaseHold[]): FulfillmentResult<never> {
362
- return holds && holds.length > 0 ? { ok: false, code, holds } : { ok: false, code };
363
- }
364
-
365
- function ok<T>(value: T): FulfillmentResult<T> {
366
- return { ok: true, value };
367
- }
368
-
369
- function isRecord(value: unknown): value is Record<string, unknown> {
370
- return typeof value === "object" && value !== null && !Array.isArray(value);
371
- }
372
-
373
- function oneOf<T extends string>(value: unknown, allowed: readonly T[]): value is T {
374
- return typeof value === "string" && (allowed as readonly string[]).includes(value);
375
- }
376
-
377
- function phaseRank(phase: BatchPhase | null): number {
378
- if (phase === "packed") return 3;
379
- if (phase === "picked") return 2;
380
- if (phase === "claimed") return 1;
381
- return 0;
382
- }
383
-
384
- function stamp(now: string, n: number): string {
385
- return `${now}#${String(n).padStart(6, "0")}`;
386
- }
387
-
388
- function jsonText(value: unknown): string {
389
- return JSON.stringify(value);
390
- }
391
-
392
- function containsForbiddenKey(value: unknown): boolean {
393
- if (!isRecord(value) && !Array.isArray(value)) return false;
394
- for (const [key, child] of Object.entries(value)) {
395
- if (FORBIDDEN_BODY_KEYS.has(key) || containsForbiddenKey(child)) return true;
396
- }
397
- return false;
398
- }
399
-
400
- async function digestHex(content: string): Promise<string> {
401
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(content));
402
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
403
- }
404
-
405
- /**
406
- * The platform purchase id of an order's label attempt. `generation` is the number of voided
407
- * label_purchase operations for the order, so each attempt after a void has a distinct id and a
408
- * message naming an earlier attempt cannot touch the current one. Generation 0 omits the suffix.
409
- */
410
- async function purchaseIdFor(tenantId: string, stage: CommerceStage, orderId: string, generation: number): Promise<string> {
411
- const suffix = generation > 0 ? `\n${generation}` : "";
412
- const digest = await digestHex(`scrappy-label-intent-v1\n${tenantId}\n${stage}\n${orderId}${suffix}`);
413
- return `label_${digest.slice(0, 32)}`;
414
- }
415
-
416
- /** The purchase ids an app message is judged against: this attempt's, and the just-voided one's. */
417
- interface PurchaseAttempt {
418
- current: string;
419
- previous: string | null;
420
- }
421
-
422
- /**
423
- * Where a message's purchase id stands. `current` names this attempt (and the open operation, when
424
- * one is open). `settled` names the just-voided attempt while no newer attempt is open. Anything
425
- * else is `stale`.
426
- */
427
- function attemptStanding(state: LoadedOrder, attempt: PurchaseAttempt, purchaseId: string): "current" | "settled" | "stale" {
428
- if (state.provider) return state.provider.purchaseId === attempt.current && purchaseId === attempt.current ? "current" : "stale";
429
- if (purchaseId === attempt.current) return "current";
430
- return attempt.previous !== null && purchaseId === attempt.previous ? "settled" : "stale";
431
- }
432
-
433
- async function purchaseAttempt(order: LoadedOrder["order"], generation: number): Promise<PurchaseAttempt> {
434
- return {
435
- current: await purchaseIdFor(order.tenantId, order.stage, order.orderId, generation),
436
- previous: generation > 0 ? await purchaseIdFor(order.tenantId, order.stage, order.orderId, generation - 1) : null,
437
- };
438
- }
439
-
440
- function observedEvent(input: {
441
- eventVersion: number;
442
- orderId: string;
443
- placedAt: string;
444
- currency: string;
445
- payment: PaymentState;
446
- compliance: ComplianceState;
447
- stock: StockState;
448
- fulfillment: FulfillmentState;
449
- label: LabelState;
450
- totals: MinorTotals;
451
- evidence: CommerceEvidence;
452
- }): string {
453
- return jsonText(
454
- publicCommerceEvent({
455
- eventVersion: input.eventVersion,
456
- orderId: input.orderId,
457
- placedAt: input.placedAt,
458
- currency: input.currency,
459
- payment: input.payment,
460
- compliance: input.compliance,
461
- stock: input.stock,
462
- fulfillment: input.fulfillment,
463
- label: input.label,
464
- totals: input.totals,
465
- verificationDetail: input.evidence,
466
- }),
467
- );
468
- }
469
-
470
- function mergePayment(local: PaymentState | null, source: PaymentState): PaymentState {
471
- if (local && ["refund_requested", "refund_unknown", "refunded", "voided"].includes(local) &&
472
- ["UNKNOWN", "pending", "authorized", "captured", "capture_unknown"].includes(source)) return local;
473
- if (local === "refunded") return local;
474
- return source;
475
- }
476
-
477
- function mergeLabel(local: LabelState | null, source: LabelState): LabelState {
478
- if (!local) return source;
479
- return LABEL_RANK[local] >= LABEL_RANK[source] ? local : source;
480
- }
481
-
482
- function parseEvidence(value: unknown): CommerceEvidence | null {
483
- if (!isRecord(value)) return null;
484
- const verification = value.verification;
485
- const tax = value.tax;
486
- const risk = value.risk;
487
- const stock = value.stock;
488
- if (!oneOf(verification, EVIDENCE_STATES) || !oneOf(tax, EVIDENCE_STATES) || !oneOf(risk, EVIDENCE_STATES) || !oneOf(stock, EVIDENCE_STATES)) {
489
- return null;
490
- }
491
- return { verification, tax, risk, stock };
492
- }
493
-
494
- function parseLines(value: unknown): { sku: string; quantity: number }[] | null {
495
- if (!Array.isArray(value)) return null;
496
- const lines: { sku: string; quantity: number }[] = [];
497
- for (const entry of value) {
498
- if (!isRecord(entry) || typeof entry.sku !== "string" || !isOpaqueId(entry.sku)) return null;
499
- if (!Number.isSafeInteger(entry.quantity) || Number(entry.quantity) < 1) return null;
500
- lines.push({ sku: entry.sku, quantity: Number(entry.quantity) });
501
- }
502
- return lines;
503
- }
504
-
505
- function parseTotals(value: unknown): MinorTotals | null {
506
- if (!isRecord(value)) return null;
507
- const totals = {
508
- subtotalMinor: Number(value.subtotalMinor),
509
- shippingMinor: Number(value.shippingMinor),
510
- taxMinor: Number(value.taxMinor),
511
- totalMinor: Number(value.totalMinor),
512
- };
513
- if (
514
- !Number.isSafeInteger(totals.subtotalMinor) ||
515
- !Number.isSafeInteger(totals.shippingMinor) ||
516
- !Number.isSafeInteger(totals.taxMinor) ||
517
- !Number.isSafeInteger(totals.totalMinor)
518
- ) {
519
- return null;
520
- }
521
- return totals;
522
- }
523
-
524
- function auditStatement(
525
- state: { order: LoadedOrder["order"] },
526
- actorId: string,
527
- kind: string,
528
- fromState: string,
529
- toState: string,
530
- version: number,
531
- at: string,
532
- ): SqlStatement {
533
- return {
534
- sql: `INSERT INTO scrappy_shipment_audit (
535
- audit_id, tenant_id, stage, order_id, at, actor_id, kind, from_state, to_state
536
- )
537
- SELECT ?, tenant_id, stage, order_id, ?, ?, ?, ?, ?
538
- FROM scrappy_commerce_orders
539
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?`,
540
- params: [
541
- `audit_${crypto.randomUUID()}`,
542
- at,
543
- actorId,
544
- kind,
545
- fromState,
546
- toState,
547
- state.order.tenantId,
548
- state.order.stage,
549
- state.order.orderId,
550
- version,
551
- ],
552
- };
553
- }
554
-
555
- export function commerceStageForEnv(env: string | undefined): CommerceStage | null {
556
- if (env === "live") return "publication";
557
- if (env === "test") return "preview";
558
- return null;
559
- }
560
-
561
- export function decideFulfillmentAccess(input: {
562
- record: SessionRecord | null | undefined;
563
- hostResource: string;
564
- nowSeconds: number;
565
- customizationEnv: string | undefined;
566
- subject: string | undefined;
567
- bodyTenantId?: string | null;
568
- }): { ok: true; actor: FulfillmentActor } | { ok: false; status: 401 | 403 | 409; code: string } {
569
- const access = decideAdminApiAccess({
570
- record: input.record,
571
- hostResource: input.hostResource,
572
- nowSeconds: input.nowSeconds,
573
- requireOwner: true,
574
- });
575
- if (!access.ok) return { ok: false, status: access.status, code: access.reason };
576
- const stage = commerceStageForEnv(input.customizationEnv);
577
- if (!stage) return { ok: false, status: 409, code: "stage-unknown" };
578
- const host = input.hostResource.trim();
579
- if (!host) return { ok: false, status: 403, code: "denied" };
580
- if (input.bodyTenantId && input.bodyTenantId !== host) return { ok: false, status: 403, code: "denied" };
581
- if (!input.subject || !isOpaqueId(input.subject)) return { ok: false, status: 403, code: "denied" };
582
- const actor: FulfillmentActor = { role: "owner", tenantId: host, stage, actorId: input.subject };
583
- if (!actorMayCommand(actor, { tenantId: host, stage })) return { ok: false, status: 403, code: "denied" };
584
- return { ok: true, actor };
585
- }
586
-
587
- function jsonResponse(body: unknown, status: number): Response {
588
- return new Response(JSON.stringify(body), {
589
- status,
590
- headers: {
591
- "content-type": "application/json; charset=utf-8",
592
- "cache-control": "no-store",
593
- "x-robots-tag": "noindex, nofollow",
594
- },
595
- });
596
- }
597
-
598
- export function fulfillmentResultResponse<T>(result: FulfillmentResult<T>, body: (value: T) => unknown): Response {
599
- if (!result.ok) {
600
- const status = result.code === "not-found" ? 404 : result.code === "denied" ? 403 : result.code === "unavailable" ? 503 : result.code === "malformed" ? 400 : 409;
601
- return jsonResponse({ error: result.code, ...(result.holds ? { holds: result.holds } : {}) }, status);
602
- }
603
- return jsonResponse(body(result.value), 200);
604
- }
605
-
606
- export async function openFulfillment(
607
- context: APIContext,
608
- bodyTenantId?: string | null,
609
- ): Promise<{ ok: false; response: Response } | { ok: true; service: FulfillmentService; actor: FulfillmentActor }> {
610
- const url = new URL(context.request.url);
611
- if (url.searchParams.has("tenant") || url.searchParams.has("tenantId") || url.searchParams.has("stage")) {
612
- return { ok: false, response: jsonResponse({ error: "denied" }, 403) };
613
- }
614
- const tenant = context.locals.tenant as
615
- | {
616
- appDomain?: string;
617
- tenant_id?: string;
618
- compliance?: { ruleProfile?: string };
619
- carrierAccountId?: unknown;
620
- }
621
- | undefined;
622
- const host = tenant?.appDomain?.trim() ?? "";
623
- const record = await readViewerSession(context);
624
- const decision = decideFulfillmentAccess({
625
- record,
626
- hostResource: host,
627
- nowSeconds: Math.floor(Date.now() / 1000),
628
- customizationEnv: context.locals.customizationEnv,
629
- subject: record?.subject,
630
- bodyTenantId,
631
- });
632
- if (!decision.ok) return { ok: false, response: jsonResponse({ error: decision.code }, decision.status) };
633
- const d1 = await readD1("STOREFRONT_APPS_DB");
634
- if (!d1) return { ok: false, response: jsonResponse({ error: "unavailable" }, 503) };
635
- const policy = carrierPolicyForTenant({
636
- tenant_id: tenant?.tenant_id || host,
637
- compliance: tenant?.compliance,
638
- carrierAccountId: tenant?.carrierAccountId,
639
- });
640
- return {
641
- ok: true,
642
- actor: decision.actor,
643
- service: new FulfillmentService(fulfillmentDbFromD1(d1), { policy, notify: dispatchCommerceDeliveries }),
644
- };
645
- }
646
-
647
- export function parseFulfillmentBody(body: unknown): FulfillmentResult<{
648
- action: string;
649
- expectedVersion?: number;
650
- scope?: string;
651
- carrier?: string;
652
- lines?: unknown;
653
- outcome?: string;
654
- adultSignature?: string;
655
- orderIds?: string[];
656
- tenantId?: string;
657
- expectedVersions?: Record<string, number>;
658
- }> {
659
- if (!isRecord(body) || containsForbiddenKey(body)) return refuse("malformed");
660
- const action = typeof body.action === "string" ? body.action : "";
661
- if (body.action !== undefined && action === "") return refuse("malformed");
662
- if (body.expectedVersion !== undefined && (!Number.isSafeInteger(body.expectedVersion) || Number(body.expectedVersion) < 1)) {
663
- return refuse("malformed");
664
- }
665
- if (body.orderIds !== undefined) {
666
- if (!Array.isArray(body.orderIds) || body.orderIds.some((id) => typeof id !== "string" || !isOpaqueId(id))) {
667
- return refuse("malformed");
668
- }
669
- }
670
- let expectedVersions: Record<string, number> | undefined;
671
- if (body.expectedVersions !== undefined) {
672
- if (!isRecord(body.expectedVersions)) return refuse("malformed");
673
- expectedVersions = {};
674
- for (const [key, value] of Object.entries(body.expectedVersions)) {
675
- if (!isOpaqueId(key) || !Number.isSafeInteger(value) || Number(value) < 1) return refuse("malformed");
676
- expectedVersions[key] = Number(value);
677
- }
678
- }
679
- const tenantId = typeof body.tenantId === "string" ? body.tenantId : undefined;
680
- return ok({
681
- action,
682
- ...(body.expectedVersion !== undefined ? { expectedVersion: Number(body.expectedVersion) } : {}),
683
- ...(typeof body.scope === "string" ? { scope: body.scope } : {}),
684
- ...(typeof body.carrier === "string" ? { carrier: body.carrier } : {}),
685
- ...(body.lines !== undefined ? { lines: body.lines } : {}),
686
- ...(typeof body.outcome === "string" ? { outcome: body.outcome } : {}),
687
- ...(typeof body.adultSignature === "string" ? { adultSignature: body.adultSignature } : {}),
688
- ...(Array.isArray(body.orderIds) ? { orderIds: body.orderIds as string[] } : {}),
689
- ...(tenantId ? { tenantId } : {}),
690
- ...(expectedVersions ? { expectedVersions } : {}),
691
- });
692
- }
693
-
694
- export async function readJsonBody(request: Request): Promise<FulfillmentResult<unknown>> {
695
- const text = await request.text();
696
- if (text.trim() === "") return ok({});
697
- try {
698
- return ok(JSON.parse(text) as unknown);
699
- } catch {
700
- return refuse("malformed");
701
- }
702
- }
703
-
704
- export class FulfillmentService {
705
- private readonly now: () => string;
706
-
707
- constructor(
708
- private readonly db: FulfillmentDatabase,
709
- private readonly options: {
710
- policy: CarrierPolicy;
711
- now?: () => string;
712
- /** Called after a commit with the delivery ids it wrote, to enqueue them and arm the commerce alarm. */
713
- notify?: (tenantId: string, deliveryIds: string[]) => void | Promise<void>;
714
- },
715
- ) {
716
- this.now = options.now ?? (() => new Date().toISOString());
717
- }
718
-
719
- get policy(): CarrierPolicy {
720
- return this.options.policy;
721
- }
722
-
723
- async get(actor: FulfillmentActor, orderId: string): Promise<FulfillmentResult<FulfillmentView>> {
724
- const scope = this.commandScope(actor);
725
- if (!scope) return refuse("denied");
726
- if (!isOpaqueId(orderId)) return refuse("not-found");
727
- const state = await this.load(scope.tenantId, scope.stage, orderId);
728
- return state ? ok(state.view) : refuse("not-found");
729
- }
730
-
731
- async list(actor: FulfillmentActor, input: {limit:number;cursor:string|null}): Promise<FulfillmentResult<{orders:FulfillmentView[];nextCursor:string|null}>> {
732
- const scope=this.commandScope(actor);
733
- if (!scope) return refuse("denied");
734
- const limit=Math.max(1,Math.min(50,input.limit));
735
- const cursor=input.cursor ?? "";
736
- if (cursor && !isOpaqueId(cursor)) return refuse("malformed");
737
- const rows=await this.db.all<{order_id:string}>(`SELECT order_id FROM scrappy_commerce_orders
738
- WHERE tenant_id=? AND stage=? AND order_id>? AND source != 'scrappy' ORDER BY order_id LIMIT ?`,[scope.tenantId,scope.stage,cursor,limit+1]);
739
- const selected=rows.slice(0,limit); const orders:FulfillmentView[]=[];
740
- for (const row of selected) { const state=await this.load(scope.tenantId,scope.stage,row.order_id); if(state) orders.push(state.view); }
741
- return ok({orders,nextCursor:rows.length>limit ? selected[selected.length-1]?.order_id ?? null:null});
742
- }
743
-
744
- async batch(actor: FulfillmentActor, batchId: string): Promise<FulfillmentResult<FulfillmentBatch>> {
745
- const scope = this.commandScope(actor);
746
- if (!scope) return refuse("denied");
747
- if (!isOpaqueId(batchId)) return refuse("not-found");
748
- const rows = await this.db.all<{ order_id: string; to_state: string }>(
749
- `SELECT order_id, to_state FROM scrappy_shipment_audit
750
- WHERE tenant_id = ? AND stage = ? AND kind = 'batch'
751
- ORDER BY at ASC, audit_id ASC`,
752
- [scope.tenantId, scope.stage],
753
- );
754
- const latest = new Map<string, { batchId: string; phase: BatchPhase }>();
755
- for (const row of rows) {
756
- const parsed = parseBatchState(row.to_state);
757
- if (parsed && isOpaqueId(row.order_id)) latest.set(row.order_id, parsed);
758
- }
759
- const orders = [...latest.entries()]
760
- .filter(([, value]) => value.batchId === batchId)
761
- .map(([orderId, value]) => ({ orderId, phase: value.phase }));
762
- if (orders.length === 0) return refuse("not-found");
763
- return ok({ batchId, orders });
764
- }
765
-
766
- async applySourceSnapshot(
767
- actor: FulfillmentActor,
768
- snapshot: SourceOrderSnapshot,
769
- ): Promise<FulfillmentResult<FulfillmentView>> {
770
- const scope = this.commandScope(actor);
771
- if (!scope) return refuse("denied");
772
- if (snapshot.tenantId !== scope.tenantId || snapshot.stage !== scope.stage) return refuse("denied");
773
- const invalid = validateSnapshot(snapshot);
774
- if (invalid) return refuse(invalid);
775
- const existing = await this.load(scope.tenantId, scope.stage, snapshot.orderId);
776
- if (!existing) {
777
- const inserted = await this.insertSnapshot(actor, snapshot);
778
- if (inserted !== "exists") return inserted;
779
- const raced = await this.load(scope.tenantId, scope.stage, snapshot.orderId);
780
- if (!raced) return refuse("unavailable");
781
- return this.updateSnapshot(actor, raced, snapshot);
782
- }
783
- return this.updateSnapshot(actor, existing, snapshot);
784
- }
785
-
786
- async claim(
787
- actor: FulfillmentActor,
788
- orderIds: readonly string[],
789
- expectedVersions?: Readonly<Record<string, number>>,
790
- ): Promise<FulfillmentResult<FulfillmentBatch>> {
791
- const scope = this.commandScope(actor);
792
- if (!scope) return refuse("denied");
793
- if (orderIds.length === 0 || new Set(orderIds).size !== orderIds.length) return refuse("malformed");
794
- if (orderIds.some((id) => !isOpaqueId(id))) return refuse("malformed");
795
- for (let attempt = 0; attempt < 5; attempt++) {
796
- const states: LoadedOrder[] = [];
797
- for (const orderId of orderIds) {
798
- const state = await this.load(scope.tenantId, scope.stage, orderId);
799
- if (!state) return refuse("not-found");
800
- states.push(state);
801
- }
802
- if (expectedVersions && states.some((state) => expectedVersions[state.order.orderId] !== state.order.eventVersion)) {
803
- return refuse("conflict");
804
- }
805
- const blocked = states.find((state) => state.order.fulfillment === "handed_off" || state.order.fulfillment === "cancelled");
806
- if (blocked) return refuse("fulfillment");
807
- const batches = new Set(states.map((state) => state.batch?.batchId).filter((id): id is string => !!id));
808
- if (states.every((state) => state.batch) && batches.size === 1) {
809
- return this.batch(actor, [...batches][0] ?? "");
810
- }
811
- if (batches.size > 0) return refuse("conflict");
812
- const sourceBlocked=states.find(s=>s.sourceHolds.length);
813
- if(sourceBlocked)return refuse(sourceBlocked.sourceHolds[0]!,sourceBlocked.sourceHolds);
814
- const batchId = `batch_${crypto.randomUUID()}`;
815
- const statements: SqlStatement[] = [claimUpdate(states,this.now())];
816
- states.forEach((state, index) => {
817
- statements.push(
818
- auditStatement(
819
- state,
820
- actor.actorId,
821
- "batch",
822
- "none",
823
- `claimed|${batchId}`,
824
- state.order.eventVersion + 1,
825
- stamp(this.now(), state.auditCount + 1 + index),
826
- ),
827
- );
828
- });
829
- const changes = await this.write(statements,states.length);
830
- if (!changes) return refuse("unavailable");
831
- if ((changes[0] ?? 0) === states.length) return this.batch(actor, batchId);
832
- if (expectedVersions) return refuse("conflict");
833
- }
834
- return refuse("conflict");
835
- }
836
-
837
- async pick(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
838
- return this.advance(actor, orderId, "picked", options);
839
- }
840
-
841
- async pack(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
842
- return this.advance(actor, orderId, "packed", options);
843
- }
844
-
845
- async release(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
846
- return this.advance(actor, orderId, null, options);
847
- }
848
-
849
- async hold(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
850
- return this.commit(actor, orderId, options.expectedVersion, (state) => {
851
- if (state.order.fulfillment === "handed_off" || state.order.fulfillment === "cancelled") return { type: "refuse", code: "fulfillment" };
852
- if (state.operatorHold) return { type: "done", view: state.view };
853
- const version = state.order.eventVersion + 1;
854
- return this.withAssignmentHeld(state, version, [
855
- {
856
- sql: `UPDATE scrappy_commerce_orders
857
- SET fulfillment_state = 'held', event_version = event_version + 1
858
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
859
- AND fulfillment_state IN ('ready', 'held')`,
860
- params: [state.order.tenantId, state.order.stage, state.order.orderId, state.order.eventVersion],
861
- },
862
- auditStatement(state, actor.actorId, "operator-hold", state.order.fulfillment, "open", version, stamp(this.now(), state.auditCount + 1)),
863
- ]);
864
- });
865
- }
866
-
867
- async clearOperatorHold(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
868
- return this.commit(actor, orderId, options.expectedVersion, (state) => {
869
- if (!state.operatorHold) return { type: "done", view: state.view };
870
- if (state.order.fulfillment === "handed_off") return { type: "refuse", code: "fulfillment" };
871
- const next = projectedFulfillment(state, false, state.cancelPending);
872
- const version = state.order.eventVersion + 1;
873
- const plan: PlanStatements = {
874
- statements: [
875
- {
876
- sql: `UPDATE scrappy_commerce_orders
877
- SET fulfillment_state = ?, event_version = event_version + 1
878
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
879
- AND fulfillment_state = 'held'`,
880
- params: [next, state.order.tenantId, state.order.stage, state.order.orderId, state.order.eventVersion],
881
- },
882
- auditStatement(state, actor.actorId, "operator-hold", "open", "cleared", version, stamp(this.now(), state.auditCount + 1)),
883
- ],
884
- deliveries: [],
885
- };
886
- const assignment = state.assignment;
887
- if (assignment?.state === "held" && !state.cancelPending && state.order.payment !== "refund_requested") {
888
- // Resume only while the install is still the configured, notifiable processor; otherwise
889
- // release it so the order waits for a new operator release.
890
- const guard = processorGuard(state.order.tenantId, state.order.stage, assignment.installId, assignment.locationId);
891
- this.appendAssignmentMove(plan, state, assignment, "active", version, guard);
892
- plan.statements.push(
893
- moveAssignmentStatement({
894
- assignmentId: assignment.assignmentId,
895
- tenantId: state.order.tenantId,
896
- stage: state.order.stage,
897
- orderId: state.order.orderId,
898
- from: ["held"],
899
- to: "released",
900
- version,
901
- now: this.now(),
902
- guard,
903
- unlessGuard: true,
904
- }),
905
- );
906
- }
907
- return { type: "write", minimumChanges: 1, statements: plan.statements, deliveries: plan.deliveries };
908
- });
909
- }
910
-
911
- async requestCancel(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
912
- return this.commit(actor, orderId, options.expectedVersion, (state) => {
913
- if (state.cancelPending || state.order.fulfillment === "cancelled") return { type: "done", view: state.view };
914
- const decision = decideCommerceCommand({
915
- command: "cancel",
916
- payment: state.order.payment,
917
- stock: state.order.stock,
918
- fulfillment: state.order.fulfillment,
919
- label: state.order.label,
920
- evidence: state.evidence,
921
- providerOutcome: state.provider?.outcome ?? null,
922
- });
923
- if (!decision.admit) return { type: "refuse", code: decision.reason };
924
- const version = state.order.eventVersion + 1;
925
- return this.withAssignmentHeld(state, version, [
926
- {
927
- sql: `UPDATE scrappy_commerce_orders
928
- SET fulfillment_state = 'held', event_version = event_version + 1
929
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
930
- AND fulfillment_state IN ('ready', 'held')`,
931
- params: [state.order.tenantId, state.order.stage, state.order.orderId, state.order.eventVersion],
932
- },
933
- auditStatement(
934
- state,
935
- actor.actorId,
936
- "pending-cancel",
937
- decision.releaseReservation ? "release-reservation" : "keep-reservation",
938
- "open",
939
- version,
940
- stamp(this.now(), state.auditCount + 1),
941
- ),
942
- ]);
943
- });
944
- }
945
-
946
- async requestRefund(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
947
- return this.commit(actor, orderId, options.expectedVersion, (state) => {
948
- if (state.order.payment === "refund_requested" || state.order.payment === "refunded") {
949
- return { type: "done", view: state.view };
950
- }
951
- if (state.order.fulfillment === "handed_off" || state.order.fulfillment === "cancelled") {
952
- return { type: "refuse", code: "fulfillment" };
953
- }
954
- const decision = decideCommerceCommand({
955
- command: "refund",
956
- payment: state.order.payment,
957
- stock: state.order.stock,
958
- fulfillment: state.order.fulfillment,
959
- label: state.order.label,
960
- evidence: state.evidence,
961
- providerOutcome: state.provider?.outcome ?? null,
962
- });
963
- if (!decision.admit) return { type: "refuse", code: decision.reason };
964
- const version = state.order.eventVersion + 1;
965
- return this.withAssignmentHeld(state, version, [
966
- {
967
- sql: `UPDATE scrappy_commerce_orders
968
- SET payment_state = 'refund_requested', fulfillment_state = 'held', event_version = event_version + 1
969
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
970
- AND payment_state = 'captured'
971
- AND fulfillment_state NOT IN ('handed_off', 'cancelled')`,
972
- params: [state.order.tenantId, state.order.stage, state.order.orderId, state.order.eventVersion],
973
- },
974
- auditStatement(state, actor.actorId, "pending-refund", state.order.payment, "open", version, stamp(this.now(), state.auditCount + 1)),
975
- ]);
976
- });
977
- }
978
-
979
- async applyLabelOutcome(actor: FulfillmentActor, orderId: string, input: LabelOutcomeInput): Promise<FulfillmentResult<FulfillmentView>> {
980
- const selected = carrierSelectionRefusal(this.policy, input.carrier);
981
- if (selected) return refuse(selected);
982
- if (!oneOf(input.outcome, ["purchased", "unknown", "voided"] as const)) return refuse("malformed");
983
- if (!oneOf(input.adultSignature, ["accepted", "refused", "absent"] as const)) return refuse("malformed");
984
- const mapped = labelOutcomeColumns(input.outcome);
985
- return this.commit(actor, orderId, input.expectedVersion, (state) => {
986
- if (state.assignment) return { type: "refuse", code: "processor-assigned" };
987
- const operation = state.provider ?? state.settledProvider;
988
- if (!state.shipment || !operation) return { type: "refuse", code: "label" };
989
- if (state.order.fulfillment === "handed_off") return { type: "refuse", code: "fulfillment" };
990
- if (state.shipment.labelPurchaseState === mapped.shipment && state.labelOutcome?.adultSignature === input.adultSignature) {
991
- return { type: "done", view: state.view };
992
- }
993
- if (input.outcome === "purchased") {
994
- if (state.sourceHolds.length) return { type: "refuse", code: state.sourceHolds[0]!, holds: state.sourceHolds };
995
- const contactHolds = releaseHolds(this.readiness(state)).filter((hold) => hold.startsWith("ship-to-"));
996
- if (contactHolds.length) return { type: "refuse", code: contactHolds[0]!, holds: contactHolds };
997
- }
998
- const version = state.order.eventVersion + 1;
999
- return {
1000
- type: "write",
1001
- minimumChanges: 1,
1002
- sourceAdvance:input.outcome==="purchased",
1003
- statements: [
1004
- {
1005
- sql: `UPDATE scrappy_commerce_orders
1006
- SET label_state = ?, event_version = event_version + 1
1007
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1008
- AND fulfillment_state != 'handed_off'
1009
- AND label_state IN ('intent', 'purchased', 'UNKNOWN', 'voided', 'void_requested')`,
1010
- params: [mapped.order, state.order.tenantId, state.order.stage, state.order.orderId, state.order.eventVersion],
1011
- },
1012
- {
1013
- sql: `UPDATE scrappy_shipments
1014
- SET label_purchase_state = ?
1015
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND handoff_state = 'none'
1016
- AND EXISTS (
1017
- SELECT 1 FROM scrappy_commerce_orders
1018
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1019
- )`,
1020
- params: [
1021
- mapped.shipment,
1022
- state.order.tenantId,
1023
- state.order.stage,
1024
- state.order.orderId,
1025
- state.order.tenantId,
1026
- state.order.stage,
1027
- state.order.orderId,
1028
- version,
1029
- ],
1030
- },
1031
- {
1032
- sql: `UPDATE scrappy_provider_operations
1033
- SET outcome = ?
1034
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND kind = 'label_purchase'
1035
- AND provider = 'unselected' AND purchase_id = ?
1036
- AND EXISTS (
1037
- SELECT 1 FROM scrappy_commerce_orders
1038
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1039
- )`,
1040
- params: [
1041
- mapped.provider,
1042
- state.order.tenantId,
1043
- state.order.stage,
1044
- state.order.orderId,
1045
- operation.purchaseId,
1046
- state.order.tenantId,
1047
- state.order.stage,
1048
- state.order.orderId,
1049
- version,
1050
- ],
1051
- },
1052
- auditStatement(
1053
- state,
1054
- actor.actorId,
1055
- "label-outcome",
1056
- state.order.label,
1057
- jsonText({ outcome: input.outcome, adultSignature: input.adultSignature }),
1058
- version,
1059
- stamp(this.now(), state.auditCount + 1),
1060
- ),
1061
- ],
1062
- };
1063
- });
1064
- }
1065
-
1066
- async handOff(actor: FulfillmentActor, orderId: string, options: FulfillmentCommandOptions = {}): Promise<FulfillmentResult<FulfillmentView>> {
1067
- const selected = carrierSelectionRefusal(this.policy, options.carrier);
1068
- if (selected) return refuse(selected);
1069
- return this.commit(actor, orderId, options.expectedVersion, async (state) => {
1070
- if (state.assignment) return { type: "refuse", code: "processor-assigned" };
1071
- if (state.shipment?.handoffState === "handed_off" || state.order.fulfillment === "handed_off") {
1072
- return { type: "done", view: state.view };
1073
- }
1074
- const code = handoffRefusal(this.readiness(state));
1075
- if (code) return { type: "refuse", code, holds: releaseHolds(this.readiness(state)) };
1076
- if (state.shipment?.labelPurchaseState !== "purchased" || state.provider?.outcome !== "accepted") {
1077
- return { type: "refuse", code: "label" };
1078
- }
1079
- const version = state.order.eventVersion + 1;
1080
- const plan: PlanStatements = { deliveries: [], statements: this.handoffStatements(state, actor.actorId, version) };
1081
- await this.appendOrderFulfilled(plan, state, version);
1082
- return { type: "write", minimumChanges: 1, sourceAdvance: true, statements: plan.statements, deliveries: plan.deliveries };
1083
- });
1084
- }
1085
-
1086
- /**
1087
- * The processor's label outcome under its assignment, from `app:<installId>` only. The first
1088
- * outcome of an attempt opens its label operation under that attempt's platform purchase id (and
1089
- * the whole-order shipment, on the first attempt). A purchase id of another attempt is a conflict;
1090
- * the just-voided id is answered only while its terminal `voided` outcome still stands.
1091
- */
1092
- async appRecordLabelOutcome(request: AppEvidenceRequest<LabelOutcomeEvidence>): Promise<AppEvidenceResponse> {
1093
- const evidence = request.evidence;
1094
- return this.appCommit(request, async (state, binding, attempt) => {
1095
- const standing = attemptStanding(state, attempt, evidence.purchaseId);
1096
- const terminalVoid = standing === "settled" && state.shipment?.labelPurchaseState === "voided";
1097
- if (standing === "stale" || (standing === "settled" && !terminalVoid)) return { type: "refuse", code: "conflict" };
1098
- const purchaseId = evidence.purchaseId;
1099
- const current = state.shipment?.labelPurchaseState ?? "none";
1100
- const unchanged = { type: "done", view: appShipmentView(state, purchaseId) } as const;
1101
- if (current === "purchased") {
1102
- if (evidence.outcome !== "purchased") return { type: "refuse", code: "label-regress" };
1103
- return sameLabelFacts(state.labelOutcome, evidence) ? unchanged : { type: "refuse", code: "conflict" };
1104
- }
1105
- if (current === "voided") return evidence.outcome === "voided" ? unchanged : { type: "refuse", code: "label-regress" };
1106
- if (current === "unknown" && evidence.outcome === "unknown") return unchanged;
1107
- if (state.order.fulfillment === "handed_off") return { type: "refuse", code: "fulfillment" };
1108
- if (evidence.carrier) {
1109
- const carrier = carrierEvidenceRefusal({ carrier: evidence.carrier, policy: this.policy, snapshotProhibited: state.prohibitedCarriers });
1110
- if (carrier) return { type: "refuse", code: carrier };
1111
- }
1112
- const mapped = labelOutcomeColumns(evidence.outcome);
1113
- const version = state.order.eventVersion + 1;
1114
- const { order } = state;
1115
- const actorId = request.actor.actorId;
1116
- let n = state.auditCount;
1117
- const nextStamp = () => stamp(this.now(), ++n);
1118
- const predicate = appWritePredicate(binding, order);
1119
- const statements: SqlStatement[] = [
1120
- {
1121
- sql: `UPDATE scrappy_commerce_orders
1122
- SET label_state = ?, event_version = event_version + 1
1123
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1124
- AND fulfillment_state != 'handed_off' AND label_state = ?
1125
- AND ${predicate.sql}`,
1126
- params: [mapped.order, order.tenantId, order.stage, order.orderId, order.eventVersion, order.label, ...predicate.params],
1127
- },
1128
- ];
1129
- if (!state.shipment || !state.provider) {
1130
- statements.push(...(await this.intentStatements(state, actorId, version, nextStamp, { assigned: true })));
1131
- }
1132
- statements.push(
1133
- {
1134
- sql: `UPDATE scrappy_shipments
1135
- SET label_purchase_state = ?
1136
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND handoff_state = 'none'
1137
- AND EXISTS (
1138
- SELECT 1 FROM scrappy_commerce_orders
1139
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1140
- )`,
1141
- params: [mapped.shipment, order.tenantId, order.stage, order.orderId, order.tenantId, order.stage, order.orderId, version],
1142
- },
1143
- {
1144
- sql: `UPDATE scrappy_provider_operations
1145
- SET outcome = ?
1146
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND kind = 'label_purchase'
1147
- AND provider = 'unselected' AND purchase_id = ?
1148
- AND EXISTS (
1149
- SELECT 1 FROM scrappy_commerce_orders
1150
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1151
- )`,
1152
- params: [mapped.provider, order.tenantId, order.stage, order.orderId, purchaseId, order.tenantId, order.stage, order.orderId, version],
1153
- },
1154
- auditStatement(state, actorId, "label-outcome", order.label, jsonText(labelOutcomeRecord(evidence)), version, nextStamp()),
1155
- );
1156
- return {
1157
- type: "write",
1158
- statements,
1159
- sourceAdvance: evidence.outcome === "purchased",
1160
- deliveries: [],
1161
- view: appShipmentView(state, purchaseId, { version, label: mapped.order, facts: parseStoredLabelFacts(labelOutcomeRecord(evidence)) }),
1162
- };
1163
- });
1164
- }
1165
-
1166
- /** The processor's confirmed handoff under its assignment: every desk handoff gate, the label carrier, one order.fulfilled. */
1167
- async appConfirmHandoff(request: AppEvidenceRequest<HandoffEvidence>): Promise<AppEvidenceResponse> {
1168
- const evidence = request.evidence;
1169
- return this.appCommit(request, async (state, binding, attempt) => {
1170
- const standing = attemptStanding(state, attempt, evidence.purchaseId);
1171
- const terminalVoid = standing === "settled" && state.shipment?.labelPurchaseState === "voided";
1172
- if (standing === "stale" || (standing === "settled" && !terminalVoid)) return { type: "refuse", code: "conflict" };
1173
- const purchaseId = evidence.purchaseId;
1174
- const labelCarrier = state.labelOutcome?.carrier ?? null;
1175
- if (state.shipment?.handoffState === "handed_off" || state.order.fulfillment === "handed_off") {
1176
- return labelCarrier === evidence.carrier
1177
- ? { type: "done", view: appShipmentView(state, purchaseId) }
1178
- : { type: "refuse", code: "carrier-mismatch" };
1179
- }
1180
- const prohibited = carrierEvidenceRefusal({ carrier: evidence.carrier, policy: this.policy, snapshotProhibited: state.prohibitedCarriers });
1181
- if (prohibited) return { type: "refuse", code: prohibited };
1182
- const readiness = this.readiness(state);
1183
- const code = handoffRefusal(readiness);
1184
- if (code) return { type: "refuse", code, holds: releaseHolds(readiness) };
1185
- if (state.shipment?.labelPurchaseState !== "purchased" || state.provider?.outcome !== "accepted") return { type: "refuse", code: "label" };
1186
- const mismatch = carrierEvidenceRefusal({
1187
- carrier: evidence.carrier,
1188
- policy: this.policy,
1189
- snapshotProhibited: state.prohibitedCarriers,
1190
- labelCarrier,
1191
- });
1192
- if (mismatch) return { type: "refuse", code: mismatch };
1193
- const version = state.order.eventVersion + 1;
1194
- const lines = await readAssignmentLines(this.db, binding.assignmentId);
1195
- const remaining = remainingLines(lines);
1196
- const facts = state.labelOutcome;
1197
- if (remaining.length > 0 && !facts?.trackingNumber) return { type: "refuse", code: "label" };
1198
- const [first, ...rest] = this.handoffStatements(state, request.actor.actorId, version);
1199
- const predicate = appWritePredicate(binding, state.order);
1200
- const plan: PlanStatements = {
1201
- deliveries: [],
1202
- statements: [{ sql: `${first!.sql} AND ${predicate.sql}`, params: [...first!.params, ...predicate.params] }, ...rest],
1203
- };
1204
- // The whole-order handoff ships every line the assignment still holds, as one shipment.
1205
- if (remaining.length > 0) {
1206
- const gate = orderCommittedAt(state.order, version);
1207
- plan.statements.push(
1208
- ...consumeLinesStatements(binding.assignmentId, lines, remaining, gate),
1209
- insertShipmentStatement(
1210
- {
1211
- shipmentId: `shp_${crypto.randomUUID()}`,
1212
- assignmentId: binding.assignmentId,
1213
- tenantId: state.order.tenantId,
1214
- stage: state.order.stage,
1215
- orderId: state.order.orderId,
1216
- installId: binding.installId,
1217
- carrier: evidence.carrier,
1218
- service: facts!.service,
1219
- trackingNumber: facts!.trackingNumber!,
1220
- trackingUrl: facts!.trackingUrl,
1221
- adultSignature: facts!.adultSignature,
1222
- lines: remaining,
1223
- now: this.now(),
1224
- },
1225
- gate,
1226
- ),
1227
- );
1228
- }
1229
- await this.appendOrderFulfilled(plan, state, version);
1230
- return {
1231
- type: "write",
1232
- statements: plan.statements,
1233
- sourceAdvance: true,
1234
- deliveries: plan.deliveries,
1235
- view: appShipmentView(state, purchaseId, { version, handoff: "handed_off" }),
1236
- };
1237
- });
1238
- }
1239
-
1240
- /**
1241
- * One shipment against the processor's assignment: some or all of its remaining line quantities.
1242
- * Every release hold, the order's carrier and adult-signature policy, and the per-line remainder
1243
- * refuse before anything is written. The order's compare-and-set serializes it with every other
1244
- * write to the order; the shipment that leaves nothing remaining hands the order off and claims
1245
- * its one `order.fulfilled`, and every other shipment emits `order.partially_fulfilled`.
1246
- */
1247
- async appRecordAssignmentShipment(request: AssignmentWriteRequest<AssignmentShipmentEvidence>): Promise<AppEvidenceResponse> {
1248
- const evidence = request.evidence;
1249
- return this.assignmentCommit(request, async (state, binding) => {
1250
- const carrier = shipmentCarrierRefusal(evidence.carrier, this.policy.prohibitedCarriers, state.prohibitedCarriers);
1251
- if (carrier) return { type: "refuse", code: carrier };
1252
- const holds = releaseHolds(this.readiness(state));
1253
- if (holds.length > 0) return { type: "refuse", code: holds[0]!, holds };
1254
- if (state.order.fulfillment !== "ready") return { type: "refuse", code: "fulfillment" };
1255
- // A label-voided reset leaves the whole-order shipment at `none`; only `voided` and `none` carry no label.
1256
- const labelInFlight =
1257
- state.shipment !== null && state.shipment.labelPurchaseState !== "voided" && state.shipment.labelPurchaseState !== "none";
1258
- if (labelInFlight || !SPLIT_LABEL_STATES.includes(state.order.label)) return { type: "refuse", code: "whole-order-label" };
1259
- if ((state.adultSignatureRequired || this.policy.adultSignatureRequired) && evidence.adultSignature !== "accepted") {
1260
- return { type: "refuse", code: "adult-signature" };
1261
- }
1262
- const lines = await readAssignmentLines(this.db, binding.assignmentId);
1263
- const lineCode = lineRefusal(lines, evidence.lines);
1264
- if (lineCode) return { type: "refuse", code: lineCode };
1265
- const complete = completesLines(lines, evidence.lines);
1266
- const version = state.order.eventVersion + 1;
1267
- const gate = orderCommittedAt(state.order, version);
1268
- const shipmentId = `shp_${crypto.randomUUID()}`;
1269
- const plan: PlanStatements = {
1270
- deliveries: [],
1271
- statements: [
1272
- assignmentOrderCas(state, binding, { complete, splitShipment: true }),
1273
- ...consumeLinesStatements(binding.assignmentId, lines, evidence.lines, gate),
1274
- insertShipmentStatement(
1275
- {
1276
- shipmentId,
1277
- assignmentId: binding.assignmentId,
1278
- tenantId: state.order.tenantId,
1279
- stage: state.order.stage,
1280
- orderId: state.order.orderId,
1281
- installId: binding.installId,
1282
- carrier: evidence.carrier,
1283
- service: evidence.service ?? null,
1284
- trackingNumber: evidence.trackingNumber,
1285
- trackingUrl: evidence.trackingUrl ?? null,
1286
- adultSignature: evidence.adultSignature,
1287
- lines: evidence.lines,
1288
- now: this.now(),
1289
- },
1290
- gate,
1291
- ),
1292
- auditStatement(
1293
- state,
1294
- request.actor.actorId,
1295
- "assignment-shipment",
1296
- "none",
1297
- jsonText({ shipmentId, assignmentId: binding.assignmentId, lines: evidence.lines }),
1298
- version,
1299
- stamp(this.now(), state.auditCount + 1),
1300
- ),
1301
- ],
1302
- };
1303
- if (complete) {
1304
- plan.statements.push(
1305
- auditStatement(state, request.actor.actorId, "transition", state.order.fulfillment, "handed_off", version, stamp(this.now(), state.auditCount + 2)),
1306
- terminalTransitionExpiryStatement(state.order, version, new Date(this.now())),
1307
- );
1308
- await this.appendOrderFulfilled(plan, state, version);
1309
- } else {
1310
- await this.appendOrderPartiallyFulfilled(plan, state, shipmentId);
1311
- }
1312
- return {
1313
- type: "write",
1314
- statements: plan.statements,
1315
- sourceAdvance: true,
1316
- deliveries: plan.deliveries,
1317
- view: { assignmentId: binding.assignmentId, shipmentId, fulfilledLines: evidence.lines, complete },
1318
- };
1319
- });
1320
- }
1321
-
1322
- /**
1323
- * The processor voided the label of the current purchase attempt, before handoff. One batch:
1324
- * the order CAS (install and assignment predicate, version, not handed off, shipment not handed
1325
- * off, the open operation under this purchase id) resets the label to `none`; the shipment label
1326
- * returns to `none`; the operation is marked voided and stays as history, which moves the order
1327
- * to its next purchase attempt; a label-voided audit row records the voided purchase id. The
1328
- * assignment stays active. The response names the next attempt's purchase id.
1329
- */
1330
- async appVoidLabel(request: AppEvidenceRequest<LabelVoidedEvidence>): Promise<AppEvidenceResponse> {
1331
- const evidence = request.evidence;
1332
- return this.appCommit(request, async (state, binding, attempt) => {
1333
- const standing = attemptStanding(state, attempt, evidence.purchaseId);
1334
- if (standing === "stale") return { type: "refuse", code: "conflict" };
1335
- if (standing === "settled") return { type: "done", view: appShipmentView(state, attempt.current) };
1336
- if ((state.shipment && state.shipment.handoffState !== "none") || state.order.fulfillment === "handed_off") {
1337
- return { type: "refuse", code: "fulfillment" };
1338
- }
1339
- const open = state.provider;
1340
- const recorded =
1341
- open !== null &&
1342
- (open.outcome === "accepted" || open.outcome === "unknown") &&
1343
- (state.shipment?.labelPurchaseState === "purchased" || state.shipment?.labelPurchaseState === "unknown") &&
1344
- (state.order.label === "purchased" || state.order.label === "printed" || state.order.label === "UNKNOWN");
1345
- if (!recorded) return { type: "refuse", code: "label" };
1346
- const { order } = state;
1347
- const version = order.eventVersion + 1;
1348
- const predicate = appWritePredicate(binding, order);
1349
- const atVersion = {
1350
- sql: `EXISTS (
1351
- SELECT 1 FROM scrappy_commerce_orders
1352
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1353
- )`,
1354
- params: [order.tenantId, order.stage, order.orderId, version],
1355
- };
1356
- const next = await purchaseIdFor(order.tenantId, order.stage, order.orderId, state.labelGeneration + 1);
1357
- const plan: PlanStatements = { deliveries: [], statements: [] };
1358
- plan.statements.push(
1359
- {
1360
- sql: `UPDATE scrappy_commerce_orders
1361
- SET label_state = 'none', event_version = event_version + 1
1362
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1363
- AND fulfillment_state != 'handed_off' AND label_state = ?
1364
- AND EXISTS (
1365
- SELECT 1 FROM scrappy_shipments AS s
1366
- WHERE s.tenant_id = ? AND s.stage = ? AND s.order_id = ? AND s.handoff_state = 'none'
1367
- )
1368
- AND EXISTS (
1369
- SELECT 1 FROM scrappy_provider_operations AS p
1370
- WHERE p.tenant_id = ? AND p.stage = ? AND p.order_id = ? AND p.kind = 'label_purchase'
1371
- AND p.purchase_id = ? AND p.outcome IN ('accepted', 'unknown')
1372
- )
1373
- AND ${predicate.sql}`,
1374
- params: [
1375
- order.tenantId, order.stage, order.orderId, order.eventVersion, order.label,
1376
- order.tenantId, order.stage, order.orderId,
1377
- order.tenantId, order.stage, order.orderId, evidence.purchaseId,
1378
- ...predicate.params,
1379
- ],
1380
- },
1381
- {
1382
- sql: `UPDATE scrappy_shipments
1383
- SET label_purchase_state = 'none', label_print_state = 'none'
1384
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND handoff_state = 'none' AND ${atVersion.sql}`,
1385
- params: [order.tenantId, order.stage, order.orderId, ...atVersion.params],
1386
- },
1387
- {
1388
- sql: `UPDATE scrappy_provider_operations
1389
- SET outcome = 'voided'
1390
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND kind = 'label_purchase'
1391
- AND purchase_id = ? AND outcome IN ('intent', 'accepted', 'unknown') AND ${atVersion.sql}`,
1392
- params: [order.tenantId, order.stage, order.orderId, evidence.purchaseId, ...atVersion.params],
1393
- },
1394
- auditStatement(
1395
- state,
1396
- request.actor.actorId,
1397
- "label-voided",
1398
- order.label,
1399
- jsonText(labelVoidedRecord(evidence.purchaseId)),
1400
- version,
1401
- stamp(this.now(), state.auditCount + 1),
1402
- ),
1403
- );
1404
- this.appendCommerceEvent(plan, {
1405
- tenantId: order.tenantId,
1406
- stage: order.stage,
1407
- topic: "fulfillment.label.voided",
1408
- payload: {
1409
- assignmentId: binding.assignmentId,
1410
- orderId: order.orderId,
1411
- purchaseId: evidence.purchaseId,
1412
- occurredAt: this.now(),
1413
- },
1414
- gate: atVersion,
1415
- installIds: [binding.installId],
1416
- });
1417
- return {
1418
- type: "write",
1419
- sourceAdvance: false,
1420
- deliveries: plan.deliveries,
1421
- statements: plan.statements,
1422
- view: appShipmentView(state, next, { version, label: "none", facts: null }),
1423
- };
1424
- });
1425
- }
1426
-
1427
- /**
1428
- * Lines of the processor's assignment it reports it cannot ship, for the operator desk. Every
1429
- * release hold refuses, and each line's quantity is at most its remainder. Nothing is cancelled,
1430
- * refunded or emitted.
1431
- */
1432
- async appRecordAssignmentException(request: AssignmentWriteRequest<AssignmentExceptionEvidence>): Promise<AppEvidenceResponse> {
1433
- const evidence = request.evidence;
1434
- return this.assignmentCommit(request, async (state, binding) => {
1435
- const holds = releaseHolds(this.readiness(state));
1436
- if (holds.length > 0) return { type: "refuse", code: holds[0]!, holds };
1437
- if (state.order.fulfillment !== "ready") return { type: "refuse", code: "fulfillment" };
1438
- const lines = await readAssignmentLines(this.db, binding.assignmentId);
1439
- const lineCode = lineRefusal(lines, evidence.lines);
1440
- if (lineCode) return { type: "refuse", code: lineCode };
1441
- const version = state.order.eventVersion + 1;
1442
- const gate = orderCommittedAt(state.order, version);
1443
- const exceptionId = `exc_${crypto.randomUUID()}`;
1444
- return {
1445
- type: "write",
1446
- statements: [
1447
- assignmentOrderCas(state, binding, { complete: false, splitShipment: false }),
1448
- insertExceptionStatement(
1449
- {
1450
- exceptionId,
1451
- assignmentId: binding.assignmentId,
1452
- tenantId: state.order.tenantId,
1453
- stage: state.order.stage,
1454
- orderId: state.order.orderId,
1455
- installId: binding.installId,
1456
- code: evidence.code,
1457
- lines: evidence.lines,
1458
- note: evidence.note ?? null,
1459
- now: this.now(),
1460
- },
1461
- gate,
1462
- ),
1463
- auditStatement(
1464
- state,
1465
- request.actor.actorId,
1466
- "assignment-exception",
1467
- "none",
1468
- jsonText({ exceptionId, assignmentId: binding.assignmentId, code: evidence.code }),
1469
- version,
1470
- stamp(this.now(), state.auditCount + 1),
1471
- ),
1472
- ],
1473
- sourceAdvance: true,
1474
- deliveries: [],
1475
- view: { assignmentId: binding.assignmentId, exceptionId, code: evidence.code },
1476
- };
1477
- });
1478
- }
1479
-
1480
- /**
1481
- * An assignment-scoped write: the order is the one the calling install's assignment names on the
1482
- * routed tenant and stage. Any other assignment answers not-assigned before anything is read or
1483
- * recorded; the write then takes the same path as every other app write.
1484
- */
1485
- private async assignmentCommit(
1486
- request: AssignmentWriteRequest<{ assignmentId: string }>,
1487
- build: (state: LoadedOrder, binding: AppAssignmentBinding) => AppPlan | Promise<AppPlan>,
1488
- ): Promise<AppEvidenceResponse> {
1489
- const binding = appBinding(request.actor, request.evidence.assignmentId);
1490
- if (!binding) return appRefusal("denied");
1491
- if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return appRefusal("malformed");
1492
- const row = await this.db.get<{ order_id: string }>(
1493
- `SELECT order_id FROM fulfillment_assignments WHERE assignment_id = ? AND tenant_id = ? AND stage = ? AND install_id = ?`,
1494
- [binding.assignmentId, request.actor.tenantId, request.actor.stage, binding.installId],
1495
- );
1496
- if (!row) return appRefusal("not-assigned");
1497
- return this.appCommit(
1498
- { actor: request.actor, orderId: row.order_id, idempotencyKey: request.idempotencyKey, body: request.body, evidence: request.evidence },
1499
- (state, bound) => build(state, bound),
1500
- );
1501
- }
1502
-
1503
- /**
1504
- * The app write path: the key ledger first, the assignment binding, the plan, then one batch whose
1505
- * first statement carries the install and assignment predicate and whose last records the key.
1506
- * A plan-time answer records the key alone. A batch that does not commit is re-classified.
1507
- */
1508
- private async appCommit(
1509
- request: AppEvidenceRequest<{ assignmentId: string; expectedVersion?: number }>,
1510
- build: (state: LoadedOrder, binding: AppAssignmentBinding, attempt: PurchaseAttempt) => AppPlan | Promise<AppPlan>,
1511
- ): Promise<AppEvidenceResponse> {
1512
- const binding = appBinding(request.actor, request.evidence.assignmentId);
1513
- if (!binding) return appRefusal("denied");
1514
- if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return appRefusal("malformed");
1515
- const { tenantId, stage } = request.actor;
1516
- const { orderId, idempotencyKey: key } = request;
1517
- if (!isOpaqueId(orderId)) return appRefusal("not-assigned");
1518
- const bodyHash = await computeBodyHash({ body: request.body, assignmentId: binding.assignmentId, orderId });
1519
- const prior = await this.priorResponse(binding.installId, key, bodyHash);
1520
- if (prior) return prior;
1521
- const state = await this.load(tenantId, stage, orderId);
1522
- const assigned = await this.assignmentRefusal(binding, tenantId, stage, orderId, state?.assignment ?? null);
1523
- if (assigned || !state) return appRefusal(assigned ?? "not-assigned");
1524
- const expected = request.evidence.expectedVersion;
1525
- if (expected !== undefined && state.order.eventVersion !== expected) return appRefusal("conflict");
1526
- const attempt = await purchaseAttempt(state.order, state.labelGeneration);
1527
- let plan: AppPlan;
1528
- try {
1529
- plan = await build(state, binding, attempt);
1530
- } catch (error) {
1531
- if (error instanceof CommercePayloadRefused) return appRefusal("malformed");
1532
- throw error;
1533
- }
1534
- if (plan.type === "done") return this.recordAppAnswer(binding.installId, key, bodyHash, { status: 200, body: plan.view });
1535
- if (plan.type === "refuse") return this.recordAppAnswer(binding.installId, key, bodyHash, appRefusal(plan.code, plan.holds));
1536
- const response: AppEvidenceResponse = { status: 200, body: plan.view };
1537
- const fence = authorityFence(state.sourceAuthority, this.now(), plan.sourceAdvance);
1538
- const [first, ...rest] = plan.statements;
1539
- if (!first) return appRefusal("unavailable");
1540
- const changes = await this.write([
1541
- { sql: `${first.sql} AND (${fence.sql})`, params: [...first.params, ...fence.params] },
1542
- ...rest,
1543
- idempotencyInsertStatement({ installId: binding.installId, key, bodyHash, response, now: this.now() }),
1544
- ]);
1545
- if (changes && (changes[0] ?? 0) >= 1) {
1546
- await this.notifyCommitted(tenantId, plan.deliveries, changes);
1547
- return response;
1548
- }
1549
- return this.classifyUncommitted(binding, state, plan.sourceAdvance, key, bodyHash, changes === null);
1550
- }
1551
-
1552
- /** Why an app batch did not commit, read once after it: install, scope, assignment, authority, key, version. */
1553
- private async classifyUncommitted(
1554
- binding: AppAssignmentBinding,
1555
- original: LoadedOrder,
1556
- sourceAdvance: boolean,
1557
- key: string,
1558
- bodyHash: string,
1559
- failed: boolean,
1560
- ): Promise<AppEvidenceResponse> {
1561
- const { tenantId, stage, orderId } = original.order;
1562
- const install = await this.db.get<{ status: string; scopes: string }>(
1563
- `SELECT status, scopes FROM app_installs WHERE install_id = ? AND tenant_id = ?`,
1564
- [binding.installId, tenantId],
1565
- );
1566
- if (!install || install.status !== "active") return appRefusal("invalid_token");
1567
- if (!scopeListIncludes(install.scopes, PROCESSOR_SCOPE)) return appRefusal("scope_denied");
1568
- const current = await this.load(tenantId, stage, orderId);
1569
- const assigned = await this.assignmentRefusal(binding, tenantId, stage, orderId, current?.assignment ?? null);
1570
- if (assigned || !current) return appRefusal(assigned ?? "not-assigned");
1571
- const fence = authorityFence(original.sourceAuthority, this.now(), sourceAdvance);
1572
- const fenced = await this.db.get<{ ok: number }>(
1573
- `SELECT 1 AS ok FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ? AND (${fence.sql})`,
1574
- [tenantId, stage, orderId, ...fence.params],
1575
- );
1576
- if (!fenced) return appRefusal(current.sourceHolds[0] ?? "source-check-pending");
1577
- const prior = await this.priorResponse(binding.installId, key, bodyHash);
1578
- if (prior) return prior;
1579
- return appRefusal(failed ? "unavailable" : "conflict");
1580
- }
1581
-
1582
- /** A same-key request already answered: its recorded response, or idempotency-conflict for another body. */
1583
- private async priorResponse(installId: string, key: string, bodyHash: string): Promise<AppEvidenceResponse | null> {
1584
- const check = await checkIdempotency(this.ledger(), installId, key, bodyHash);
1585
- if (check.status === "proceed") return null;
1586
- if (check.status === "conflict") return appRefusal("idempotency-conflict");
1587
- return replayedResponse(check.responseBody) ?? appRefusal("idempotency-conflict");
1588
- }
1589
-
1590
- /** Records a plan-time answer under its key; a same-key race answers with whatever won. */
1591
- private async recordAppAnswer(installId: string, key: string, bodyHash: string, response: AppEvidenceResponse): Promise<AppEvidenceResponse> {
1592
- let changes: number[];
1593
- try {
1594
- changes = await this.db.batch([idempotencyInsertStatement({ installId, key, bodyHash, response, now: this.now() })]);
1595
- } catch {
1596
- return appRefusal("unavailable");
1597
- }
1598
- if ((changes[0] ?? 0) >= 1) return response;
1599
- return (await this.priorResponse(installId, key, bodyHash)) ?? appRefusal("unavailable");
1600
- }
1601
-
1602
- /** The order's assignment as the calling install sees it: null when its bound assignment is active. */
1603
- private async assignmentRefusal(
1604
- binding: AppAssignmentBinding,
1605
- tenantId: string,
1606
- stage: CommerceStage,
1607
- orderId: string,
1608
- open: OpenAssignment | null,
1609
- ): Promise<"not-assigned" | "assignment-ended" | "assignment-held" | null> {
1610
- if (open && open.installId === binding.installId) {
1611
- if (open.assignmentId !== binding.assignmentId) return "assignment-ended";
1612
- return open.state === "held" ? "assignment-held" : null;
1613
- }
1614
- const named = await this.db.get<{ n: number }>(
1615
- `SELECT 1 AS n FROM fulfillment_assignments WHERE tenant_id = ? AND stage = ? AND order_id = ? AND install_id = ? LIMIT 1`,
1616
- [tenantId, stage, orderId, binding.installId],
1617
- );
1618
- return named ? "assignment-ended" : "not-assigned";
1619
- }
1620
-
1621
- /** The idempotency ledger over this store. */
1622
- private ledger(): Queryable {
1623
- const db = this.db;
1624
- return {
1625
- all: async <T,>(sql: string, ...params: unknown[]) => (await db.all(sql, params)) as T[],
1626
- first: async <T,>(sql: string, ...params: unknown[]) => ((await db.get(sql, params)) ?? null) as T | null,
1627
- run: async (sql: string, ...params: unknown[]) => {
1628
- await db.batch([{ sql, params }]);
1629
- },
1630
- exec: async () => {
1631
- throw new Error("storage");
1632
- },
1633
- };
1634
- }
1635
-
1636
- /** The whole-order handoff: order CAS, shipment move, transition audit, and the contact expiry. */
1637
- private handoffStatements(state: LoadedOrder, actorId: string, version: number): SqlStatement[] {
1638
- const { order } = state;
1639
- return [
1640
- {
1641
- sql: `UPDATE scrappy_commerce_orders
1642
- SET fulfillment_state = 'handed_off', event_version = event_version + 1
1643
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1644
- AND payment_state = 'captured' AND stock_state = 'confirmed'
1645
- AND fulfillment_state = 'ready' AND label_state IN ('purchased', 'printed')
1646
- AND EXISTS (
1647
- SELECT 1 FROM scrappy_shipments
1648
- WHERE tenant_id = ? AND stage = ? AND order_id = ?
1649
- AND scope = 'whole-order' AND label_purchase_state = 'purchased' AND handoff_state = 'none'
1650
- )`,
1651
- params: [order.tenantId, order.stage, order.orderId, order.eventVersion, order.tenantId, order.stage, order.orderId],
1652
- },
1653
- {
1654
- sql: `UPDATE scrappy_shipments
1655
- SET handoff_state = 'handed_off'
1656
- WHERE tenant_id = ? AND stage = ? AND order_id = ?
1657
- AND scope = 'whole-order' AND label_purchase_state = 'purchased' AND handoff_state = 'none'
1658
- AND EXISTS (
1659
- SELECT 1 FROM scrappy_commerce_orders
1660
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1661
- )`,
1662
- params: [order.tenantId, order.stage, order.orderId, order.tenantId, order.stage, order.orderId, version],
1663
- },
1664
- auditStatement(state, actorId, "transition", order.fulfillment, "handed_off", version, stamp(this.now(), state.auditCount + 1)),
1665
- terminalTransitionExpiryStatement(order, version, new Date(this.now())),
1666
- ];
1667
- }
1668
-
1669
- /** Returns are not automated. This records nothing. */
1670
- createReturn(actor: FulfillmentActor, _orderId: string): FulfillmentResult<never> {
1671
- if (!this.commandScope(actor)) return refuse("denied");
1672
- return refuse("returns-not-automated");
1673
- }
1674
-
1675
- /** Merchant and desk commands. An install actor (`app:`) commands only through the app methods. */
1676
- private commandScope(actor: FulfillmentActor): { tenantId: string; stage: CommerceStage } | null {
1677
- if (!isOpaqueId(actor.actorId) || actor.actorId.startsWith(APP_ACTOR_PREFIX)) return null;
1678
- const scope = { tenantId: actor.tenantId, stage: actor.stage };
1679
- return actorMayCommand(actor, scope) ? scope : null;
1680
- }
1681
-
1682
- private readiness(state: LoadedOrder): ReadinessInput {
1683
- return {
1684
- shipTo: state.shipTo,
1685
- sourceHolds: state.sourceHolds,
1686
- payment: state.order.payment,
1687
- stock: state.order.stock,
1688
- fulfillment: state.order.fulfillment,
1689
- label: state.order.label,
1690
- evidence: state.evidence,
1691
- operatorHold: state.operatorHold,
1692
- cancelPending: state.cancelPending,
1693
- providerOutcome: state.provider?.outcome ?? null,
1694
- adultSignature: state.labelOutcome?.adultSignature ?? "absent",
1695
- adultSignatureRequired: state.adultSignatureRequired || this.policy.adultSignatureRequired,
1696
- };
1697
- }
1698
-
1699
- private async advance(
1700
- actor: FulfillmentActor,
1701
- orderId: string,
1702
- phase: BatchPhase | null,
1703
- options: FulfillmentCommandOptions,
1704
- ): Promise<FulfillmentResult<FulfillmentView>> {
1705
- const selected = carrierSelectionRefusal(this.policy, options.carrier);
1706
- if (selected) return refuse(selected);
1707
- if (options.scope !== undefined && options.scope !== "whole-order") return refuse("partial-shipment");
1708
- if (options.lines !== undefined) return refuse("partial-shipment");
1709
- // The install a release's first assignment plan targeted; a CAS-miss retry stays bound to it.
1710
- let boundInstall: string | null = null;
1711
- return this.commit(actor, orderId, options.expectedVersion, async (state) => {
1712
- if (!state.batch) return { type: "refuse", code: "batch" };
1713
- if (state.order.fulfillment === "handed_off" || state.order.fulfillment === "cancelled") {
1714
- return { type: "refuse", code: "fulfillment" };
1715
- }
1716
- const raising = phase !== null && phaseRank(state.batch.phase) < phaseRank(phase);
1717
- const wantSlip = phase === "packed" && !state.packingSlip;
1718
- const readiness = this.readiness(state);
1719
- const releasable = canRelease(readiness);
1720
- if (raising && !releasable) return {type:"refuse",code:releaseHolds(readiness)[0] ?? "held",holds:releaseHolds(readiness)};
1721
- if (phase === null && (boundInstall !== null || state.processor)) {
1722
- const target = boundInstall ?? state.processor!.installId;
1723
- // The install that already holds the order's assignment answers done at any version.
1724
- if (state.assignment) {
1725
- return state.assignment.installId === target ? { type: "done", view: state.view } : { type: "refuse", code: "assignment-conflict" };
1726
- }
1727
- // A desk release carries the version it saw; any other version lost to a concurrent change.
1728
- if (options.expectedVersion !== undefined && state.order.eventVersion !== options.expectedVersion) {
1729
- return { type: "refuse", code: "assignment-conflict" };
1730
- }
1731
- if (!state.processor || state.processor.installId !== target || !state.processor.notifiable) {
1732
- return { type: "refuse", code: "assignment-conflict" };
1733
- }
1734
- if (state.shipment || holdsLiveLabelOperation(state)) return { type: "refuse", code: "label-intent" };
1735
- if (!releasable) {
1736
- const holds = releaseHolds(readiness);
1737
- return { type: "refuse", code: holds[0] ?? "hold", holds };
1738
- }
1739
- boundInstall = target;
1740
- return this.assignmentPlan(state, target);
1741
- }
1742
- if (phase === null && state.assignment) return { type: "refuse", code: "processor-assigned" };
1743
- const labelAcceptsIntent = state.order.label === "none" || state.order.label === "voided" || state.order.label === "intent";
1744
- const wantIntent = (phase === null || phase === "picked" || phase === "packed") && releasable && !state.shipment && labelAcceptsIntent
1745
- && !state.processor && !state.assignment;
1746
- if (phase === null && !state.shipment && !wantIntent) {
1747
- if (!releasable) {
1748
- const holds = releaseHolds(readiness);
1749
- return { type: "refuse", code: holds[0] ?? "hold", holds };
1750
- }
1751
- const labelCode = state.order.label === "UNKNOWN" || state.order.label === "void_requested" ? "reconcile" : "label";
1752
- return { type: "refuse", code: labelCode };
1753
- }
1754
- if (!raising && !wantSlip && !wantIntent) {
1755
- if (state.shipment || phase !== null) return { type: "done", view: state.view };
1756
- }
1757
- const version = state.order.eventVersion + 1;
1758
- const statements: SqlStatement[] = [touchOrder(state, wantIntent)];
1759
- let n = state.auditCount;
1760
- if (raising && phase) {
1761
- n += 1;
1762
- statements.push(auditStatement(state, actor.actorId, "batch", state.batch.phase, `${phase}|${state.batch.batchId}`, version, stamp(this.now(), n)));
1763
- }
1764
- if (wantSlip) {
1765
- n += 1;
1766
- const slip = packingSlip(state, this.policy);
1767
- statements.push(auditStatement(state, actor.actorId, "packing-slip", "none", jsonText(slip), version, stamp(this.now(), n)));
1768
- }
1769
- if (wantIntent) {
1770
- const intent = await this.intentStatements(state, actor.actorId, version, () => {
1771
- n += 1;
1772
- return stamp(this.now(), n);
1773
- });
1774
- statements.push(...intent);
1775
- }
1776
- return { type: "write", statements, minimumChanges: 1, sourceAdvance:true };
1777
- });
1778
- }
1779
-
1780
- private async intentStatements(
1781
- state: LoadedOrder,
1782
- actorId: string,
1783
- version: number,
1784
- nextStamp: () => string,
1785
- /** The assigned processor's first label outcome opens the shipment under its own assignment. */
1786
- options: { assigned?: boolean } = {},
1787
- ): Promise<SqlStatement[]> {
1788
- const purchaseId =
1789
- state.provider?.purchaseId ?? (await purchaseIdFor(state.order.tenantId, state.order.stage, state.order.orderId, state.labelGeneration));
1790
- const intent = {
1791
- purchaseId,
1792
- adultSignatureRequired: this.policy.adultSignatureRequired,
1793
- prohibitedCarriers: [...this.policy.prohibitedCarriers],
1794
- carrierAccountId: this.policy.carrierAccountId,
1795
- vendorSelected: false as const,
1796
- };
1797
- const { order } = state;
1798
- return [
1799
- {
1800
- sql: `INSERT INTO scrappy_shipments (
1801
- tenant_id, stage, order_id, scope, label_purchase_state, label_print_state, handoff_state
1802
- )
1803
- SELECT tenant_id, stage, order_id, 'whole-order', 'intent', 'none', 'none'
1804
- FROM scrappy_commerce_orders AS o
1805
- WHERE o.tenant_id = ? AND o.stage = ? AND o.order_id = ? AND o.event_version = ?
1806
- AND NOT EXISTS (
1807
- SELECT 1 FROM scrappy_shipments AS s
1808
- WHERE s.tenant_id = o.tenant_id AND s.stage = o.stage AND s.order_id = o.order_id
1809
- )
1810
- AND (? = 1 OR NOT EXISTS (
1811
- SELECT 1 FROM fulfillment_assignments AS fa
1812
- WHERE fa.tenant_id = o.tenant_id AND fa.stage = o.stage AND fa.order_id = o.order_id
1813
- AND fa.state IN ('active', 'held')
1814
- ))`,
1815
- params: [order.tenantId, order.stage, order.orderId, version, options.assigned ? 1 : 0],
1816
- },
1817
- {
1818
- sql: `INSERT INTO scrappy_provider_operations (
1819
- tenant_id, stage, provider, purchase_id, order_id, kind, outcome, amount_minor
1820
- )
1821
- SELECT tenant_id, stage, 'unselected', ?, order_id, 'label_purchase', 'intent', amount_minor
1822
- FROM scrappy_commerce_orders AS o
1823
- WHERE o.tenant_id = ? AND o.stage = ? AND o.order_id = ? AND o.event_version = ?
1824
- AND NOT EXISTS (
1825
- SELECT 1 FROM scrappy_provider_operations AS p
1826
- WHERE p.tenant_id = o.tenant_id AND p.stage = o.stage AND p.order_id = o.order_id
1827
- AND p.kind = 'label_purchase' AND p.outcome IN ('intent', 'accepted', 'unknown')
1828
- )`,
1829
- params: [purchaseId, order.tenantId, order.stage, order.orderId, version],
1830
- },
1831
- auditStatement(state, actorId, "label-intent", state.order.label, jsonText(intent), version, nextStamp()),
1832
- ];
1833
- }
1834
-
1835
- private async commit(
1836
- actor: FulfillmentActor,
1837
- orderId: string,
1838
- expectedVersion: number | undefined,
1839
- build: (state: LoadedOrder) => CommitPlan | Promise<CommitPlan>,
1840
- ): Promise<FulfillmentResult<FulfillmentView>> {
1841
- const scope = this.commandScope(actor);
1842
- if (!scope) return refuse("denied");
1843
- if (!isOpaqueId(orderId)) return refuse("not-found");
1844
- let assignmentPlan = false;
1845
- for (let attempt = 0; attempt < 5; attempt++) {
1846
- const state = await this.load(scope.tenantId, scope.stage, orderId);
1847
- if (!state) return refuse("not-found");
1848
- let plan: CommitPlan;
1849
- try {
1850
- plan = await build(state);
1851
- } catch (error) {
1852
- if (error instanceof CommercePayloadRefused) return refuse("malformed");
1853
- throw error;
1854
- }
1855
- if (plan.type === "done") return ok(plan.view);
1856
- if (plan.type === "refuse") return refuse(plan.code, plan.holds);
1857
- assignmentPlan = plan.assignment === true;
1858
- if (expectedVersion !== undefined && state.order.eventVersion !== expectedVersion) return refuse("conflict");
1859
- const fence=authorityFence(state.sourceAuthority,this.now(),plan.sourceAdvance===true);
1860
- const first=plan.statements[0];
1861
- if(!first)return refuse("unavailable");
1862
- const guarded=[{sql:`${first.sql} AND (${fence.sql})`,params:[...first.params,...fence.params]},...plan.statements.slice(1)];
1863
- const changes = await this.write(guarded);
1864
- if (!changes) return refuse("unavailable");
1865
- if ((changes[0] ?? 0) >= plan.minimumChanges) {
1866
- await this.notifyCommitted(scope.tenantId, plan.deliveries ?? [], changes);
1867
- const next = await this.load(scope.tenantId, scope.stage, orderId);
1868
- return next ? ok(next.view) : refuse("not-found");
1869
- }
1870
- if (expectedVersion !== undefined && !assignmentPlan) return refuse("conflict");
1871
- }
1872
- return refuse(assignmentPlan ? "assignment-conflict" : "conflict");
1873
- }
1874
-
1875
- /** A hold-shaped write: the order statements plus, for an active assignment, its move to held. */
1876
- private withAssignmentHeld(state: LoadedOrder, version: number, statements: SqlStatement[]): CommitPlan {
1877
- const plan: PlanStatements = { statements, deliveries: [] };
1878
- if (state.assignment?.state === "active") this.appendAssignmentMove(plan, state, state.assignment, "held", version);
1879
- return { type: "write", minimumChanges: 1, statements: plan.statements, deliveries: plan.deliveries };
1880
- }
1881
-
1882
- /**
1883
- * Release to the configured processor: the order CAS (also requiring the config to name
1884
- * `installId` and the install to be notifiable), the active assignment, and its one
1885
- * `fulfillment.assignment.created` delivery to that install. No label intent is written.
1886
- */
1887
- private assignmentPlan(state: LoadedOrder, installId: string): CommitPlan {
1888
- const { order } = state;
1889
- const version = order.eventVersion + 1;
1890
- const assignmentId = `asg_${crypto.randomUUID()}`;
1891
- const touch = touchOrder(state, false);
1892
- const locationId = state.processor?.installId === installId ? state.processor.locationId : DEFAULT_LOCATION;
1893
- const guard = processorGuard(order.tenantId, order.stage, installId, locationId);
1894
- const plan: PlanStatements = {
1895
- statements: [
1896
- { sql: `${touch.sql} AND ${guard.sql}`, params: [...touch.params, ...guard.params] },
1897
- insertAssignmentStatement({
1898
- assignmentId,
1899
- tenantId: order.tenantId,
1900
- stage: order.stage,
1901
- orderId: order.orderId,
1902
- installId,
1903
- locationId,
1904
- version,
1905
- now: this.now(),
1906
- }),
1907
- ...insertAssignmentLinesStatements({
1908
- assignmentId,
1909
- tenantId: order.tenantId,
1910
- stage: order.stage,
1911
- orderId: order.orderId,
1912
- version,
1913
- lines: state.routing.lines,
1914
- }),
1915
- ],
1916
- deliveries: [],
1917
- };
1918
- this.appendCommerceEvent(plan, {
1919
- tenantId: order.tenantId,
1920
- stage: order.stage,
1921
- topic: "fulfillment.assignment.created",
1922
- payload: assignmentPayload(state, assignmentId, "active", version, this.now()),
1923
- gate: assignmentAtGate(assignmentId, "active", version),
1924
- installIds: [installId],
1925
- });
1926
- return {
1927
- type: "write",
1928
- minimumChanges: 1,
1929
- sourceAdvance: true,
1930
- assignment: true,
1931
- statements: plan.statements,
1932
- deliveries: plan.deliveries,
1933
- };
1934
- }
1935
-
1936
- /** The handoff's `order.fulfilled`: claim it for this order, and write the event only under that claim. */
1937
- private async appendOrderFulfilled(plan: PlanStatements, state: LoadedOrder, version: number): Promise<void> {
1938
- const { order } = state;
1939
- const key = { tenantId: order.tenantId, stage: order.stage, source: order.source, sourceOrderId: order.sourceOrderId };
1940
- const eventId = crypto.randomUUID();
1941
- plan.statements.push(
1942
- handoffClaimStatement(key, eventId, this.now(), {
1943
- sql: `EXISTS (SELECT 1 FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?)`,
1944
- params: [order.tenantId, order.stage, order.orderId, version],
1945
- }),
1946
- );
1947
- const targets = commerceTargetsQuery(order.tenantId, "order.fulfilled", order.stage);
1948
- const installs = await this.db.all<{ install_id: string }>(targets.sql, targets.params);
1949
- const payload: Record<string, unknown> = { id: order.sourceOrderId, status: "fulfilled", currency: order.currency };
1950
- if (state.lines.length > 0) payload.lineItems = state.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }));
1951
- this.appendCommerceEvent(plan, {
1952
- tenantId: order.tenantId,
1953
- stage: order.stage,
1954
- topic: "order.fulfilled",
1955
- payload,
1956
- gate: claimedByEventGate(key, eventId),
1957
- installIds: installs.map((row) => row.install_id),
1958
- eventId,
1959
- });
1960
- }
1961
-
1962
- /** A partial shipment's `order.partially_fulfilled`, written only with its own shipment row. */
1963
- private async appendOrderPartiallyFulfilled(plan: PlanStatements, state: LoadedOrder, shipmentId: string): Promise<void> {
1964
- const { order } = state;
1965
- const targets = commerceTargetsQuery(order.tenantId, "order.partially_fulfilled", order.stage);
1966
- const installs = await this.db.all<{ install_id: string }>(targets.sql, targets.params);
1967
- const payload: Record<string, unknown> = { id: order.sourceOrderId, status: "created", currency: order.currency };
1968
- if (state.lines.length > 0) payload.lineItems = state.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }));
1969
- this.appendCommerceEvent(plan, {
1970
- tenantId: order.tenantId,
1971
- stage: order.stage,
1972
- topic: "order.partially_fulfilled",
1973
- payload,
1974
- gate: shipmentCommittedGate(shipmentId),
1975
- installIds: installs.map((row) => row.install_id),
1976
- });
1977
- }
1978
-
1979
- /**
1980
- * The processor's reconciliation read: the calling install's active assignments on this tenant
1981
- * and stage whose order is still releasable at its current event version, oldest first.
1982
- */
1983
- async listAssignments(input: {
1984
- tenantId: string;
1985
- stage: CommerceStage;
1986
- installId: string;
1987
- limit: number;
1988
- cursor: string | null;
1989
- }): Promise<FulfillmentResult<{ assignments: AssignmentReadItem[]; nextCursor: string | null }>> {
1990
- const limit = Math.max(1, Math.min(100, Math.trunc(input.limit)));
1991
- let after: [string, string] = ["", ""];
1992
- if (input.cursor !== null) {
1993
- const decoded = decodeAssignmentCursor(input.cursor);
1994
- if (!decoded) return ok({ assignments: [], nextCursor: null });
1995
- after = decoded;
1996
- }
1997
- const rows = await this.db.all<{ assignment_id: string; order_id: string; assigned_at: string }>(
1998
- `SELECT assignment_id, order_id, assigned_at FROM fulfillment_assignments
1999
- WHERE tenant_id = ? AND stage = ? AND install_id = ? AND state = 'active'
2000
- AND (assigned_at > ? OR (assigned_at = ? AND assignment_id > ?))
2001
- ORDER BY assigned_at ASC, assignment_id ASC LIMIT ?`,
2002
- [input.tenantId, input.stage, input.installId, after[0], after[0], after[1], limit + 1],
2003
- );
2004
- const page = rows.slice(0, limit);
2005
- const assignments: AssignmentReadItem[] = [];
2006
- for (const row of page) {
2007
- const state = await this.load(input.tenantId, input.stage, row.order_id);
2008
- if (!state || state.assignment?.assignmentId !== row.assignment_id || state.assignment.installId !== input.installId) continue;
2009
- if (state.assignment.state !== "active" || state.lines.length === 0) continue;
2010
- if (!canRelease(this.readiness(state))) continue;
2011
- const lines = await readAssignmentLines(this.db, row.assignment_id);
2012
- assignments.push({
2013
- assignmentId: row.assignment_id,
2014
- orderId: row.order_id,
2015
- stage: input.stage,
2016
- eventVersion: state.order.eventVersion,
2017
- assignedAt: row.assigned_at,
2018
- purchaseId: await purchaseIdFor(input.tenantId, input.stage, row.order_id, state.labelGeneration),
2019
- lineItems: state.lines.map((line) => ({ sku: line.sku, quantity: line.quantity })),
2020
- locationId: state.assignment.locationId,
2021
- allowedCarriers: allowedCarriers(this.policy.prohibitedCarriers, state.prohibitedCarriers),
2022
- adultSignatureRequired: state.adultSignatureRequired || this.policy.adultSignatureRequired,
2023
- lines: lines.map((line) => ({
2024
- lineId: line.lineId,
2025
- sku: line.sku,
2026
- locationId: line.locationId,
2027
- quantity: line.assigned,
2028
- shipped: line.shipped,
2029
- cancelled: line.cancelled,
2030
- remaining: remainingQuantity(line),
2031
- })),
2032
- });
2033
- }
2034
- const last = page[page.length - 1];
2035
- return ok({ assignments, nextCursor: rows.length > limit && last ? encodeAssignmentCursor(last.assigned_at, last.assignment_id) : null });
2036
- }
2037
-
2038
- private async notifyCommitted(tenantId: string, deliveries: readonly PlannedDelivery[], changes: readonly number[]): Promise<void> {
2039
- const committed = deliveries.filter((delivery) => (changes[delivery.index] ?? 0) > 0).map((delivery) => delivery.deliveryId);
2040
- if (committed.length === 0 || !this.options.notify) return;
2041
- try {
2042
- await this.options.notify(tenantId, committed);
2043
- } catch {
2044
- // The delivery rows are committed and pending; the tenant commerce alarm redelivers them.
2045
- }
2046
- }
2047
-
2048
- /** Appends one commerce event (gated on `gate`) and a delivery per install to `plan`. */
2049
- private appendCommerceEvent(
2050
- plan: PlanStatements,
2051
- input: {
2052
- tenantId: string;
2053
- stage: CommerceStage;
2054
- topic: CommerceTopic;
2055
- payload: Record<string, unknown>;
2056
- gate: SqlStatement;
2057
- installIds: readonly string[];
2058
- eventId?: string;
2059
- },
2060
- ): void {
2061
- const targets = input.installIds.map((installId) => ({ installId, deliveryId: crypto.randomUUID() }));
2062
- const built = commerceEventStatements({
2063
- eventId: input.eventId ?? crypto.randomUUID(),
2064
- tenantId: input.tenantId,
2065
- stage: input.stage,
2066
- topic: input.topic,
2067
- payload: input.payload,
2068
- gate: { sql: input.gate.sql, params: [...input.gate.params] },
2069
- targets,
2070
- now: this.now(),
2071
- });
2072
- built.forEach((statement, index) => {
2073
- const target = index > 0 ? targets[index - 1] : undefined;
2074
- if (target) plan.deliveries.push({ index: plan.statements.length, deliveryId: target.deliveryId });
2075
- plan.statements.push(statement);
2076
- });
2077
- }
2078
-
2079
- /** Appends the assignment's move to `to` at `version` plus its `fulfillment.assignment.updated` event. */
2080
- private appendAssignmentMove(
2081
- plan: PlanStatements,
2082
- state: LoadedOrder,
2083
- assignment: OpenAssignment,
2084
- to: ReportedAssignmentState,
2085
- version: number,
2086
- guard?: SqlStatement,
2087
- ): void {
2088
- const from: AssignmentState[] = to === "cancelled" ? ["active", "held"] : to === "held" ? ["active"] : ["held"];
2089
- plan.statements.push(
2090
- moveAssignmentStatement({
2091
- assignmentId: assignment.assignmentId,
2092
- tenantId: state.order.tenantId,
2093
- stage: state.order.stage,
2094
- orderId: state.order.orderId,
2095
- from,
2096
- to,
2097
- version,
2098
- now: this.now(),
2099
- guard,
2100
- }),
2101
- );
2102
- this.appendCommerceEvent(plan, {
2103
- tenantId: state.order.tenantId,
2104
- stage: state.order.stage,
2105
- topic: "fulfillment.assignment.updated",
2106
- payload: assignmentPayload(state, assignment.assignmentId, to, version, this.now()),
2107
- gate: assignmentAtGate(assignment.assignmentId, to, version),
2108
- installIds: [assignment.installId],
2109
- });
2110
- }
2111
-
2112
- private async write(statements: readonly SqlStatement[],minimumChanges=1): Promise<number[] | null> {
2113
- try {
2114
- if(!statements.length)return [];
2115
- // A competing transaction can occupy the expected next event version. Abort this
2116
- // entire batch unless its first CAS actually wrote; version-only side effects are unsafe.
2117
- const gated=[statements[0]!,{sql:`SELECT json(CASE WHEN changes() >= ? THEN 'true' ELSE 'cas-not-applied' END)`,params:[minimumChanges]},...statements.slice(1)];
2118
- const changes=await this.db.batch(gated);
2119
- return [changes[0] ?? 0,...changes.slice(2)];
2120
- } catch(error) {
2121
- let cause:unknown=error;
2122
- for(let depth=0;depth<4&&cause instanceof Error;depth++,cause=cause.cause){if(cause.message.includes("malformed JSON"))return statements.map(()=>0);}
2123
- return null;
2124
- }
2125
- }
2126
-
2127
- private async insertSnapshot(actor: FulfillmentActor, snapshot: SourceOrderSnapshot): Promise<FulfillmentResult<FulfillmentView> | "exists"> {
2128
- const payment = mergePayment(null, snapshot.payment);
2129
- const label = mergeLabel(null, snapshot.label);
2130
- const fulfillment = projectedFromSnapshot(null, snapshot, payment, false, false);
2131
- const version = 1;
2132
- const at = stamp(this.now(), 1);
2133
- const statements: SqlStatement[] = [
2134
- {
2135
- sql: `INSERT INTO scrappy_commerce_orders (
2136
- tenant_id, stage, order_id, source, source_order_id, currency, placed_at,
2137
- payment_state, compliance_state, stock_state, fulfillment_state, label_state,
2138
- amount_minor, event_version
2139
- )
2140
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1
2141
- WHERE NOT EXISTS (
2142
- SELECT 1 FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ?
2143
- )`,
2144
- params: [
2145
- snapshot.tenantId,
2146
- snapshot.stage,
2147
- snapshot.orderId,
2148
- snapshot.source,
2149
- snapshot.sourceOrderId,
2150
- snapshot.currency,
2151
- snapshot.placedAt,
2152
- payment,
2153
- snapshot.compliance,
2154
- snapshot.stock,
2155
- fulfillment,
2156
- label,
2157
- snapshot.amountMinor,
2158
- snapshot.tenantId,
2159
- snapshot.stage,
2160
- snapshot.orderId,
2161
- ],
2162
- },
2163
- ];
2164
- const gate = `tenant_id = ? AND stage = ? AND order_id = ? AND event_version = 1 AND source = ? AND source_order_id = ?`;
2165
- const gateParams = [snapshot.tenantId, snapshot.stage, snapshot.orderId, snapshot.source, snapshot.sourceOrderId];
2166
- const stub = {
2167
- order: {
2168
- tenantId: snapshot.tenantId,
2169
- stage: snapshot.stage,
2170
- orderId: snapshot.orderId,
2171
- source: snapshot.source,
2172
- sourceOrderId: snapshot.sourceOrderId,
2173
- currency: snapshot.currency,
2174
- placedAt: snapshot.placedAt,
2175
- payment,
2176
- compliance: snapshot.compliance,
2177
- stock: snapshot.stock,
2178
- fulfillment,
2179
- label,
2180
- amountMinor: snapshot.amountMinor,
2181
- eventVersion: version,
2182
- },
2183
- };
2184
- if (snapshot.evidenceExpiresAt) statements.push(gatedAudit(stub, actor.actorId, "evidence-expires", "none", snapshot.evidenceExpiresAt, stamp(this.now(), 6), gate, gateParams));
2185
- statements.push(
2186
- gatedAudit(stub, actor.actorId, "evidence", "none", jsonText(snapshot.evidence), at, gate, gateParams),
2187
- gatedAudit(stub, actor.actorId, "lines", "none", jsonText(snapshot.lines), stamp(this.now(), 2), gate, gateParams),
2188
- gatedAudit(stub, actor.actorId, "totals", "none", jsonText(snapshot.totals), stamp(this.now(), 3), gate, gateParams),
2189
- gatedAudit(
2190
- stub,
2191
- actor.actorId,
2192
- "public-event",
2193
- "none",
2194
- observedEvent({
2195
- eventVersion: version,
2196
- orderId: snapshot.orderId,
2197
- placedAt: snapshot.placedAt,
2198
- currency: snapshot.currency,
2199
- payment,
2200
- compliance: snapshot.compliance,
2201
- stock: snapshot.stock,
2202
- fulfillment,
2203
- label,
2204
- totals: snapshot.totals,
2205
- evidence: snapshot.evidence,
2206
- }),
2207
- stamp(this.now(), 5),
2208
- gate,
2209
- gateParams,
2210
- ),
2211
- );
2212
- if (snapshot.sourceVersion !== undefined) statements.push(projectionCheckpoint(snapshot,version,this.now()));
2213
- const changes = await this.write(statements);
2214
- if (!changes) {const existing=await this.load(snapshot.tenantId,snapshot.stage,snapshot.orderId);return existing?"exists":refuse("unavailable");}
2215
- if ((changes[0] ?? 0) !== 1) return "exists";
2216
- const loaded = await this.load(snapshot.tenantId, snapshot.stage, snapshot.orderId);
2217
- return loaded ? ok(loaded.view) : refuse("unavailable");
2218
- }
2219
-
2220
- private updateSnapshot(
2221
- actor: FulfillmentActor,
2222
- _existing: LoadedOrder,
2223
- snapshot: SourceOrderSnapshot,
2224
- ): Promise<FulfillmentResult<FulfillmentView>> {
2225
- return this.commit(actor, snapshot.orderId, undefined, async (state) => {
2226
- if (snapshot.sourceVersion !== undefined) {
2227
- const checkpoint=await this.db.get<{source_version:number}>(`SELECT source_version FROM commerce_projection_checkpoints WHERE tenant_id=? AND stage=? AND order_id=?`,[snapshot.tenantId,snapshot.stage,snapshot.orderId]);
2228
- if (checkpoint && Number(checkpoint.source_version)>=snapshot.sourceVersion) return {type:"done",view:state.view};
2229
- }
2230
- const payment = mergePayment(state.order.payment, snapshot.payment);
2231
- const label = mergeLabel(state.order.label, snapshot.label);
2232
- const confirmedCancel = snapshot.fulfillment === "cancelled" || payment === "voided" || payment === "refunded";
2233
- const cancelPending = state.cancelPending && !confirmedCancel;
2234
- const fulfillment = projectedFromSnapshot(state.order.fulfillment, snapshot, payment, state.operatorHold, cancelPending);
2235
- const version = state.order.eventVersion + 1;
2236
- const statements: SqlStatement[] = [
2237
- {
2238
- sql: `UPDATE scrappy_commerce_orders
2239
- SET payment_state = ?, compliance_state = ?, stock_state = ?, fulfillment_state = ?,
2240
- label_state = ?, amount_minor = ?, event_version = event_version + 1
2241
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
2242
- AND (? = 'handed_off' OR fulfillment_state != 'handed_off' OR ? = 'handed_off')`,
2243
- params: [
2244
- payment,
2245
- snapshot.compliance,
2246
- snapshot.stock,
2247
- state.order.fulfillment === "handed_off" ? "handed_off" : fulfillment,
2248
- label,
2249
- snapshot.amountMinor,
2250
- state.order.tenantId,
2251
- state.order.stage,
2252
- state.order.orderId,
2253
- state.order.eventVersion,
2254
- state.order.fulfillment,
2255
- fulfillment,
2256
- ],
2257
- },
2258
- ];
2259
- let n = state.auditCount;
2260
- const nextVersion = version;
2261
- if(snapshot.evidenceExpiresAt) {
2262
- n+=1; statements.push(auditStatement(state,actor.actorId,"evidence-expires","source",snapshot.evidenceExpiresAt,version,stamp(this.now(),n)));
2263
- }
2264
-
2265
- n += 1;
2266
- statements.push(auditStatement(state, actor.actorId, "evidence", "source", jsonText(snapshot.evidence), nextVersion, stamp(this.now(), n)));
2267
- n += 1;
2268
- statements.push(auditStatement(state, actor.actorId, "lines", "source", jsonText(snapshot.lines), nextVersion, stamp(this.now(), n)));
2269
- n += 1;
2270
- statements.push(auditStatement(state, actor.actorId, "totals", "source", jsonText(snapshot.totals), nextVersion, stamp(this.now(), n)));
2271
- const storedFulfillment = state.order.fulfillment === "handed_off" ? "handed_off" : fulfillment;
2272
- n += 1;
2273
- statements.push(
2274
- auditStatement(
2275
- state,
2276
- actor.actorId,
2277
- "public-event",
2278
- "source",
2279
- observedEvent({
2280
- eventVersion: nextVersion,
2281
- orderId: state.order.orderId,
2282
- placedAt: state.order.placedAt,
2283
- currency: state.order.currency,
2284
- payment,
2285
- compliance: snapshot.compliance,
2286
- stock: snapshot.stock,
2287
- fulfillment: storedFulfillment,
2288
- label,
2289
- totals: snapshot.totals,
2290
- evidence: snapshot.evidence,
2291
- }),
2292
- nextVersion,
2293
- stamp(this.now(), n),
2294
- ),
2295
- );
2296
- if (confirmedCancel && state.order.fulfillment !== "handed_off") {
2297
- n += 1;
2298
- statements.push(auditStatement(state, actor.actorId, "pending-cancel", "open", "confirmed", nextVersion, stamp(this.now(), n)));
2299
- statements.push(terminalTransitionExpiryStatement(state.order, nextVersion, new Date(this.now())));
2300
- }
2301
- if (snapshot.sourceVersion !== undefined) statements.push(projectionCheckpoint(snapshot,nextVersion,this.now()));
2302
- const plan: PlanStatements = { statements, deliveries: [] };
2303
- if (confirmedCancel && state.assignment) this.appendAssignmentMove(plan, state, state.assignment, "cancelled", nextVersion);
2304
- return { type: "write", statements: plan.statements, deliveries: plan.deliveries, minimumChanges: 1 };
2305
- });
2306
- }
2307
-
2308
- private async load(tenantId: string, stage: CommerceStage, orderId: string): Promise<LoadedOrder | null> {
2309
- const row = await this.db.get<Record<string, unknown>>(
2310
- `SELECT tenant_id, stage, order_id, source, source_order_id, currency, placed_at,
2311
- payment_state, compliance_state, stock_state, fulfillment_state, label_state,
2312
- amount_minor, event_version
2313
- FROM scrappy_commerce_orders
2314
- WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
2315
- [tenantId, stage, orderId],
2316
- );
2317
- if (!row) return null;
2318
- if (
2319
- !oneOf(row.payment_state, PAYMENT_STATES) ||
2320
- !oneOf(row.compliance_state, COMPLIANCE_STATES) ||
2321
- !oneOf(row.stock_state, STOCK_STATES) ||
2322
- !oneOf(row.fulfillment_state, FULFILLMENT_STATES) ||
2323
- !oneOf(row.label_state, LABEL_STATES) ||
2324
- !oneOf(row.stage, ["preview", "publication"] as const) ||
2325
- typeof row.order_id !== "string" ||
2326
- typeof row.currency !== "string" ||
2327
- typeof row.placed_at !== "string" ||
2328
- typeof row.source !== "string" ||
2329
- typeof row.source_order_id !== "string"
2330
- ) {
2331
- return null;
2332
- }
2333
- const audits = await this.db.all<{ kind: string; from_state: string; to_state: string }>(
2334
- `SELECT kind, from_state, to_state FROM scrappy_shipment_audit
2335
- WHERE tenant_id = ? AND stage = ? AND order_id = ?
2336
- ORDER BY at ASC, audit_id ASC`,
2337
- [tenantId, stage, orderId],
2338
- );
2339
- const shipment = await this.db.get<{ label_purchase_state: string; handoff_state: string; scope: string }>(
2340
- `SELECT scope, label_purchase_state, handoff_state FROM scrappy_shipments
2341
- WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
2342
- [tenantId, stage, orderId],
2343
- );
2344
- const providers = await this.db.all<{ purchase_id: string; outcome: string }>(
2345
- `SELECT purchase_id, outcome FROM scrappy_provider_operations
2346
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND kind = 'label_purchase'`,
2347
- [tenantId, stage, orderId],
2348
- );
2349
- let evidence = FAIL_CLOSED_EVIDENCE;
2350
- let evidenceExpiresAt:string|null=null;
2351
- let lines: { sku: string; quantity: number }[] = [];
2352
- let totals: MinorTotals | null = null;
2353
- let batch: { batchId: string; phase: BatchPhase } | null = null;
2354
- let operatorHold = false;
2355
- let cancelPending = false;
2356
- let packingSlip: PackingSlip | null = null;
2357
- let labelOutcome: LoadedOrder["labelOutcome"] = null;
2358
- let intentAccount: string | null = null;
2359
- let intentProhibited: string[] = [...this.policy.prohibitedCarriers];
2360
- let intentAdult = this.policy.adultSignatureRequired;
2361
- for (const audit of audits) {
2362
- if (audit.kind === "evidence") evidence = parseEvidence(parseJson(audit.to_state)) ?? FAIL_CLOSED_EVIDENCE;
2363
- else if (audit.kind === "evidence-expires") evidenceExpiresAt=audit.to_state;
2364
- else if (audit.kind === "lines") lines = parseLines(parseJson(audit.to_state)) ?? [];
2365
- else if (audit.kind === "totals") totals = parseTotals(parseJson(audit.to_state));
2366
- else if (audit.kind === "batch") batch = parseBatchState(audit.to_state);
2367
- else if (audit.kind === "operator-hold") operatorHold = audit.to_state === "open";
2368
- else if (audit.kind === "pending-cancel") cancelPending = audit.to_state === "open";
2369
- else if (audit.kind === "packing-slip") packingSlip = parseSlip(parseJson(audit.to_state));
2370
- else if (audit.kind === "label-outcome") labelOutcome = parseStoredLabelFacts(parseJson(audit.to_state));
2371
- else if (audit.kind === "label-voided") labelOutcome = null;
2372
- else if (audit.kind === "label-intent") {
2373
- const intent = parseJson(audit.to_state);
2374
- if (isRecord(intent)) {
2375
- intentAccount = typeof intent.carrierAccountId === "string" ? intent.carrierAccountId : null;
2376
- intentAdult = intent.adultSignatureRequired === true;
2377
- intentProhibited = Array.isArray(intent.prohibitedCarriers)
2378
- ? intent.prohibitedCarriers.filter((item): item is string => typeof item === "string")
2379
- : intentProhibited;
2380
- }
2381
- }
2382
- }
2383
- if(evidenceExpiresAt && (!Number.isFinite(Date.parse(evidenceExpiresAt)) || Date.parse(evidenceExpiresAt)<=Date.parse(this.now()))) {
2384
- evidence={verification:"stale",tax:"stale",risk:"stale",stock:"stale"};
2385
- }
2386
- const provider = openProvider(providers);
2387
- const labelGeneration = providers.filter((row) => row.outcome === "voided").length;
2388
- const lastVoided = labelGeneration > 0
2389
- ? await purchaseIdFor(tenantId, stage, orderId, labelGeneration - 1)
2390
- : null;
2391
- const settledProvider = provider ? null : settledOperation(providers, lastVoided);
2392
- const order = {
2393
- tenantId,
2394
- stage: row.stage,
2395
- orderId: row.order_id,
2396
- source: row.source,
2397
- sourceOrderId: row.source_order_id,
2398
- currency: row.currency,
2399
- placedAt: row.placed_at,
2400
- payment: row.payment_state,
2401
- compliance: row.compliance_state,
2402
- stock: row.stock_state,
2403
- fulfillment: row.fulfillment_state,
2404
- label: row.label_state,
2405
- amountMinor: Number(row.amount_minor),
2406
- eventVersion: Number(row.event_version),
2407
- };
2408
- let sourceAuthority:AuthorityRow|null=null;let sourceHolds:SourceReadiness[];
2409
- try { sourceAuthority=await this.db.get<AuthorityRow & Record<string,unknown>>(`SELECT * FROM commerce_source_authority WHERE tenant_id=? AND stage=? AND source=? AND source_order_id=?`,[tenantId,stage,order.source,order.sourceOrderId]) ?? null;
2410
- sourceHolds=sourceAuthority?.order_id!==order.orderId?["source-authority-unavailable"]:authorityHolds(sourceAuthority,this.now());
2411
- }catch{sourceHolds=["source-authority-unreadable"];}
2412
- const routing = await routeOrderLines(this.db, { tenantId, stage, orderId }, lines);
2413
- const processor = await resolveProcessor(this.db, tenantId, stage, routing.locationId);
2414
- const assignment = await readOpenAssignment(this.db, tenantId, stage, orderId);
2415
- const exceptions = await readOpenExceptions(this.db, { tenantId, stage, orderId });
2416
- const contacts = await readOrderContactAvailability({
2417
- all: (sql, ...params) => this.db.all(sql, params),
2418
- }, { tenantId, stage, orderIds: [orderId], now: new Date(this.now()) });
2419
- const loaded: LoadedOrder = {
2420
- shipTo: contacts.get(orderId)?.shipTo ?? "unreadable",
2421
- sourceAuthority,sourceHolds,
2422
- order,
2423
- evidence,
2424
- lines,
2425
- totals,
2426
- batch,
2427
- operatorHold,
2428
- cancelPending,
2429
- packingSlip,
2430
- shipment: shipment && shipment.scope === "whole-order"
2431
- ? { labelPurchaseState: shipment.label_purchase_state, handoffState: shipment.handoff_state }
2432
- : null,
2433
- provider,
2434
- settledProvider,
2435
- labelGeneration,
2436
- labelOutcome,
2437
- carrierAccountId: intentAccount,
2438
- prohibitedCarriers: intentProhibited,
2439
- adultSignatureRequired: intentAdult,
2440
- auditCount: audits.length,
2441
- routing,
2442
- processor,
2443
- assignment,
2444
- view: {
2445
- orderId: order.orderId,
2446
- tenantId: order.tenantId,
2447
- stage: order.stage,
2448
- eventVersion: order.eventVersion,
2449
- payment: order.payment,
2450
- compliance: order.compliance,
2451
- stock: order.stock,
2452
- fulfillment: order.fulfillment,
2453
- label: order.label,
2454
- holds: [],
2455
- canRelease: false,
2456
- canHandOff: false,
2457
- batch,
2458
- shipment: null,
2459
- packingSlip,
2460
- lines, evidence, placedAt:order.placedAt, currency:order.currency,
2461
- processor,
2462
- assignment: assignment ? { assignmentId: assignment.assignmentId, installId: assignment.installId, state: assignment.state } : null,
2463
- exceptions,
2464
- },
2465
- };
2466
- const readiness = this.readiness(loaded);
2467
- const holds = releaseHolds(readiness);
2468
- loaded.view.holds = holds;
2469
- if(holds.length&&order.fulfillment==="ready")loaded.view.fulfillment="held";
2470
- loaded.view.canRelease = canRelease(readiness) && !loaded.shipment && !assignment;
2471
- loaded.view.canHandOff = handoffRefusal(readiness) === null && loaded.shipment?.handoffState !== "handed_off";
2472
- loaded.view.shipment = loaded.shipment
2473
- ? {
2474
- scope: "whole-order",
2475
- purchaseId: (provider ?? settledProvider)?.purchaseId ?? null,
2476
- labelPurchaseState: loaded.shipment.labelPurchaseState,
2477
- handoffState: loaded.shipment.handoffState,
2478
- vendorSelected: false,
2479
- carrierAccountId: loaded.carrierAccountId,
2480
- adultSignatureRequired: loaded.adultSignatureRequired,
2481
- prohibitedCarriers: loaded.prohibitedCarriers,
2482
- carrier: labelOutcome?.carrier ?? null,
2483
- service: labelOutcome?.service ?? null,
2484
- trackingNumber: labelOutcome?.trackingNumber ?? null,
2485
- trackingUrl: labelOutcome?.trackingUrl ?? null,
2486
- }
2487
- : null;
2488
- return loaded;
2489
- }
2490
- }
2491
-
2492
- export interface AssignmentReadItem {
2493
- assignmentId: string;
2494
- orderId: string;
2495
- stage: CommerceStage;
2496
- eventVersion: number;
2497
- assignedAt: string;
2498
- purchaseId: string;
2499
- lineItems: { sku: string; quantity: number }[];
2500
- /** The processor-config location the assignment was routed through (`*` for the catch-all). */
2501
- locationId: string;
2502
- /** Carriers this order may ship with: the closed set minus the tenant's and the order's prohibited carriers. */
2503
- allowedCarriers: string[];
2504
- adultSignatureRequired: boolean;
2505
- /** One entry per sku with its shipped, cancelled and remaining quantity. */
2506
- lines: AssignmentReadLine[];
2507
- }
2508
-
2509
- export interface AssignmentReadLine {
2510
- lineId: string;
2511
- sku: string;
2512
- locationId: string;
2513
- quantity: number;
2514
- shipped: number;
2515
- cancelled: number;
2516
- remaining: number;
2517
- }
2518
-
2519
- /**
2520
- * The first statement of an assignment shipment or exception: the order's compare-and-set at its
2521
- * read version, under the install and assignment predicate. A split shipment also requires that no
2522
- * whole-order label is in flight, and the completing one hands the order off.
2523
- */
2524
- function assignmentOrderCas(
2525
- state: LoadedOrder,
2526
- binding: AppAssignmentBinding,
2527
- options: { complete: boolean; splitShipment: boolean },
2528
- ): SqlStatement {
2529
- const { order } = state;
2530
- const predicate = appWritePredicate(binding, order);
2531
- const label = options.splitShipment
2532
- ? `AND label_state IN (${SPLIT_LABEL_STATES.map(() => "?").join(", ")})
2533
- AND NOT EXISTS (
2534
- SELECT 1 FROM scrappy_shipments AS s
2535
- WHERE s.tenant_id = ? AND s.stage = ? AND s.order_id = ? AND s.label_purchase_state NOT IN ('none', 'voided')
2536
- )`
2537
- : "";
2538
- return {
2539
- sql: `UPDATE scrappy_commerce_orders
2540
- SET event_version = event_version + 1${options.complete ? ", fulfillment_state = 'handed_off'" : ""}
2541
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
2542
- AND payment_state = 'captured' AND stock_state = 'confirmed' AND fulfillment_state = 'ready'
2543
- ${label}
2544
- AND ${predicate.sql}`,
2545
- params: [
2546
- order.tenantId,
2547
- order.stage,
2548
- order.orderId,
2549
- order.eventVersion,
2550
- ...(options.splitShipment ? [...SPLIT_LABEL_STATES, order.tenantId, order.stage, order.orderId] : []),
2551
- ...predicate.params,
2552
- ],
2553
- };
2554
- }
2555
-
2556
- function encodeAssignmentCursor(assignedAt: string, assignmentId: string): string {
2557
- return btoa(JSON.stringify([assignedAt, assignmentId])).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2558
- }
2559
-
2560
- function decodeAssignmentCursor(cursor: string): [string, string] | null {
2561
- if (cursor.length === 0 || cursor.length > 512 || !/^[A-Za-z0-9_-]+$/.test(cursor)) return null;
2562
- try {
2563
- const parsed: unknown = JSON.parse(atob(cursor.replace(/-/g, "+").replace(/_/g, "/")));
2564
- if (!Array.isArray(parsed) || parsed.length !== 2) return null;
2565
- const [assignedAt, assignmentId] = parsed as unknown[];
2566
- return typeof assignedAt === "string" && typeof assignmentId === "string" ? [assignedAt, assignmentId] : null;
2567
- } catch {
2568
- return null;
2569
- }
2570
- }
2571
-
2572
- /** `FulfillmentAssignmentData` (asyncapi.yaml): exactly these six keys. */
2573
- function assignmentPayload(
2574
- state: LoadedOrder,
2575
- assignmentId: string,
2576
- assignmentState: ReportedAssignmentState,
2577
- version: number,
2578
- now: string,
2579
- ): Record<string, unknown> {
2580
- return {
2581
- assignmentId,
2582
- orderId: state.order.orderId,
2583
- stage: state.order.stage,
2584
- state: assignmentState,
2585
- eventVersion: version,
2586
- occurredAt: now,
2587
- };
2588
- }
2589
-
2590
- /** A whole-order label purchase is in flight or held by the provider. */
2591
- function holdsLiveLabelOperation(state: LoadedOrder): boolean {
2592
- const outcome = state.provider?.outcome;
2593
- return outcome === "intent" || outcome === "accepted" || outcome === "unknown";
2594
- }
2595
-
2596
- function touchOrder(state: LoadedOrder, wantIntent: boolean): SqlStatement {
2597
- return {
2598
- sql: `UPDATE scrappy_commerce_orders
2599
- SET event_version = event_version + 1,
2600
- label_state = CASE WHEN ? = 1 THEN 'intent' ELSE label_state END
2601
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
2602
- AND fulfillment_state NOT IN ('handed_off', 'cancelled')
2603
- AND (? = 0 OR (
2604
- payment_state = 'captured' AND stock_state = 'confirmed' AND fulfillment_state = 'ready'
2605
- AND label_state IN ('none', 'voided', 'intent')
2606
- ))`,
2607
- params: [
2608
- wantIntent ? 1 : 0,
2609
- state.order.tenantId,
2610
- state.order.stage,
2611
- state.order.orderId,
2612
- state.order.eventVersion,
2613
- wantIntent ? 1 : 0,
2614
- ],
2615
- };
2616
- }
2617
-
2618
- function claimUpdate(states: readonly LoadedOrder[],now:string): SqlStatement {
2619
- const first = states[0];
2620
- if (!first) return { sql: "SELECT 0", params: [] };
2621
- const fences=states.map(state=>authorityFence(state.sourceAuthority,now,true));
2622
- const match = states.map((_,i) => `(order_id = ? AND event_version = ? AND (${fences[i]!.sql}))`).join(" OR ");
2623
- const versionParams = states.flatMap((state,i) => [state.order.orderId, state.order.eventVersion,...fences[i]!.params]);
2624
- return {
2625
- sql: `UPDATE scrappy_commerce_orders
2626
- SET event_version = event_version + 1
2627
- WHERE tenant_id = ? AND stage = ? AND (${match})
2628
- AND fulfillment_state NOT IN ('handed_off', 'cancelled')
2629
- AND (
2630
- SELECT COUNT(*) FROM scrappy_commerce_orders
2631
- WHERE tenant_id = ? AND stage = ? AND (${match})
2632
- AND fulfillment_state NOT IN ('handed_off', 'cancelled')
2633
- ) = ?`,
2634
- params: [first.order.tenantId, first.order.stage, ...versionParams, first.order.tenantId, first.order.stage, ...versionParams, states.length],
2635
- };
2636
- }
2637
-
2638
- function gatedAudit(
2639
- state: { order: LoadedOrder["order"] },
2640
- actorId: string,
2641
- kind: string,
2642
- fromState: string,
2643
- toState: string,
2644
- at: string,
2645
- gate: string,
2646
- gateParams: readonly unknown[],
2647
- ): SqlStatement {
2648
- return {
2649
- sql: `INSERT INTO scrappy_shipment_audit (
2650
- audit_id, tenant_id, stage, order_id, at, actor_id, kind, from_state, to_state
2651
- )
2652
- SELECT ?, tenant_id, stage, order_id, ?, ?, ?, ?, ?
2653
- FROM scrappy_commerce_orders
2654
- WHERE ${gate}
2655
- AND NOT EXISTS (
2656
- SELECT 1 FROM scrappy_shipment_audit AS existing
2657
- WHERE existing.tenant_id = scrappy_commerce_orders.tenant_id
2658
- AND existing.stage = scrappy_commerce_orders.stage
2659
- AND existing.order_id = scrappy_commerce_orders.order_id
2660
- AND existing.kind = ?
2661
- )`,
2662
- params: [`audit_${crypto.randomUUID()}`, at, actorId, kind, fromState, toState, ...gateParams, kind],
2663
- };
2664
- }
2665
-
2666
- function packingSlip(state: LoadedOrder, policy: CarrierPolicy): PackingSlip {
2667
- return {
2668
- orderId: state.order.orderId,
2669
- currency: state.order.currency,
2670
- lines: state.lines.map((line) => ({ sku: line.sku, quantity: line.quantity })),
2671
- adultSignatureRequired: policy.adultSignatureRequired,
2672
- prohibitedCarriers: [...policy.prohibitedCarriers],
2673
- };
2674
- }
2675
-
2676
- function projectedFulfillment(
2677
- state: LoadedOrder,
2678
- operatorHold: boolean,
2679
- cancelPending: boolean,
2680
- ): FulfillmentState {
2681
- return projectedFromSnapshot(
2682
- state.order.fulfillment,
2683
- {
2684
- fulfillment: state.order.fulfillment,
2685
- stock: state.order.stock,
2686
- label: state.order.label,
2687
- evidence: state.evidence,
2688
- },
2689
- state.order.payment,
2690
- operatorHold,
2691
- cancelPending,
2692
- );
2693
- }
2694
-
2695
- function projectedFromSnapshot(
2696
- current: FulfillmentState | null,
2697
- snapshot: Pick<SourceOrderSnapshot, "fulfillment" | "stock" | "label" | "evidence">,
2698
- payment: PaymentState,
2699
- operatorHold: boolean,
2700
- cancelPending: boolean,
2701
- ): FulfillmentState {
2702
- if (current === "handed_off") return "handed_off";
2703
- if (current === "cancelled") return "cancelled";
2704
- if (snapshot.fulfillment === "cancelled" || payment === "voided" || payment === "refunded") return "cancelled";
2705
- if (snapshot.fulfillment === "UNKNOWN") return "UNKNOWN";
2706
- const holds = releaseHolds({
2707
- // Source disposition is independent of contact delivery; commands re-read the vault.
2708
- shipTo: "present",
2709
- payment,
2710
- stock: snapshot.stock,
2711
- fulfillment: "ready",
2712
- label: snapshot.label,
2713
- evidence: snapshot.evidence,
2714
- operatorHold,
2715
- cancelPending,
2716
- providerOutcome: null,
2717
- adultSignature: "absent",
2718
- adultSignatureRequired: false,
2719
- });
2720
- if (holds.length > 0 || operatorHold || cancelPending) return "held";
2721
- return "ready";
2722
- }
2723
-
2724
- function validateSnapshot(snapshot: SourceOrderSnapshot): string | null {
2725
- if (!isOpaqueId(snapshot.orderId) || !isOpaqueId(snapshot.source) || !isOpaqueId(snapshot.sourceOrderId)) return "malformed";
2726
- if (!/^[A-Z]{3}$/.test(snapshot.currency)) return "malformed";
2727
- if (snapshot.placedAt.trim() === "" || snapshot.placedAt.includes("\n")) return "malformed";
2728
- if (!Number.isSafeInteger(snapshot.amountMinor) || snapshot.amountMinor < 0) return "malformed";
2729
- if (!oneOf(snapshot.payment, PAYMENT_STATES) || !oneOf(snapshot.compliance, COMPLIANCE_STATES)) return "malformed";
2730
- if (!oneOf(snapshot.stock, STOCK_STATES) || !oneOf(snapshot.fulfillment, FULFILLMENT_STATES)) return "malformed";
2731
- if (!oneOf(snapshot.label, LABEL_STATES) || !oneOf(snapshot.stage, ["preview", "publication"] as const)) return "malformed";
2732
- if (!parseEvidence(snapshot.evidence) || !parseLines(snapshot.lines) || !parseTotals(snapshot.totals)) return "malformed";
2733
- if (snapshot.amountMinor !== snapshot.totals.totalMinor || !totalsMatch(snapshot.totals)) return "malformed";
2734
- return null;
2735
- }
2736
-
2737
- function labelOutcomeColumns(outcome: "purchased" | "unknown" | "voided"): {
2738
- order: LabelState;
2739
- shipment: string;
2740
- provider: ProviderOutcome;
2741
- } {
2742
- if (outcome === "purchased") return { order: "purchased", shipment: "purchased", provider: "accepted" };
2743
- if (outcome === "voided") return { order: "voided", shipment: "voided", provider: "voided" };
2744
- return { order: "UNKNOWN", shipment: "unknown", provider: "unknown" };
2745
- }
2746
-
2747
- function parseBatchState(value: string): { batchId: string; phase: BatchPhase } | null {
2748
- const split = value.indexOf("|");
2749
- if (split <= 0) return null;
2750
- const phase = value.slice(0, split);
2751
- const batchId = value.slice(split + 1);
2752
- if ((phase !== "claimed" && phase !== "picked" && phase !== "packed") || !isOpaqueId(batchId)) return null;
2753
- return { phase, batchId };
2754
- }
2755
-
2756
- function parseSlip(value: unknown): PackingSlip | null {
2757
- if (!isRecord(value) || typeof value.orderId !== "string" || typeof value.currency !== "string") return null;
2758
- const lines = parseLines(value.lines);
2759
- if (!lines) return null;
2760
- return {
2761
- orderId: value.orderId,
2762
- currency: value.currency,
2763
- lines,
2764
- adultSignatureRequired: value.adultSignatureRequired === true,
2765
- prohibitedCarriers: Array.isArray(value.prohibitedCarriers)
2766
- ? value.prohibitedCarriers.filter((item): item is string => typeof item === "string")
2767
- : [],
2768
- };
2769
- }
2770
-
2771
- const APP_ACTOR_PREFIX = "app:";
2772
-
2773
- /** The binding an install actor writes under; null for any other actor or an unusable id. */
2774
- function appBinding(actor: FulfillmentActor, assignmentId: string): AppAssignmentBinding | null {
2775
- if (actor.role !== "caller" || !actor.actorId.startsWith(APP_ACTOR_PREFIX)) return null;
2776
- const installId = actor.actorId.slice(APP_ACTOR_PREFIX.length);
2777
- if (!isOpaqueId(installId) || !isOpaqueId(assignmentId)) return null;
2778
- if (!actorMayCommand(actor, { tenantId: actor.tenantId, stage: actor.stage })) return null;
2779
- return { installId, assignmentId };
2780
- }
2781
-
2782
- function scopeListIncludes(scopes: unknown, scope: string): boolean {
2783
- const parsed = typeof scopes === "string" ? parseJson(scopes) : null;
2784
- return Array.isArray(parsed) && parsed.includes(scope);
2785
- }
2786
-
2787
- /** The minimized app view of `state`, or of its planned successor when `next` is given. */
2788
- function appShipmentView(
2789
- state: LoadedOrder,
2790
- purchaseId: string,
2791
- next: { version?: number; label?: LabelState; handoff?: AppShipmentView["handoff"]; facts?: StoredLabelFacts | null } = {},
2792
- ): AppShipmentView {
2793
- const handoff =
2794
- next.handoff ??
2795
- (state.shipment?.handoffState === "handed_off" || state.order.fulfillment === "handed_off"
2796
- ? "handed_off"
2797
- : state.order.fulfillment === "UNKNOWN"
2798
- ? "unknown"
2799
- : "none");
2800
- const facts = next.facts === undefined ? state.labelOutcome : next.facts;
2801
- return {
2802
- orderId: state.order.orderId,
2803
- version: next.version ?? state.order.eventVersion,
2804
- label: next.label ?? state.order.label,
2805
- handoff,
2806
- purchaseId,
2807
- ...(facts?.carrier ? { carrier: facts.carrier } : {}),
2808
- ...(facts?.trackingNumber && facts.trackingUrl ? { tracking: { number: facts.trackingNumber, url: facts.trackingUrl } } : {}),
2809
- };
2810
- }
2811
-
2812
- /** A stored audit state that is not JSON parses to null, which every caller fails closed on. */
2813
- function parseJson(value: string): unknown {
2814
- try {
2815
- return JSON.parse(value) as unknown;
2816
- } catch (error) {
2817
- if (error instanceof SyntaxError) return null;
2818
- throw error;
2819
- }
2820
- }
2821
-
2822
- /** The open label_purchase operation; the unique index allows at most one. */
2823
- function openProvider(rows: readonly { purchase_id: string; outcome: string }[]): LoadedOrder["provider"] {
2824
- const open = rows.find((row) => row.outcome === "intent" || row.outcome === "accepted" || row.outcome === "unknown");
2825
- if (!open || !oneOf(open.outcome, ["intent", "accepted", "unknown"] as const)) return null;
2826
- return { purchaseId: open.purchase_id, outcome: open.outcome };
2827
- }
2828
-
2829
- /** With none open, the operation of the latest voided attempt, else any settled one. */
2830
- function settledOperation(rows: readonly { purchase_id: string; outcome: string }[], lastVoided: string | null): LoadedOrder["settledProvider"] {
2831
- const chosen = rows.find((row) => row.purchase_id === lastVoided) ?? rows[0];
2832
- if (!chosen || !oneOf(chosen.outcome, ["voided", "refunded"] as const)) return null;
2833
- return { purchaseId: chosen.purchase_id, outcome: chosen.outcome };
2834
- }
2835
-
2836
- function projectionCheckpoint(snapshot:SourceOrderSnapshot,version:number,at:string):SqlStatement {
2837
- return {sql:`INSERT INTO commerce_projection_checkpoints(tenant_id,stage,order_id,source_version,projected_at)
2838
- SELECT ?,?,?,?,? WHERE EXISTS(SELECT 1 FROM scrappy_commerce_orders WHERE tenant_id=? AND stage=? AND order_id=? AND event_version=?)
2839
- ON CONFLICT(tenant_id,stage,order_id) DO UPDATE SET source_version=excluded.source_version,projected_at=excluded.projected_at
2840
- WHERE excluded.source_version>commerce_projection_checkpoints.source_version`,
2841
- params:[snapshot.tenantId,snapshot.stage,snapshot.orderId,snapshot.sourceVersion,at,snapshot.tenantId,snapshot.stage,snapshot.orderId,version]};
2842
- }