@openrails/billing-ui 0.281.0 → 0.283.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 (221) hide show
  1. package/README.md +108 -364
  2. package/dist/account/format.d.ts +6 -2
  3. package/dist/admin/context.d.ts +38 -46
  4. package/dist/admin/lib/api/endpoints.d.ts +4 -4
  5. package/dist/admin/lib/api/index.d.ts +4 -4
  6. package/dist/admin/lib/api/metrics.d.ts +15 -6
  7. package/dist/admin/lib/capabilities.d.ts +2 -0
  8. package/dist/admin/lib/duration.d.ts +4 -0
  9. package/dist/admin/lib/format.d.ts +29 -1
  10. package/dist/admin/lib/mutations.d.ts +0 -10
  11. package/dist/admin/lib/queries.d.ts +16 -10
  12. package/dist/admin/messages.d.ts +61 -20
  13. package/dist/admin/pages/catalog/price-wizard-logic.d.ts +2 -0
  14. package/dist/admin/pages/catalog/price-wizard.d.ts +1 -3
  15. package/dist/admin/pages/customers/credits.d.ts +4 -1
  16. package/dist/admin/pages/dashboard/levels.d.ts +8 -0
  17. package/dist/admin/pages/dashboard/lib.d.ts +16 -7
  18. package/dist/admin/pages/dashboard/programs.d.ts +3 -0
  19. package/dist/admin/pages/dashboard/query-builder.d.ts +20 -0
  20. package/dist/admin/pages/dashboard/range.d.ts +8 -2
  21. package/dist/admin/pages/dashboard/registry.d.ts +14 -0
  22. package/dist/admin/pages/dashboard/reports-model.d.ts +8 -4
  23. package/dist/admin/pages/dashboard/reports.d.ts +1 -1
  24. package/dist/admin/pages/dashboard/units.d.ts +5 -0
  25. package/dist/admin/pages/dashboard/use-range.d.ts +5 -1
  26. package/dist/admin/pages/dashboard/widget-editor.d.ts +7 -2
  27. package/dist/admin/pages/dashboard/widget-tile.d.ts +10 -4
  28. package/dist/admin/pages/dashboard/widget-viz.d.ts +10 -5
  29. package/dist/admin/pages/ops/signals.d.ts +4 -0
  30. package/dist/admin/pages/payments/attempts.d.ts +2 -2
  31. package/dist/admin/pages/payments/health-model.d.ts +20 -20
  32. package/dist/admin/pages/subscriptions/views.d.ts +4 -0
  33. package/dist/admin-attempts-CRkxeVfQ.js +417 -0
  34. package/dist/admin-attempts-CRkxeVfQ.js.map +1 -0
  35. package/dist/{admin-auth-BUUdvmqC.js → admin-auth-C0pBH3kp.js} +2 -2
  36. package/dist/{admin-auth-BUUdvmqC.js.map → admin-auth-C0pBH3kp.js.map} +1 -1
  37. package/dist/{admin-badge-CAlUmS2s.js → admin-badge-C_-j7ANF.js} +2 -2
  38. package/dist/{admin-badge-CAlUmS2s.js.map → admin-badge-C_-j7ANF.js.map} +1 -1
  39. package/dist/{admin-button-Bn4otsuw.js → admin-button-BV5MAL2H.js} +2 -2
  40. package/dist/{admin-button-Bn4otsuw.js.map → admin-button-BV5MAL2H.js.map} +1 -1
  41. package/dist/{admin-capabilities-DS-X-__V.js → admin-capabilities-B3ZfkA49.js} +21 -13
  42. package/dist/admin-capabilities-B3ZfkA49.js.map +1 -0
  43. package/dist/{admin-card-BHKW1dfB.js → admin-card-DQ61c-kV.js} +2 -2
  44. package/dist/{admin-card-BHKW1dfB.js.map → admin-card-DQ61c-kV.js.map} +1 -1
  45. package/dist/admin-catalog-DAnsClai.js +867 -0
  46. package/dist/admin-catalog-DAnsClai.js.map +1 -0
  47. package/dist/{admin-cursor-pager-Qo9Sq6lN.js → admin-cursor-pager-dkNj-gb6.js} +22 -22
  48. package/dist/{admin-cursor-pager-Qo9Sq6lN.js.map → admin-cursor-pager-dkNj-gb6.js.map} +1 -1
  49. package/dist/admin-customer-search-DDMn_5Us.js +115 -0
  50. package/dist/admin-customer-search-DDMn_5Us.js.map +1 -0
  51. package/dist/{admin-customers-BZP6Jv-i.js → admin-customers-BMaugwpg.js} +24 -25
  52. package/dist/admin-customers-BMaugwpg.js.map +1 -0
  53. package/dist/admin-dashboard-DbbfrIOq.js +510 -0
  54. package/dist/admin-dashboard-DbbfrIOq.js.map +1 -0
  55. package/dist/{admin-data-table-BiFmcf0Z.js → admin-data-table-BjA8cBsr.js} +5 -5
  56. package/dist/{admin-data-table-BiFmcf0Z.js.map → admin-data-table-BjA8cBsr.js.map} +1 -1
  57. package/dist/admin-detail-BVJcnTO-.js +1361 -0
  58. package/dist/admin-detail-BVJcnTO-.js.map +1 -0
  59. package/dist/{admin-detail-cijme9Lc.js → admin-detail-DO9wd12I.js} +130 -107
  60. package/dist/admin-detail-DO9wd12I.js.map +1 -0
  61. package/dist/{admin-detail-CQws8363.js → admin-detail-M7YFYOGN.js} +211 -210
  62. package/dist/{admin-detail-CQws8363.js.map → admin-detail-M7YFYOGN.js.map} +1 -1
  63. package/dist/admin-detail-sOLj-K-Y.js +336 -0
  64. package/dist/{admin-detail-NApy5bio.js.map → admin-detail-sOLj-K-Y.js.map} +1 -1
  65. package/dist/admin-detail-uZ-eR2TT.js +292 -0
  66. package/dist/{admin-detail-C6VH3i2v.js.map → admin-detail-uZ-eR2TT.js.map} +1 -1
  67. package/dist/{admin-dialog-CgYGInHi.js → admin-dialog-BxRcYcQM.js} +3 -3
  68. package/dist/{admin-dialog-CgYGInHi.js.map → admin-dialog-BxRcYcQM.js.map} +1 -1
  69. package/dist/{admin-dropdown-menu-CU9RxoEJ.js → admin-dropdown-menu-DlyaKwyU.js} +2 -2
  70. package/dist/{admin-dropdown-menu-CU9RxoEJ.js.map → admin-dropdown-menu-DlyaKwyU.js.map} +1 -1
  71. package/dist/{admin-dunning-D8lAP7OA.js → admin-dunning-CDy6aMAj.js} +2 -2
  72. package/dist/{admin-dunning-D8lAP7OA.js.map → admin-dunning-CDy6aMAj.js.map} +1 -1
  73. package/dist/{admin-fact-card-lN-MsuSp.js → admin-fact-card-2DujC_r3.js} +2 -2
  74. package/dist/{admin-fact-card-lN-MsuSp.js.map → admin-fact-card-2DujC_r3.js.map} +1 -1
  75. package/dist/{admin-utils-CX097OR7.js → admin-format-Bc4NWK0F.js} +495 -328
  76. package/dist/admin-format-Bc4NWK0F.js.map +1 -0
  77. package/dist/{admin-health-CnagC763.js → admin-health-DePsyIlc.js} +217 -196
  78. package/dist/admin-health-DePsyIlc.js.map +1 -0
  79. package/dist/{admin-imports-SM_fKKgW.js → admin-imports-BrQH3u9M.js} +85 -86
  80. package/dist/{admin-imports-SM_fKKgW.js.map → admin-imports-BrQH3u9M.js.map} +1 -1
  81. package/dist/{admin-input-B_EUzCAE.js → admin-input-BZ2ExV_5.js} +2 -2
  82. package/dist/{admin-input-B_EUzCAE.js.map → admin-input-BZ2ExV_5.js.map} +1 -1
  83. package/dist/{admin-label-DQsOkp1p.js → admin-label-DecDO0oV.js} +2 -2
  84. package/dist/{admin-label-DQsOkp1p.js.map → admin-label-DecDO0oV.js.map} +1 -1
  85. package/dist/{admin-linked-table-row-BFsgc9tz.js → admin-linked-table-row-ChxhVptQ.js} +3 -3
  86. package/dist/{admin-linked-table-row-BFsgc9tz.js.map → admin-linked-table-row-ChxhVptQ.js.map} +1 -1
  87. package/dist/{admin-map-dialog-Dt3gTuTD.js → admin-map-dialog-CQmGOBMw.js} +12 -12
  88. package/dist/{admin-map-dialog-Dt3gTuTD.js.map → admin-map-dialog-CQmGOBMw.js.map} +1 -1
  89. package/dist/admin-metering-OXGOVQ7e.js +1716 -0
  90. package/dist/{admin-metering-DM4KhjOq.js.map → admin-metering-OXGOVQ7e.js.map} +1 -1
  91. package/dist/{admin-missing-record-G2Jz-VUn.js → admin-missing-record-B_9LpSIW.js} +4 -4
  92. package/dist/{admin-missing-record-G2Jz-VUn.js.map → admin-missing-record-B_9LpSIW.js.map} +1 -1
  93. package/dist/admin-ops-BTSunx1i.js +357 -0
  94. package/dist/{admin-ops-mwzj-jpg.js.map → admin-ops-BTSunx1i.js.map} +1 -1
  95. package/dist/{admin-orders-D_aqV66h.js → admin-orders-LqlpQVFo.js} +59 -60
  96. package/dist/{admin-orders-D_aqV66h.js.map → admin-orders-LqlpQVFo.js.map} +1 -1
  97. package/dist/{admin-parked-2FjIfyMg.js → admin-parked-Ch6mlS5f.js} +61 -62
  98. package/dist/{admin-parked-2FjIfyMg.js.map → admin-parked-Ch6mlS5f.js.map} +1 -1
  99. package/dist/{admin-payments-B4hh31PR.js → admin-payments-yNntF4i4.js} +42 -42
  100. package/dist/{admin-payments-B4hh31PR.js.map → admin-payments-yNntF4i4.js.map} +1 -1
  101. package/dist/{admin-price-detail--5Bovz20.js → admin-price-detail-DvmcYr8B.js} +131 -132
  102. package/dist/admin-price-detail-DvmcYr8B.js.map +1 -0
  103. package/dist/{admin-price-format-C-pus9FL.js → admin-price-format-Btdg11-J.js} +14 -5
  104. package/dist/admin-price-format-Btdg11-J.js.map +1 -0
  105. package/dist/admin-price-wizard-EFO3nBV8.js +376 -0
  106. package/dist/admin-price-wizard-EFO3nBV8.js.map +1 -0
  107. package/dist/{admin-proposals-DPRFoWel.js → admin-proposals-CO0LKHM8.js} +119 -120
  108. package/dist/{admin-proposals-DPRFoWel.js.map → admin-proposals-CO0LKHM8.js.map} +1 -1
  109. package/dist/admin-provider-prices-ZjQeEV1n.js +239 -0
  110. package/dist/{admin-provider-prices-B8Oc86dP.js.map → admin-provider-prices-ZjQeEV1n.js.map} +1 -1
  111. package/dist/admin-query-builder-DedekYUU.js +252 -0
  112. package/dist/admin-query-builder-DedekYUU.js.map +1 -0
  113. package/dist/{admin-range-picker-CSWcCYkg.js → admin-range-picker-1WGFlYYw.js} +46 -24
  114. package/dist/admin-range-picker-1WGFlYYw.js.map +1 -0
  115. package/dist/admin-records-A2R52prt.js +389 -0
  116. package/dist/{admin-records-CWbfqyT8.js.map → admin-records-A2R52prt.js.map} +1 -1
  117. package/dist/admin-reports-ySY9v463.js +420 -0
  118. package/dist/admin-reports-ySY9v463.js.map +1 -0
  119. package/dist/{admin-select-DSGCZFiZ.js → admin-select-CgZq2j0G.js} +2 -2
  120. package/dist/{admin-select-DSGCZFiZ.js.map → admin-select-CgZq2j0G.js.map} +1 -1
  121. package/dist/admin-settings-kOW1nPGB.js +1818 -0
  122. package/dist/admin-settings-kOW1nPGB.js.map +1 -0
  123. package/dist/{admin-shared-DdN2hyaR.js → admin-shared-DoBOSwkv.js} +33 -34
  124. package/dist/{admin-shared-DdN2hyaR.js.map → admin-shared-DoBOSwkv.js.map} +1 -1
  125. package/dist/admin-signals-D_iWk2r5.js +124 -0
  126. package/dist/admin-signals-D_iWk2r5.js.map +1 -0
  127. package/dist/{admin-skeleton-DOfsDIu0.js → admin-skeleton-DdqwXcr4.js} +2 -2
  128. package/dist/{admin-skeleton-DOfsDIu0.js.map → admin-skeleton-DdqwXcr4.js.map} +1 -1
  129. package/dist/{admin-status-badge-BLEGt2Fw.js → admin-status-badge-B8rjk6QR.js} +5 -3
  130. package/dist/admin-status-badge-B8rjk6QR.js.map +1 -0
  131. package/dist/{admin-subscriptions-PL5G3f0O.js → admin-subscriptions-CjYPSPs-.js} +43 -38
  132. package/dist/admin-subscriptions-CjYPSPs-.js.map +1 -0
  133. package/dist/{admin-switch-aOiQQzST.js → admin-switch-CyYmt8wi.js} +2 -2
  134. package/dist/{admin-switch-aOiQQzST.js.map → admin-switch-CyYmt8wi.js.map} +1 -1
  135. package/dist/{admin-table-DIKl2rpV.js → admin-table-ByPfWNq8.js} +2 -2
  136. package/dist/{admin-table-DIKl2rpV.js.map → admin-table-ByPfWNq8.js.map} +1 -1
  137. package/dist/admin-tabs-DKa6QljL.js +45 -0
  138. package/dist/admin-tabs-DKa6QljL.js.map +1 -0
  139. package/dist/{admin-textarea-W52-l_0n.js → admin-textarea-CQg__KGc.js} +2 -2
  140. package/dist/{admin-textarea-W52-l_0n.js.map → admin-textarea-CQg__KGc.js.map} +1 -1
  141. package/dist/{admin-typed-confirm-dialog-B_00EHlT.js → admin-typed-confirm-dialog-BvAYEh3H.js} +6 -6
  142. package/dist/{admin-typed-confirm-dialog-B_00EHlT.js.map → admin-typed-confirm-dialog-BvAYEh3H.js.map} +1 -1
  143. package/dist/admin-widget-tile-DDI3eaRy.js +290 -0
  144. package/dist/admin-widget-tile-DDI3eaRy.js.map +1 -0
  145. package/dist/admin-widget-viz-Db9CQ2Sx.js +1084 -0
  146. package/dist/admin-widget-viz-Db9CQ2Sx.js.map +1 -0
  147. package/dist/admin.css +1 -1
  148. package/dist/admin.js +660 -609
  149. package/dist/admin.js.map +1 -1
  150. package/dist/buy-button.d.ts +4 -2
  151. package/dist/cart.d.ts +4 -2
  152. package/dist/client/client.d.ts +16 -3
  153. package/dist/client/generated/error-codes.d.ts +1 -1
  154. package/dist/client/generated/routes.d.ts +296 -181
  155. package/dist/client/generated/wire.d.ts +514 -277
  156. package/dist/client/index.d.ts +1 -1
  157. package/dist/client/types.d.ts +76 -8
  158. package/dist/{client-DwsFGm4M.js → client-D8qT6xjo.js} +86 -44
  159. package/dist/client-D8qT6xjo.js.map +1 -0
  160. package/dist/client.js +1 -1
  161. package/dist/components/billing-fields.d.ts +5 -3
  162. package/dist/components/platform-card-form.d.ts +3 -1
  163. package/dist/{hooks-C-MhXjQh.js → hooks-CX09fAJA.js} +86 -60
  164. package/dist/hooks-CX09fAJA.js.map +1 -0
  165. package/dist/index.d.ts +1 -1
  166. package/dist/index.js +847 -779
  167. package/dist/index.js.map +1 -1
  168. package/dist/lib/billing-fields.d.ts +15 -0
  169. package/dist/lib/billing.d.ts +23 -5
  170. package/dist/lib/price-label.d.ts +1 -1
  171. package/dist/locales/en.d.ts +4 -0
  172. package/dist/locales/en.js +4 -0
  173. package/dist/locales/en.js.map +1 -1
  174. package/dist/product-list.d.ts +4 -2
  175. package/dist/react/config.d.ts +10 -2
  176. package/dist/react/index.d.ts +1 -1
  177. package/dist/react.js +1 -1
  178. package/dist/styles.css +1 -1
  179. package/dist/tokenized-card-form.d.ts +10 -2
  180. package/docs/payment-form-contract.md +6 -15
  181. package/package.json +6 -6
  182. package/dist/admin/lib/api/copilot.d.ts +0 -6
  183. package/dist/admin/pages/catalog/copilot-panel.d.ts +0 -4
  184. package/dist/admin-attempts-DjgBAbx9.js +0 -418
  185. package/dist/admin-attempts-DjgBAbx9.js.map +0 -1
  186. package/dist/admin-capabilities-DS-X-__V.js.map +0 -1
  187. package/dist/admin-catalog-BdLDhr8R.js +0 -1096
  188. package/dist/admin-catalog-BdLDhr8R.js.map +0 -1
  189. package/dist/admin-customers-BZP6Jv-i.js.map +0 -1
  190. package/dist/admin-dashboard-BJSonknv.js +0 -461
  191. package/dist/admin-dashboard-BJSonknv.js.map +0 -1
  192. package/dist/admin-detail-C03O0R6e.js +0 -1351
  193. package/dist/admin-detail-C03O0R6e.js.map +0 -1
  194. package/dist/admin-detail-C6VH3i2v.js +0 -293
  195. package/dist/admin-detail-NApy5bio.js +0 -337
  196. package/dist/admin-detail-cijme9Lc.js.map +0 -1
  197. package/dist/admin-format-D9Ablh0P.js +0 -169
  198. package/dist/admin-format-D9Ablh0P.js.map +0 -1
  199. package/dist/admin-health-CnagC763.js.map +0 -1
  200. package/dist/admin-metering-DM4KhjOq.js +0 -1717
  201. package/dist/admin-ops-mwzj-jpg.js +0 -358
  202. package/dist/admin-price-detail--5Bovz20.js.map +0 -1
  203. package/dist/admin-price-format-C-pus9FL.js.map +0 -1
  204. package/dist/admin-price-wizard-Cj_Bgh-V.js +0 -354
  205. package/dist/admin-price-wizard-Cj_Bgh-V.js.map +0 -1
  206. package/dist/admin-provider-prices-B8Oc86dP.js +0 -240
  207. package/dist/admin-range-picker-CSWcCYkg.js.map +0 -1
  208. package/dist/admin-records-CWbfqyT8.js +0 -390
  209. package/dist/admin-reports-CAHWO_d6.js +0 -319
  210. package/dist/admin-reports-CAHWO_d6.js.map +0 -1
  211. package/dist/admin-settings-BrvNTJlM.js +0 -1818
  212. package/dist/admin-settings-BrvNTJlM.js.map +0 -1
  213. package/dist/admin-status-badge-BLEGt2Fw.js.map +0 -1
  214. package/dist/admin-subscriptions-PL5G3f0O.js.map +0 -1
  215. package/dist/admin-tabs-DR74xX0-.js +0 -156
  216. package/dist/admin-tabs-DR74xX0-.js.map +0 -1
  217. package/dist/admin-utils-CX097OR7.js.map +0 -1
  218. package/dist/admin-widget-viz-DVV9aTQp.js +0 -643
  219. package/dist/admin-widget-viz-DVV9aTQp.js.map +0 -1
  220. package/dist/client-DwsFGm4M.js.map +0 -1
  221. package/dist/hooks-C-MhXjQh.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin-format-Bc4NWK0F.js","names":["sonnerToast","currencyUnits","AdminUIContext","createContext","useAdminUI","context","useContext","id","value","message","AdminMessage","GATEWAY_STATUS","FETCH_FAILURE","transportFailure","error","name","code","status","en","ApiError","body","fallback","parseError","res","failure","unanswered","buildURL","url","base","path","query","params","k","v","qs","collectCursorPages","rows","cursor","page","loadPage","createAdminClient","baseUrl","options","selectedMerchant","send","headers","opts","init","apiResponse","merchant","requested","ATTEMPT_FILTERS","CYCLE_FILTERS","filtersFrom","out","key","keys","REFUNDABLE_RAILS","createEndpoints","client","listCustomers","api","getCustomer","customerId","listCustomerEntitlements","listCustomerProductAccess","listCustomerPaymentMethods","grantProductAccess","grant","revokeProductAccess","grantId","listSubscriptions","filters","getSubscription","cancelSubscription","revokeAccess","resumeSubscription","changeSubscriptionPaymentMethod","paymentMethodId","listSubscriptionChangeOptions","previewSubscriptionChange","change","changeSubscription","idempotencyKey","listPayments","getPayment","refundPayment","reason","listPaymentAttempts","getPaymentAttempt","listRenewals","getRenewal","listProducts","getProduct","createProduct","updateProduct","listUsageMeters","getUsageMeter","putUsageMeter","putUsageMeterRateCard","meter","rateCard","listPrices","productId","createPrice","getPrice","verify","updatePrice","getPriceHistory","priceId","previewPriceMigration","productKey","priceKey","createPriceMigration","toPriceId","effectiveAt","listPriceMigrations","cancelPriceMigration","applyCatalog","document","force","listFindings","getFinding","resolveFinding","listDestructiveHolds","clearDestructiveHold","getMerchantConfiguration","updateMerchantConfiguration","listPSPs","listCustodians","deleteCustomerPaymentMethod","customer","method","putCustodian","listRails","getConfig","signal","createPSP","updatePSP","previewPSPRouting","queryless","viz","CHART_VIZ","createMetrics","at","customerPath","createCreditEndpoints","createOrderEndpoints","listOrders","getOrder","listOrderPayments","applyUsageAction","request","createInvoiceProfileEndpoints","endpoints","updateCustomer","profile","settings","createImportEndpoints","ids","createAdminAPI","staffErrors","sentence","trimmed","text","first","errorText","createAdminToast","scoped","namespace","toast","createToastHandlers","toastApiError","err","action","toastStaleEdit","what","metricsRow","row","result","column","i","collectPages","buildQueryKeys","root","queryErrorMeta","errorAction","createQueries","currentMerchantRoot","queryRoot","queryKeys","queryOptions","search","limit","keepPreviousData","metricsQuery","group","n","getAdminAccess","listWebhooks","getDashboard","getMetricsSchema","listDisputePrograms","EXPORT_PAGE","collectAllCursorPages","listPage","invalidateExact","queryClient","invalidateExactOnSuccess","queryKey","invalidateTreeOnSuccess","reloadIfMoved","createMutations","queries","readOnlyNow","adminQueries","webhooksChanged","dashboardKey","merchantQueryKeys","mutationOptions","putDashboard","widgets","saved","customersKey","term","subscriptionsKey","paymentsKey","opsKey","outcome","notes","customerKey","subscriptionKey","subscriptionId","paymentId","amount","product","active","revision","price","metersKey","created","migration","migrationId","update","psp","currency","l","createWebhook","webhook","updateWebhook","deleteWebhook","createCreditQueries","scopedCustomerKey","assertMerchant","listCreditGrants","listBalanceTransactions","createCreditGrant","input","revokeCreditGrant","createOrderQueries","orderAPI","profileAPI","orderKeys","orderQueries","usageActionMutation","invoiceProfileMutation","importBusy","POLL_MS","keysOf","createImportQueries","importKeys","pinnedKeys","version","ref","o","mappings","finding","createAdminServices","AdminContext","useAdminContext","useAdminServices","Context","subscribe","notify","snapshot","AdminRouter","current","useSyncExternalStore","basePath","pathname","navigation","relative","states","setStates","useState","href","useCallback","to","resolved","navigate","target","previous","useMemo","useRouter","router","useLocation","useNavigate","useParams","useSearchParams","location","Link","props","onClick","event","Navigate","useEffect","replace","RouteParams","cn","inputs","twMerge","clsx","BRAND_ALIASES","BRAND_LABELS","cardBrandLabel","brand","resolveCardBrand","OPENRAILS_CURRENCY_SCALES","INT64_MIN","INT64_MAX","intlFormatsDecimalStringsExactly","LEGACY_EXACT_UNITS","currencyScale","supportedCurrencies","validDecimals","decimals","exactUnits","unitsToDecimal","decimalFromUnits","absolute","scale","fraction","formatUnits","units","decimal","digits","merchantUnits","currencies","u","formatSummaryAmount","unit","formatNativeAmount","unitScales","balances","b","declaredUnits","formatScaledAmount","formatBalanceAmount","balance","amountFromInput","match","major","signed","nativeAmountFromInput","nativeAmountToInput","formatDate","iso","d","formatCard","card","formatCardExpiry","shortId","customerName","c","rowCustomer","timeAgo","then","secs","mins","hours","days"],"sources":["../src/admin/ui-context.tsx","../src/client/errors.ts","../src/locales/en.ts","../src/admin/lib/api/client.ts","../src/admin/lib/api/endpoints.ts","../src/admin/lib/api/metrics.ts","../src/admin/lib/api/credit-endpoints.ts","../src/admin/lib/api/order-endpoints.ts","../src/admin/lib/api/invoice-profile-endpoints.ts","../src/admin/lib/api/import-endpoints.ts","../src/admin/lib/api/index.ts","../src/admin/lib/error-text.ts","../src/admin/lib/toast.ts","../src/admin/lib/queries.ts","../src/admin/lib/mutations.ts","../src/admin/lib/credit-queries.ts","../src/admin/lib/order-queries.ts","../src/admin/lib/import-queries.ts","../src/admin/context.tsx","../src/admin/router.tsx","../src/admin/lib/utils.ts","../src/lib/card-brands.ts","../src/client/generated/currencies.ts","../src/admin/lib/format.ts"],"sourcesContent":["import { createContext, useContext } from \"react\"\n\nexport const AdminUIContext = createContext<{\n namespace: string\n messages?: Record<string, string>\n}>({ namespace: \"\" })\n\nexport function useAdminUI() {\n const context = useContext(AdminUIContext)\n function id(value: string): string\n function id(value: string | undefined): string | undefined\n function id(value: string | undefined) {\n return value === undefined ? undefined : `${context.namespace}${value}`\n }\n return {\n text: (message: string) => context.messages?.[message] ?? message,\n id,\n }\n}\n\nexport function AdminMessage({ id }: { id: string }) {\n return useAdminUI().text(id)\n}\n","// Mirrors OpenRails internal/api.ErrorResponse:\n// {\"error\":{\"type\",\"code\",\"message\",\"request_id?\",\"param?\",\"metadata?\"}}.\nexport interface BillingErrorBody {\n type: string\n code: string\n message: string\n request_id?: string\n param?: string\n metadata?: Record<string, unknown>\n /** The order a failed payment left open (402 card_error). */\n order?: unknown\n}\n\n// Local codes: network_error (no server reached), server_unavailable (a\n// gateway or timeout answered), server_error (a 5xx without an envelope),\n// invalid_response, unknown_error, and the wallet codes a wallet next action\n// raises (wallet_rejected, wallet_no_signature, wallet_required).\nexport class BillingError extends Error {\n readonly status: number\n readonly type: string\n readonly code: string\n readonly param?: string\n readonly requestId?: string\n readonly metadata: Record<string, unknown>\n /** The order a failed payment left open, unvalidated. */\n readonly order?: unknown\n\n constructor(status: number, body: BillingErrorBody) {\n super(body.message)\n this.name = \"BillingError\"\n this.status = status\n this.type = body.type\n this.code = body.code\n this.param = body.param\n this.requestId = body.request_id\n this.metadata = body.metadata ?? {}\n this.order = body.order\n }\n}\n\nexport const isBillingError = (value: unknown): value is BillingError =>\n value instanceof BillingError\n\n/** A server failure (HTTP 5xx) from any client or host source that carries a numeric `status`. */\nexport const isServerError = (value: unknown): boolean => {\n const status = (value as { status?: unknown } | null)?.status\n return typeof status === \"number\" && status >= 500 && status < 600\n}\n\nexport function localError(code: string, message: string): BillingError {\n return new BillingError(0, { type: \"local\", code, message })\n}\n\nexport async function readBillingError(res: Response): Promise<BillingError> {\n let body: unknown\n try {\n body = await res.json()\n } catch {\n body = undefined\n }\n const err = (body as { error?: unknown } | undefined)?.error\n if (err && typeof err === \"object\") {\n const e = err as Partial<BillingErrorBody>\n if (typeof e.code === \"string\" && e.code) {\n return new BillingError(res.status, {\n type: typeof e.type === \"string\" ? e.type : \"\",\n code: e.code,\n message: typeof e.message === \"string\" ? e.message : e.code,\n request_id:\n typeof e.request_id === \"string\"\n ? e.request_id\n : (res.headers.get(\"X-Request-ID\") ?? undefined),\n param: typeof e.param === \"string\" ? e.param : undefined,\n metadata:\n e.metadata && typeof e.metadata === \"object\" ? e.metadata : undefined,\n order: e.order,\n })\n }\n }\n return new BillingError(res.status, {\n type: res.status >= 500 ? \"api_error\" : \"\",\n code:\n typeof err === \"string\" && err\n ? err\n : GATEWAY_STATUS.has(res.status)\n ? \"server_unavailable\"\n : res.status >= 500\n ? \"server_error\"\n : \"unknown_error\",\n message: `HTTP ${res.status}`,\n })\n}\n\n// A gateway answered for OpenRails: down, restarting or timed out (52x: Cloudflare).\nconst GATEWAY_STATUS = new Set([502, 503, 504, 520, 521, 522, 523, 524])\n\n// fetch rejects with a TypeError when no server answers (offline, DNS,\n// connection refused, CORS); engines word it differently.\nconst FETCH_FAILURE = /fetch|network|load failed|connection/i\n\n/** The local code of a request OpenRails never answered, if it is one. */\nexport function transportFailure(\n error: unknown\n): \"network_error\" | \"server_unavailable\" | undefined {\n if (error instanceof TypeError) {\n const offline = globalThis.navigator?.onLine === false\n return offline || FETCH_FAILURE.test(error.message)\n ? \"network_error\"\n : undefined\n }\n if (!error || typeof error !== \"object\") return undefined\n const { name, code, status } = error as {\n name?: unknown\n code?: unknown\n status?: unknown\n }\n if (name === \"TimeoutError\") return \"server_unavailable\"\n if (code === \"network_error\" || code === \"server_unavailable\") return code\n if (code === undefined || code === \"unknown_error\" || code === \"server_error\")\n return typeof status === \"number\" && GATEWAY_STATUS.has(status)\n ? \"server_unavailable\"\n : undefined\n return undefined\n}\n\n// Normalizes anything a client call can throw into a BillingError.\nexport function toBillingError(error: unknown): BillingError {\n if (error instanceof BillingError) return error\n const transport = transportFailure(error)\n if (transport)\n return localError(\n transport,\n error instanceof Error ? error.message : transport\n )\n return localError(\n \"unknown_error\",\n error instanceof Error ? error.message : String(error)\n )\n}\n","// Source of truth: every other locale is a partial of this tree.\nexport const en = {\n billingNotifications: {\n paymentMethodRequiredTitle: \"Update payment method\",\n authenticationRequiredTitle: \"Payment authentication required\",\n collectionStoppedTitle: \"Automatic payments stopped\",\n\n paymentFailed: \"Payment failed\",\n membershipEnded: \"Premium membership ended\",\n membershipDowngraded: \"Membership downgraded\",\n retryScheduled:\n \"When this notice was created, another payment attempt was scheduled for {date}.\",\n paymentMethodRequired:\n \"A new payment method was required before another payment attempt.\",\n retryStopped: \"No further automatic payment attempt was scheduled.\",\n retryUnknown:\n \"No retry schedule was available when this notice was created.\",\n endedAt: \"Your premium access ended on {date}.\",\n ended: \"Your premium access has ended.\",\n downgradedTo: \"Your membership changed from {from} to {to}.\",\n downgraded: \"Your queued membership downgrade has taken effect.\",\n instructions: {\n update_payment_method:\n \"Update your payment method and check your billing page for the current payment status.\",\n resubscribe:\n \"Choose a membership to restore access. Check your billing page before starting a new subscription.\",\n authenticate_payment:\n \"Complete payment authentication on your billing page.\",\n contact_support: \"Contact support for help with this payment.\",\n manage_billing:\n \"Open your billing page to check the current payment status and available next steps.\",\n },\n actions: {\n update_payment_method: \"Update payment method\",\n resubscribe: \"Choose membership\",\n authenticate_payment: \"Complete authentication\",\n contact_support: \"Contact support\",\n manage_billing: \"View billing\",\n },\n },\n\n common: {\n cancel: \"Cancel\",\n close: \"Close\",\n retry: \"Try again\",\n loading: \"Loading...\",\n previous: \"Previous\",\n next: \"Next\",\n notAvailable: \"—\",\n },\n status: {\n active: \"Active\",\n pending: \"Pending\",\n past_due: \"Past due\",\n canceled: \"Canceled\",\n cancel_scheduled: \"Ending\",\n unknown: \"Unknown\",\n awaiting_method: \"Update card\",\n unverified: \"Verifying\",\n succeeded: \"Paid\",\n failed: \"Failed\",\n refunded: \"Refunded\",\n partially_refunded: \"Partly refunded\",\n expired: \"Expired\",\n expiring_soon: \"Expires soon\",\n needs_attention: \"Needs attention\",\n default: \"Default\",\n },\n interval: {\n every: {\n hour: { one: \"every hour\", other: \"every {count} hours\" },\n day: { one: \"every day\", other: \"every {count} days\" },\n week: { one: \"every week\", other: \"every {count} weeks\" },\n month: { one: \"monthly\", other: \"every {count} months\" },\n },\n per: {\n hour: { one: \"/ hour\", other: \"/ {count} hours\" },\n day: { one: \"/ day\", other: \"/ {count} days\" },\n week: { one: \"/ week\", other: \"/ {count} weeks\" },\n },\n access: {\n hour: { one: \"1 hour of access\", other: \"{count} hours of access\" },\n day: { one: \"1 day of access\", other: \"{count} days of access\" },\n week: { one: \"1 week of access\", other: \"{count} weeks of access\" },\n },\n duration: {\n hour: { one: \"1 hour\", other: \"{count} hours\" },\n day: { one: \"1 day\", other: \"{count} days\" },\n week: { one: \"1 week\", other: \"{count} weeks\" },\n },\n once: \"one-time\",\n permanent: \"Access with no scheduled expiry\",\n },\n products: {\n empty: \"Nothing on sale unlocks this\",\n once: \"{amount}\",\n rent: \"Rent for {period}, {amount}\",\n recurring: \"{amount} {every}\",\n },\n subscriptions: {\n title: \"Subscriptions\",\n description: \"Your plans and when they renew.\",\n empty: \"No subscriptions yet\",\n emptyDescription: \"Plans you subscribe to will appear here.\",\n browsePlans: \"Browse plans\",\n fallbackName: \"Subscription\",\n renews: \"Renews {date}\",\n endsOn: \"Access until {date}\",\n noMorePayments: \"No further payments\",\n endedOn: \"Ended {date}\",\n pastDue: \"Payment failed. Update your card to keep access.\",\n cancel: \"Cancel\",\n cancelLabel: \"Cancel {name}\",\n resume: \"Resume\",\n resumed: \"Your subscription will continue.\",\n manageAtProvider: \"Manage\",\n updating: \"Updating...\",\n paidWith: \"{brand} •••• {last4}\",\n wallet: \"Solana wallet\",\n changeCard: \"Change card\",\n changeCardLabel: \"Change card for {name}\",\n changePlan: \"Change plan\",\n changePlanLabel: \"Change plan for {name}\",\n },\n resume: {\n chooseCard: \"Choose a payment method\",\n savedCardUnavailable:\n \"This saved card is not available. Choose another card or add one.\",\n title: \"Resume {name}?\",\n description:\n \"Your subscription renews on {date}, and {price} will be charged to your card then and every billing period until you cancel.\",\n descriptionNoDate:\n \"Your subscription will renew, and your card will be charged each billing period until you cancel.\",\n keepCanceled: \"Keep canceled\",\n confirm: \"Resume subscription\",\n },\n changeCard: {\n title: \"Pay {name} with\",\n description: \"Future renewals charge the selected card.\",\n none: \"Add another card under Payment methods to switch.\",\n confirm: \"Use this card\",\n current: \"Current\",\n useDefault: \"Your default card ({card})\",\n done: \"Payment card updated.\",\n },\n changePlan: {\n title: \"Change {name}\",\n description:\n \"An upgrade starts now; a downgrade starts at your next renewal.\",\n none: \"There are no other plans to switch to right now.\",\n chargeNow: \"{amount} now, then {next} from {date}\",\n chargeNowEstimate: \"About {amount} now, then {next} from {date}\",\n atPeriodEnd: \"No charge now. Switches on {date}, then {next}\",\n confirm: \"Change plan\",\n signing: \"Waiting for wallet...\",\n confirming: \"Confirming...\",\n done: \"You're now on {name}.\",\n scheduled: \"{name} starts {date}.\",\n processing:\n \"Plan change submitted; it will apply once your provider confirms it.\",\n actionRequired: \"This change needs another step. Try again.\",\n },\n renewal: {\n title: \"Renew your subscription\",\n description:\n \"Your subscription has ended. Renew your plan to get your access back.\",\n action: \"Renew now\",\n },\n cancel: {\n title: \"Cancel {name}?\",\n description: \"Future payments stop. You keep access already purchased.\",\n revokeOnChain:\n \"Also cancel on chain (requires a wallet signature and network fee).\",\n solanaDescription:\n \"Your wallet signs an on-chain cancellation. You keep access already purchased.\",\n reasonLabel: \"Why are you cancelling?\",\n reasonPlaceholder: \"Your feedback helps us improve.\",\n reasonHint: \"{count}/{max}\",\n reasonTooShort: \"Enter at least {min} characters.\",\n keep: \"Keep subscription\",\n confirm: \"Cancel subscription\",\n confirmWallet: \"Sign with wallet\",\n working: \"Cancelling...\",\n preparing: \"Preparing transaction...\",\n signing: \"Confirm in your wallet...\",\n confirming: \"Recording cancellation...\",\n done: \"Cancellation requested.\",\n },\n paymentMethods: {\n title: \"Payment methods\",\n description: \"Cards saved for your subscriptions.\",\n empty: \"No saved cards\",\n emptyDescription: \"Cards you save appear here.\",\n add: \"Add card\",\n addTitle: \"Add a card\",\n addDescription:\n \"Card details go straight to the payment processor; this site never sees them.\",\n save: \"Save card\",\n added: \"Card saved.\",\n provider: \"Payment provider\",\n saveNotice:\n \"Cards you enter are saved to your account for future payments.\",\n unavailable: \"Secure card entry is unavailable for this provider.\",\n addUnavailable: \"Adding a card is temporarily unavailable.\",\n verificationPending:\n \"Card verification is pending. Check your saved cards before trying again.\",\n cardLabel: \"{brand} •••• {last4}\",\n fallbackBrand: \"Card\",\n expires: \"Expires {date}\",\n usedBy: \"Used by {names}\",\n defaultFor: \"Default for {currencies}\",\n makeDefault: \"Make default\",\n defaultUpdated: \"Default card updated.\",\n remove: \"Remove\",\n removeLabel: \"Remove {label}\",\n removeTitle: \"Remove {label}?\",\n removeDescription:\n \"A card used by an active subscription must be replaced before it can be removed.\",\n removeConfirm: \"Remove card\",\n removed: \"Card removed.\",\n removeFailed: \"Card removal could not be confirmed. Please try again.\",\n inUse:\n \"This card pays for an active subscription. Switch that subscription to another card first.\",\n },\n purchase: {\n renews: \"Renews {period}\",\n },\n history: {\n title: \"Payment history\",\n description: \"Charges and refunds on your account.\",\n empty: \"No payments yet\",\n emptyDescription: \"Completed payments will appear here.\",\n date: \"Date\",\n item: \"Item\",\n subscription: \"Subscription\",\n purchase: \"Purchase\",\n method: \"Method\",\n status: \"Status\",\n amount: \"Amount\",\n refund: \"Refund\",\n refundedAmount: \"{amount} refunded\",\n page: \"Page {page}\",\n rail: {\n card: \"Card\",\n solana: \"Solana\",\n ccbill: \"Card\",\n nmi: \"Card\",\n stripe: \"Card\",\n },\n },\n errors: {\n generic: \"Something went wrong. Please try again.\",\n network_error:\n \"Couldn't reach the server. Check your connection and try again.\",\n server_unavailable:\n \"The server isn't responding right now. Please try again in a moment.\",\n invalid_response: \"The server sent an unexpected response.\",\n authentication_required: \"Your session expired. Sign in again.\",\n resource_access_denied: \"You don't have access to this.\",\n resource_not_found: \"This item no longer exists.\",\n resource_conflict: \"This changed in the meantime. Refresh and try again.\",\n rate_limit_exceeded: \"Too many requests. Wait a moment and try again.\",\n provider_writes_disabled:\n \"Payments are switched off on this site right now.\",\n service_unavailable: \"Billing is temporarily unavailable. Try again soon.\",\n internal_error: \"Something went wrong on our side. Please try again.\",\n card_declined: \"The card was declined.\",\n ccbill_email_required: \"Verify your email to pay with CCBill.\",\n ccbill_username_required: \"Set a username to pay with CCBill.\",\n customer_email_required:\n \"Verify your email and set a username to pay with CCBill.\",\n payment_provider_rejected: \"The payment provider rejected the request.\",\n provider_outcome_unknown:\n \"We couldn't confirm the result with the provider. Check again shortly.\",\n payment_in_progress: \"A payment is already in progress.\",\n payment_method_delete_unsupported:\n \"This card can't be removed here. Contact support.\",\n payment_method_delete_failed:\n \"The provider couldn't remove this card. Try again later.\",\n customer_session_required: \"Sign in again to do this.\",\n invoker_scoped_principal: \"This account can't manage billing.\",\n csrf_origin_denied: \"The request was blocked. Reload the page.\",\n wallet_rejected: \"The wallet request was declined.\",\n wallet_no_signature: \"The wallet did not sign the transaction.\",\n subscription_change_in_flight:\n \"A plan change for this subscription is still being processed. Please wait for it to finish.\",\n subscription_change_idempotency_conflict:\n \"That plan change was already submitted with different details. Please try again.\",\n subscription_change_already_scheduled:\n \"A plan change is already scheduled for your next renewal.\",\n subscription_change_target_inactive: \"That plan is no longer available.\",\n subscription_not_active: \"Only an active subscription can change plans.\",\n },\n}\n","import type { BillingAdminAuth, BillingAdminResource } from \"../../types\"\nimport type { OpenRailsErrorCode } from \"../../../client/generated/error-codes\"\nimport type { ListPage } from \"../../../client/generated/wire\"\nimport { transportFailure } from \"../../../client/errors\"\nimport { en } from \"../../../locales/en\"\n\n// Stripe-shaped error envelope (internal/api); codes are billing.ErrorCodes.\nexport interface ApiErrorBody {\n error?: {\n type?: string\n code?: OpenRailsErrorCode\n message?: string\n param?: string\n metadata?: Record<string, unknown>\n }\n}\n\nexport class ApiError extends Error {\n status: number\n type?: string\n code?: OpenRailsErrorCode\n param?: string\n metadata?: Record<string, unknown>\n\n constructor(status: number, body: ApiErrorBody | null, fallback: string) {\n super(body?.error?.message || fallback)\n this.status = status\n this.type = body?.error?.type\n this.code = body?.error?.code\n this.param = body?.error?.param\n this.metadata = body?.error?.metadata\n }\n\n get isPermissionDenied() {\n return this.status === 403\n }\n\n // The object changed since the revision the request named.\n get revisionMismatch() {\n return this.status === 409 && this.code === \"revision_mismatch\"\n }\n\n // The merchant's configuration is read from a file: no edit applies.\n get merchantConfigReadOnly() {\n return this.status === 409 && this.code === \"merchant_config_read_only\"\n }\n}\n\nasync function parseError(res: Response): Promise<ApiError> {\n let body: ApiErrorBody | null = null\n try {\n body = (await res.json()) as ApiErrorBody\n } catch {\n // non-JSON error body\n }\n const failure = body?.error?.code\n ? undefined\n : transportFailure({ status: res.status })\n return new ApiError(\n res.status,\n body,\n failure ? en.errors[failure] : `request failed (${res.status})`\n )\n}\n\n// A request OpenRails never answered (status 0), named for the operator.\nfunction unanswered(error: unknown): ApiError | undefined {\n const failure = transportFailure(error)\n return failure && new ApiError(0, null, en.errors[failure])\n}\n\nexport interface RequestOptions {\n method?: string\n body?: unknown\n // Preserve catalog JSON/YAML bytes and exact monetary literals.\n rawBody?: string\n headers?: Record<string, string>\n query?: Record<string, string | number | boolean | undefined>\n signal?: AbortSignal\n}\n\nfunction buildURL(base: string, path: string, query?: RequestOptions[\"query\"]) {\n let url = base + path\n if (query) {\n const params = new URLSearchParams()\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined && v !== \"\") params.set(k, String(v))\n }\n const qs = params.toString()\n if (qs) url += `?${qs}`\n }\n return url\n}\n\nexport interface ApiResponse<T> {\n status: number\n body: T\n}\n\n// One cursor page request: cursor is the previous page's next_cursor.\nexport interface PageRequest {\n limit?: number\n cursor?: string\n}\n\n// collectCursorPages walks a cursor list to its end.\nexport async function collectCursorPages<T>(\n loadPage: (cursor?: string) => Promise<ListPage<T>>,\n signal?: AbortSignal\n): Promise<T[]> {\n const rows: T[] = []\n let cursor: string | undefined\n for (;;) {\n signal?.throwIfAborted()\n const page = await loadPage(cursor)\n rows.push(...page.data)\n if (!page.next_cursor) return rows\n if (page.next_cursor === cursor)\n throw new Error(\"List paging stopped before all records were loaded\")\n cursor = page.next_cursor\n }\n}\n\n// The cursor list envelope: next_cursor is null on the last page.\nexport interface CursorEnvelope<T> {\n data: T[]\n next_cursor: string | null\n}\n\nexport interface AdminClientOptions {\n namespace?: string\n isCurrent?: () => boolean\n baseUrl: string\n auth: BillingAdminAuth\n merchant?: { id: string; slug: string }\n exchange?: Omit<BillingAdminResource, \"group\">\n}\n\n/** One immutable transport per component and selected merchant. */\nexport function createAdminClient(options: AdminClientOptions) {\n const baseUrl = options.baseUrl.replace(/\\/$/, \"\")\n const selectedMerchant = () =>\n options.isCurrent && !options.isCurrent()\n ? undefined\n : options.merchant?.slug\n async function send<T>(\n path: string,\n opts: RequestOptions\n ): Promise<ApiResponse<T>> {\n const headers: Record<string, string> = { ...opts.headers }\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\"\n const init: RequestInit = {\n method: opts.method ?? \"GET\",\n headers,\n signal: opts.signal,\n body:\n opts.rawBody ??\n (opts.body !== undefined ? JSON.stringify(opts.body) : undefined),\n }\n const url = buildURL(baseUrl, path, opts.query)\n let res: Response\n if (options.exchange) {\n if (!options.merchant?.id || !options.auth.resourceFetch)\n throw new Error(\n \"Merchant token exchange needs a merchant id and resourceFetch transport\"\n )\n try {\n res = await options.auth.resourceFetch(url, {\n ...init,\n ...options.exchange,\n group: options.merchant.id,\n })\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"error\" in error &&\n error.error === \"invalid_target\"\n )\n throw new ApiError(\n 403,\n {\n error: {\n code: \"merchant_unresolved\",\n message: \"You hold no role at this merchant.\",\n },\n },\n \"Merchant refused\"\n )\n throw (!opts.signal?.aborted && unanswered(error)) || error\n }\n } else {\n try {\n res = await options.auth.authFetch(url, init)\n } catch (error) {\n throw (!opts.signal?.aborted && unanswered(error)) || error\n }\n }\n if (!res.ok) throw await parseError(res)\n return {\n status: res.status,\n body: (res.status === 204 ? undefined : await res.json()) as T,\n }\n }\n async function apiResponse<T>(\n path: string,\n opts: RequestOptions = {}\n ): Promise<ApiResponse<T>> {\n return send<T>(path, opts)\n }\n const api = async <T>(path: string, opts: RequestOptions = {}) =>\n (await apiResponse<T>(path, opts)).body\n const queryRoot = (requested?: string) => {\n const merchant =\n requested !== undefined &&\n requested !== options.merchant?.slug &&\n requested !== options.merchant?.id\n ? requested\n : options.merchant?.id || options.merchant?.slug || \"unselected\"\n return [\n ...(options.namespace ? [\"billing-admin\", options.namespace] : []),\n \"merchant\",\n merchant,\n ] as const\n }\n return {\n namespace: options.namespace,\n api,\n apiResponse,\n selectedMerchant,\n queryRoot,\n }\n}\nexport type AdminClient = ReturnType<typeof createAdminClient>\n","import type { AdminClient } from \"./client\"\nimport { type CursorEnvelope, type PageRequest } from \"./client\"\n\nimport type {\n AdminAccess,\n AlertWebhook,\n Allowance,\n CatalogApplicationReceipt,\n CreateAlertWebhookParams,\n CreatePSPParams,\n Custodian,\n SetCustodianParams,\n CreatePriceParams,\n Customer,\n CustomerSettingsResult,\n DestructiveHold,\n Finding,\n FindingResolution,\n ListPage,\n MerchantConfigurationState,\n Meter,\n PSP,\n Payment,\n PaymentAttempt,\n PaymentMethod,\n Price,\n PriceKeyMovement,\n Product,\n PublicConfig,\n RatePrice,\n Renewal,\n RefundPaymentParams,\n SubscriptionChangeOption,\n UpdateAlertWebhookParams,\n UpdateCustomerParams,\n UpdateMerchantConfigurationParams,\n UpdatePSPParams,\n UpdatePriceParams,\n UpdateProductParams,\n} from \"#orck/client/generated/wire\"\n\nimport type {\n AdminSubscription,\n CustomerEntitlement,\n PSPRoutingPreview,\n RawProductAccessGrant,\n PriceMigration,\n PriceMigrationCancel,\n PriceMigrationPreview,\n ChangeSubscriptionParams,\n SubscriptionChange,\n SubscriptionChangePreview,\n} from \"./types\"\n\nexport interface ProductGrant {\n productId: string\n hours?: number\n endsAt?: string\n reason?: \"comp\" | \"staff\"\n note?: string\n}\n\n// --- Subscriptions ---\n\nexport interface SubscriptionFilters {\n status?: string\n // dunning \"true\" keeps the subscriptions past_due or awaiting_method.\n dunning?: string\n rail?: string\n customer_id?: string\n price_id?: string\n // UTC dates (YYYY-MM-DD).\n expires_before?: string\n canceled_after?: string\n // created_at (newest first), current_period_ends_at (soonest first) or\n // canceled_at (latest first).\n sort?: string\n // at_risk \"true\" keeps the subscriptions whose MRR is at risk.\n at_risk?: string\n}\n\n// --- Payments ---\n\n// Payments are listed newest first.\nexport interface PaymentFilters {\n customer_id?: string\n subscription_id?: string\n order_id?: string\n status?: Payment[\"status\"]\n rail?: string\n kind?: Payment[\"kind\"]\n transaction_id?: string\n}\n\n// --- Payment attempts and renewals (#1116) ---\n// Filters are the API's query parameters verbatim; a text filter is one value\n// or a comma-separated list, so a console URL carries them unchanged.\n\nexport type AttemptFilters = Partial<\n Record<(typeof ATTEMPT_FILTERS)[number], string>\n>\n\nexport const ATTEMPT_FILTERS = [\n \"kind\",\n \"owner\",\n \"outcome\",\n \"decline_cause\",\n \"reason\",\n \"response_code\",\n \"card_entry\",\n \"source\",\n \"observed_via\",\n \"avs_result\",\n \"cvv_result\",\n \"psp_id\",\n \"customer_id\",\n \"payment_id\",\n \"order_id\",\n \"subscription_id\",\n \"cycle_id\",\n \"since\",\n \"until\",\n] as const\n\nexport type CycleFilters = Partial<\n Record<(typeof CYCLE_FILTERS)[number], string>\n>\n\nexport const CYCLE_FILTERS = [\n \"owner\",\n \"first_outcome\",\n \"miss_reason\",\n \"outcome\",\n \"psp_id\",\n \"subscription_id\",\n \"due_since\",\n \"due_until\",\n] as const\n\n// filtersFrom reads the named filters from a console URL.\nexport function filtersFrom<K extends string>(\n params: URLSearchParams,\n keys: readonly K[]\n): Partial<Record<K, string>> {\n const out: Partial<Record<K, string>> = {}\n for (const key of keys) {\n const v = params.get(key)?.trim()\n if (v) out[key] = v\n }\n return out\n}\n\n// Rails whose refunds route through a provider API today (admin_payments.go);\n// off-rail payments are refunded where they were taken.\nexport const REFUNDABLE_RAILS = [\"nmi\", \"stripe\"]\n\n// --- Catalog ---\n\n// PAGE_MAX is the largest page a list route serves.\nexport const PAGE_MAX = 500\n\nexport interface ProductRequest {\n key: string\n display_name: string\n description: string\n tier_group?: string\n tier_rank?: number\n entitlements?: string[]\n}\n\nexport interface UsageMeterRequest {\n event_type: string\n value_property: string\n aggregation: \"sum\" | \"count\"\n unit?: string\n group_by: Record<string, string>\n // Omitted keeps the meter's rate card; null removes it.\n rate_card?: DefaultUsageRateCardRequest | null\n // The meter's revision this edit read; 0 for a new meter.\n expected_revision?: number\n}\n\nexport interface DefaultUsageRateCardRequest {\n product_id: string\n filter: Record<string, string[]>\n price: RatePrice\n allowance?: Allowance\n}\n\nexport type { CatalogApplicationReceipt } from \"#orck/client/generated/wire\"\nexport function createEndpoints(client: AdminClient) {\n const { api } = client\n\n // --- Customers ---\n\n const listCustomers = (\n search: string,\n limit: number,\n cursor: string,\n signal?: AbortSignal\n ) =>\n api<ListPage<Customer>>(\"/admin/customers\", {\n query: { search, limit, cursor },\n signal,\n })\n\n // getCustomer is one customer: settings, and per currency its balance,\n // arrears and collection card. Its lists are their own routes.\n const getCustomer = (customerId: string, signal?: AbortSignal) =>\n api<Customer>(`/admin/customers/${customerId}`, { signal })\n\n const listCustomerEntitlements = (\n customerId: string,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<CustomerEntitlement>>(\"/admin/entitlements\", {\n query: { customer_id: customerId, ...page },\n signal,\n })\n\n const listCustomerProductAccess = (\n customerId: string,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<RawProductAccessGrant>>(\"/admin/product-access\", {\n query: { customer_id: customerId, ...page },\n signal,\n })\n\n const listCustomerPaymentMethods = (\n customerId: string,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<PaymentMethod>>(\n `/admin/customers/${customerId}/payment-methods`,\n { query: { ...page }, signal }\n )\n\n // grantProductAccess grants one product free; the customer holds its keys\n // while the grant is live.\n const grantProductAccess = (customerId: string, grant: ProductGrant) =>\n api<{ items: RawProductAccessGrant[] }>(`/admin/product-access`, {\n method: \"POST\",\n headers: { \"Idempotency-Key\": crypto.randomUUID() },\n body: {\n items: [\n {\n customer_id: customerId,\n product_id: grant.productId,\n ...(grant.hours ? { hours: grant.hours } : {}),\n ...(grant.endsAt ? { ends_at: grant.endsAt } : {}),\n ...(grant.reason ? { reason: grant.reason } : {}),\n ...(grant.note ? { note: grant.note } : {}),\n },\n ],\n },\n })\n\n // revokeProductAccess takes a product back; the window keeps its row and the\n // reason.\n const revokeProductAccess = (grantId: string, reason: string) =>\n api<void>(`/admin/product-access/${grantId}/revoke`, {\n method: \"POST\",\n body: { reason },\n })\n\n const listSubscriptions = (\n filters: SubscriptionFilters,\n limit: number,\n cursor?: string,\n signal?: AbortSignal\n ) =>\n api<CursorEnvelope<AdminSubscription>>(\"/admin/subscriptions\", {\n query: { ...filters, limit, ...(cursor ? { cursor } : {}) },\n signal,\n })\n\n const getSubscription = (id: string, signal?: AbortSignal) =>\n api<AdminSubscription>(`/admin/subscriptions/${id}`, { signal })\n\n const cancelSubscription = (\n id: string,\n reason: string,\n revokeAccess: boolean\n ) =>\n api<AdminSubscription>(`/admin/subscriptions/${id}/cancel`, {\n method: \"POST\",\n body: { reason, revoke_access: revokeAccess },\n })\n\n const resumeSubscription = (id: string) =>\n api<AdminSubscription>(`/admin/subscriptions/${id}/resume`, {\n method: \"POST\",\n })\n\n // null makes the subscription follow the customer's default card.\n const changeSubscriptionPaymentMethod = (\n id: string,\n paymentMethodId: string | null\n ) =>\n api<AdminSubscription>(`/admin/subscriptions/${id}/payment-method`, {\n method: \"PUT\",\n body: { payment_method_id: paymentMethodId },\n })\n\n const listSubscriptionChangeOptions = (id: string, signal?: AbortSignal) =>\n api<ListPage<SubscriptionChangeOption>>(\n `/admin/subscriptions/${id}/change/options`,\n { signal }\n )\n\n const previewSubscriptionChange = (\n id: string,\n change: ChangeSubscriptionParams\n ) =>\n api<SubscriptionChangePreview>(\n `/admin/subscriptions/${id}/change/preview`,\n {\n method: \"POST\",\n body: change,\n }\n )\n\n // A change is a durable operation keyed by this header: the same key replays\n // its result, so a retry must reuse the key of the reviewed change.\n const changeSubscription = (\n id: string,\n change: ChangeSubscriptionParams,\n idempotencyKey: string\n ) =>\n api<SubscriptionChange>(`/admin/subscriptions/${id}/change`, {\n method: \"POST\",\n headers: { \"Idempotency-Key\": idempotencyKey },\n body: change,\n })\n\n const listPayments = (\n filters: PaymentFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<Payment>>(\"/admin/payments\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const getPayment = (id: string, signal?: AbortSignal) =>\n api<Payment>(`/admin/payments/${id}`, { signal })\n\n // refundPayment answers the refund: succeeded, or pending (202) while the\n // rail settles it.\n const refundPayment = (\n id: string,\n amount: string,\n reason: string,\n revokeAccess: boolean\n ) => {\n const body: RefundPaymentParams = {\n amount,\n reason: reason || undefined,\n revoke_access: revokeAccess,\n }\n return api<Payment>(`/admin/payments/${id}/refunds`, {\n method: \"POST\",\n headers: { \"Idempotency-Key\": crypto.randomUUID() },\n body,\n })\n }\n\n const listPaymentAttempts = (\n filters: AttemptFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<PaymentAttempt>>(\"/admin/payment-attempts\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const getPaymentAttempt = (id: string, signal?: AbortSignal) =>\n api<PaymentAttempt>(`/admin/payment-attempts/${id}`, { signal })\n\n const listRenewals = (\n filters: CycleFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<Renewal>>(\"/admin/renewals\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const getRenewal = (id: string, signal?: AbortSignal) =>\n api<Renewal>(`/admin/renewals/${id}`, { signal })\n\n // archived: false lists live products, true archived ones, undefined both.\n // Each product carries its current prices.\n const listProducts = (\n limit: number,\n cursor?: string,\n archived?: boolean,\n signal?: AbortSignal\n ) =>\n api<ListPage<Product>>(\"/catalog/products\", {\n query: { limit, cursor, archived },\n signal,\n })\n\n const getProduct = (id: string, signal?: AbortSignal) =>\n api<Product>(`/catalog/products/${id}`, { signal })\n\n const createProduct = (body: ProductRequest) =>\n api<Product>(\"/catalog/products\", { method: \"POST\", body })\n\n // updateProduct is a merge patch: omitted fields stay, null clears\n // description and tier_group; entitlements: [] clears the granted keys.\n const updateProduct = (id: string, body: UpdateProductParams) =>\n api<Product>(`/catalog/products/${id}`, {\n method: \"PATCH\",\n body,\n })\n\n const listUsageMeters = (\n limit = PAGE_MAX,\n cursor?: string,\n signal?: AbortSignal\n ) =>\n api<ListPage<Meter>>(\"/catalog/meters\", {\n query: { limit, cursor },\n signal,\n })\n\n const getUsageMeter = (key: string, signal?: AbortSignal) =>\n api<Meter>(`/catalog/meters/${encodeURIComponent(key)}`, {\n signal,\n })\n\n const putUsageMeter = (key: string, body: UsageMeterRequest) =>\n api<Meter>(`/catalog/meters/${encodeURIComponent(key)}`, {\n method: \"PUT\",\n body,\n })\n\n // putUsageMeterRateCard sets a meter's rate card, or removes it with null.\n // The rate card is a field of the meter, so the meter is restated with it.\n const putUsageMeterRateCard = (\n meter: Meter,\n rateCard: DefaultUsageRateCardRequest | null\n ) =>\n putUsageMeter(meter.key, {\n event_type: meter.event_type,\n value_property: meter.value_property,\n aggregation: meter.aggregation as UsageMeterRequest[\"aggregation\"],\n unit: meter.unit,\n group_by: meter.group_by ?? {},\n rate_card: rateCard,\n expected_revision: meter.revision,\n })\n\n const listPrices = (\n limit: number,\n cursor?: string,\n productId?: string,\n signal?: AbortSignal\n ) =>\n api<ListPage<Price>>(\"/catalog/prices\", {\n query: { limit, cursor, product_id: productId },\n signal,\n })\n\n // A price that declares the key of a live price with other terms becomes\n // its new version and archives the old one.\n const createPrice = (body: CreatePriceParams) =>\n api<Price>(\"/catalog/prices\", { method: \"POST\", body })\n\n // getPrice returns the price with its state on each linked PSP. verify\n // reads its verification instead, which also reads the provider's copy and\n // reports its drift: a read, never a write, and slow enough that it stays\n // opt-in.\n const getPrice = (id: string, verify = false, signal?: AbortSignal) =>\n api<Price>(\n `/catalog/prices/${encodeURIComponent(id)}${verify ? \"/verification\" : \"\"}`,\n { signal }\n )\n\n // updatePrice archives or restores a price, or changes its PSP links\n // (a PSP set to null is unlinked).\n const updatePrice = (id: string, body: UpdatePriceParams) =>\n api<Price>(`/catalog/prices/${encodeURIComponent(id)}`, {\n method: \"PATCH\",\n body,\n })\n\n // getPriceHistory returns the history of a price's key, most recent first:\n // when the key moved to which price.\n const getPriceHistory = (priceId: string, signal?: AbortSignal) =>\n api<ListPage<PriceKeyMovement>>(\n `/catalog/prices/${encodeURIComponent(priceId)}/history`,\n {\n query: { limit: PAGE_MAX },\n signal,\n }\n )\n\n // --- Price migrations ---\n\n // previewPriceMigration is the wizard's affected-count dry run, called\n // before the price edit lands: by key with no target it counts every\n // version's subscribers. It never writes. Sent no effective_at, it\n // answers the server's now as effective_at: the wizard's clock.\n const previewPriceMigration = (productKey: string, priceKey: string) =>\n api<PriceMigrationPreview>(\"/catalog/price-migrations/preview\", {\n method: \"POST\",\n body: { product_key: productKey, price_key: priceKey },\n })\n\n // createPriceMigration moves the subscribers of every version of priceKey\n // but toPriceId to it, each at its first renewal on or after effectiveAt.\n const createPriceMigration = (\n productKey: string,\n priceKey: string,\n toPriceId: string,\n effectiveAt: string\n ) =>\n api<PriceMigration>(\"/catalog/price-migrations\", {\n method: \"POST\",\n body: {\n product_key: productKey,\n price_key: priceKey,\n to_price_id: toPriceId,\n effective_at: effectiveAt,\n },\n })\n\n // listPriceMigrations lists a price key's migrations, newest first.\n const listPriceMigrations = (\n productKey: string,\n priceKey: string,\n limit = 20,\n signal?: AbortSignal\n ) =>\n api<CursorEnvelope<PriceMigration>>(\"/catalog/price-migrations\", {\n query: { product_key: productKey, price_key: priceKey, limit },\n signal,\n })\n\n const cancelPriceMigration = (id: string) =>\n api<PriceMigrationCancel>(`/catalog/price-migrations/${id}/cancel`, {\n method: \"POST\",\n })\n\n // JSON is valid YAML too. Keep the reviewed document byte-for-byte unchanged\n // instead of parsing/re-encoding money in the browser. The server deduplicates\n // batches by their canonical content. force overwrites what edits set.\n const applyCatalog = (document: string, force = false) =>\n api<CatalogApplicationReceipt>(\"/catalog/apply\", {\n method: \"POST\",\n rawBody: document,\n headers: { \"Content-Type\": \"application/yaml\" },\n ...(force ? { query: { force: \"true\" } } : {}),\n })\n\n // --- Ops ---\n\n // listFindings reads the findings queue; type is one finding type or a prefix\n // ending in \".*\" (pull.*).\n const listFindings = (\n filters: { status?: string; severity?: string; type?: string },\n limit: number,\n signal?: AbortSignal\n ) =>\n api<ListPage<Finding>>(\"/merchant/findings\", {\n query: { ...filters, limit },\n signal,\n })\n\n const getFinding = (id: string) => api<Finding>(`/merchant/findings/${id}`)\n\n const resolveFinding = (\n id: string,\n outcome: \"approve\" | \"ignore\",\n notes: string\n ) =>\n api<FindingResolution>(`/merchant/findings/${id}/resolve`, {\n method: \"POST\",\n body: { outcome, notes },\n })\n\n // listDestructiveHolds reads the holds the destructive-action limit opened.\n const listDestructiveHolds = (cursor?: string, signal?: AbortSignal) =>\n api<ListPage<DestructiveHold>>(\"/merchant/destructive-holds\", {\n query: { limit: 100, cursor },\n signal,\n })\n\n // clearDestructiveHold lifts a hold. The server requires a different person\n // from the one the hold stopped, holding the unlock permission.\n const clearDestructiveHold = (id: string, reason: string) =>\n api<DestructiveHold>(\n `/merchant/destructive-holds/${encodeURIComponent(id)}/clear`,\n { method: \"POST\", body: { reason } }\n )\n\n // --- Settings ---\n\n const getMerchantConfiguration = (signal?: AbortSignal) =>\n api<MerchantConfigurationState>(\"/merchant/configuration\", { signal })\n\n // Merges the fields it names. expected_revision is the revision the form\n // read; a configuration changed since is refused with revision_mismatch.\n const updateMerchantConfiguration = (\n body: UpdateMerchantConfigurationParams\n ) =>\n api<MerchantConfigurationState>(\"/merchant/configuration\", {\n method: \"PATCH\",\n body,\n })\n\n // A merchant has a handful of PSPs: one page holds them all.\n const listPSPs = (signal?: AbortSignal) =>\n api<ListPage<PSP>>(\"/merchant/psps?limit=500\", { signal })\n\n const listCustodians = (signal?: AbortSignal) =>\n api<{ data: Custodian[] }>(\"/merchant/custodians\", { signal })\n\n const deleteCustomerPaymentMethod = (customer: string, method: string) =>\n api<void>(\n `/admin/customers/${encodeURIComponent(customer)}/payment-methods/${encodeURIComponent(method)}`,\n { method: \"DELETE\" }\n )\n\n const putCustodian = (key: string, body: SetCustodianParams) =>\n api<Custodian>(`/merchant/custodians/${encodeURIComponent(key)}`, {\n method: \"PUT\",\n body,\n })\n\n // The rail registry is static per build: it arrives with the configuration.\n const listRails = async (signal?: AbortSignal) =>\n (await getConfig(signal)).rails\n\n // Credentials are write-only and checked with the provider before anything\n // is stored.\n const createPSP = (body: CreatePSPParams) =>\n api<PSP>(\"/merchant/psps\", { method: \"POST\", body })\n\n // Changes settings, rotates credentials (omitted ones keep their values) or\n // archives the PSP: the rail's last active PSP needs allow_last\n // (409 psp_last_active). expected_revision refuses a PSP changed since.\n const updatePSP = (id: string, body: UpdatePSPParams) =>\n api<PSP>(`/merchant/psps/${encodeURIComponent(id)}`, {\n method: \"PATCH\",\n body,\n })\n\n // previewPSPRouting (or#288) explains which PSP a purchase for this price\n // would use and why each other PSP was passed over. Read-only: it runs the\n // production decision path without creating a session.\n const previewPSPRouting = (\n body: { price_id: string; country?: string; psp?: string },\n signal?: AbortSignal\n ) =>\n api<PSPRoutingPreview>(\"/merchant/psps/routing-preview\", {\n method: \"POST\",\n body,\n signal,\n })\n\n // The public configuration: what the deployment serves, the currency\n // registry and the payment setup.\n const getConfig = (signal?: AbortSignal) =>\n api<PublicConfig>(\"/config\", { signal })\n\n // getAdminAccess is what the signed-in staff member may use of each staff\n // route group that is mounted: the console's areas.\n const getAdminAccess = (signal?: AbortSignal) =>\n api<AdminAccess>(\"/admin/access\", { signal })\n\n // updateCustomer returns the customer's ID and saved settings.\n const updateCustomer = (customerId: string, params: UpdateCustomerParams) =>\n api<CustomerSettingsResult>(`/admin/customers/${customerId}`, {\n method: \"PATCH\",\n body: params,\n })\n\n // --- Alerting: webhooks (#736) ---\n\n const listWebhooks = (signal?: AbortSignal) =>\n api<ListPage<AlertWebhook>>(\"/merchant/alert-webhooks\", { signal })\n\n const createWebhook = (body: CreateAlertWebhookParams) =>\n api<AlertWebhook>(\"/merchant/alert-webhooks\", { method: \"POST\", body })\n\n // Omitted fields keep their values; the URL is write-only.\n const updateWebhook = (id: string, body: UpdateAlertWebhookParams) =>\n api<AlertWebhook>(`/merchant/alert-webhooks/${id}`, {\n method: \"PATCH\",\n body,\n })\n\n const deleteWebhook = (id: string) =>\n api<void>(`/merchant/alert-webhooks/${id}`, { method: \"DELETE\" })\n return {\n listCustomers,\n getCustomer,\n listCustomerEntitlements,\n listCustomerProductAccess,\n listCustomerPaymentMethods,\n grantProductAccess,\n revokeProductAccess,\n listSubscriptions,\n getSubscription,\n cancelSubscription,\n resumeSubscription,\n changeSubscriptionPaymentMethod,\n listSubscriptionChangeOptions,\n previewSubscriptionChange,\n changeSubscription,\n listPayments,\n getPayment,\n refundPayment,\n listPaymentAttempts,\n getPaymentAttempt,\n listRenewals,\n getRenewal,\n listProducts,\n getProduct,\n createProduct,\n updateProduct,\n listUsageMeters,\n getUsageMeter,\n putUsageMeter,\n putUsageMeterRateCard,\n listPrices,\n createPrice,\n getPrice,\n updatePrice,\n getPriceHistory,\n previewPriceMigration,\n createPriceMigration,\n listPriceMigrations,\n cancelPriceMigration,\n applyCatalog,\n listFindings,\n getFinding,\n resolveFinding,\n listDestructiveHolds,\n clearDestructiveHold,\n getMerchantConfiguration,\n updateMerchantConfiguration,\n listPSPs,\n listRails,\n createPSP,\n listCustodians,\n putCustodian,\n deleteCustomerPaymentMethod,\n updatePSP,\n previewPSPRouting,\n getConfig,\n getAdminAccess,\n updateCustomer,\n listWebhooks,\n createWebhook,\n updateWebhook,\n deleteWebhook,\n }\n}\n","// Metrics and dashboard API; types mirror the Go handlers.\nimport type {\n DashboardProfile,\n DisputeStanding,\n ListPage,\n MetricsSchema,\n} from \"#orck/client/generated/wire\"\nimport type { AdminClient } from \"./client\"\n\nexport type {\n DashboardProfile,\n DisputeStanding,\n MetricsMeasure,\n MetricsSchema,\n MetricsThreshold,\n} from \"#orck/client/generated/wire\"\n\nexport interface MetricsRange {\n from?: string\n to?: string\n // Relative trailing window ending today (\"7d\", \"12w\", \"6m\", \"1y\") —\n // mutually exclusive with from/to; saved widgets prefer it.\n last?: string\n // A window starting today (what is scheduled ahead), like last.\n next?: string\n}\n\nexport interface OrderTerm {\n measure?: string\n dimension?: string\n dir?: \"asc\" | \"desc\"\n}\n\nexport interface QueryMetricsParams {\n measures: string[]\n by?: string[]\n grain?: string\n range: MetricsRange\n filters?: Record<string, string[]>\n order?: OrderTerm[]\n limit?: number\n compare?: Compare\n}\n\n// Compare is the window a change is measured against.\nexport type Compare = \"previous_period\" | \"previous_year\"\n\nexport interface MetricsColumn {\n name: string\n kind: \"time\" | \"dimension\" | \"measure\"\n unit?: string\n}\n\nexport type MetricsCell = string | number | null\n\nexport interface MetricsResult {\n grain?: string\n // The merchant's accounting timezone: each time cell is the instant its\n // bucket starts there.\n timezone?: string\n range: { from: string; to: string }\n columns: MetricsColumn[]\n rows: MetricsCell[][]\n compare_range?: { from: string; to: string }\n compare_rows?: MetricsCell[][]\n}\n\n// A kpi is a tile's value, its change and a sparkline; a heading is a\n// section title and programs the dispute program standings, both with no\n// query.\nexport type WidgetViz =\n | \"kpi\"\n | \"stat\"\n | \"line\"\n | \"area\"\n | \"bar\"\n | \"donut\"\n | \"table\"\n | \"cohort\"\n | \"funnel\"\n | \"heading\"\n | \"programs\"\n\n// queryless: a viz that draws no metrics query.\nexport const queryless = (viz: WidgetViz) =>\n viz === \"heading\" || viz === \"programs\"\n\n// CHART_VIZ are the vizzes a widget with a query may take.\nexport const CHART_VIZ: WidgetViz[] = [\n \"kpi\",\n \"stat\",\n \"line\",\n \"area\",\n \"bar\",\n \"donut\",\n \"table\",\n \"cohort\",\n \"funnel\",\n]\n\nexport interface WidgetGrid {\n x: number\n y: number\n w: number\n h: number\n}\n\nexport interface Widget {\n id: string\n title: string\n viz: WidgetViz\n query: QueryMetricsParams\n grid: WidgetGrid\n // fixed_range keeps the query's own range; other widgets follow the\n // dashboard's range picker.\n fixed_range: boolean\n}\n\nexport interface Dashboard {\n widgets: Widget[]\n is_default: boolean\n // profile is what the default layout was built for; null on a saved one.\n profile?: DashboardProfile | null\n updated_at?: string\n updated_by?: string\n}\n\nexport function createMetrics(client: AdminClient) {\n const { api } = client\n const metricsQuery = (query: QueryMetricsParams, signal?: AbortSignal) =>\n api<MetricsResult>(\"/metrics/query\", {\n method: \"POST\",\n body: query,\n signal,\n })\n\n const getDashboard = (signal?: AbortSignal) =>\n api<Dashboard>(\"/metrics/dashboard\", { signal })\n\n const getMetricsSchema = (signal?: AbortSignal) =>\n api<MetricsSchema>(\"/metrics/schema\", { signal })\n\n const putDashboard = (widgets: Widget[]) =>\n api<Dashboard>(\"/merchant/dashboard\", { method: \"PUT\", body: { widgets } })\n\n // Each card PSP's standing in the dispute programs for the month holding\n // at (now when absent).\n const listDisputePrograms = (at?: string, signal?: AbortSignal) =>\n api<ListPage<DisputeStanding>>(\n `/metrics/dispute-programs${at ? `?at=${encodeURIComponent(at)}` : \"\"}`,\n { signal }\n )\n\n return {\n metricsQuery,\n getDashboard,\n getMetricsSchema,\n putDashboard,\n listDisputePrograms,\n }\n}\n","import type { AdminClient } from \"./client\"\n\nimport type {\n CreditGrant,\n CreditGrantInput,\n BalanceTransaction,\n ListPage,\n} from \"./credit-types\"\n\nconst customerPath = (id: string) =>\n `/admin/customers/${encodeURIComponent(id)}`\nexport function createCreditEndpoints(client: AdminClient) {\n const { api } = client\n\n const listCreditGrants = (\n customer: string,\n currency: string,\n limit: number,\n cursor: string,\n signal?: AbortSignal\n ) =>\n api<ListPage<CreditGrant>>(\"/admin/credit-grants\", {\n query: { customer_id: customer, currency, limit, cursor },\n signal,\n })\n\n // A grant is a batch of one; the batch route is all or none.\n const createCreditGrant = async (\n customer: string,\n body: CreditGrantInput\n ) => {\n const out = await api<{ items: CreditGrant[] }>(\"/admin/credit-grants\", {\n method: \"POST\",\n body: { items: [{ customer_id: customer, ...body }] },\n })\n return out.items[0]\n }\n\n const revokeCreditGrant = (grant: string, reason: string) =>\n api<CreditGrant>(\n `/admin/credit-grants/${encodeURIComponent(grant)}/revoke`,\n { method: \"POST\", body: { reason } }\n )\n\n const listBalanceTransactions = (\n customer: string,\n currency: string,\n limit: number,\n cursor: string,\n signal?: AbortSignal\n ) =>\n api<ListPage<BalanceTransaction>>(\n `${customerPath(customer)}/balance/transactions`,\n {\n query: { currency, limit, cursor },\n signal,\n }\n )\n return {\n listCreditGrants,\n createCreditGrant,\n revokeCreditGrant,\n listBalanceTransactions,\n }\n}\n","import type { AdminClient } from \"./client\"\nimport { type PageRequest } from \"./client\"\n\nimport type {\n RecordExternalPaymentParams,\n ListPage,\n Order,\n Payment,\n} from \"#orck/client/generated/wire\"\n\n// Orders are listed newest first.\nexport interface OrderFilters {\n customer_id?: string\n origin?: string\n status?: string\n // overdue \"true\" keeps the open orders still owed past their due date.\n overdue?: string\n // ids reads the orders of these ids, comma-separated, and takes no other\n // filter or page.\n ids?: string\n}\n\n// UsageAction is what staff do to an unpaid usage order.\nexport type UsageAction =\n \"waive_balance\" | \"mark_uncollectible\" | \"record_payment\"\n\nexport interface UsageActionRequest {\n id: string\n action: UsageAction\n amount?: string\n reference?: string\n}\nexport function createOrderEndpoints(client: AdminClient) {\n const { api } = client\n\n const listOrders = (\n filters: OrderFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<Order>>(\"/admin/orders\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const getOrder = (id: string, signal?: AbortSignal) =>\n api<Order>(`/admin/orders/${id}`, { signal })\n\n // An order's payments are payments naming it.\n const listOrderPayments = (\n id: string,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<Payment>>(\"/admin/payments\", {\n query: { order_id: id, ...page },\n signal,\n })\n\n function applyUsageAction(\n request: UsageActionRequest\n ): Promise<Order | Payment> {\n if (request.action === \"record_payment\") {\n const body: RecordExternalPaymentParams = {\n order_id: request.id,\n amount: request.amount ?? \"\",\n transaction_id: request.reference ?? \"\",\n }\n return api<Payment>(\"/admin/payments\", { method: \"POST\", body })\n }\n const path = {\n waive_balance: \"waive-balance\",\n mark_uncollectible: \"mark-uncollectible\",\n }[request.action]\n return api<Order>(`/admin/orders/${request.id}/${path}`, {\n method: \"POST\",\n })\n }\n return { listOrders, getOrder, listOrderPayments, applyUsageAction }\n}\n","import type { createEndpoints } from \"./endpoints\"\n\nimport type { InvoiceProfile } from \"#orck/client/generated/wire\"\nexport function createInvoiceProfileEndpoints(\n endpoints: ReturnType<typeof createEndpoints>\n) {\n const { getCustomer } = endpoints\n const { updateCustomer } = endpoints\n\n // getInvoiceProfile is the customer's invoice_profile setting; null while it\n // has none.\n const getInvoiceProfile = async (customerId: string, signal?: AbortSignal) =>\n (await getCustomer(customerId, signal)).settings.invoice_profile ?? null\n\n const putInvoiceProfile = async (\n customerId: string,\n profile: InvoiceProfile\n ) => {\n const { settings } = await updateCustomer(customerId, {\n invoice_profile: profile,\n })\n return settings.invoice_profile\n }\n return { getInvoiceProfile, putInvoiceProfile }\n}\n","import type { AdminClient, PageRequest } from \"./client\"\n\nimport type {\n CreatePSPImportParams,\n CreateProviderPriceParams,\n Customer,\n Finding,\n LinkPSPImportParams,\n ListPage,\n PSPImport,\n PSPImportMapping,\n PSPImportMappingsResult,\n PSPImportRecord,\n ParkedSubscription,\n Price,\n ProposalResults,\n ProviderCatalogObject,\n} from \"#orck/client/generated/wire\"\n\nexport interface PSPImportFilters {\n // A PSP's id or key.\n psp?: string\n}\n\nexport interface PSPImportRecordFilters {\n state?: PSPImportRecord[\"state\"]\n kind?: PSPImportRecord[\"kind\"]\n}\n\n// One PSP's observed catalog. import keeps the prices that import's staged\n// subscriptions name, each with their count.\nexport interface ProviderCatalogFilters {\n psp: string\n kind?: ProviderCatalogObject[\"kind\"]\n mapped?: boolean\n retired?: boolean\n import?: string\n}\n\nexport interface ParkedFilters {\n psp?: string\n reason?: ParkedSubscription[\"reason\"]\n released?: boolean\n}\n\n// Open pull.* proposals by default. ids alone names up to 100, whatever\n// their state.\nexport interface ProposalFilters {\n ids?: string\n psp_id?: string\n pull_id?: string\n kind?: string\n}\n\n// PSP imports, the observed provider catalog and parked subscriptions: the\n// pull, its mapping and what webhooks could not land.\nexport function createImportEndpoints(client: AdminClient) {\n const { api } = client\n\n const listPSPImports = (\n filters: PSPImportFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<PSPImport>>(\"/merchant/psp-imports\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const getPSPImport = (id: string, signal?: AbortSignal) =>\n api<PSPImport>(`/merchant/psp-imports/${encodeURIComponent(id)}`, {\n signal,\n })\n\n // createPSPImport queues a manual pull; the server picks its rules.\n const createPSPImport = (params: CreatePSPImportParams) =>\n api<PSPImport>(\"/merchant/psp-imports\", { method: \"POST\", body: params })\n\n const listPSPImportRecords = (\n id: string,\n filters: PSPImportRecordFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<PSPImportRecord>>(\n `/merchant/psp-imports/${encodeURIComponent(id)}/records`,\n { query: { ...filters, ...page }, signal }\n )\n\n // linkPSPImport stores links and price picks, then decides every record not\n // yet imported again; empty params only re-link.\n const linkPSPImport = (id: string, params: LinkPSPImportParams) =>\n api<PSPImport>(`/merchant/psp-imports/${encodeURIComponent(id)}/link`, {\n method: \"POST\",\n body: params,\n })\n\n // applyPSPImport queues the landing of the linked records.\n const applyPSPImport = (id: string) =>\n api<PSPImport>(`/merchant/psp-imports/${encodeURIComponent(id)}/apply`, {\n method: \"POST\",\n })\n\n const setPSPImportMappings = (mappings: PSPImportMapping[]) =>\n api<PSPImportMappingsResult>(\"/merchant/psp-import-mappings\", {\n method: \"POST\",\n body: { mappings },\n })\n\n const listProviderCatalog = (\n filters: ProviderCatalogFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<ProviderCatalogObject>>(\"/merchant/provider-catalog\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const createProviderPrice = (params: CreateProviderPriceParams) =>\n api<Price>(\"/catalog/provider-prices\", { method: \"POST\", body: params })\n\n const listParkedSubscriptions = (\n filters: ParkedFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<ParkedSubscription>>(\"/merchant/parked-subscriptions\", {\n query: { ...filters, ...page },\n signal,\n })\n\n const listProposals = (\n filters: ProposalFilters,\n page: PageRequest,\n signal?: AbortSignal\n ) =>\n api<ListPage<Finding>>(\"/merchant/proposals\", {\n query: { ...filters, ...page },\n signal,\n })\n\n // approveProposals approves up to 100 proposals. The key replays the first\n // answer: a retry of the same batch reuses it.\n const approveProposals = (ids: string[], notes: string, key: string) =>\n api<ProposalResults>(\"/merchant/proposals/approve\", {\n method: \"POST\",\n headers: { \"Idempotency-Key\": key },\n body: { ids, notes },\n })\n\n const dismissProposals = (ids: string[], notes: string) =>\n api<ProposalResults>(\"/merchant/proposals/dismiss\", {\n method: \"POST\",\n body: { ids, notes },\n })\n\n // customersByIds reads named customers: only those with billing rows exist.\n const customersByIds = (ids: string[], signal?: AbortSignal) =>\n api<ListPage<Customer>>(\"/admin/customers\", {\n query: { ids: ids.join(\",\") },\n signal,\n })\n\n return {\n listPSPImports,\n getPSPImport,\n createPSPImport,\n listPSPImportRecords,\n linkPSPImport,\n applyPSPImport,\n setPSPImportMappings,\n listProviderCatalog,\n createProviderPrice,\n listParkedSubscriptions,\n customersByIds,\n listProposals,\n approveProposals,\n dismissProposals,\n }\n}\n","import type { AdminClient } from \"./client\"\nimport { createEndpoints } from \"./endpoints\"\nimport { createMetrics } from \"./metrics\"\nimport { createCreditEndpoints } from \"./credit-endpoints\"\nimport { createOrderEndpoints } from \"./order-endpoints\"\nimport { createInvoiceProfileEndpoints } from \"./invoice-profile-endpoints\"\nimport { createImportEndpoints } from \"./import-endpoints\"\n\nexport function createAdminAPI(client: AdminClient) {\n const endpoints = createEndpoints(client)\n return {\n ...endpoints,\n ...createMetrics(client),\n ...createCreditEndpoints(client),\n ...createOrderEndpoints(client),\n ...createInvoiceProfileEndpoints(endpoints),\n ...createImportEndpoints(client),\n }\n}\n\nexport type AdminAPI = ReturnType<typeof createAdminAPI>\n","import { ApiError } from \"#orck/admin/lib/api/client\"\nimport { en } from \"../../locales/en\"\n\n// Staff wording for refusals the shared customer strings do not cover.\nconst staffErrors: Record<string, string> = {\n destructive_actions_held:\n \"Refunds, revokes and cancels are paused for you after several in a short time. Someone else can clear the hold on the Ops page.\",\n authorization_unavailable:\n \"Billing couldn't check your permissions just now. Try again in a moment.\",\n permission_required: \"Your role doesn't allow this.\",\n}\n\nconst sentence = (text: string) => {\n const trimmed = text.trim()\n if (!trimmed) return trimmed\n const first = trimmed.charAt(0).toUpperCase() + trimmed.slice(1)\n return /[.!?]$/.test(first) ? first : `${first}.`\n}\n\n// errorText is a failure as a plain sentence for staff, with the API's code\n// kept apart for a secondary detail line, never the main text.\nexport function errorText(error: unknown): { text: string; code?: string } {\n if (!(error instanceof ApiError))\n return {\n text: sentence(\n error instanceof Error && error.message\n ? error.message\n : en.errors.generic\n ),\n }\n const code = error.code\n // The server's own message names the specific problem; the shared wording\n // only stands in when it sent none.\n const known =\n (code && staffErrors[code]) ||\n (error.message\n ? undefined\n : (code && (en.errors as Record<string, string>)[code]) ||\n (error.status === 404 ? en.errors.resource_not_found : undefined) ||\n (error.status === 403 ? staffErrors.permission_required : undefined))\n return {\n text: known ?? sentence(error.message || en.errors.generic),\n code,\n }\n}\n","import { toast as sonnerToast } from \"sonner\"\n\nimport { ApiError } from \"#orck/admin/lib/api/client\"\nimport { errorText } from \"#orck/admin/lib/error-text\"\n\nexport function createAdminToast(namespace?: string) {\n const scoped =\n (send: typeof sonnerToast.error) =>\n (\n message: Parameters<typeof send>[0],\n options?: Parameters<typeof send>[1]\n ) =>\n send(message, { ...options, toasterId: namespace })\n return Object.assign(scoped(sonnerToast), {\n error: scoped(sonnerToast.error),\n success: scoped(sonnerToast.success),\n info: scoped(sonnerToast.info),\n warning: scoped(sonnerToast.warning),\n })\n}\n\nexport function createToastHandlers(\n toast: ReturnType<typeof createAdminToast>\n) {\n // toastApiError renders the unified internal/api error envelope consistently.\n // 403s read as a role/permission gap (the API is the authority on\n // permissions — the UI gates on its answers rather than duplicating RBAC).\n function toastApiError(err: unknown, action: string) {\n if (err instanceof ApiError) {\n if (err.code === \"revision_mismatch\") {\n toast.error(`${action}: changed since you opened it`, {\n description: \"The latest version is loaded; review it and try again.\",\n })\n return\n }\n if (err.code === \"person_required\") {\n toast.error(`${action}: only a signed-in person can do this`, {\n description: err.message,\n })\n return\n }\n }\n // A plain sentence; the API's code stays in the secondary line for\n // support, never in the title.\n const { text, code } = errorText(err)\n toast.error(\n `Couldn't ${action.charAt(0).toLowerCase()}${action.slice(1)}`,\n {\n description: code ? `${text} Code: ${code}.` : text,\n }\n )\n }\n\n // toastStaleEdit answers an edit refused with revision_mismatch: the caller\n // closes the form and the reload shows what changed.\n function toastStaleEdit(what: string) {\n toast.error(`${what} changed since you opened it`, {\n description: \"Reloaded. Review the current version and edit again.\",\n })\n }\n\n return { toastApiError, toastStaleEdit }\n}\n","import type { AdminClient } from \"./api/client\"\nimport type { AdminAPI } from \"./api\"\nimport { keepPreviousData, queryOptions } from \"@tanstack/react-query\"\nimport { collectCursorPages } from \"#orck/admin/lib/api/client\"\n\nimport type { ListPage } from \"#orck/client/generated/wire\"\nimport {\n PAGE_MAX,\n type AttemptFilters,\n type CycleFilters,\n type PaymentFilters,\n type SubscriptionFilters,\n} from \"#orck/admin/lib/api/endpoints\"\nimport {\n type MetricsCell,\n type QueryMetricsParams,\n type MetricsResult,\n} from \"#orck/admin/lib/api/metrics\"\n\nimport type { FindingsGauges } from \"#orck/admin/lib/api/types\"\n\n// metricsRow reads a query without a group-by: its one row, by column name.\nfunction metricsRow(result: MetricsResult): Record<string, MetricsCell> {\n const row = result.rows[0] ?? []\n return Object.fromEntries(\n result.columns.map((column, i) => [column.name, row[i] ?? null])\n )\n}\n\n// Complete collections are explicit: selectors need every eligible record,\n// while catalog screens fetch only their visible page.\nexport async function collectPages<T>(\n loadPage: (\n cursor: string | undefined,\n signal?: AbortSignal\n ) => Promise<ListPage<T>>,\n signal?: AbortSignal\n): Promise<ListPage<T>> {\n const data = await collectCursorPages(\n (cursor) => loadPage(cursor, signal),\n signal\n )\n return { data, next_cursor: null }\n}\n\ntype MerchantRoot = readonly string[]\n\n// One vocabulary of merchant-scoped keys, bound to a root that is either read\n// live or pinned once. Nothing below reaches for the selected merchant itself.\nconst buildQueryKeys = (root: () => MerchantRoot) => ({\n merchant: () => root(),\n customers: () => [...root(), \"customers\"] as const,\n customer: (id: string) => [...root(), \"customers\", id] as const,\n subscriptions: () => [...root(), \"subscriptions\"] as const,\n subscription: (id: string) => [...root(), \"subscriptions\", id] as const,\n payments: () => [...root(), \"payments\"] as const,\n payment: (id: string) => [...root(), \"payments\", id] as const,\n attempts: () => [...root(), \"payment-attempts\"] as const,\n cycles: () => [...root(), \"renewals\"] as const,\n catalog: () => [...root(), \"catalog\"] as const,\n usageMeters: () => [...root(), \"catalog\", \"meters\"] as const,\n usageMeter: (key: string) => [...root(), \"catalog\", \"meters\", key] as const,\n settings: () => [...root(), \"settings\"] as const,\n alerts: () => [...root(), \"alerts\"] as const,\n ops: () => [...root(), \"ops\"] as const,\n dashboard: () => [...root(), \"dashboard\"] as const,\n notifications: () => [...root(), \"notifications\"] as const,\n})\n\nexport type MerchantQueryKeys = ReturnType<typeof buildQueryKeys>\n\nconst queryErrorMeta = (errorAction?: string) =>\n errorAction ? { errorAction } : undefined\nexport function createQueries(client: AdminClient, api: AdminAPI) {\n const { queryRoot } = client\n const {\n getCustomer,\n getMerchantConfiguration,\n getPayment,\n getPaymentAttempt,\n getPrice,\n getPriceHistory,\n getProduct,\n getRenewal,\n getSubscription,\n getUsageMeter,\n listCustomerEntitlements,\n listCustomerPaymentMethods,\n listCustomerProductAccess,\n listCustomers,\n listFindings,\n listDestructiveHolds,\n listPaymentAttempts,\n listPSPs,\n listRails,\n previewPSPRouting,\n listPayments,\n listPrices,\n listProducts,\n listRenewals,\n listPriceMigrations,\n listSubscriptionChangeOptions,\n listSubscriptions,\n listUsageMeters,\n getAdminAccess,\n getConfig,\n listWebhooks,\n getDashboard,\n getMetricsSchema,\n metricsQuery,\n listDisputePrograms,\n } = api\n\n const currentMerchantRoot = queryRoot\n\n // Read keys belong to this instance and selected merchant.\n const queryKeys: MerchantQueryKeys = buildQueryKeys(currentMerchantRoot)\n\n // Pinned keys: the selected merchant is read once, here. Keys derived from the\n // result name that merchant forever, so work started under one merchant can\n // never invalidate under another that the operator selected while it ran.\n const merchantQueryKeys = (): MerchantQueryKeys => {\n const root = currentMerchantRoot()\n return buildQueryKeys(() => root)\n }\n\n const adminQueries = {\n customers: (search: string, limit: number, cursor: string) =>\n queryOptions({\n queryKey: [...queryKeys.customers(), { search, limit, cursor }],\n queryFn: ({ signal }) => listCustomers(search, limit, cursor, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load customers\" },\n }),\n customer: (id: string) =>\n queryOptions({\n queryKey: queryKeys.customer(id),\n queryFn: ({ signal }) => getCustomer(id, signal),\n enabled: Boolean(id),\n }),\n // One page of each of a customer's lists, for the customer page.\n customerSubscriptions: (id: string, limit: number, cursor: string) =>\n queryOptions({\n queryKey: [\n ...queryKeys.customer(id),\n \"subscriptions\",\n { limit, cursor },\n ],\n queryFn: ({ signal }) =>\n listSubscriptions(\n { customer_id: id },\n limit,\n cursor || undefined,\n signal\n ),\n enabled: Boolean(id),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load subscriptions\" },\n }),\n customerPayments: (id: string, limit: number, cursor: string) =>\n queryOptions({\n queryKey: [...queryKeys.customer(id), \"payments\", { limit, cursor }],\n queryFn: ({ signal }) =>\n listPayments(\n { customer_id: id },\n { limit, cursor: cursor || undefined },\n signal\n ),\n enabled: Boolean(id),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load payments\" },\n }),\n customerPaymentMethodsPage: (id: string, limit: number, cursor: string) =>\n queryOptions({\n queryKey: [\n ...queryKeys.customer(id),\n \"payment-methods\",\n { limit, cursor },\n ],\n queryFn: ({ signal }) =>\n listCustomerPaymentMethods(\n id,\n { limit, cursor: cursor || undefined },\n signal\n ),\n enabled: Boolean(id),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load payment methods\" },\n }),\n customerEntitlements: (id: string, limit: number, cursor: string) =>\n queryOptions({\n queryKey: [\n ...queryKeys.customer(id),\n \"entitlements\",\n { limit, cursor },\n ],\n queryFn: ({ signal }) =>\n listCustomerEntitlements(\n id,\n { limit, cursor: cursor || undefined },\n signal\n ),\n enabled: Boolean(id),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load entitlements\" },\n }),\n customerProductAccess: (id: string, limit: number, cursor: string) =>\n queryOptions({\n queryKey: [\n ...queryKeys.customer(id),\n \"product-access\",\n { limit, cursor },\n ],\n queryFn: ({ signal }) =>\n listCustomerProductAccess(\n id,\n { limit, cursor: cursor || undefined },\n signal\n ),\n enabled: Boolean(id),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load product access\" },\n }),\n subscriptions: (\n filters: SubscriptionFilters,\n limit: number,\n cursor: string\n ) =>\n queryOptions({\n queryKey: [...queryKeys.subscriptions(), { filters, limit, cursor }],\n queryFn: ({ signal }) =>\n listSubscriptions(filters, limit, cursor || undefined, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load subscriptions\" },\n }),\n subscription: (id: string) =>\n queryOptions({\n queryKey: queryKeys.subscription(id),\n queryFn: ({ signal }) => getSubscription(id, signal),\n enabled: Boolean(id),\n }),\n // The prices staff can change the subscription to; a refusal says why\n // it cannot change.\n subscriptionChangeOptions: (id: string) =>\n queryOptions({\n queryKey: [...queryKeys.subscription(id), \"change-options\"],\n queryFn: ({ signal }) => listSubscriptionChangeOptions(id, signal),\n // A change invalidates the subscription; a detail view re-read\n // within a minute reuses the previews.\n staleTime: 60_000,\n }),\n // Every saved method: pickers must offer all of them.\n customerPaymentMethods: (customerId?: string) =>\n queryOptions({\n queryKey: [\n ...queryKeys.customer(customerId ?? \"unselected\"),\n \"payment-methods\",\n ],\n queryFn: ({ signal }) =>\n collectCursorPages(\n (cursor) =>\n listCustomerPaymentMethods(\n customerId!,\n { limit: 100, cursor },\n signal\n ),\n signal\n ),\n enabled: Boolean(customerId),\n }),\n payments: (filters: PaymentFilters, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...queryKeys.payments(), { filters, limit, cursor }],\n queryFn: ({ signal }) =>\n listPayments(filters, { limit, cursor }, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load payments\" },\n }),\n payment: (id: string) =>\n queryOptions({\n queryKey: queryKeys.payment(id),\n queryFn: ({ signal }) => getPayment(id, signal),\n enabled: Boolean(id),\n }),\n attempts: (filters: AttemptFilters, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...queryKeys.attempts(), { filters, limit, cursor }],\n queryFn: ({ signal }) =>\n listPaymentAttempts(filters, { limit, cursor }, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load payment attempts\" },\n }),\n attempt: (id: string) =>\n queryOptions({\n queryKey: [...queryKeys.attempts(), id],\n queryFn: ({ signal }) => getPaymentAttempt(id, signal),\n enabled: Boolean(id),\n meta: { errorAction: \"Load payment attempt\" },\n }),\n cycles: (filters: CycleFilters, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...queryKeys.cycles(), { filters, limit, cursor }],\n queryFn: ({ signal }) =>\n listRenewals(filters, { limit, cursor }, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load renewals\" },\n }),\n cycle: (id: string) =>\n queryOptions({\n queryKey: [...queryKeys.cycles(), id],\n queryFn: ({ signal }) => getRenewal(id, signal),\n enabled: Boolean(id),\n meta: { errorAction: \"Load renewal\" },\n }),\n products: (\n options: { limit?: number; cursor?: string; errorAction?: string } = {}\n ) => {\n const { limit = 100, cursor, errorAction } = options\n return queryOptions({\n queryKey: [...queryKeys.catalog(), \"products\", { limit, cursor }],\n queryFn: ({ signal }) => listProducts(limit, cursor, undefined, signal),\n placeholderData: keepPreviousData,\n meta: queryErrorMeta(errorAction),\n })\n },\n allProducts: (options: { errorAction?: string } = {}) =>\n queryOptions({\n queryKey: [...queryKeys.catalog(), \"products\", \"all\"],\n queryFn: ({ signal }) =>\n collectPages(\n (cursor, signal) =>\n listProducts(PAGE_MAX, cursor, undefined, signal),\n signal\n ),\n meta: queryErrorMeta(options.errorAction),\n }),\n prices: (\n options: {\n productId?: string\n limit?: number\n cursor?: string\n errorAction?: string\n } = {}\n ) => {\n const { productId, limit = 100, cursor, errorAction } = options\n return queryOptions({\n queryKey: [\n ...queryKeys.catalog(),\n \"prices\",\n { productId, limit, cursor },\n ],\n queryFn: ({ signal }) => listPrices(limit, cursor, productId, signal),\n placeholderData: keepPreviousData,\n meta: queryErrorMeta(errorAction),\n })\n },\n allPrices: (options: { productId?: string; errorAction?: string } = {}) =>\n queryOptions({\n queryKey: [\n ...queryKeys.catalog(),\n \"prices\",\n \"all\",\n { productId: options.productId },\n ],\n queryFn: ({ signal }) =>\n collectPages(\n (cursor, signal) =>\n listPrices(PAGE_MAX, cursor, options.productId, signal),\n signal\n ),\n meta: queryErrorMeta(options.errorAction),\n }),\n price: (\n id: string,\n options: { verify?: boolean; errorAction?: string } = {}\n ) => {\n const { verify = false, errorAction } = options\n return queryOptions({\n queryKey: [...queryKeys.catalog(), \"prices\", id, { verify }],\n queryFn: ({ signal }) => getPrice(id, verify, signal),\n enabled: Boolean(id),\n placeholderData: keepPreviousData,\n meta: queryErrorMeta(errorAction),\n })\n },\n product: (id?: string) =>\n queryOptions({\n queryKey: [...queryKeys.catalog(), \"products\", id ?? \"unselected\"],\n queryFn: ({ signal }) => getProduct(id!, signal),\n enabled: Boolean(id),\n }),\n priceHistory: (priceId?: string) =>\n queryOptions({\n queryKey: [\n ...queryKeys.catalog(),\n \"prices\",\n \"history\",\n priceId ?? \"unselected\",\n ],\n queryFn: ({ signal }) => getPriceHistory(priceId!, signal),\n enabled: Boolean(priceId),\n }),\n priceMigrations: (productKey?: string, priceKey?: string, limit = 5) =>\n queryOptions({\n queryKey: [\n ...queryKeys.catalog(),\n \"price-migrations\",\n { productKey, priceKey, limit },\n ],\n queryFn: ({ signal }) =>\n listPriceMigrations(productKey!, priceKey!, limit, signal),\n enabled: Boolean(productKey && priceKey),\n }),\n pspRouting: (priceId: string) =>\n queryOptions({\n queryKey: [...queryKeys.catalog(), \"prices\", priceId, \"routing\"],\n queryFn: ({ signal }) =>\n previewPSPRouting({ price_id: priceId }, signal),\n enabled: Boolean(priceId),\n meta: { errorAction: \"Check purchase readiness\" },\n }),\n usageMeters: (limit = 200, cursor?: string) =>\n queryOptions({\n queryKey: [...queryKeys.usageMeters(), { limit, cursor }],\n queryFn: ({ signal }) => listUsageMeters(limit, cursor, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load usage meters\" },\n }),\n allUsageMeters: () =>\n queryOptions({\n queryKey: [...queryKeys.usageMeters(), \"all\"],\n queryFn: ({ signal }) =>\n collectPages(\n (cursor, signal) => listUsageMeters(PAGE_MAX, cursor, signal),\n signal\n ),\n meta: { errorAction: \"Load usage meters\" },\n }),\n usageMeter: (key: string) =>\n queryOptions({\n queryKey: queryKeys.usageMeter(key),\n queryFn: ({ signal }) => getUsageMeter(key, signal),\n enabled: Boolean(key),\n meta: { errorAction: \"Load usage meter\" },\n }),\n findings: (enabled = true) =>\n queryOptions({\n queryKey: [...queryKeys.ops(), \"findings\", { limit: 100 }],\n queryFn: ({ signal }) => listFindings({}, 100, signal),\n enabled,\n meta: { errorAction: \"Load findings\" },\n }),\n destructiveHolds: (enabled = true) =>\n queryOptions({\n queryKey: [...queryKeys.ops(), \"destructive-holds\"],\n queryFn: ({ signal }) =>\n collectPages(\n (cursor, signal) => listDestructiveHolds(cursor, signal),\n signal\n ),\n enabled,\n meta: { errorAction: \"Load holds\" },\n }),\n findingSummary: () =>\n queryOptions({\n queryKey: [...queryKeys.ops(), \"findings\", \"summary\"],\n queryFn: async ({ signal }): Promise<FindingsGauges> => {\n const result = await metricsQuery(\n {\n measures: [\"open_findings\"],\n by: [\"finding_group\"],\n range: { last: \"1d\" },\n },\n signal\n )\n const group: Record<string, number> = {}\n for (const row of result.rows)\n group[String(row[0])] = Number(row[1] ?? 0)\n return {\n total_open: Object.values(group).reduce((n, v) => n + v, 0),\n orphaned_members: group.orphaned ?? 0,\n freeloaders: group.freeloader ?? 0,\n duplicate_coverage: group.duplicate_coverage ?? 0,\n }\n },\n meta: { errorAction: \"Load the findings summary\" },\n }),\n merchantConfiguration: (errorAction?: string) =>\n queryOptions({\n queryKey: queryKeys.settings(),\n queryFn: ({ signal }) => getMerchantConfiguration(signal),\n meta: queryErrorMeta(errorAction),\n }),\n psps: () =>\n queryOptions({\n queryKey: [...queryKeys.settings(), \"psps\"],\n queryFn: ({ signal }) => listPSPs(signal),\n meta: { errorAction: \"Load PSPs\" },\n }),\n rails: () =>\n queryOptions({\n queryKey: [...queryKeys.settings(), \"rails\"],\n queryFn: ({ signal }) => listRails(signal),\n staleTime: Infinity,\n meta: { errorAction: \"Load rails\" },\n }),\n config: () =>\n queryOptions({\n queryKey: [\"config\"],\n queryFn: ({ signal }) => getConfig(signal),\n staleTime: 5 * 60_000,\n meta: { errorAction: \"Load configuration\" },\n }),\n access: () =>\n queryOptions({\n queryKey: [...queryKeys.merchant(), \"access\"],\n queryFn: ({ signal }) => getAdminAccess(signal),\n staleTime: 5 * 60_000,\n meta: { errorAction: \"Load your access\" },\n }),\n webhooks: () =>\n queryOptions({\n queryKey: [...queryKeys.alerts(), \"webhooks\"],\n queryFn: ({ signal }) => listWebhooks(signal),\n meta: { errorAction: \"Load webhooks\" },\n }),\n dashboard: () =>\n queryOptions({\n queryKey: queryKeys.dashboard(),\n queryFn: ({ signal }) => getDashboard(signal),\n meta: { errorAction: \"Load dashboard\" },\n }),\n // The registry changes only with a deployment.\n metricsSchema: (enabled = true) =>\n queryOptions({\n queryKey: [...queryKeys.dashboard(), \"schema\"],\n queryFn: ({ signal }) => getMetricsSchema(signal),\n staleTime: Infinity,\n enabled,\n meta: { errorAction: \"Load the metrics schema\" },\n }),\n widgetMetrics: (query?: QueryMetricsParams) =>\n queryOptions({\n queryKey: [...queryKeys.dashboard(), \"metrics\", query ?? \"unselected\"],\n queryFn: ({ signal }) => metricsQuery(query!, signal),\n enabled: Boolean(query),\n }),\n disputePrograms: (at?: string) =>\n queryOptions({\n queryKey: [...queryKeys.dashboard(), \"dispute-programs\", at ?? \"now\"],\n queryFn: ({ signal }) => listDisputePrograms(at, signal),\n meta: { errorAction: \"Load dispute programs\" },\n }),\n // The bell lists the open findings that need a person and counts them.\n notifications: (enabled: boolean) =>\n queryOptions({\n queryKey: queryKeys.notifications(),\n queryFn: ({ signal }) =>\n listFindings({ status: \"requires_review\" }, 10, signal),\n enabled,\n }),\n unreadNotifications: () =>\n queryOptions({\n queryKey: [...queryKeys.notifications(), \"count\"],\n queryFn: async ({ signal }) =>\n Number(\n metricsRow(\n await metricsQuery(\n {\n measures: [\"open_findings\"],\n range: { last: \"1d\" },\n filters: { finding_status: [\"requires_review\"] },\n },\n signal\n )\n ).open_findings ?? 0\n ),\n refetchInterval: 30_000,\n retry: false,\n }),\n }\n return { queryKeys, merchantQueryKeys, adminQueries }\n}\n","import type { AdminClient } from \"./api/client\"\nimport type { AdminAPI } from \"./api\"\nimport type { createQueries } from \"./queries\"\nimport { ApiError, collectCursorPages } from \"#orck/admin/lib/api/client\"\n\nimport type {\n CreateAlertWebhookParams,\n CreatePSPParams,\n CreatePriceParams,\n Meter,\n UpdateAlertWebhookParams,\n UpdateMerchantConfigurationParams,\n UpdatePSPParams,\n UpdateProductParams,\n} from \"#orck/client/generated/wire\"\n\nimport {\n mutationOptions,\n type QueryClient,\n type QueryKey,\n} from \"@tanstack/react-query\"\nimport {\n type DefaultUsageRateCardRequest,\n type PaymentFilters,\n type ProductGrant,\n type ProductRequest,\n type UsageMeterRequest,\n type SubscriptionFilters,\n} from \"#orck/admin/lib/api/endpoints\"\nimport { type Widget } from \"#orck/admin/lib/api/metrics\"\n\nimport type {\n ChangeSubscriptionParams,\n Customer,\n} from \"#orck/client/generated/wire\"\n\nimport type { AdminSubscription } from \"#orck/admin/lib/api/types\"\n\nconst EXPORT_PAGE = 200\n\nconst collectAllCursorPages = async <T>(\n listPage: (\n limit: number,\n cursor?: string\n ) => Promise<{ data: T[]; next_cursor: string | null }>\n) => {\n const rows: T[] = []\n let cursor: string | undefined\n for (;;) {\n const page = await listPage(EXPORT_PAGE, cursor)\n rows.push(...page.data)\n if (!page.next_cursor || page.data.length === 0) return rows\n cursor = page.next_cursor\n }\n}\n\nconst invalidateExact = (\n queryClient: QueryClient,\n queryKey: readonly unknown[]\n) => queryClient.invalidateQueries({ queryKey, exact: true })\n\nconst invalidateExactOnSuccess =\n (queryClient: QueryClient, queryKey: readonly unknown[]) => () =>\n invalidateExact(queryClient, queryKey)\n\nconst invalidateTreeOnSuccess =\n (queryClient: QueryClient, queryKey: readonly unknown[]) => () =>\n queryClient.invalidateQueries({ queryKey })\n\n// reloadIfMoved refetches what an edit was refused for: an object another\n// edit changed since it was read (revision_mismatch).\nconst reloadIfMoved =\n (queryClient: QueryClient, ...queryKeys: QueryKey[]) =>\n (err: unknown) => {\n if (err instanceof ApiError && err.code === \"revision_mismatch\") {\n void Promise.all(\n queryKeys.map((queryKey) => queryClient.invalidateQueries({ queryKey }))\n )\n }\n }\n\n// CUSTOMER_MATCHES is how many matching customers a search offers to choose.\nexport const CUSTOMER_MATCHES = 8\n\nexport function createMutations(\n client: AdminClient,\n api: AdminAPI,\n queries: ReturnType<typeof createQueries>\n) {\n const { selectedMerchant } = client\n const {\n cancelPriceMigration,\n cancelSubscription,\n changeSubscriptionPaymentMethod,\n changeSubscription,\n createPrice,\n createProduct,\n createWebhook,\n createPSP,\n deleteWebhook,\n getCustomer,\n grantProductAccess,\n listCustomers,\n listPayments,\n listSubscriptions,\n putUsageMeterRateCard,\n updatePSP,\n putUsageMeter,\n previewPriceMigration,\n previewSubscriptionChange,\n applyCatalog,\n refundPayment,\n createPriceMigration,\n resolveFinding,\n clearDestructiveHold,\n resumeSubscription,\n revokeProductAccess,\n updateCustomer,\n updateMerchantConfiguration,\n updatePrice,\n updateProduct,\n updateWebhook,\n putDashboard,\n } = api\n\n const { adminQueries, merchantQueryKeys } = queries\n\n // Every factory pins the selected merchant once, up front, with\n // merchantQueryKeys(). Callbacks fire after the request returns, by which time\n // the operator may have switched merchants, so a key built inside onSuccess /\n // onSettled from the live queryKeys would name the wrong merchant: the\n // initiating merchant's screens stay stale and an untouched merchant's cache is\n // invalidated. Importing the live queryKeys here is blocked by lint.\n const readOnlyNow = (queryClient: QueryClient) => (err: Error) => {\n if (err instanceof ApiError && err.merchantConfigReadOnly)\n void queryClient.invalidateQueries({\n queryKey: adminQueries.config().queryKey,\n })\n }\n\n const webhooksChanged =\n (queryClient: QueryClient, keys: ReturnType<typeof merchantQueryKeys>) =>\n () =>\n Promise.all([\n invalidateExact(queryClient, [...keys.alerts(), \"webhooks\"]),\n invalidateExact(queryClient, keys.settings()),\n ])\n const adminMutations = {\n saveDashboard: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n const dashboardKey = keys.dashboard()\n return mutationOptions({\n mutationKey: [...dashboardKey, \"save\"],\n mutationFn: (widgets: Widget[]) => putDashboard(widgets),\n onSuccess: (saved) => queryClient.setQueryData(dashboardKey, saved),\n })\n },\n\n // findCustomers resolves a search term to customers: one more than\n // CUSTOMER_MATCHES, so a caller can tell there are more to narrow.\n findCustomers: () => {\n const keys = merchantQueryKeys()\n const customersKey = keys.customers()\n return mutationOptions({\n mutationKey: [...customersKey, \"find\"],\n mutationFn: async (term: string) =>\n (await listCustomers(term, CUSTOMER_MATCHES + 1, \"\")).data,\n })\n },\n exportCustomers: () => {\n const keys = merchantQueryKeys()\n const customersKey = keys.customers()\n return mutationOptions({\n mutationKey: [...customersKey, \"export\"],\n mutationFn: (search: string) =>\n collectAllCursorPages<Customer>((limit, cursor) =>\n listCustomers(search, limit, cursor ?? \"\")\n ),\n })\n },\n exportSubscriptions: () => {\n const keys = merchantQueryKeys()\n const subscriptionsKey = keys.subscriptions()\n return mutationOptions({\n mutationKey: [...subscriptionsKey, \"export\"],\n mutationFn: (filters: SubscriptionFilters) =>\n collectAllCursorPages<AdminSubscription>((limit, cursor) =>\n listSubscriptions(filters, limit, cursor)\n ),\n })\n },\n exportPayments: () => {\n const keys = merchantQueryKeys()\n const paymentsKey = keys.payments()\n return mutationOptions({\n mutationKey: [...paymentsKey, \"export\"],\n mutationFn: (filters: PaymentFilters) =>\n collectCursorPages((cursor) =>\n listPayments(filters, { limit: EXPORT_PAGE, cursor })\n ),\n })\n },\n resolveFinding: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n const opsKey = keys.ops()\n return mutationOptions({\n mutationKey: [...opsKey, \"findings\", \"resolve\"],\n mutationFn: ({\n id,\n outcome,\n notes,\n }: {\n id: string\n outcome: \"approve\" | \"ignore\"\n notes: string\n }) => resolveFinding(id, outcome, notes),\n onSuccess: invalidateTreeOnSuccess(queryClient, opsKey),\n })\n },\n clearDestructiveHold: (queryClient: QueryClient) => {\n const opsKey = merchantQueryKeys().ops()\n return mutationOptions({\n mutationKey: [...opsKey, \"destructive-holds\", \"clear\"],\n mutationFn: ({ id, reason }: { id: string; reason: string }) =>\n clearDestructiveHold(id, reason),\n onSuccess: invalidateTreeOnSuccess(queryClient, opsKey),\n })\n },\n refundPayment: (\n queryClient: QueryClient,\n paymentId: string,\n customerId?: string,\n subscriptionId?: string\n ) => {\n const keys = merchantQueryKeys()\n const paymentsKey = keys.payments()\n const customerKey = customerId ? keys.customer(customerId) : undefined\n const subscriptionKey = subscriptionId\n ? keys.subscription(subscriptionId)\n : undefined\n return mutationOptions({\n mutationKey: [...paymentsKey, paymentId, \"refund\"],\n mutationFn: ({\n amount,\n reason,\n revokeAccess,\n }: {\n amount: string\n reason: string\n revokeAccess: boolean\n }) => refundPayment(paymentId, amount, reason, revokeAccess),\n onSuccess: () =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: paymentsKey }),\n ...(customerKey\n ? [queryClient.invalidateQueries({ queryKey: customerKey })]\n : []),\n ...(subscriptionKey\n ? [queryClient.invalidateQueries({ queryKey: subscriptionKey })]\n : []),\n ]),\n })\n },\n cancelSubscription: (\n queryClient: QueryClient,\n subscriptionId: string,\n customerId?: string\n ) => {\n const keys = merchantQueryKeys()\n const subscriptionsKey = keys.subscriptions()\n const customerKey = customerId ? keys.customer(customerId) : undefined\n return mutationOptions({\n mutationKey: [...subscriptionsKey, subscriptionId, \"cancel\"],\n mutationFn: ({\n reason,\n revokeAccess,\n }: {\n reason: string\n revokeAccess: boolean\n }) => cancelSubscription(subscriptionId, reason, revokeAccess),\n onSuccess: () =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: subscriptionsKey }),\n ...(customerKey\n ? [queryClient.invalidateQueries({ queryKey: customerKey })]\n : []),\n ]),\n })\n },\n resumeSubscription: (\n queryClient: QueryClient,\n subscriptionId: string,\n customerId?: string\n ) => {\n const keys = merchantQueryKeys()\n const subscriptionsKey = keys.subscriptions()\n const customerKey = customerId ? keys.customer(customerId) : undefined\n return mutationOptions({\n mutationKey: [...subscriptionsKey, subscriptionId, \"resume\"],\n mutationFn: () => resumeSubscription(subscriptionId),\n onSuccess: () =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: subscriptionsKey }),\n ...(customerKey\n ? [queryClient.invalidateQueries({ queryKey: customerKey })]\n : []),\n ]),\n })\n },\n changeSubscriptionPaymentMethod: (\n queryClient: QueryClient,\n subscriptionId: string,\n customerId?: string\n ) => {\n const keys = merchantQueryKeys()\n const subscriptionsKey = keys.subscriptions()\n const customerKey = customerId ? keys.customer(customerId) : undefined\n return mutationOptions({\n mutationKey: [...subscriptionsKey, subscriptionId, \"payment-method\"],\n mutationFn: (paymentMethodId: string | null) =>\n changeSubscriptionPaymentMethod(subscriptionId, paymentMethodId),\n onSuccess: () =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: subscriptionsKey }),\n ...(customerKey\n ? [queryClient.invalidateQueries({ queryKey: customerKey })]\n : []),\n ]),\n })\n },\n previewSubscriptionChange: (subscriptionId: string) => {\n const keys = merchantQueryKeys()\n const subscriptionsKey = keys.subscriptions()\n return mutationOptions({\n mutationKey: [...subscriptionsKey, subscriptionId, \"change\", \"preview\"],\n mutationFn: (change: ChangeSubscriptionParams) =>\n previewSubscriptionChange(subscriptionId, change),\n })\n },\n changeSubscription: (\n queryClient: QueryClient,\n subscriptionId: string,\n customerId?: string\n ) => {\n const keys = merchantQueryKeys()\n const subscriptionsKey = keys.subscriptions()\n const customerKey = customerId ? keys.customer(customerId) : undefined\n const paymentsKey = keys.payments()\n return mutationOptions({\n mutationKey: [...subscriptionsKey, subscriptionId, \"change\"],\n mutationFn: (request: {\n change: ChangeSubscriptionParams\n idempotencyKey: string\n }) =>\n changeSubscription(\n subscriptionId,\n request.change,\n request.idempotencyKey\n ),\n onSuccess: () =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: subscriptionsKey }),\n queryClient.invalidateQueries({ queryKey: paymentsKey }),\n ...(customerKey\n ? [queryClient.invalidateQueries({ queryKey: customerKey })]\n : []),\n ]),\n })\n },\n grantCustomerProductAccess: (\n queryClient: QueryClient,\n customerId: string\n ) => {\n const keys = merchantQueryKeys()\n const customerKey = keys.customer(customerId)\n return mutationOptions({\n mutationKey: [...customerKey, \"product-access\", \"grant\"],\n mutationFn: (grant: ProductGrant) =>\n grantProductAccess(customerId, grant),\n onSuccess: invalidateTreeOnSuccess(queryClient, customerKey),\n })\n },\n revokeCustomerProductAccess: (\n queryClient: QueryClient,\n customerId: string\n ) => {\n const keys = merchantQueryKeys()\n const customerKey = keys.customer(customerId)\n return mutationOptions({\n mutationKey: [...customerKey, \"product-access\", \"revoke\"],\n mutationFn: ({\n grantId,\n reason,\n }: {\n grantId: string\n reason: string\n }) => revokeProductAccess(grantId, reason),\n onSuccess: invalidateTreeOnSuccess(queryClient, customerKey),\n })\n },\n applyCatalog: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"apply\"],\n mutationFn: ({\n document,\n force,\n }: {\n document: string\n force: boolean\n }) => applyCatalog(document, force),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n })\n },\n createProduct: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"products\", \"create\"],\n mutationFn: (product: ProductRequest) => createProduct(product),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n })\n },\n updateProduct: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"products\", \"update\"],\n mutationFn: ({\n id,\n product,\n }: {\n id: string\n product: UpdateProductParams\n }) => updateProduct(id, product),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n onError: reloadIfMoved(queryClient, keys.catalog()),\n })\n },\n setProductActive: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"products\", \"set-active\"],\n mutationFn: ({\n id,\n active,\n revision,\n }: {\n id: string\n active: boolean\n revision: number\n }) =>\n updateProduct(id, { archived: !active, expected_revision: revision }),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n onError: reloadIfMoved(queryClient, keys.catalog()),\n })\n },\n createPrice: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"prices\", \"create\"],\n mutationFn: (price: CreatePriceParams) => createPrice(price),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n })\n },\n setPriceActive: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"prices\", \"set-active\"],\n mutationFn: ({\n id,\n active,\n revision,\n }: {\n id: string\n active: boolean\n revision: number\n }) =>\n updatePrice(id, { archived: !active, expected_revision: revision }),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n onError: reloadIfMoved(queryClient, keys.catalog()),\n })\n },\n putUsageMeter: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n const metersKey = keys.usageMeters()\n return mutationOptions({\n mutationKey: [...metersKey, \"put\"],\n mutationFn: ({\n key,\n meter,\n }: {\n key: string\n meter: UsageMeterRequest\n }) => putUsageMeter(key, meter),\n onSuccess: (_result, { key }) =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: metersKey }),\n queryClient.invalidateQueries({\n queryKey: keys.usageMeter(key),\n }),\n ]),\n onError: reloadIfMoved(queryClient, metersKey),\n })\n },\n putDefaultUsageRateCard: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n const metersKey = keys.usageMeters()\n return mutationOptions({\n mutationKey: [...metersKey, \"rate-card\", \"put\"],\n mutationFn: ({\n meter,\n rateCard,\n }: {\n meter: Meter\n rateCard: DefaultUsageRateCardRequest\n }) => putUsageMeterRateCard(meter, rateCard),\n onSuccess: (_result, { meter }) =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: metersKey }),\n queryClient.invalidateQueries({\n queryKey: keys.usageMeter(meter.key),\n }),\n ]),\n onError: reloadIfMoved(queryClient, metersKey),\n })\n },\n deleteDefaultUsageRateCard: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n const metersKey = keys.usageMeters()\n return mutationOptions({\n mutationKey: [...metersKey, \"rate-card\", \"delete\"],\n mutationFn: (meter: Meter) => putUsageMeterRateCard(meter, null),\n onSuccess: (_result, meter) =>\n Promise.all([\n queryClient.invalidateQueries({ queryKey: metersKey }),\n queryClient.invalidateQueries({\n queryKey: keys.usageMeter(meter.key),\n }),\n ]),\n })\n },\n previewPriceChange: () => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"prices\", \"preview-change\"],\n mutationFn: ({\n productKey,\n priceKey,\n }: {\n productKey: string\n priceKey: string\n }) => previewPriceMigration(productKey, priceKey),\n })\n },\n changePrice: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"prices\", \"change\"],\n mutationFn: async ({\n price,\n migration,\n }: {\n price: CreatePriceParams\n migration?: {\n productKey: string\n priceKey: string\n effectiveAt: string\n }\n }) => {\n const created = await createPrice(price)\n if (migration) {\n await createPriceMigration(\n migration.productKey,\n migration.priceKey,\n created.id,\n migration.effectiveAt\n )\n }\n return created\n },\n // The price can be created before scheduling fails. Always refresh so\n // the UI reflects that partial server-side success, or the key's\n // current revision after a revision_mismatch.\n onSettled: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n })\n },\n cancelPriceMigration: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.catalog(), \"price-migrations\", \"cancel\"],\n mutationFn: (migrationId: string) => cancelPriceMigration(migrationId),\n onSuccess: invalidateTreeOnSuccess(queryClient, keys.catalog()),\n })\n },\n // Merchant-config edits: a refused revision means the form is stale, so\n // reload either way; merchant_config_read_only rereads the capabilities so\n // the console turns read-only.\n updateMerchantConfiguration: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.settings(), \"update\"],\n mutationFn: (update: UpdateMerchantConfigurationParams) =>\n updateMerchantConfiguration(update),\n onSettled: invalidateExactOnSuccess(queryClient, keys.settings()),\n onError: readOnlyNow(queryClient),\n })\n },\n createPSP: (queryClient: QueryClient) => {\n const merchant = selectedMerchant()\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.settings(), \"psps\", \"create\"],\n retry: false,\n gcTime: 0,\n mutationFn: (psp: CreatePSPParams) => {\n if (selectedMerchant() !== merchant)\n throw new Error(\"Merchant changed; reopen this form before saving\")\n return createPSP(psp)\n },\n onSettled: invalidateExactOnSuccess(queryClient, [\n ...keys.settings(),\n \"psps\",\n ]),\n onError: readOnlyNow(queryClient),\n })\n },\n // Rotation, settings and archiving: one PATCH at the revision the caller\n // read. A refused revision reloads the list.\n updatePSP: (queryClient: QueryClient) => {\n const merchant = selectedMerchant()\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.settings(), \"psps\", \"update\"],\n retry: false,\n gcTime: 0,\n mutationFn: ({ id, psp }: { id: string; psp: UpdatePSPParams }) => {\n if (selectedMerchant() !== merchant)\n throw new Error(\"Merchant changed; reopen this form before saving\")\n return updatePSP(id, psp)\n },\n onSettled: invalidateExactOnSuccess(queryClient, [\n ...keys.settings(),\n \"psps\",\n ]),\n onError: readOnlyNow(queryClient),\n })\n },\n setCreditLimit: () => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.settings(), \"customer-controls\", \"credit-limit\"],\n mutationFn: ({\n customerId,\n currency,\n amount,\n }: {\n customerId: string\n currency: string\n amount: string\n }) =>\n updateCustomer(customerId, { credit_limits: [{ currency, amount }] }),\n })\n },\n lookupCustomerControls: () => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.settings(), \"customer-controls\", \"lookup\"],\n mutationFn: async ({\n customerId,\n currency,\n }: {\n customerId: string\n currency: string\n }) => {\n const { settings } = await getCustomer(customerId).catch((err) => {\n if (err instanceof ApiError && err.status === 404)\n throw new Error(\"No customer has this ID\")\n throw err\n })\n const code = currency.toUpperCase()\n return {\n currency: code,\n creditLimit:\n settings.credit_limits.find((l) => l.currency === code)?.amount ??\n \"0\",\n trustLevel:\n settings.trust_levels.find((l) => l.currency === code)\n ?.trust_level ?? \"\",\n }\n },\n })\n },\n // Alert webhooks live in the merchant's configuration, so a change moves\n // its revision too.\n createWebhook: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.alerts(), \"webhooks\", \"create\"],\n mutationFn: (webhook: CreateAlertWebhookParams) =>\n createWebhook(webhook),\n onSuccess: webhooksChanged(queryClient, keys),\n onError: readOnlyNow(queryClient),\n })\n },\n updateWebhook: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.alerts(), \"webhooks\", \"update\"],\n mutationFn: ({\n id,\n webhook,\n }: {\n id: string\n webhook: UpdateAlertWebhookParams\n }) => updateWebhook(id, webhook),\n onSuccess: webhooksChanged(queryClient, keys),\n onError: readOnlyNow(queryClient),\n })\n },\n deleteWebhook: (queryClient: QueryClient) => {\n const keys = merchantQueryKeys()\n return mutationOptions({\n mutationKey: [...keys.alerts(), \"webhooks\", \"delete\"],\n mutationFn: (id: string) => deleteWebhook(id),\n onSuccess: webhooksChanged(queryClient, keys),\n onError: readOnlyNow(queryClient),\n })\n },\n }\n return { adminMutations }\n}\n","import type { AdminClient } from \"./api/client\"\nimport type { AdminAPI } from \"./api\"\nimport {\n mutationOptions,\n queryOptions,\n type QueryClient,\n} from \"@tanstack/react-query\"\n\nimport type { CreditGrantInput } from \"#orck/admin/lib/api/credit-types\"\n\nexport const creditCustomerKey = (merchant: string, customer: string) =>\n [\"merchant\", merchant, \"customers\", customer] as const\nexport function createCreditQueries(client: AdminClient, api: AdminAPI) {\n const { selectedMerchant } = client\n const scopedCustomerKey = (merchant: string, customer: string) =>\n [...client.queryRoot(merchant), \"customers\", customer] as const\n const {\n createCreditGrant,\n listCreditGrants,\n listBalanceTransactions,\n revokeCreditGrant,\n } = api\n\n // An embedded console with no merchant prop has the empty slug; it is still\n // the selected merchant. Only a scope that changed underneath is refused.\n function assertMerchant(merchant: string) {\n if (selectedMerchant() !== merchant)\n throw new Error(\n \"The selected merchant changed. Reload this customer's credits.\"\n )\n }\n\n const creditQueries = {\n grants: (\n merchant: string,\n customer: string,\n currency: string,\n limit: number,\n cursor: string\n ) =>\n queryOptions({\n queryKey: [\n ...scopedCustomerKey(merchant, customer),\n \"credit-grants\",\n currency,\n limit,\n cursor,\n ],\n enabled: Boolean(customer && currency),\n queryFn: ({ signal }) => {\n assertMerchant(merchant)\n return listCreditGrants(customer, currency, limit, cursor, signal)\n },\n }),\n transactions: (\n merchant: string,\n customer: string,\n currency: string,\n limit: number,\n cursor: string\n ) =>\n queryOptions({\n queryKey: [\n ...scopedCustomerKey(merchant, customer),\n \"transactions\",\n currency,\n limit,\n cursor,\n ],\n enabled: Boolean(customer && currency),\n queryFn: ({ signal }) => {\n assertMerchant(merchant)\n return listBalanceTransactions(\n customer,\n currency,\n limit,\n cursor,\n signal\n )\n },\n }),\n }\n\n const creditMutations = {\n grant: (client: QueryClient, merchant: string, customer: string) =>\n mutationOptions({\n mutationFn: (input: CreditGrantInput) => {\n assertMerchant(merchant)\n return createCreditGrant(customer, input)\n },\n onSettled: () =>\n client.invalidateQueries({\n queryKey: scopedCustomerKey(merchant, customer),\n }),\n }),\n revoke: (client: QueryClient, merchant: string, customer: string) =>\n mutationOptions({\n mutationFn: ({ grant, reason }: { grant: string; reason: string }) => {\n assertMerchant(merchant)\n return revokeCreditGrant(grant, reason)\n },\n onSettled: () =>\n client.invalidateQueries({\n queryKey: scopedCustomerKey(merchant, customer),\n }),\n }),\n }\n return { assertMerchant, creditQueries, creditMutations }\n}\n","import type { AdminClient } from \"./api/client\"\nimport type { AdminAPI } from \"./api\"\nimport type { createQueries } from \"./queries\"\nimport {\n keepPreviousData,\n queryOptions,\n mutationOptions,\n type QueryClient,\n} from \"@tanstack/react-query\"\n\nimport type { OrderFilters } from \"./api/order-endpoints\"\n\nimport type { InvoiceProfile } from \"#orck/client/generated/wire\"\nexport function createOrderQueries(\n client: AdminClient,\n api: AdminAPI,\n queries: ReturnType<typeof createQueries>\n) {\n const { queryRoot } = client\n const { queryKeys } = queries\n const orderAPI = api\n const profileAPI = api\n\n const orderKeys = {\n root: () => [...queryRoot(), \"orders\"] as const,\n detail: (id: string) => [...orderKeys.root(), id] as const,\n profile: (customerId: string) =>\n [...queryKeys.customer(customerId), \"invoice-profile\"] as const,\n }\n\n const orderQueries = {\n list: (filters: OrderFilters, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...orderKeys.root(), \"list\", filters, limit, cursor],\n queryFn: ({ signal }) =>\n orderAPI.listOrders(filters, { limit, cursor }, signal),\n placeholderData: keepPreviousData,\n }),\n // The orders of ids in one request, for a page naming what its rows'\n // orders bought.\n byIds: (ids: string[]) =>\n queryOptions({\n queryKey: [...orderKeys.root(), \"ids\", ids],\n queryFn: ({ signal }) =>\n orderAPI.listOrders({ ids: ids.join(\",\") }, {}, signal),\n enabled: ids.length > 0,\n }),\n detail: (id: string) =>\n queryOptions({\n queryKey: orderKeys.detail(id),\n queryFn: ({ signal }) => orderAPI.getOrder(id, signal),\n enabled: !!id,\n }),\n payments: (id: string, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...orderKeys.detail(id), \"payments\", limit, cursor],\n queryFn: ({ signal }) =>\n orderAPI.listOrderPayments(id, { limit, cursor }, signal),\n enabled: !!id,\n placeholderData: keepPreviousData,\n }),\n // The customer's invoice profile: the terms and document fields their\n // next usage orders take.\n profile: (customerId: string) =>\n queryOptions({\n queryKey: orderKeys.profile(customerId),\n queryFn: ({ signal }) =>\n profileAPI.getInvoiceProfile(customerId, signal),\n enabled: !!customerId,\n }),\n }\n\n function usageActionMutation(client: QueryClient, customerId: string) {\n const root = orderKeys.root(),\n customer = queryKeys.customer(customerId)\n return mutationOptions({\n mutationFn: orderAPI.applyUsageAction,\n onSettled: async () => {\n await Promise.all([\n client.invalidateQueries({ queryKey: root }),\n client.invalidateQueries({ queryKey: customer }),\n ])\n },\n })\n }\n\n function invoiceProfileMutation(client: QueryClient, customerId: string) {\n const key = orderKeys.profile(customerId)\n return mutationOptions({\n mutationFn: (profile: InvoiceProfile) =>\n profileAPI.putInvoiceProfile(customerId, profile),\n onSuccess: () => client.invalidateQueries({ queryKey: key }),\n })\n }\n return {\n orderKeys,\n orderQueries,\n usageActionMutation,\n invoiceProfileMutation,\n }\n}\n","import type { AdminClient } from \"./api/client\"\nimport type { AdminAPI } from \"./api\"\nimport {\n keepPreviousData,\n mutationOptions,\n queryOptions,\n type QueryClient,\n} from \"@tanstack/react-query\"\n\nimport { collectCursorPages } from \"#orck/admin/lib/api/client\"\nimport type {\n ParkedFilters,\n ProposalFilters,\n ProviderCatalogFilters,\n PSPImportFilters,\n PSPImportRecordFilters,\n} from \"#orck/admin/lib/api/import-endpoints\"\nimport type {\n CreatePSPImportParams,\n CreateProviderPriceParams,\n LinkPSPImportParams,\n PSPImport,\n PSPImportMapping,\n} from \"#orck/client/generated/wire\"\n\n// An import's job is running: its page polls.\nexport const importBusy = (status?: PSPImport[\"status\"]) =>\n status === \"pulling\" || status === \"applying\"\n\nconst POLL_MS = 2_000\n\nconst keysOf = (root: () => readonly string[]) => ({\n imports: () => [...root(), \"psp-imports\"] as const,\n import: (id: string) => [...root(), \"psp-imports\", id] as const,\n providerCatalog: () => [...root(), \"provider-catalog\"] as const,\n parked: () => [...root(), \"parked\"] as const,\n proposals: () => [...root(), \"proposals\"] as const,\n catalog: () => [...root(), \"catalog\"] as const,\n ops: () => [...root(), \"ops\"] as const,\n})\n\nexport function createImportQueries(client: AdminClient, api: AdminAPI) {\n const { queryRoot } = client\n const importKeys = keysOf(queryRoot)\n // Mutations pin the merchant they started under, as createMutations does.\n const pinnedKeys = () => {\n const root = queryRoot()\n return keysOf(() => root)\n }\n\n const importQueries = {\n list: (filters: PSPImportFilters, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...importKeys.imports(), \"list\", filters, limit, cursor],\n queryFn: ({ signal }) =>\n api.listPSPImports(filters, { limit, cursor }, signal),\n placeholderData: keepPreviousData,\n refetchInterval: (query) =>\n query.state.data?.data.some((i) => importBusy(i.status))\n ? POLL_MS\n : false,\n meta: { errorAction: \"Load PSP imports\" },\n }),\n // The PSP's newest import: whose rules a pull copies.\n latest: (psp: string) =>\n queryOptions({\n queryKey: [...importKeys.imports(), \"latest\", psp],\n queryFn: async ({ signal }) =>\n (await api.listPSPImports({ psp }, { limit: 1 }, signal)).data[0] ??\n null,\n enabled: Boolean(psp),\n }),\n detail: (id: string) =>\n queryOptions({\n queryKey: importKeys.import(id),\n queryFn: ({ signal }) => api.getPSPImport(id, signal),\n enabled: Boolean(id),\n refetchInterval: (query) =>\n importBusy(query.state.data?.status) ? POLL_MS : false,\n meta: { errorAction: \"Load PSP import\" },\n }),\n // version is the import's state: a re-link that finishes reloads them.\n records: (\n id: string,\n filters: PSPImportRecordFilters,\n limit: number,\n cursor?: string,\n version?: string\n ) =>\n queryOptions({\n queryKey: [\n ...importKeys.import(id),\n \"records\",\n filters,\n limit,\n cursor,\n version,\n ],\n queryFn: ({ signal }) =>\n api.listPSPImportRecords(id, filters, { limit, cursor }, signal),\n enabled: Boolean(id && version),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load import records\" },\n }),\n providerCatalog: (\n filters: ProviderCatalogFilters,\n limit: number,\n cursor?: string\n ) =>\n queryOptions({\n queryKey: [...importKeys.providerCatalog(), filters, limit, cursor],\n queryFn: ({ signal }) =>\n api.listProviderCatalog(filters, { limit, cursor }, signal),\n enabled: Boolean(filters.psp),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load provider prices\" },\n }),\n // One observed price by its ref; the route has no ref filter and a PSP\n // has few prices.\n providerPrice: (psp: string, ref: string) =>\n queryOptions({\n queryKey: [...importKeys.providerCatalog(), \"price\", psp, ref],\n queryFn: async ({ signal }) =>\n (\n await collectCursorPages(\n (cursor) =>\n api.listProviderCatalog(\n { psp, kind: \"price\" },\n { limit: 500, cursor },\n signal\n ),\n signal\n )\n ).find((o) => o.ref === ref) ?? null,\n enabled: Boolean(psp && ref),\n meta: { errorAction: \"Load provider price\" },\n }),\n parked: (filters: ParkedFilters, limit: number, cursor?: string) =>\n queryOptions({\n queryKey: [...importKeys.parked(), filters, limit, cursor],\n queryFn: ({ signal }) =>\n api.listParkedSubscriptions(filters, { limit, cursor }, signal),\n placeholderData: keepPreviousData,\n meta: { errorAction: \"Load parked subscriptions\" },\n }),\n // Every listed proposal: the inbox groups and selects across pages.\n proposals: (filters: ProposalFilters) =>\n queryOptions({\n queryKey: [...importKeys.proposals(), filters],\n queryFn: ({ signal }) =>\n collectCursorPages(\n (cursor) =>\n api.listProposals(\n filters,\n filters.ids ? {} : { limit: 500, cursor },\n signal\n ),\n signal\n ),\n meta: { errorAction: \"Load proposals\" },\n }),\n customers: (ids: string[]) =>\n queryOptions({\n queryKey: [...queryRoot(), \"customers\", \"ids\", ids],\n queryFn: ({ signal }) => api.customersByIds(ids, signal),\n enabled: ids.length > 0,\n }),\n }\n\n const importMutations = {\n create: (queryClient: QueryClient) => {\n const keys = pinnedKeys()\n return mutationOptions({\n mutationFn: (params: CreatePSPImportParams) =>\n api.createPSPImport(params),\n onSuccess: () =>\n queryClient.invalidateQueries({ queryKey: keys.imports() }),\n })\n },\n link: (queryClient: QueryClient) => {\n const keys = pinnedKeys()\n return mutationOptions({\n mutationFn: ({\n id,\n params,\n }: {\n id: string\n params: LinkPSPImportParams\n }) => api.linkPSPImport(id, params),\n onSuccess: (_, { id }) =>\n queryClient.invalidateQueries({ queryKey: keys.import(id) }),\n })\n },\n apply: (queryClient: QueryClient) => {\n const keys = pinnedKeys()\n return mutationOptions({\n mutationFn: (id: string) => api.applyPSPImport(id),\n onSuccess: () =>\n queryClient.invalidateQueries({ queryKey: keys.imports() }),\n })\n },\n setMappings: () =>\n mutationOptions({\n mutationFn: (mappings: PSPImportMapping[]) =>\n api.setPSPImportMappings(mappings),\n }),\n // Mapping releases parks and resolves findings on the server.\n mapPrice: (queryClient: QueryClient) => {\n const keys = pinnedKeys()\n return mutationOptions({\n mutationFn: (params: CreateProviderPriceParams) =>\n api.createProviderPrice(params),\n onSuccess: () =>\n Promise.all(\n [\n keys.providerCatalog(),\n keys.parked(),\n keys.imports(),\n keys.catalog(),\n keys.ops(),\n ].map((queryKey) => queryClient.invalidateQueries({ queryKey }))\n ),\n })\n },\n // One approve or dismiss call; the inbox runs a listed set in batches\n // and reloads only when asked, so each row keeps its outcome.\n decide: (queryClient: QueryClient) => {\n const keys = pinnedKeys()\n return mutationOptions({\n mutationFn: ({\n action,\n ids,\n notes,\n key,\n }: {\n action: \"approve\" | \"dismiss\"\n ids: string[]\n notes: string\n key: string\n }) =>\n action === \"approve\"\n ? api.approveProposals(ids, notes, key)\n : api.dismissProposals(ids, notes),\n onSettled: () =>\n Promise.all(\n [keys.imports(), keys.ops()].map((queryKey) =>\n queryClient.invalidateQueries({ queryKey })\n )\n ),\n })\n },\n // dismissPrice ignores an unmapped price's finding: not ours.\n dismissPrice: (queryClient: QueryClient) => {\n const keys = pinnedKeys()\n return mutationOptions({\n mutationFn: ({ finding, notes }: { finding: string; notes: string }) =>\n api.resolveFinding(finding, \"ignore\", notes),\n onSuccess: () =>\n Promise.all(\n [keys.providerCatalog(), keys.ops()].map((queryKey) =>\n queryClient.invalidateQueries({ queryKey })\n )\n ),\n })\n },\n }\n\n return { importKeys, importQueries, importMutations }\n}\n","import { createContext, useContext } from \"react\"\nimport type { BillingAdminMerchant, BillingAdminProps } from \"./types\"\nimport { createAdminClient, type AdminClientOptions } from \"./lib/api/client\"\nimport { createAdminAPI } from \"./lib/api\"\nimport { createAdminToast, createToastHandlers } from \"./lib/toast\"\nimport { createQueries } from \"./lib/queries\"\nimport { createMutations } from \"./lib/mutations\"\nimport { createCreditQueries } from \"./lib/credit-queries\"\nimport { createOrderQueries } from \"./lib/order-queries\"\nimport { createImportQueries } from \"./lib/import-queries\"\n\n/** Every request and cache key is bound to this instance's selected merchant. */\nexport function createAdminServices(options: AdminClientOptions) {\n const client = createAdminClient(options)\n const api = createAdminAPI(client)\n const queries = createQueries(client, api)\n const toast = createAdminToast(options.namespace)\n return {\n toast,\n ...createToastHandlers(toast),\n ...client,\n ...api,\n ...queries,\n ...createMutations(client, api, queries),\n ...createCreditQueries(client, api),\n ...createOrderQueries(client, api, queries),\n ...createImportQueries(client, api),\n }\n}\n\nexport interface AdminContextValue {\n props: BillingAdminProps\n services: ReturnType<typeof createAdminServices>\n merchants: BillingAdminMerchant[]\n activeMerchant?: BillingAdminMerchant\n selectMerchant(slug: string): void\n portal: HTMLElement | null\n}\n\nexport const AdminContext = createContext<AdminContextValue | null>(null)\n\nexport function useAdminContext() {\n const value = useContext(AdminContext)\n if (!value) throw new Error(\"BillingAdmin context is missing\")\n return value\n}\n\nexport const useAdminServices = () => useAdminContext().services\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n type ComponentProps,\n type ReactNode,\n} from \"react\"\nimport type { BillingAdminNavigation } from \"./types\"\n\ntype NavigateOptions = { replace?: boolean; state?: unknown }\ntype Location = { pathname: string; search: string; state: unknown }\ninterface RouterValue {\n location: Location\n href(to: string): string\n navigate(to: string | number, options?: NavigateOptions): void\n params: Record<string, string>\n}\nconst Context = createContext<RouterValue | null>(null)\nconst subscribe = (notify: () => void) => {\n window.addEventListener(\"popstate\", notify)\n return () => window.removeEventListener(\"popstate\", notify)\n}\nconst snapshot = () => window.location.pathname + window.location.search\n\nexport function AdminRouter({\n basePath = \"/\",\n navigation,\n children,\n}: {\n basePath?: string\n navigation?: BillingAdminNavigation\n children: ReactNode\n}) {\n const current = useSyncExternalStore(subscribe, snapshot, () => basePath)\n const base = basePath.replace(/\\/$/, \"\")\n const fallback = new URL(current, \"http://billing.local\")\n const pathname = navigation?.pathname ?? fallback.pathname\n const search = navigation?.search ?? fallback.search\n const relative =\n pathname === base\n ? \"/\"\n : pathname.startsWith(base + \"/\")\n ? pathname.slice(base.length)\n : \"/\"\n const [states, setStates] = useState(() => new Map<string, unknown>())\n const href = useCallback(\n (to: string) => {\n if (/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(to)) return to\n const resolved = new URL(to, \"http://billing.local\" + relative + search)\n return base + resolved.pathname + resolved.search + resolved.hash\n },\n [base, relative, search]\n )\n const navigate = useCallback(\n (to: string | number, options: NavigateOptions = {}) => {\n if (typeof to === \"number\") {\n window.history.go(to)\n return\n }\n const target = href(to)\n if (/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(target)) {\n window.location.assign(target)\n return\n }\n setStates((previous) => new Map(previous).set(target, options.state))\n if (navigation) navigation.navigate(target, { replace: options.replace })\n else {\n window.history[options.replace ? \"replaceState\" : \"pushState\"](\n options.state ?? null,\n \"\",\n target\n )\n window.dispatchEvent(new PopStateEvent(\"popstate\"))\n }\n },\n [href, navigation]\n )\n const value = useMemo<RouterValue>(\n () => ({\n location: {\n pathname: relative,\n search,\n state:\n states.get(pathname + search) ??\n (!navigation ? window.history.state : null),\n },\n href,\n navigate,\n params: {},\n }),\n [relative, pathname, search, href, navigate, navigation, states]\n )\n return <Context.Provider value={value}>{children}</Context.Provider>\n}\n\nfunction useRouter() {\n const router = useContext(Context)\n if (!router) throw new Error(\"BillingAdmin router is missing\")\n return router\n}\nexport const useLocation = () => useRouter().location\nexport const useNavigate = () => useRouter().navigate\nexport const useParams = <T extends string = string>() =>\n useRouter().params as Partial<Record<T, string>>\nexport function useSearchParams() {\n const { location, navigate } = useRouter()\n const params = useMemo(\n () => new URLSearchParams(location.search),\n [location.search]\n )\n const set = (\n value: URLSearchParams | Record<string, string>,\n options?: NavigateOptions\n ) => {\n const query = new URLSearchParams(value).toString()\n navigate(location.pathname + (query ? \"?\" + query : \"\"), options)\n }\n return [params, set] as const\n}\n\nexport function Link({\n to,\n onClick,\n ...props\n}: Omit<ComponentProps<\"a\">, \"href\"> & { to: string }) {\n const { href, navigate } = useRouter()\n return (\n <a\n {...props}\n href={href(to)}\n onClick={(event) => {\n onClick?.(event)\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey ||\n props.target ||\n props.download\n )\n return\n event.preventDefault()\n navigate(to)\n }}\n />\n )\n}\n\nexport function Navigate({ to, replace }: { to: string; replace?: boolean }) {\n const navigate = useNavigate()\n useEffect(() => navigate(to, { replace }), [navigate, to, replace])\n return null\n}\n\nexport function RouteParams({\n params,\n children,\n}: {\n params: Record<string, string>\n children: ReactNode\n}) {\n const router = useRouter()\n return (\n <Context.Provider value={{ ...router, params }}>\n {children}\n </Context.Provider>\n )\n}\n","import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs))\n}\n","// Card-network identity: which marks we ship and how a rail's spelling maps\n// onto them.\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\"\n\nconst BRAND_ALIASES: Record<string, CardBrand> = {\n visa: \"visa\",\n mastercard: \"mastercard\",\n mc: \"mastercard\",\n master: \"mastercard\",\n amex: \"amex\",\n americanexpress: \"amex\",\n \"american express\": \"amex\",\n}\n\n// How people write each brand; a brand not here is shown capitalized.\nconst BRAND_LABELS: Record<string, string> = {\n visa: \"Visa\",\n mastercard: \"Mastercard\",\n amex: \"Amex\",\n discover: \"Discover\",\n jcb: \"JCB\",\n diners: \"Diners Club\",\n unionpay: \"UnionPay\",\n}\n\n// cardBrandLabel is the rail's spelling of a brand (\"VISA\", \"mc\",\n// \"american_express\") as people read it; undefined when there is none.\nexport function cardBrandLabel(brand?: string | null): string | undefined {\n const value = brand?.trim()\n if (!value) return undefined\n const key = value.toLowerCase().replace(/[^a-z]/g, \"\")\n return (\n BRAND_LABELS[resolveCardBrand(value) ?? key] ??\n value[0].toUpperCase() + value.slice(1).toLowerCase()\n )\n}\n\n// Resolves the rail's spelling of a brand (\"Visa\", \"MASTERCARD\", \"amex\") onto\n// the marks we ship; anything unknown falls back to a text plate.\nexport function resolveCardBrand(brand?: string): CardBrand | undefined {\n const key = brand\n ?.trim()\n .toLowerCase()\n .replace(/[^a-z ]/g, \"\")\n return key ? BRAND_ALIASES[key] : undefined\n}\n","// Generated by `go run ./scripts/contracts -write` from the currency registry (billing.Currencies). Do not edit.\n\n// Currency code to native-unit decimals.\nexport const OPENRAILS_CURRENCY_SCALES: Readonly<Record<string, number>> = {\n AED: 6,\n AUD: 6,\n BRL: 6,\n CAD: 6,\n CHF: 6,\n CNY: 6,\n CZK: 6,\n DKK: 6,\n EUR: 6,\n GBP: 6,\n HKD: 6,\n ILS: 6,\n INR: 6,\n JPY: 4,\n KRW: 4,\n MXN: 6,\n MYR: 6,\n NOK: 6,\n NZD: 6,\n PHP: 6,\n PLN: 6,\n PYUSD: 6,\n SAR: 6,\n SEK: 6,\n SGD: 6,\n SOL: 9,\n THB: 6,\n TRY: 6,\n USD: 6,\n USD1: 6,\n USDC: 6,\n USDG: 6,\n USDT: 6,\n ZAR: 6,\n}\n","import type { CardDetails, CustomerContact } from \"#orck/client/generated/wire\"\nimport { cardBrandLabel } from \"#orck/lib/card-brands\"\nimport { OPENRAILS_CURRENCY_SCALES as currencyUnits } from \"#orck/client/generated/currencies\"\n\n// Money is an integer count of native units. A JSON number is exact only as a\n// safe integer; exact int64 amounts arrive as decimal strings.\nexport type MoneyAmount = number | string\n\nconst INT64_MIN = -(1n << 63n)\nconst INT64_MAX = (1n << 63n) - 1n\n\n// Intl.NumberFormat formats a decimal string exactly only since ECMA-402 2023\n// (Chrome/Edge 106, Firefox 116, Safari 15.4); older engines coerce it through\n// Number. Probed once with 2^53 + 1, which a Number cannot hold.\nexport const intlFormatsDecimalStringsExactly: boolean = (() => {\n try {\n return (\n new Intl.NumberFormat(\"en\", { useGrouping: false }).format(\n \"9007199254740993\" as `${number}`\n ) === \"9007199254740993\"\n )\n } catch {\n return false\n }\n})()\n\n// Below 10^15 native units a Number-coerced decimal still rounds back to the\n// exact digits at every registry scale; from 10^15 the coerced value can differ\n// in the last digit, so a legacy engine refuses instead of misformatting.\nconst LEGACY_EXACT_UNITS = 10n ** 15n\n\n// currencyScale is the engine registry's native decimals (generated from\n// billing.Currencies).\nexport function currencyScale(currency: string): number | undefined {\n const code = currency.trim().toUpperCase()\n return Object.hasOwn(currencyUnits, code)\n ? currencyUnits[code as keyof typeof currencyUnits]\n : undefined\n}\n\nexport const supportedCurrencies = Object.keys(currencyUnits)\n\nfunction validDecimals(decimals: number): boolean {\n return Number.isInteger(decimals) && decimals >= 0 && decimals <= 18\n}\n\nfunction exactUnits(amount: MoneyAmount): bigint | null {\n if (typeof amount === \"number\")\n return Number.isSafeInteger(amount) ? BigInt(amount) : null\n if (!/^-?\\d{1,19}$/.test(amount)) return null\n const value = BigInt(amount)\n return value < INT64_MIN || value > INT64_MAX ? null : value\n}\n\n// unitsToDecimal renders native units as an exact major-unit decimal, or null\n// when the amount is not an exact int64.\nexport function unitsToDecimal(\n amount: MoneyAmount,\n decimals: number\n): string | null {\n const value = exactUnits(amount)\n if (value === null || !validDecimals(decimals)) return null\n return decimalFromUnits(value, decimals)\n}\n\nfunction decimalFromUnits(value: bigint, decimals: number): string {\n const absolute = value < 0n ? -value : value\n const scale = 10n ** BigInt(decimals)\n const fraction = (absolute % scale)\n .toString()\n .padStart(decimals, \"0\")\n .replace(/0+$/, \"\")\n return `${value < 0n ? \"-\" : \"\"}${absolute / scale}${fraction ? `.${fraction}` : \"\"}`\n}\n\n// formatUnits formats native units at an explicit scale without passing\n// through a JS number; an engine without exact decimal-string Intl refuses\n// the amounts it cannot hold.\nexport function formatUnits(\n amount: MoneyAmount,\n currency: string,\n decimals: number,\n // digits rounds the display to fewer decimals than the units carry.\n digits = decimals\n): string {\n const units = exactUnits(amount)\n if (units === null || !validDecimals(decimals))\n return `${currency} amount exceeds the exact display range`\n if (\n !intlFormatsDecimalStringsExactly &&\n (units >= LEGACY_EXACT_UNITS || units <= -LEGACY_EXACT_UNITS)\n )\n return `${currency} amount exceeds this browser's exact display range`\n const decimal = decimalFromUnits(units, decimals) as `${number}`\n const code = currency.trim().toUpperCase()\n if (/^[A-Z]{3}$/.test(code))\n return new Intl.NumberFormat(undefined, {\n style: \"currency\",\n currency: code,\n maximumFractionDigits: digits,\n }).format(decimal)\n const number = new Intl.NumberFormat(undefined, {\n maximumFractionDigits: digits,\n }).format(decimal)\n return `${number} ${currency}`\n}\n\n// MerchantUnits are the merchant's own units by code: each one's scale and\n// name.\nexport type MerchantUnits = Record<string, { scale: number; name: string }>\n\n// merchantUnits are the units a merchant declares, by code.\nexport function merchantUnits(\n currencies: { code: string; scale: number; name: string }[] | undefined\n): MerchantUnits {\n return Object.fromEntries(\n (currencies ?? []).map((u) => [\n u.code.toUpperCase(),\n { scale: u.scale, name: u.name || u.code },\n ])\n )\n}\n\n// formatSummaryAmount is money in a chart or tile: one of the merchant's\n// units at its scale with its name, a fiat amount to its minor unit\n// (cents), any other to four decimals. Exact amounts are formatNativeAmount's.\nexport function formatSummaryAmount(\n amount: MoneyAmount,\n currency: string,\n units: MerchantUnits = {}\n): string {\n const unit = units[currency.trim().toUpperCase()]\n if (unit) {\n const value = exactUnits(amount)\n if (value === null || !validDecimals(unit.scale))\n return `${currency} amount exceeds the exact display range`\n const number = new Intl.NumberFormat(undefined, {\n minimumFractionDigits: unit.scale,\n maximumFractionDigits: unit.scale,\n }).format(decimalFromUnits(value, unit.scale) as `${number}`)\n return `${number} ${unit.name}`\n }\n const scale = currencyScale(currency)\n if (scale === undefined) return formatNativeAmount(amount, currency)\n const code = currency.trim().toUpperCase()\n const digits = Intl.supportedValuesOf(\"currency\").includes(code)\n ? new Intl.NumberFormat(undefined, {\n style: \"currency\",\n currency: code,\n }).resolvedOptions().maximumFractionDigits!\n : 4\n return formatUnits(amount, currency, scale, Math.min(digits, scale))\n}\n\n// formatNativeAmount formats an amount at its currency's registered scale.\nexport function formatNativeAmount(\n amount: MoneyAmount,\n currency: string\n): string {\n const scale = currencyScale(currency)\n return scale === undefined\n ? `Amount in unregistered currency ${currency || \"(none)\"}`\n : formatUnits(amount, currency, scale)\n}\n\n// UnitScales are the merchant's own units' scales, by code.\nexport type UnitScales = Record<string, number>\n\n// unitScales are the units a customer's balances name.\nexport function unitScales(\n balances: { currency: string; unit: { scale: number } | null }[]\n): UnitScales {\n return Object.fromEntries(\n balances.flatMap((b) =>\n b.unit ? [[b.currency.toUpperCase(), b.unit.scale]] : []\n )\n )\n}\n\n// declaredUnits are the scales of the units a merchant declares.\nexport function declaredUnits(\n currencies: { code: string; scale: number }[] | undefined\n): UnitScales {\n return Object.fromEntries(\n (currencies ?? []).map((u) => [u.code.toUpperCase(), u.scale])\n )\n}\n\n// formatScaledAmount formats an amount at its currency's scale: one of the\n// merchant's units in units, else the registry's.\nexport function formatScaledAmount(\n amount: MoneyAmount,\n currency: string,\n units: UnitScales\n): string {\n const scale = units[currency.trim().toUpperCase()]\n return scale === undefined\n ? formatNativeAmount(amount, currency)\n : formatUnits(amount, currency, scale)\n}\n\n// formatBalanceAmount formats one of a balance's amounts: at its unit's scale\n// when it counts one of the merchant's own units.\nexport function formatBalanceAmount(\n amount: MoneyAmount,\n balance: { currency: string; unit: { scale: number } | null }\n): string {\n return balance.unit\n ? formatUnits(amount, balance.currency, balance.unit.scale)\n : formatNativeAmount(amount, balance.currency)\n}\n\n// Canonical monetary wire input: an exact signed int64 decimal string.\nexport function amountFromInput(\n major: string,\n decimals: number\n): string | null {\n if (!validDecimals(decimals)) return null\n const match = /^([+-]?)(\\d*)(?:\\.(\\d*))?$/.exec(major.trim())\n if (!match || (!match[2] && !match[3]) || (match[3]?.length ?? 0) > decimals)\n return null\n const value =\n BigInt(match[2] || \"0\") * 10n ** BigInt(decimals) +\n BigInt((match[3] || \"\").padEnd(decimals, \"0\") || \"0\")\n const signed = match[1] === \"-\" ? -value : value\n if (signed < INT64_MIN || signed > INT64_MAX) return null\n return signed.toString()\n}\n\n// nativeAmountFromInput converts a major-unit input to exact native units at\n// the currency's registered scale, as the int64 decimal string money wires use.\nexport function nativeAmountFromInput(\n major: string,\n currency: string\n): string | null {\n const scale = currencyScale(currency)\n return scale === undefined ? null : amountFromInput(major, scale)\n}\n\n// nativeAmountToInput prefills an editable major-unit amount. A JSON number\n// beyond the safe-integer range has already lost digits, so it is refused\n// before any BigInt or string conversion and the field starts empty: an empty\n// input never passes nativeAmountFromInput, so a rounded value is never saved.\nexport function nativeAmountToInput(\n amount: MoneyAmount | undefined,\n currency: string\n): string {\n const scale = currencyScale(currency)\n if (amount === undefined || scale === undefined) return \"\"\n if (typeof amount === \"number\" && !Number.isSafeInteger(amount)) return \"\"\n return unitsToDecimal(amount, scale) ?? \"\"\n}\n\nexport function formatDate(iso?: string | null): string {\n if (!iso) return \"—\"\n const d = new Date(iso)\n if (Number.isNaN(d.getTime())) return \"—\"\n return d.toLocaleString(undefined, {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n })\n}\n\n// formatCard names a card by brand and last four digits.\nexport function formatCard(card?: CardDetails | null): string {\n return card?.last4\n ? `${cardBrandLabel(card.brand) ?? \"Card\"} ••••${card.last4}`\n : \"—\"\n}\n\nexport function formatCardExpiry(card?: CardDetails | null): string {\n return `${card?.exp_month ?? \"??\"}/${card?.exp_year ?? \"????\"}`\n}\n\nexport function shortId(id: string, n = 8): string {\n return id.length > n ? `${id.slice(0, n)}…` : id\n}\n\n// customerName names a customer by its directory contact, else its id.\nexport function customerName(c: {\n id: string\n contact: { email: string | null; name: string | null } | null\n}): string {\n return c.contact?.name || c.contact?.email || shortId(c.id, 13)\n}\n\n// rowCustomer names a list row's customer by its directory contact, else its\n// id.\nexport function rowCustomer(row: {\n customer_id: string\n customer_contact?: CustomerContact\n}): string {\n return customerName({\n id: row.customer_id,\n contact: row.customer_contact ?? null,\n })\n}\n\n// timeAgo renders a compact relative time (\"3m\", \"2h\", \"5d\") for feeds like the\n// notification bell; falls back to a short date past a week.\nexport function timeAgo(iso?: string | null): string {\n if (!iso) return \"\"\n const then = new Date(iso).getTime()\n if (Number.isNaN(then)) return \"\"\n const secs = Math.round((Date.now() - then) / 1000)\n if (secs < 45) return \"just now\"\n if (secs < 90) return \"1m\"\n const mins = Math.round(secs / 60)\n if (mins < 60) return `${mins}m`\n const hours = Math.round(mins / 60)\n if (hours < 24) return `${hours}h`\n const days = Math.round(hours / 24)\n if (days < 7) return `${days}d`\n return new Date(then).toLocaleDateString(undefined, {\n month: \"short\",\n day: \"numeric\",\n })\n}\n"],"mappings":";;;;;;;AAEA,IAAaE,IAAiBC,EAG3B,EAAE,WAAW,GAAG,CAAC;AAEpB,SAAgBC,IAA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QAAQ;EACR,YAAY;EACZ,iBAAiB;EACjB,YAAY;EACZ,iBAAiB;CACnB;CACA,QAAQ;EACN,YAAY;EACZ,sBACE;EACF,OAAO;EACP,aACE;EACF,mBACE;EACF,cAAc;EACd,SAAS;CACX;CACA,YAAY;EACV,OAAO;EACP,aAAa;EACb,MAAM;EACN,SAAS;EACT,SAAS;EACT,YAAY;EACZ,MAAM;CACR;CACA,YAAY;EACV,OAAO;EACP,aACE;EACF,MAAM;EACN,WAAW;EACX,mBAAmB;EACnB,aAAa;EACb,SAAS;EACT,SAAS;EACT,YAAY;EACZ,MAAM;EACN,WAAW;EACX,YACE;EACF,gBAAgB;CAClB;CACA,SAAS;EACP,OAAO;EACP,aACE;EACF,QAAQ;CACV;CACA,QAAQ;EACN,OAAO;EACP,aAAa;EACb,eACE;EACF,mBACE;EACF,aAAa;EACb,mBAAmB;EACnB,YAAY;EACZ,gBAAgB;EAChB,MAAM;EACN,SAAS;EACT,eAAe;EACf,SAAS;EACT,WAAW;EACX,SAAS;EACT,YAAY;EACZ,MAAM;CACR;CACA,gBAAgB;EACd,OAAO;EACP,aAAa;EACb,OAAO;EACP,kBAAkB;EAClB,KAAK;EACL,UAAU;EACV,gBACE;EACF,MAAM;EACN,OAAO;EACP,UAAU;EACV,YACE;EACF,aAAa;EACb,gBAAgB;EAChB,qBACE;EACF,WAAW;EACX,eAAe;EACf,SAAS;EACT,QAAQ;EACR,YAAY;EACZ,aAAa;EACb,gBAAgB;EAChB,QAAQ;EACR,aAAa;EACb,aAAa;EACb,mBACE;EACF,eAAe;EACf,SAAS;EACT,cAAc;EACd,OACE;CACJ;CACA,UAAU,EACR,QAAQ,kBACV;CACA,SAAS;EACP,OAAO;EACP,aAAa;EACb,OAAO;EACP,kBAAkB;EAClB,MAAM;EACN,MAAM;EACN,cAAc;EACd,UAAU;EACV,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,gBAAgB;EAChB,MAAM;EACN,MAAM;GACJ,MAAM;G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