@aglyn/plugins-commerce 1.26.5 → 1.27.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.
@@ -15,17 +15,58 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { booleanField as bool, integerField as int, nullableField as nullable, objectKindField as OBJECT_FIELD, openObjectField as objectOf, postalAddressField as ADDRESS, queryParam as q, RECORD_STAMPS as STAMPS, stringField as str, stringListField as strList, SITE_ID_PATH_PARAM } from "@aglyn/tenant-data-admin/server/api-v1-description";
18
- /**
18
+ import { SCREEN_SEO_TEXT_GUIDANCE } from "@aglyn/aglyn/app-utils/screen-seo-fields";
19
+ import { COMMERCE_MAX_OPTION_VALUES, COMMERCE_MAX_OPTIONS, COMMERCE_MAX_VARIANTS, COMMERCE_SLUG_MAX_LENGTH } from "../../model/commerce.js";
20
+ import { PRODUCT_NAME_MAX_LENGTH } from "../../model/product-write.js";
21
+ /*
19
22
  * A site's products and orders as the customer API's OpenAPI document
20
- * describes them — what the console's builder turns into paths, tags and
21
- * schemas, and the MCP tools derive from. Transcribed unchanged from the
22
- * builder's own list when the resources moved here (AGL-3080);
23
- * `api-v1-openapi.spec.ts` holds the document to every endpoint the
24
- * documentation promises.
23
+ * describes them. Transcribed unchanged from the builder's own list when the
24
+ * resources moved here (AGL-3080).
25
+ */ const PRODUCT_ID_PATH_PARAM = {
26
+ name: 'productId',
27
+ description: 'Required. The product’s id — the `id` of a product from `listProducts`.'
28
+ };
29
+ const VARIANT_ID_PATH_PARAM = {
30
+ name: 'variantId',
31
+ description: 'Required. The variant’s id — the `id` of one of the product’s `variants`, from `getProduct`.'
32
+ };
33
+ const SEO_TITLE_MAX = SCREEN_SEO_TEXT_GUIDANCE.title;
34
+ const SEO_DESCRIPTION_MAX = SCREEN_SEO_TEXT_GUIDANCE.description;
35
+ /** One variant's writable fields, shared by the variant write and each entry of a product write's `variants`. */ const VARIANT_WRITE_FIELDS = {
36
+ priceUsd: nullable({
37
+ type: 'number',
38
+ minimum: 0,
39
+ description: 'Price in US dollars. `null` leaves the variant unpriced: the store shows “Price coming soon” and does not sell it. A product created without a price is unpriced.'
40
+ }),
41
+ compareAtPriceUsd: nullable({
42
+ type: 'number',
43
+ minimum: 0,
44
+ description: 'The strike-through price, in US dollars; it must be higher than `priceUsd`. `null` removes it.'
45
+ }),
46
+ sku: nullable(str('Stock-keeping code, unique within the product. `null` or an empty string removes it.')),
47
+ barcode: nullable(str('Barcode, such as a UPC or EAN. `null` or an empty string removes it.')),
48
+ weightGrams: nullable({
49
+ type: 'number',
50
+ minimum: 0,
51
+ description: 'Shipping weight in grams. `null` removes it.'
52
+ }),
53
+ inventory: nullable({
54
+ type: 'integer',
55
+ minimum: 0,
56
+ description: 'Stock on hand. `0` is sold out; `null` means stock is not tracked and the variant never sells out. A digital or service subscription takes only `null`.'
57
+ })
58
+ };
59
+ /**
60
+ * A site's products, as the customer API's OpenAPI document describes them —
61
+ * what the console's builder turns into paths, tags and schemas, and the MCP
62
+ * tools derive from. The writes (AGL-4235) are the console editor's: the
63
+ * members `handleProducts` accepts are exactly `writable` and the
64
+ * `ProductVariantWrite` schema, and `api-v1-openapi.spec.ts` holds the
65
+ * document to every endpoint the documentation promises.
25
66
  */ export const PRODUCTS_API_V1_DESCRIPTION = {
26
67
  tag: 'Products',
27
68
  docsPage: 'products',
28
- description: 'A site’s catalog. Read-only over the API.',
69
+ description: 'A site’s catalog: its products, their options and variants, prices and stock.',
29
70
  schemaName: 'Product',
30
71
  required: [
31
72
  'id',
@@ -38,11 +79,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
38
79
  name: str('Product name.'),
39
80
  slug: str('URL slug.'),
40
81
  description: nullable(str('Description.')),
41
- type: str('Product type.'),
42
- status: str('Publication status.'),
82
+ type: str('Product type: `physical`, `digital` or `service`.'),
83
+ status: str('Publication status: `draft`, `active` or `archived`. Only an active product is shown in the store.'),
43
84
  tags: strList('Free-form tags.'),
44
85
  categoryIds: strList('Categories this product belongs to.'),
45
- mediaUrls: strList('Image URLs.'),
86
+ mediaUrls: strList('Image URLs. The first is the product’s main image.'),
46
87
  options: {
47
88
  type: 'array',
48
89
  description: 'Option definitions, e.g. size.',
@@ -60,8 +101,93 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
60
101
  }
61
102
  },
62
103
  inventory: nullable(int('Stock on hand, when tracked.')),
104
+ seo: objectOf('The product page’s search listing: `title` and `description`, each `null` where the page uses the product’s own name and description.'),
63
105
  subscription: nullable(objectOf('Subscription terms, when the product is one.'))
64
106
  }, STAMPS),
107
+ writable: [
108
+ 'name',
109
+ 'description',
110
+ 'status',
111
+ 'type',
112
+ 'slug',
113
+ 'tags',
114
+ 'categoryIds',
115
+ 'mediaUrls',
116
+ 'options',
117
+ 'variants',
118
+ 'seo'
119
+ ],
120
+ writeOnly: {
121
+ name: str(`Product name, at most ${PRODUCT_NAME_MAX_LENGTH} characters.`),
122
+ description: nullable(str('Description. `null` clears it.')),
123
+ status: {
124
+ type: 'string',
125
+ enum: [
126
+ 'draft',
127
+ 'active',
128
+ 'archived'
129
+ ],
130
+ description: 'Publication status. A new product is a `draft`, not shown in the store, unless this says `active`. `archived` takes it out of the store.'
131
+ },
132
+ type: {
133
+ type: 'string',
134
+ enum: [
135
+ 'physical',
136
+ 'service'
137
+ ],
138
+ description: 'Product type. Defaults to `physical`. A digital product delivers files uploaded in the console, so it is created there.'
139
+ },
140
+ slug: str(`URL slug: lowercase letters, numbers and dashes, at most ${COMMERCE_SLUG_MAX_LENGTH} characters. Made from the name when a new product has none. A slug another product of the site uses is refused.`),
141
+ tags: strList('Free-form tags. Replaces the product’s tags.'),
142
+ categoryIds: strList('Ids of the site’s product categories. Replaces the product’s categories.'),
143
+ mediaUrls: strList('Image URLs, the first the main image. Replaces the product’s images.'),
144
+ options: {
145
+ type: 'array',
146
+ description: `Up to ${COMMERCE_MAX_OPTIONS} options, such as size and color. Replaces the product’s options, and its variants become every combination of their values: a combination the product already sells keeps its variant, price and stock, and a new one starts at the first variant’s price and stock. A product holds at most ${COMMERCE_MAX_VARIANTS} variants.`,
147
+ items: {
148
+ type: 'object',
149
+ required: [
150
+ 'name',
151
+ 'values'
152
+ ],
153
+ additionalProperties: false,
154
+ properties: {
155
+ name: str('The option’s name, such as `Size`. Unique within the product.'),
156
+ values: strList(`The option’s values, such as \`S\`, \`M\`, \`L\`; at most ${COMMERCE_MAX_OPTION_VALUES}.`)
157
+ }
158
+ }
159
+ },
160
+ variants: {
161
+ type: 'array',
162
+ description: 'Changes to the product’s variants, applied after `options`. Each entry names one variant by its `id`, or by its `options`, and sets the fields it carries. Variants are not added or removed here; they follow the options.',
163
+ items: {
164
+ type: 'object',
165
+ additionalProperties: false,
166
+ properties: _extends({
167
+ id: str('The variant’s id, from the product’s `variants`.'),
168
+ options: objectOf('The variant’s option values by option name, such as `{ "Size": "M" }`; names the variant when `id` is not sent.')
169
+ }, VARIANT_WRITE_FIELDS)
170
+ }
171
+ },
172
+ seo: {
173
+ type: 'object',
174
+ additionalProperties: false,
175
+ description: 'The product page’s search listing. A member left out stays as it is.',
176
+ properties: {
177
+ title: nullable(str(`The page title search engines show, at most ${SEO_TITLE_MAX} characters. \`null\` uses the product’s name.`)),
178
+ description: nullable(str(`The summary search engines show, at most ${SEO_DESCRIPTION_MAX} characters. \`null\` uses the product’s description.`))
179
+ }
180
+ }
181
+ },
182
+ writeNote: 'A create needs a `name`. A `PATCH` changes only the members it carries.',
183
+ components: {
184
+ ProductVariantWrite: {
185
+ type: 'object',
186
+ description: 'Writable fields of one product variant. A member left out stays as it is. Any other member is a `400` that names it, never silently ignored.',
187
+ properties: VARIANT_WRITE_FIELDS,
188
+ additionalProperties: false
189
+ }
190
+ },
65
191
  ops: [
66
192
  {
67
193
  path: '/v1/sites/{siteId}/products',
@@ -70,7 +196,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
70
196
  summary: 'List a site’s products',
71
197
  list: true,
72
198
  returns: 'Product',
73
- description: 'Lists the products in one site’s store, with prices, stock and variants. Needs `siteId` from List sites. Read only: products are edited in the console.',
199
+ description: 'Lists the products in one site’s store, with prices, stock and variants. Needs `siteId` from List sites.',
74
200
  pathParams: [
75
201
  SITE_ID_PATH_PARAM
76
202
  ]
@@ -84,11 +210,71 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
84
210
  returns: 'Product',
85
211
  pathParams: [
86
212
  SITE_ID_PATH_PARAM,
87
- {
88
- name: 'productId',
89
- description: 'Product id.'
90
- }
213
+ PRODUCT_ID_PATH_PARAM
91
214
  ]
215
+ },
216
+ // openWorld: an active product is on sale in the site’s public store.
217
+ {
218
+ path: '/v1/sites/{siteId}/products',
219
+ method: 'post',
220
+ operationId: 'createProduct',
221
+ summary: 'Create a product',
222
+ accepts: 'ProductWrite',
223
+ returns: 'Product',
224
+ creates: true,
225
+ bodyRequires: [
226
+ 'name'
227
+ ],
228
+ description: 'Adds a product to one site’s store. It is a draft, not shown in the store, unless `status` is `active`. Needs `siteId` from List sites and a `name`. Options make its variants; prices and stock are set on them. Returns the new product.',
229
+ pathParams: [
230
+ SITE_ID_PATH_PARAM
231
+ ],
232
+ openWorld: true
233
+ },
234
+ // openWorld: a change to a product on sale changes what the public store shows.
235
+ {
236
+ path: '/v1/sites/{siteId}/products/{productId}',
237
+ method: 'patch',
238
+ operationId: 'updateProduct',
239
+ summary: 'Update a product',
240
+ accepts: 'ProductWrite',
241
+ returns: 'Product',
242
+ description: 'Changes a product’s details, options, variants, prices or stock; fields not sent stay as they are. A product on sale shows the change in the store at once. Needs `siteId` from List sites and `productId` from List a site’s products. Returns the product.',
243
+ pathParams: [
244
+ SITE_ID_PATH_PARAM,
245
+ PRODUCT_ID_PATH_PARAM
246
+ ],
247
+ openWorld: true
248
+ },
249
+ // openWorld: a deleted product leaves the public store.
250
+ {
251
+ path: '/v1/sites/{siteId}/products/{productId}',
252
+ method: 'delete',
253
+ operationId: 'deleteProduct',
254
+ summary: 'Delete a product',
255
+ returns: 'Deleted',
256
+ description: 'Deletes a product: it leaves the store at once and can no longer be bought. Needs `siteId` from List sites and `productId` from List a site’s products.',
257
+ pathParams: [
258
+ SITE_ID_PATH_PARAM,
259
+ PRODUCT_ID_PATH_PARAM
260
+ ],
261
+ openWorld: true
262
+ },
263
+ // openWorld: a variant’s price and stock are what the public store sells it at.
264
+ {
265
+ path: '/v1/sites/{siteId}/products/{productId}/variants/{variantId}',
266
+ method: 'patch',
267
+ operationId: 'updateProductVariant',
268
+ summary: 'Update a product variant',
269
+ accepts: 'ProductVariantWrite',
270
+ returns: 'Product',
271
+ description: 'Changes one variant’s price, compare-at price, SKU, barcode, weight or stock; fields not sent stay as they are. A product on sale shows the change in the store at once. Needs `siteId` from List sites, `productId` from List a site’s products and `variantId` from the product’s variants. Returns the product.',
272
+ pathParams: [
273
+ SITE_ID_PATH_PARAM,
274
+ PRODUCT_ID_PATH_PARAM,
275
+ VARIANT_ID_PATH_PARAM
276
+ ],
277
+ openWorld: true
92
278
  }
93
279
  ]
94
280
  };
@@ -173,7 +359,8 @@ export const ORDERS_API_V1_DESCRIPTION = {
173
359
  refundedCents: int('Amount refunded so far.'),
174
360
  livemode: bool('Whether real money moved: `false` for an order paid in Stripe test mode, such as a store rehearsal.'),
175
361
  disputed: bool('Whether a chargeback is open.'),
176
- taxMode: nullable(str('The tax regime: `stripe-automatic` (Stripe Tax, collected and remitted by the platform as marketplace facilitator), `manual` (your own rate) or `none`. `null` on an order from before it was recorded.')),
362
+ taxMode: nullable(str('The tax regime: `stripe-automatic` (Stripe Tax), `manual` (your own rate) or `none`. `stripe-automatic` tax on a sale whose `chargeModel` is `direct` was calculated on your own Stripe account and is yours to remit; on any other sale the platform collects and remits it as marketplace facilitator. `null` on an order from before it was recorded.')),
363
+ chargeModel: nullable(str('Where the sale was charged: `direct` on your own Stripe account, so the money, Stripe’s fees and any Stripe Tax on it are yours. `null` when it was charged through the platform’s account, or on an order from before it was recorded.')),
177
364
  taxEngine: nullable(objectOf('The tax service you connected, when one was asked for this sale’s tax: `provider` (`avalara` or `taxjar`), `providerLabel`, `status` (`quoted` when its tax was charged, `fallback` when it did not answer and your own rate was charged), `reason` (`timeout` or `error` on a fallback) and `sandbox`. `null` when no service was asked.')),
178
365
  shippingAddress: ADDRESS(),
179
366
  couponCode: nullable(str('Coupon applied.')),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/openapi.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type ApiV1ResourceDescription,\n booleanField as bool,\n integerField as int,\n nullableField as nullable,\n objectKindField as OBJECT_FIELD,\n openObjectField as objectOf,\n postalAddressField as ADDRESS,\n queryParam as q,\n RECORD_STAMPS as STAMPS,\n stringField as str,\n stringListField as strList,\n SITE_ID_PATH_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * A site's products and orders as the customer API's OpenAPI document\n * describes them — what the console's builder turns into paths, tags and\n * schemas, and the MCP tools derive from. Transcribed unchanged from the\n * builder's own list when the resources moved here (AGL-3080);\n * `api-v1-openapi.spec.ts` holds the document to every endpoint the\n * documentation promises.\n */\nexport const PRODUCTS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Products',\n docsPage: 'products',\n description: 'A site’s catalog. Read-only over the API.',\n schemaName: 'Product',\n required: ['id', 'object', 'name'],\n fields: {\n id: str('Product id.'),\n object: OBJECT_FIELD('product'),\n name: str('Product name.'),\n slug: str('URL slug.'),\n description: nullable(str('Description.')),\n type: str('Product type.'),\n status: str('Publication status.'),\n tags: strList('Free-form tags.'),\n categoryIds: strList('Categories this product belongs to.'),\n mediaUrls: strList('Image URLs.'),\n options: { type: 'array', description: 'Option definitions, e.g. size.', items: { type: 'object', additionalProperties: true } },\n variants: { type: 'array', description: 'Purchasable variants.', items: { type: 'object', additionalProperties: true } },\n inventory: nullable(int('Stock on hand, when tracked.')),\n subscription: nullable(objectOf('Subscription terms, when the product is one.')),\n ...STAMPS,\n },\n ops: [\n { path: '/v1/sites/{siteId}/products', method: 'get', operationId: 'listProducts', summary: 'List a site’s products', list: true, returns: 'Product', description: 'Lists the products in one site’s store, with prices, stock and variants. Needs `siteId` from List sites. Read only: products are edited in the console.', pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/products/{productId}', method: 'get', operationId: 'getProduct', summary: 'Get a product', description: 'Returns one product with its variants. Needs `siteId` from List sites and `productId` from List a site’s products.', returns: 'Product', pathParams: [SITE_ID_PATH_PARAM, { name: 'productId', description: 'Product id.' }] },\n ],\n}\n\nexport const ORDERS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Orders',\n docsPage: 'orders',\n description: 'A site’s orders. Status moves are constrained.',\n schemaName: 'Order',\n required: ['id', 'object', 'number', 'status'],\n writable: ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify'],\n writeOnly: {\n status: { type: 'string', enum: ['fulfilled', 'delivered'], description: 'The status to move the order to.' },\n carrier: str('Free text, e.g. `UPS`. Trimmed to 40 characters. USPS, UPS, FedEx, DHL, Canada Post, Royal Mail and Australia Post get a tracking link.'),\n trackingNumber: str('Free text. Trimmed to 60 characters.'),\n trackingUrl: str('An https tracking link, for a carrier the link is not derived for.'),\n lineItems: {\n type: 'array',\n description:\n 'With `status: fulfilled`, the units this shipment covers: `[{ lineItemId, quantity }]`, where `lineItemId` is the line’s index. Omitted, the shipment covers everything still to ship. More than is left is `409 conflict` (`code: \"over_fulfilled\"`). Send an `Idempotency-Key` header so a retried partial shipment is recorded once.',\n items: { type: 'object', additionalProperties: true },\n },\n notify: bool('Whether the buyer is told about this shipment. Defaults to true.'),\n },\n writeRequired: ['status'],\n fields: {\n id: str('Order id.'),\n object: OBJECT_FIELD('order'),\n number: int('Human-facing order number.'),\n status: str('Order status.'),\n channel: str('`online` by default. Older orders carry no stored value, so `?channel=online` drops them after the read.'),\n currency: str('ISO 4217 code.'),\n customerEmail: nullable(str('Customer email.')),\n customerName: nullable(str('Customer name.')),\n lineItems: { type: 'array', description: 'What was bought.', items: { type: 'object', additionalProperties: true } },\n totals: objectOf('Money totals, in the smallest unit of `currency`. `extrasCents` is the optional lines the buyer added at checkout, inside `totalCents` and outside `itemsCents`.'),\n extras: { type: 'array', description: 'Optional lines the buyer added at checkout, such as package protection: `[{ id, pluginId, key, label, amountCents, quoteRef }]`. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n credits: { type: 'array', description: 'Store credit another plugin kept that paid part of the sale, such as rewards: `[{ providerId, pluginId, reference, label, last4, amountCents, appliedAs }]`. `appliedAs` is `discount` for a checkout redemption and `tender` for a register payment. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n refundedCents: int('Amount refunded so far.'),\n livemode: bool('Whether real money moved: `false` for an order paid in Stripe test mode, such as a store rehearsal.'),\n disputed: bool('Whether a chargeback is open.'),\n taxMode: nullable(str('The tax regime: `stripe-automatic` (Stripe Tax, collected and remitted by the platform as marketplace facilitator), `manual` (your own rate) or `none`. `null` on an order from before it was recorded.')),\n taxEngine: nullable(objectOf('The tax service you connected, when one was asked for this sale’s tax: `provider` (`avalara` or `taxjar`), `providerLabel`, `status` (`quoted` when its tax was charged, `fallback` when it did not answer and your own rate was charged), `reason` (`timeout` or `error` on a fallback) and `sandbox`. `null` when no service was asked.')),\n shippingAddress: ADDRESS(),\n couponCode: nullable(str('Coupon applied.')),\n fulfillments: { type: 'array', description: 'Shipments and deliveries.', items: { type: 'object', additionalProperties: true } },\n created: STAMPS.created,\n },\n ops: [\n { path: '/v1/sites/{siteId}/orders', method: 'get', operationId: 'listOrders', summary: 'List a site’s orders', description: 'Lists the orders placed in one site’s store, with status, items, totals and shipments. Needs `siteId` from List sites. Filter by status or channel.', list: true, returns: 'Order', filters: [q('channel', 'Orders from one sales channel, such as `online`.'), q('status', 'Order status.')], pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'get', operationId: 'getOrder', summary: 'Get an order', description: 'Returns one order with its items, totals and shipments. Needs `siteId` from List sites and `orderId` from List a site’s orders.', returns: 'Order', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }] },\n // openWorld: it emails the buyer about the shipment unless `notify` is false.\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'patch', operationId: 'updateOrder', summary: 'Mark an order shipped or delivered', accepts: 'OrderWrite', returns: 'Order', description: 'Records a shipment: sets `status` to `fulfilled` (shipped) or `delivered`, with optional carrier, tracking number and the items shipped. The buyer is emailed about it unless `notify` is false. An order cannot be cancelled or refunded here; that is done in the console. Needs `siteId` and `orderId`. Returns the order.', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }], openWorld: true },\n ],\n}\n"],"names":["booleanField","bool","integerField","int","nullableField","nullable","objectKindField","OBJECT_FIELD","openObjectField","objectOf","postalAddressField","ADDRESS","queryParam","q","RECORD_STAMPS","STAMPS","stringField","str","stringListField","strList","SITE_ID_PATH_PARAM","PRODUCTS_API_V1_DESCRIPTION","tag","docsPage","description","schemaName","required","fields","id","object","name","slug","type","status","tags","categoryIds","mediaUrls","options","items","additionalProperties","variants","inventory","subscription","ops","path","method","operationId","summary","list","returns","pathParams","ORDERS_API_V1_DESCRIPTION","writable","writeOnly","enum","carrier","trackingNumber","trackingUrl","lineItems","notify","writeRequired","number","channel","currency","customerEmail","customerName","totals","extras","credits","refundedCents","livemode","disputed","taxMode","taxEngine","shippingAddress","couponCode","fulf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tE,SAASY,IAAI;QACzB2D,cAAc;YAAE5C,MAAM;YAASR,aAAa;YAA6Bc,OAAO;gBAAEN,MAAM;gBAAUO,sBAAsB;YAAK;QAAE;QAC/HsC,SAAS9D,OAAO8D,OAAO;IACzB;IACAlC,KAAK;QACH;YAAEC,MAAM;YAA6BC,QAAQ;YAAOC,aAAa;YAAcC,SAAS;YAAwBvB,aAAa;YAAuJwB,MAAM;YAAMC,SAAS;YAAS6B,SAAS;gBAACjE,EAAE,WAAW;gBAAqDA,EAAE,UAAU;aAAiB;YAAEqC,YAAY;gBAAC9B;aAAmB;QAAC;QAC9b;YAAEwB,MAAM;YAAuCC,QAAQ;YAAOC,aAAa;YAAYC,SAAS;YAAgBvB,aAAa;YAAmIyB,SAAS;YAASC,YAAY;gBAAC9B;gBAAoB;oBAAEU,MAAM;oBAAWN,aAAa;gBAAY;aAAE;QAAC;QAClW,8EAA8E;QAC9E;YAAEoB,MAAM;YAAuCC,QAAQ;YAASC,aAAa;YAAeC,SAAS;YAAsCgC,SAAS;YAAc9B,SAAS;YAASzB,aAAa;YAAiU0B,YAAY;gBAAC9B;gBAAoB;oBAAEU,MAAM;oBAAWN,aAAa;gBAAY;aAAE;YAAEwD,WAAW;QAAK;KACpmB;AACH,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/openapi.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type ApiV1ResourceDescription,\n booleanField as bool,\n integerField as int,\n nullableField as nullable,\n objectKindField as OBJECT_FIELD,\n openObjectField as objectOf,\n postalAddressField as ADDRESS,\n queryParam as q,\n RECORD_STAMPS as STAMPS,\n stringField as str,\n stringListField as strList,\n SITE_ID_PATH_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\nimport { SCREEN_SEO_TEXT_GUIDANCE } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport {\n COMMERCE_MAX_OPTION_VALUES,\n COMMERCE_MAX_OPTIONS,\n COMMERCE_MAX_VARIANTS,\n COMMERCE_SLUG_MAX_LENGTH,\n} from '../../model/commerce'\nimport { PRODUCT_NAME_MAX_LENGTH } from '../../model/product-write'\n\n/*\n * A site's products and orders as the customer API's OpenAPI document\n * describes them. Transcribed unchanged from the builder's own list when the\n * resources moved here (AGL-3080).\n */\n\nconst PRODUCT_ID_PATH_PARAM = { name: 'productId', description: 'Required. The product’s id — the `id` of a product from `listProducts`.' }\nconst VARIANT_ID_PATH_PARAM = { name: 'variantId', description: 'Required. The variant’s id — the `id` of one of the product’s `variants`, from `getProduct`.' }\n\nconst SEO_TITLE_MAX = SCREEN_SEO_TEXT_GUIDANCE.title\nconst SEO_DESCRIPTION_MAX = SCREEN_SEO_TEXT_GUIDANCE.description\n\n/** One variant's writable fields, shared by the variant write and each entry of a product write's `variants`. */\nconst VARIANT_WRITE_FIELDS = {\n priceUsd: nullable({ type: 'number', minimum: 0, description: 'Price in US dollars. `null` leaves the variant unpriced: the store shows “Price coming soon” and does not sell it. A product created without a price is unpriced.' }),\n compareAtPriceUsd: nullable({ type: 'number', minimum: 0, description: 'The strike-through price, in US dollars; it must be higher than `priceUsd`. `null` removes it.' }),\n sku: nullable(str('Stock-keeping code, unique within the product. `null` or an empty string removes it.')),\n barcode: nullable(str('Barcode, such as a UPC or EAN. `null` or an empty string removes it.')),\n weightGrams: nullable({ type: 'number', minimum: 0, description: 'Shipping weight in grams. `null` removes it.' }),\n inventory: nullable({ type: 'integer', minimum: 0, description: 'Stock on hand. `0` is sold out; `null` means stock is not tracked and the variant never sells out. A digital or service subscription takes only `null`.' }),\n}\n\n/**\n * A site's products, as the customer API's OpenAPI document describes them —\n * what the console's builder turns into paths, tags and schemas, and the MCP\n * tools derive from. The writes (AGL-4235) are the console editor's: the\n * members `handleProducts` accepts are exactly `writable` and the\n * `ProductVariantWrite` schema, and `api-v1-openapi.spec.ts` holds the\n * document to every endpoint the documentation promises.\n */\nexport const PRODUCTS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Products',\n docsPage: 'products',\n description: 'A site’s catalog: its products, their options and variants, prices and stock.',\n schemaName: 'Product',\n required: ['id', 'object', 'name'],\n fields: {\n id: str('Product id.'),\n object: OBJECT_FIELD('product'),\n name: str('Product name.'),\n slug: str('URL slug.'),\n description: nullable(str('Description.')),\n type: str('Product type: `physical`, `digital` or `service`.'),\n status: str('Publication status: `draft`, `active` or `archived`. Only an active product is shown in the store.'),\n tags: strList('Free-form tags.'),\n categoryIds: strList('Categories this product belongs to.'),\n mediaUrls: strList('Image URLs. The first is the product’s main image.'),\n options: { type: 'array', description: 'Option definitions, e.g. size.', items: { type: 'object', additionalProperties: true } },\n variants: { type: 'array', description: 'Purchasable variants.', items: { type: 'object', additionalProperties: true } },\n inventory: nullable(int('Stock on hand, when tracked.')),\n seo: objectOf('The product page’s search listing: `title` and `description`, each `null` where the page uses the product’s own name and description.'),\n subscription: nullable(objectOf('Subscription terms, when the product is one.')),\n ...STAMPS,\n },\n writable: ['name', 'description', 'status', 'type', 'slug', 'tags', 'categoryIds', 'mediaUrls', 'options', 'variants', 'seo'],\n writeOnly: {\n name: str(`Product name, at most ${PRODUCT_NAME_MAX_LENGTH} characters.`),\n description: nullable(str('Description. `null` clears it.')),\n status: { type: 'string', enum: ['draft', 'active', 'archived'], description: 'Publication status. A new product is a `draft`, not shown in the store, unless this says `active`. `archived` takes it out of the store.' },\n type: { type: 'string', enum: ['physical', 'service'], description: 'Product type. Defaults to `physical`. A digital product delivers files uploaded in the console, so it is created there.' },\n slug: str(`URL slug: lowercase letters, numbers and dashes, at most ${COMMERCE_SLUG_MAX_LENGTH} characters. Made from the name when a new product has none. A slug another product of the site uses is refused.`),\n tags: strList('Free-form tags. Replaces the product’s tags.'),\n categoryIds: strList('Ids of the site’s product categories. Replaces the product’s categories.'),\n mediaUrls: strList('Image URLs, the first the main image. Replaces the product’s images.'),\n options: {\n type: 'array',\n description: `Up to ${COMMERCE_MAX_OPTIONS} options, such as size and color. Replaces the product’s options, and its variants become every combination of their values: a combination the product already sells keeps its variant, price and stock, and a new one starts at the first variant’s price and stock. A product holds at most ${COMMERCE_MAX_VARIANTS} variants.`,\n items: {\n type: 'object',\n required: ['name', 'values'],\n additionalProperties: false,\n properties: {\n name: str('The option’s name, such as `Size`. Unique within the product.'),\n values: strList(`The option’s values, such as \\`S\\`, \\`M\\`, \\`L\\`; at most ${COMMERCE_MAX_OPTION_VALUES}.`),\n },\n },\n },\n variants: {\n type: 'array',\n description: 'Changes to the product’s variants, applied after `options`. Each entry names one variant by its `id`, or by its `options`, and sets the fields it carries. Variants are not added or removed here; they follow the options.',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n id: str('The variant’s id, from the product’s `variants`.'),\n options: objectOf('The variant’s option values by option name, such as `{ \"Size\": \"M\" }`; names the variant when `id` is not sent.'),\n ...VARIANT_WRITE_FIELDS,\n },\n },\n },\n seo: {\n type: 'object',\n additionalProperties: false,\n description: 'The product page’s search listing. A member left out stays as it is.',\n properties: {\n title: nullable(str(`The page title search engines show, at most ${SEO_TITLE_MAX} characters. \\`null\\` uses the product’s name.`)),\n description: nullable(str(`The summary search engines show, at most ${SEO_DESCRIPTION_MAX} characters. \\`null\\` uses the product’s description.`)),\n },\n },\n },\n writeNote: 'A create needs a `name`. A `PATCH` changes only the members it carries.',\n components: {\n ProductVariantWrite: {\n type: 'object',\n description: 'Writable fields of one product variant. A member left out stays as it is. Any other member is a `400` that names it, never silently ignored.',\n properties: VARIANT_WRITE_FIELDS,\n additionalProperties: false,\n },\n },\n ops: [\n { path: '/v1/sites/{siteId}/products', method: 'get', operationId: 'listProducts', summary: 'List a site’s products', list: true, returns: 'Product', description: 'Lists the products in one site’s store, with prices, stock and variants. Needs `siteId` from List sites.', pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/products/{productId}', method: 'get', operationId: 'getProduct', summary: 'Get a product', description: 'Returns one product with its variants. Needs `siteId` from List sites and `productId` from List a site’s products.', returns: 'Product', pathParams: [SITE_ID_PATH_PARAM, PRODUCT_ID_PATH_PARAM] },\n // openWorld: an active product is on sale in the site’s public store.\n { path: '/v1/sites/{siteId}/products', method: 'post', operationId: 'createProduct', summary: 'Create a product', accepts: 'ProductWrite', returns: 'Product', creates: true, bodyRequires: ['name'], description: 'Adds a product to one site’s store. It is a draft, not shown in the store, unless `status` is `active`. Needs `siteId` from List sites and a `name`. Options make its variants; prices and stock are set on them. Returns the new product.', pathParams: [SITE_ID_PATH_PARAM], openWorld: true },\n // openWorld: a change to a product on sale changes what the public store shows.\n { path: '/v1/sites/{siteId}/products/{productId}', method: 'patch', operationId: 'updateProduct', summary: 'Update a product', accepts: 'ProductWrite', returns: 'Product', description: 'Changes a product’s details, options, variants, prices or stock; fields not sent stay as they are. A product on sale shows the change in the store at once. Needs `siteId` from List sites and `productId` from List a site’s products. Returns the product.', pathParams: [SITE_ID_PATH_PARAM, PRODUCT_ID_PATH_PARAM], openWorld: true },\n // openWorld: a deleted product leaves the public store.\n { path: '/v1/sites/{siteId}/products/{productId}', method: 'delete', operationId: 'deleteProduct', summary: 'Delete a product', returns: 'Deleted', description: 'Deletes a product: it leaves the store at once and can no longer be bought. Needs `siteId` from List sites and `productId` from List a site’s products.', pathParams: [SITE_ID_PATH_PARAM, PRODUCT_ID_PATH_PARAM], openWorld: true },\n // openWorld: a variant’s price and stock are what the public store sells it at.\n { path: '/v1/sites/{siteId}/products/{productId}/variants/{variantId}', method: 'patch', operationId: 'updateProductVariant', summary: 'Update a product variant', accepts: 'ProductVariantWrite', returns: 'Product', description: 'Changes one variant’s price, compare-at price, SKU, barcode, weight or stock; fields not sent stay as they are. A product on sale shows the change in the store at once. Needs `siteId` from List sites, `productId` from List a site’s products and `variantId` from the product’s variants. Returns the product.', pathParams: [SITE_ID_PATH_PARAM, PRODUCT_ID_PATH_PARAM, VARIANT_ID_PATH_PARAM], openWorld: true },\n ],\n}\n\nexport const ORDERS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Orders',\n docsPage: 'orders',\n description: 'A site’s orders. Status moves are constrained.',\n schemaName: 'Order',\n required: ['id', 'object', 'number', 'status'],\n writable: ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify'],\n writeOnly: {\n status: { type: 'string', enum: ['fulfilled', 'delivered'], description: 'The status to move the order to.' },\n carrier: str('Free text, e.g. `UPS`. Trimmed to 40 characters. USPS, UPS, FedEx, DHL, Canada Post, Royal Mail and Australia Post get a tracking link.'),\n trackingNumber: str('Free text. Trimmed to 60 characters.'),\n trackingUrl: str('An https tracking link, for a carrier the link is not derived for.'),\n lineItems: {\n type: 'array',\n description:\n 'With `status: fulfilled`, the units this shipment covers: `[{ lineItemId, quantity }]`, where `lineItemId` is the line’s index. Omitted, the shipment covers everything still to ship. More than is left is `409 conflict` (`code: \"over_fulfilled\"`). Send an `Idempotency-Key` header so a retried partial shipment is recorded once.',\n items: { type: 'object', additionalProperties: true },\n },\n notify: bool('Whether the buyer is told about this shipment. Defaults to true.'),\n },\n writeRequired: ['status'],\n fields: {\n id: str('Order id.'),\n object: OBJECT_FIELD('order'),\n number: int('Human-facing order number.'),\n status: str('Order status.'),\n channel: str('`online` by default. Older orders carry no stored value, so `?channel=online` drops them after the read.'),\n currency: str('ISO 4217 code.'),\n customerEmail: nullable(str('Customer email.')),\n customerName: nullable(str('Customer name.')),\n lineItems: { type: 'array', description: 'What was bought.', items: { type: 'object', additionalProperties: true } },\n totals: objectOf('Money totals, in the smallest unit of `currency`. `extrasCents` is the optional lines the buyer added at checkout, inside `totalCents` and outside `itemsCents`.'),\n extras: { type: 'array', description: 'Optional lines the buyer added at checkout, such as package protection: `[{ id, pluginId, key, label, amountCents, quoteRef }]`. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n credits: { type: 'array', description: 'Store credit another plugin kept that paid part of the sale, such as rewards: `[{ providerId, pluginId, reference, label, last4, amountCents, appliedAs }]`. `appliedAs` is `discount` for a checkout redemption and `tender` for a register payment. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n refundedCents: int('Amount refunded so far.'),\n livemode: bool('Whether real money moved: `false` for an order paid in Stripe test mode, such as a store rehearsal.'),\n disputed: bool('Whether a chargeback is open.'),\n taxMode: nullable(str('The tax regime: `stripe-automatic` (Stripe Tax), `manual` (your own rate) or `none`. `stripe-automatic` tax on a sale whose `chargeModel` is `direct` was calculated on your own Stripe account and is yours to remit; on any other sale the platform collects and remits it as marketplace facilitator. `null` on an order from before it was recorded.')),\n chargeModel: nullable(str('Where the sale was charged: `direct` on your own Stripe account, so the money, Stripe’s fees and any Stripe Tax on it are yours. `null` when it was charged through the platform’s account, or on an order from before it was recorded.')),\n taxEngine: nullable(objectOf('The tax service you connected, when one was asked for this sale’s tax: `provider` (`avalara` or `taxjar`), `providerLabel`, `status` (`quoted` when its tax was charged, `fallback` when it did not answer and your own rate was charged), `reason` (`timeout` or `error` on a fallback) and `sandbox`. `null` when no service was asked.')),\n shippingAddress: ADDRESS(),\n couponCode: nullable(str('Coupon applied.')),\n fulfillments: { type: 'array', description: 'Shipments and deliveries.', items: { type: 'object', additionalProperties: true } },\n created: STAMPS.created,\n },\n ops: [\n { path: '/v1/sites/{siteId}/orders', method: 'get', operationId: 'listOrders', summary: 'List a site’s orders', description: 'Lists the orders placed in one site’s store, with status, items, totals and shipments. Needs `siteId` from List sites. Filter by status or channel.', list: true, returns: 'Order', filters: [q('channel', 'Orders from one sales channel, such as `online`.'), q('status', 'Order status.')], pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'get', operationId: 'getOrder', summary: 'Get an order', description: 'Returns one order with its items, totals and shipments. Needs `siteId` from List sites and `orderId` from List a site’s orders.', returns: 'Order', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }] },\n // openWorld: it emails the buyer about the shipment unless `notify` is false.\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'patch', operationId: 'updateOrder', summary: 'Mark an order shipped or delivered', accepts: 'OrderWrite', returns: 'Order', description: 'Records a shipment: sets `status` to `fulfilled` (shipped) or `delivered`, with optional carrier, tracking number and the items shipped. The buyer is emailed about it unless `notify` is false. An order cannot be cancelled or refunded here; that is done in the console. Needs `siteId` and `orderId`. Returns the order.', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }], openWorld: true },\n ],\n}\n"],"names":["booleanField","bool","integerField","int","nullableField","nullable","objectKindField","OBJECT_FIELD","openObjectField","objectOf","postalAddressField","ADDRESS","queryParam","q","RECORD_STAMPS","STAMPS","stringField","str","stringListField","strList","SITE_ID_PATH_PARAM","SCREEN_SEO_TEXT_GUIDANCE","COMMERCE_MAX_OPTION_VALUES","COMMERCE_MAX_OPTIONS","COMMERCE_MAX_VARIANTS","COMMERCE_SLUG_MAX_LENGTH","PRODUCT_NAME_MAX_LENGTH","PRODUCT_ID_PATH_PARAM","name","description","VARIANT_ID_PATH_PARAM","SEO_TITLE_MAX","title","SEO_DESCRIPTION_MAX","VARIANT_WRITE_FIELDS","priceUsd","type","minimum","compareAtPriceUsd","sku","barcode","weightGrams","inventory","PRODUCTS_API_V1_DESCRIPTION","tag","docsPage","schemaName","required","fields","id","object","slug","status","tags","categoryIds","mediaUrls","options","items","additionalProperties","variants","seo","subscription","writable","writeOnly","enum","properties","values","writeNote","components","ProductVariantWrite","ops","path","method","operationId","summary","list","returns","pathParams","accepts","creates","bodyRequires","openWorld","ORDERS_API_V1_DESCRIPTION","carrier","trackingNumber","trackingUrl","lineItems","notify","writeRequired","number","channel","currency","customerEmail","customerName","totals","extras","credits","refundedCents","livemode","disputed","taxMode","chargeModel","taxEngine","shippingAddress","couponCode","fulfillments","created","filters"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgBC,IAAI,EACpBC,gBAAgBC,GAAG,EACnBC,iBAAiBC,QAAQ,EACzBC,mBAAmBC,YAAY,EAC/BC,mBAAmBC,QAAQ,EAC3BC,sBAAsBC,OAAO,EAC7BC,cAAcC,CAAC,EACfC,iBAAiBC,MAAM,EACvBC,eAAeC,GAAG,EAClBC,mBAAmBC,OAAO,EAC1BC,kBAAkB,QACb,qDAAoD;AAC3D,SAASC,wBAAwB,QAAQ,2CAA0C;AACnF,SACEC,0BAA0B,EAC1BC,oBAAoB,EACpBC,qBAAqB,EACrBC,wBAAwB,QACnB,0BAAsB;AAC7B,SAASC,uBAAuB,QAAQ,+BAA2B;AAEnE;;;;CAIC,GAED,MAAMC,wBAAwB;IAAEC,MAAM;IAAaC,aAAa;AAA0E;AAC1I,MAAMC,wBAAwB;IAAEF,MAAM;IAAaC,aAAa;AAA+F;AAE/J,MAAME,gBAAgBV,yBAAyBW,KAAK;AACpD,MAAMC,sBAAsBZ,yBAAyBQ,WAAW;AAEhE,+GAA+G,GAC/G,MAAMK,uBAAuB;IAC3BC,UAAU9B,SAAS;QAAE+B,MAAM;QAAUC,SAAS;QAAGR,aAAa;IAAoK;IAClOS,mBAAmBjC,SAAS;QAAE+B,MAAM;QAAUC,SAAS;QAAGR,aAAa;IAAiG;IACxKU,KAAKlC,SAASY,IAAI;IAClBuB,SAASnC,SAASY,IAAI;IACtBwB,aAAapC,SAAS;QAAE+B,MAAM;QAAUC,SAAS;QAAGR,aAAa;IAA+C;IAChHa,WAAWrC,SAAS;QAAE+B,MAAM;QAAWC,SAAS;QAAGR,aAAa;IAA0J;AAC5N;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMc,8BAAwD;IACnEC,KAAK;IACLC,UAAU;IACVhB,aAAa;IACbiB,YAAY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mB;AACH,EAAC"}
@@ -67,6 +67,7 @@ export declare function orderViewFromData(id: string, data: Record<string, any>)
67
67
  refundedCents: number;
68
68
  livemode: boolean;
69
69
  taxMode: string;
70
+ chargeModel: "direct";
70
71
  taxEngine: import("../../model/commerce-tax-engine").OrderTaxEngineStamp;
71
72
  disputed: boolean;
72
73
  shippingAddress: unknown;
@@ -94,6 +95,13 @@ export declare function orderCreditsView(data: Record<string, any>): Array<{
94
95
  amountCents: number;
95
96
  appliedAs: 'discount' | 'tender';
96
97
  }>;
98
+ /**
99
+ * `direct` when the sale was charged on the seller's own Stripe account. An
100
+ * online sale says so on the order; a register card taken on the store's own
101
+ * account says so on its payment, so a succeeded card payment that does
102
+ * counts too.
103
+ */
104
+ export declare function orderChargeModelView(data: Record<string, any>): 'direct' | null;
97
105
  /**
98
106
  * A register sale's settled tenders as the order event names them (AGL-3614).
99
107
  * An order from before the split-tender ledger is one payment, inferred the
@@ -92,11 +92,17 @@ import { orderPayments } from "../../model/commerce-pos.js";
92
92
  checkoutSessionId: data.checkoutSessionId,
93
93
  $id: id
94
94
  }),
95
- // Who the tax was charged under (AGL-3614): `stripe-automatic` tax is
96
- // Aglyn's to remit as marketplace facilitator and never reaches the
97
- // merchant's account, which a ledger posting the sale has to know. An
98
- // order from before the regime was recorded says `null`, never a guess.
95
+ // Who the tax was charged under (AGL-3614): `stripe-automatic` tax on a
96
+ // sale that is not `direct` is Aglyn's to remit as marketplace facilitator
97
+ // and never reaches the merchant's account; on a `direct` sale Stripe Tax
98
+ // ran on the seller's own account and the tax is the seller's. A ledger
99
+ // posting the sale has to know which. An order from before the regime was
100
+ // recorded says `null`, never a guess.
99
101
  taxMode: typeof data.taxMode === 'string' && data.taxMode ? data.taxMode : null,
102
+ // Where the sale was charged (AGL-3614): `direct` on the seller's own
103
+ // Stripe account, so the money, Stripe's fees and any Stripe Tax are the
104
+ // seller's; `null` through the platform's account, or not recorded.
105
+ chargeModel: orderChargeModelView(data),
100
106
  // The merchant's own tax service (AGL-3631): which one priced the sale, or
101
107
  // that it was asked and the store's own rates were charged instead
102
108
  // (`status: 'fallback'`). `null` when no service was asked. The regime is
@@ -176,6 +182,17 @@ const CARD_METHODS = new Set([
176
182
  'card_keyed',
177
183
  'card_link'
178
184
  ]);
185
+ /**
186
+ * `direct` when the sale was charged on the seller's own Stripe account. An
187
+ * online sale says so on the order; a register card taken on the store's own
188
+ * account says so on its payment, so a succeeded card payment that does
189
+ * counts too.
190
+ */ export function orderChargeModelView(data) {
191
+ if ((data == null ? void 0 : data.chargeModel) === 'direct') return 'direct';
192
+ const payments = Array.isArray(data == null ? void 0 : data.payments) ? data.payments : [];
193
+ const directCard = payments.some((payment)=>(payment == null ? void 0 : payment.status) === 'succeeded' && CARD_METHODS.has(payment.method) && payment.chargeModel === 'direct');
194
+ return directCard ? 'direct' : null;
195
+ }
179
196
  /**
180
197
  * A register sale's settled tenders as the order event names them (AGL-3614).
181
198
  * An order from before the split-tender ledger is one payment, inferred the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/order-view.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { serialize } from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { fulfillmentLineQuantities } from '../../model/order-fulfillment'\nimport { fulfillmentTrackingUrl } from '../../model/tracking-url'\nimport { orderTaxEngineView } from '../../model/commerce-tax-engine'\nimport { orderIsTestMode } from '../../model/commerce-orders'\nimport { orderPayments, type OrderPaymentMethod } from '../../model/commerce-pos'\n\n/**\n * The public order shape from an order's data (AGL-3611): the same object the\n * API returns, so an order event and an outbound webhook carry exactly what\n * `GET /v1/sites/{id}/orders/{id}` would.\n */\nexport function orderViewFromData(id: string, data: Record<string, any>) {\n const totals = (data.totals ?? {}) as Record<string, unknown>\n const legacyTotal = Number(data.amountCents ?? NaN)\n const totalCents = Number.isFinite(Number(totals.totalCents))\n ? Number(totals.totalCents)\n : Number.isFinite(legacyTotal)\n ? legacyTotal\n : null\n const legacyFee = Number(data.feeCents ?? NaN)\n return {\n id,\n object: 'order',\n number: typeof data.number === 'number' ? data.number : null,\n status: (data.status as string) ?? null,\n channel: (data.channel as string) ?? 'online',\n currency: 'usd',\n customerEmail: data.customerEmail ?? null,\n customerName: data.customerName ?? null,\n lineItems: serialize(data.lineItems ?? []),\n totals: {\n itemsCents: Number(totals.itemsCents ?? 0),\n shippingCents: Number(totals.shippingCents ?? 0),\n taxCents: Number(totals.taxCents ?? 0),\n discountCents: Number(totals.discountCents ?? 0),\n totalCents,\n // The Connect application fee. NOT subtracted from `totalCents` — it is\n // Aglyn's cut of a total the shopper already paid in full, so a client\n // that nets it out of revenue would understate what it collected.\n feeCents: Number.isFinite(Number(totals.feeCents))\n ? Number(totals.feeCents)\n : Number.isFinite(legacyFee)\n ? legacyFee\n : 0,\n // Optional lines the buyer added at checkout (AGL-3635), inside\n // `totalCents` and outside `itemsCents`.\n extrasCents: Number(totals.extrasCents ?? 0) || 0,\n // A register tip (AGL-3607), on top of `totalCents` and not revenue.\n tipCents: Math.max(0, Math.round(Number(totals.tipCents ?? 0)) || 0),\n },\n // How a register sale was paid (AGL-3614): one entry per tender that\n // succeeded. A ledger needs it because only the card tenders went through\n // Stripe; cash went in the drawer, a gift card spent value the store\n // already held. Empty for every sale that is not the register's.\n payments: orderPaymentsView(data),\n // The part of `discountCents` a gift card paid online (AGL-3614).\n giftCardRedeemedCents: Math.max(0, Math.round(Number(data.giftCardRedeemedCents ?? 0)) || 0),\n // What those lines were and whose offer each was: the fact a plugin that\n // insures a parcel reads off `order.paid` to know it was bought.\n extras: (Array.isArray(data.extras) ? data.extras : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.id === 'string')\n .map((entry: Record<string, unknown>) => ({\n id: String(entry.id),\n pluginId: String(entry.pluginId ?? ''),\n key: String(entry.key ?? ''),\n label: String(entry.label ?? ''),\n amountCents: Number(entry.amountCents ?? 0) || 0,\n quoteRef: typeof entry.quoteRef === 'string' ? entry.quoteRef : null,\n })),\n // Store credit another plugin kept that paid part of the sale (AGL-3640):\n // a rewards redemption online comes off the goods (`discount`), one at\n // the register is one of its payments (`tender`). The provider reads its\n // own `reference` back off `order.paid` and `order.refunded`.\n credits: orderCreditsView(data),\n // Money already handed back, for any reason. A chargeback lands here too,\n // so `refundedCents > 0` does not by itself mean the merchant chose it.\n refundedCents: Number(data.refundedCents ?? 0),\n // Whether real money moved (AGL-3699): `false` for a Stripe test-mode\n // order, so a subscriber that tells an outside service about a sale —\n // a review invitation, a ledger — can leave a store's rehearsal out.\n // The seller's own rule: the recorded fact, else the session id.\n livemode: !orderIsTestMode({\n livemode: data.livemode,\n checkoutSessionId: data.checkoutSessionId,\n $id: id,\n }),\n // Who the tax was charged under (AGL-3614): `stripe-automatic` tax is\n // Aglyn's to remit as marketplace facilitator and never reaches the\n // merchant's account, which a ledger posting the sale has to know. An\n // order from before the regime was recorded says `null`, never a guess.\n taxMode: typeof data.taxMode === 'string' && data.taxMode ? data.taxMode : null,\n // The merchant's own tax service (AGL-3631): which one priced the sale, or\n // that it was asked and the store's own rates were charged instead\n // (`status: 'fallback'`). `null` when no service was asked. The regime is\n // still `taxMode` — a service the merchant connected answers for tax the\n // merchant remits.\n taxEngine: orderTaxEngineView(data.taxEngine),\n disputed: Boolean(data.dispute),\n shippingAddress: serialize(data.shippingAddress) ?? null,\n couponCode: data.couponCode ?? null,\n // Shipment records — the half of fulfilment an integration can use\n // without a write (AGL-2460). `status` says an order is `fulfilled`; it\n // does not say which carrier took it or under what tracking number, so a\n // 3PL or accounting reconcile could see THAT an order shipped and never\n // WHICH shipment it was. The console's order dialog shows both, and an\n // order that has been shipped twice (a split shipment) is indistinguish-\n // able from one shipped once when only the status is published.\n //\n // `atMs` is a number of milliseconds, not a Firestore Timestamp, so\n // `serialize` passes it through untouched. It is republished as `at` in\n // ISO 8601 to match `created` and every other time this API emits: one\n // object publishing two time formats is a bug an integrator finds late,\n // in their own timezone conversion, and blames on their own code.\n fulfillments: (Array.isArray(data.fulfillments) ? data.fulfillments : []).map(\n (entry: Record<string, unknown>) => {\n const atMs = Number((entry ?? {}).atMs)\n return {\n id: (entry ?? {}).id ?? null,\n lineItemIds: Array.isArray((entry ?? {}).lineItemIds)\n ? (entry as { lineItemIds: unknown[] }).lineItemIds\n : [],\n // Units per line (AGL-3611); a fulfillment recorded before\n // quantities shipped every unit of the lines it names.\n lines: fulfillmentLineQuantities(\n { lineItems: Array.isArray(data.lineItems) ? data.lineItems : [] },\n (entry ?? {}) as never,\n ),\n status: (entry ?? {}).status === 'cancelled' ? 'cancelled' : 'active',\n carrier: (entry ?? {}).carrier ?? null,\n trackingNumber: (entry ?? {}).trackingNumber ?? null,\n trackingUrl: fulfillmentTrackingUrl((entry ?? {}) as never),\n labelUrl: (entry ?? {}).labelUrl ?? null,\n at: Number.isFinite(atMs) ? new Date(atMs).toISOString() : null,\n }\n },\n ),\n created: serialize(data.createdAt) ?? null,\n }\n}\n\n/** The plugin credits an order carries, online and at the register (AGL-3640). */\nexport function orderCreditsView(data: Record<string, any>): Array<{\n providerId: string\n pluginId: string\n reference: string\n label: string\n last4: string\n amountCents: number\n appliedAs: 'discount' | 'tender'\n}> {\n const online = (Array.isArray(data.credits) ? data.credits : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.providerId === 'string')\n .map((entry: Record<string, unknown>) => ({\n providerId: String(entry.providerId),\n pluginId: String(entry.pluginId ?? String(entry.providerId).split('.')[0]),\n reference: String(entry.reference ?? ''),\n label: String(entry.label ?? ''),\n last4: String(entry.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(entry.amountCents) || 0)),\n appliedAs: entry.appliedAs === 'tender' ? ('tender' as const) : ('discount' as const),\n }))\n const register = (Array.isArray(data.payments) ? data.payments : [])\n .filter(\n (payment: Record<string, unknown>) =>\n payment &&\n payment.method === 'credit' &&\n payment.status === 'succeeded' &&\n typeof payment.creditProviderId === 'string',\n )\n .map((payment: Record<string, unknown>) => ({\n providerId: String(payment.creditProviderId),\n pluginId: String(payment.creditProviderId).split('.')[0],\n reference: String(payment.creditReference ?? ''),\n label: String(payment.creditLabel ?? ''),\n last4: String(payment.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(payment.amountCents) || 0)),\n appliedAs: 'tender' as const,\n }))\n return [...online, ...register].filter((credit) => credit.reference && credit.amountCents > 0)\n}\n\nconst CARD_METHODS: ReadonlySet<OrderPaymentMethod> = new Set(['card_present', 'card_keyed', 'card_link'])\n\n/**\n * A register sale's settled tenders as the order event names them (AGL-3614).\n * An order from before the split-tender ledger is one payment, inferred the\n * way the register's own reader infers it, with the order's tip and fee.\n */\nexport function orderPaymentsView(data: Record<string, any>): Array<{\n method: OrderPaymentMethod\n amountCents: number\n tipCents: number\n feeCents: number\n}> {\n if (data?.channel !== 'pos') return []\n const whole = (value: unknown) => Math.max(0, Math.round(Number(value ?? 0)) || 0)\n return orderPayments(data)\n .filter((payment) => payment.status === 'succeeded')\n .map((payment) => {\n const legacy = payment.id === 'legacy'\n return {\n method: payment.method,\n amountCents: whole(payment.amountCents),\n tipCents: whole(legacy ? data.totals?.tipCents : payment.tipCents),\n // The application fee Stripe took from this payment; a tender Stripe\n // never saw carried none.\n feeCents: legacy\n ? CARD_METHODS.has(payment.method) ? whole(data.totals?.feeCents ?? data.feeCents) : 0\n : whole(payment.feeCents),\n }\n })\n}\n"],"names":["serialize","fulfillmentLineQuantities","fulfillmentTrackingUrl","orderTaxEngineView","orderIsTestMode","orderPayments","orderViewFromData","id","data","totals","legacyTotal","Number","amountCents","NaN","totalCents","isFinite","legacyFee","feeCents","object","number","status","channel","currency","customerEmail","customerName","lineItems","itemsCents","shippingCents","taxCents","discountCents","extrasCents","tipCents","Math","max","round","payments","orderPaymentsView","giftCardRedeemedCents","extras","Array","isArray","filter","entry","map","String","pluginId","key","label","quoteRef","credits","orderCreditsView","refundedCents","livemode","checkoutSessionId","$id","taxMode","taxEngine","disputed","Boolean","dispute","shippingAddress","couponCode","fulfillments","atMs","lineItemIds","lines","carrier","trackingNumber","trackingUrl","labelUrl","at","Date","toISOString","created","createdAt","online","providerId","split","reference","last4","trunc","appliedAs","register","payment","method","creditProviderId","creditReference","creditLabel","credit","CARD_METHODS","Set","whole","value","legacy","has"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,6CAA4C;AACtE,SAASC,yBAAyB,QAAQ,mCAA+B;AACzE,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SAASC,eAAe,QAAQ,iCAA6B;AAC7D,SAASC,aAAa,QAAiC,8BAA0B;AAEjF;;;;CAIC,GACD,OAAO,SAASC,kBAAkBC,EAAU,EAAEC,IAAyB;QACrDA,cACWA,mBAMFA,gBAKdA,cACCA,eAEKA,qBACDA,oBACOA,iBAEAC,oBACGA,uBACLA,kBACKA,uBAYFA,qBAEoBA,kBAQWD,6BAoB/BA,qBAsBLR,YACLQ,kBAqCHR;IA5HX,MAAMS,UAAUD,eAAAA,KAAKC,MAAM,YAAXD,eAAe,CAAC;IAChC,MAAME,cAAcC,QAAOH,oBAAAA,KAAKI,WAAW,YAAhBJ,oBAAoBK;IAC/C,MAAMC,aAAaH,OAAOI,QAAQ,CAACJ,OAAOF,OAAOK,UAAU,KACvDH,OAAOF,OAAOK,UAAU,IACxBH,OAAOI,QAAQ,CAACL,eACdA,cACA;IACN,MAAMM,YAAYL,QAAOH,iBAAAA,KAAKS,QAAQ,YAAbT,iBAAiBK;IAC1C,OAAO;QACLN;QAC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QAC9B,OAAO;YACL6E,QAAQD,QAAQC,MAAM;YACtBxE,aAAa+E,MAAMR,QAAQvE,WAAW;YACtCmB,UAAU4D,MAAME,UAASrF,eAAAA,KAAKC,MAAM,qBAAXD,aAAauB,QAAQ,GAAGoD,QAAQpD,QAAQ;YACjE,qEAAqE;YACrE,0BAA0B;YAC1Bd,UAAU4E,SACNJ,aAAaK,GAAG,CAACX,QAAQC,MAAM,IAAIO,eAAMnF,gBAAAA,KAAKC,MAAM,qBAAXD,cAAaS,QAAQ,mBAAIT,KAAKS,QAAQ,IAAI,IACnF0E,MAAMR,QAAQlE,QAAQ;QAC5B;IACF;AACJ"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/order-view.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { serialize } from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { fulfillmentLineQuantities } from '../../model/order-fulfillment'\nimport { fulfillmentTrackingUrl } from '../../model/tracking-url'\nimport { orderTaxEngineView } from '../../model/commerce-tax-engine'\nimport { orderIsTestMode } from '../../model/commerce-orders'\nimport { orderPayments, type OrderPaymentMethod } from '../../model/commerce-pos'\n\n/**\n * The public order shape from an order's data (AGL-3611): the same object the\n * API returns, so an order event and an outbound webhook carry exactly what\n * `GET /v1/sites/{id}/orders/{id}` would.\n */\nexport function orderViewFromData(id: string, data: Record<string, any>) {\n const totals = (data.totals ?? {}) as Record<string, unknown>\n const legacyTotal = Number(data.amountCents ?? NaN)\n const totalCents = Number.isFinite(Number(totals.totalCents))\n ? Number(totals.totalCents)\n : Number.isFinite(legacyTotal)\n ? legacyTotal\n : null\n const legacyFee = Number(data.feeCents ?? NaN)\n return {\n id,\n object: 'order',\n number: typeof data.number === 'number' ? data.number : null,\n status: (data.status as string) ?? null,\n channel: (data.channel as string) ?? 'online',\n currency: 'usd',\n customerEmail: data.customerEmail ?? null,\n customerName: data.customerName ?? null,\n lineItems: serialize(data.lineItems ?? []),\n totals: {\n itemsCents: Number(totals.itemsCents ?? 0),\n shippingCents: Number(totals.shippingCents ?? 0),\n taxCents: Number(totals.taxCents ?? 0),\n discountCents: Number(totals.discountCents ?? 0),\n totalCents,\n // The Connect application fee. NOT subtracted from `totalCents` — it is\n // Aglyn's cut of a total the shopper already paid in full, so a client\n // that nets it out of revenue would understate what it collected.\n feeCents: Number.isFinite(Number(totals.feeCents))\n ? Number(totals.feeCents)\n : Number.isFinite(legacyFee)\n ? legacyFee\n : 0,\n // Optional lines the buyer added at checkout (AGL-3635), inside\n // `totalCents` and outside `itemsCents`.\n extrasCents: Number(totals.extrasCents ?? 0) || 0,\n // A register tip (AGL-3607), on top of `totalCents` and not revenue.\n tipCents: Math.max(0, Math.round(Number(totals.tipCents ?? 0)) || 0),\n },\n // How a register sale was paid (AGL-3614): one entry per tender that\n // succeeded. A ledger needs it because only the card tenders went through\n // Stripe; cash went in the drawer, a gift card spent value the store\n // already held. Empty for every sale that is not the register's.\n payments: orderPaymentsView(data),\n // The part of `discountCents` a gift card paid online (AGL-3614).\n giftCardRedeemedCents: Math.max(0, Math.round(Number(data.giftCardRedeemedCents ?? 0)) || 0),\n // What those lines were and whose offer each was: the fact a plugin that\n // insures a parcel reads off `order.paid` to know it was bought.\n extras: (Array.isArray(data.extras) ? data.extras : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.id === 'string')\n .map((entry: Record<string, unknown>) => ({\n id: String(entry.id),\n pluginId: String(entry.pluginId ?? ''),\n key: String(entry.key ?? ''),\n label: String(entry.label ?? ''),\n amountCents: Number(entry.amountCents ?? 0) || 0,\n quoteRef: typeof entry.quoteRef === 'string' ? entry.quoteRef : null,\n })),\n // Store credit another plugin kept that paid part of the sale (AGL-3640):\n // a rewards redemption online comes off the goods (`discount`), one at\n // the register is one of its payments (`tender`). The provider reads its\n // own `reference` back off `order.paid` and `order.refunded`.\n credits: orderCreditsView(data),\n // Money already handed back, for any reason. A chargeback lands here too,\n // so `refundedCents > 0` does not by itself mean the merchant chose it.\n refundedCents: Number(data.refundedCents ?? 0),\n // Whether real money moved (AGL-3699): `false` for a Stripe test-mode\n // order, so a subscriber that tells an outside service about a sale —\n // a review invitation, a ledger — can leave a store's rehearsal out.\n // The seller's own rule: the recorded fact, else the session id.\n livemode: !orderIsTestMode({\n livemode: data.livemode,\n checkoutSessionId: data.checkoutSessionId,\n $id: id,\n }),\n // Who the tax was charged under (AGL-3614): `stripe-automatic` tax on a\n // sale that is not `direct` is Aglyn's to remit as marketplace facilitator\n // and never reaches the merchant's account; on a `direct` sale Stripe Tax\n // ran on the seller's own account and the tax is the seller's. A ledger\n // posting the sale has to know which. An order from before the regime was\n // recorded says `null`, never a guess.\n taxMode: typeof data.taxMode === 'string' && data.taxMode ? data.taxMode : null,\n // Where the sale was charged (AGL-3614): `direct` on the seller's own\n // Stripe account, so the money, Stripe's fees and any Stripe Tax are the\n // seller's; `null` through the platform's account, or not recorded.\n chargeModel: orderChargeModelView(data),\n // The merchant's own tax service (AGL-3631): which one priced the sale, or\n // that it was asked and the store's own rates were charged instead\n // (`status: 'fallback'`). `null` when no service was asked. The regime is\n // still `taxMode` — a service the merchant connected answers for tax the\n // merchant remits.\n taxEngine: orderTaxEngineView(data.taxEngine),\n disputed: Boolean(data.dispute),\n shippingAddress: serialize(data.shippingAddress) ?? null,\n couponCode: data.couponCode ?? null,\n // Shipment records — the half of fulfilment an integration can use\n // without a write (AGL-2460). `status` says an order is `fulfilled`; it\n // does not say which carrier took it or under what tracking number, so a\n // 3PL or accounting reconcile could see THAT an order shipped and never\n // WHICH shipment it was. The console's order dialog shows both, and an\n // order that has been shipped twice (a split shipment) is indistinguish-\n // able from one shipped once when only the status is published.\n //\n // `atMs` is a number of milliseconds, not a Firestore Timestamp, so\n // `serialize` passes it through untouched. It is republished as `at` in\n // ISO 8601 to match `created` and every other time this API emits: one\n // object publishing two time formats is a bug an integrator finds late,\n // in their own timezone conversion, and blames on their own code.\n fulfillments: (Array.isArray(data.fulfillments) ? data.fulfillments : []).map(\n (entry: Record<string, unknown>) => {\n const atMs = Number((entry ?? {}).atMs)\n return {\n id: (entry ?? {}).id ?? null,\n lineItemIds: Array.isArray((entry ?? {}).lineItemIds)\n ? (entry as { lineItemIds: unknown[] }).lineItemIds\n : [],\n // Units per line (AGL-3611); a fulfillment recorded before\n // quantities shipped every unit of the lines it names.\n lines: fulfillmentLineQuantities(\n { lineItems: Array.isArray(data.lineItems) ? data.lineItems : [] },\n (entry ?? {}) as never,\n ),\n status: (entry ?? {}).status === 'cancelled' ? 'cancelled' : 'active',\n carrier: (entry ?? {}).carrier ?? null,\n trackingNumber: (entry ?? {}).trackingNumber ?? null,\n trackingUrl: fulfillmentTrackingUrl((entry ?? {}) as never),\n labelUrl: (entry ?? {}).labelUrl ?? null,\n at: Number.isFinite(atMs) ? new Date(atMs).toISOString() : null,\n }\n },\n ),\n created: serialize(data.createdAt) ?? null,\n }\n}\n\n/** The plugin credits an order carries, online and at the register (AGL-3640). */\nexport function orderCreditsView(data: Record<string, any>): Array<{\n providerId: string\n pluginId: string\n reference: string\n label: string\n last4: string\n amountCents: number\n appliedAs: 'discount' | 'tender'\n}> {\n const online = (Array.isArray(data.credits) ? data.credits : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.providerId === 'string')\n .map((entry: Record<string, unknown>) => ({\n providerId: String(entry.providerId),\n pluginId: String(entry.pluginId ?? String(entry.providerId).split('.')[0]),\n reference: String(entry.reference ?? ''),\n label: String(entry.label ?? ''),\n last4: String(entry.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(entry.amountCents) || 0)),\n appliedAs: entry.appliedAs === 'tender' ? ('tender' as const) : ('discount' as const),\n }))\n const register = (Array.isArray(data.payments) ? data.payments : [])\n .filter(\n (payment: Record<string, unknown>) =>\n payment &&\n payment.method === 'credit' &&\n payment.status === 'succeeded' &&\n typeof payment.creditProviderId === 'string',\n )\n .map((payment: Record<string, unknown>) => ({\n providerId: String(payment.creditProviderId),\n pluginId: String(payment.creditProviderId).split('.')[0],\n reference: String(payment.creditReference ?? ''),\n label: String(payment.creditLabel ?? ''),\n last4: String(payment.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(payment.amountCents) || 0)),\n appliedAs: 'tender' as const,\n }))\n return [...online, ...register].filter((credit) => credit.reference && credit.amountCents > 0)\n}\n\nconst CARD_METHODS: ReadonlySet<OrderPaymentMethod> = new Set(['card_present', 'card_keyed', 'card_link'])\n\n/**\n * `direct` when the sale was charged on the seller's own Stripe account. An\n * online sale says so on the order; a register card taken on the store's own\n * account says so on its payment, so a succeeded card payment that does\n * counts too.\n */\nexport function orderChargeModelView(data: Record<string, any>): 'direct' | null {\n if (data?.chargeModel === 'direct') return 'direct'\n const payments = Array.isArray(data?.payments) ? (data.payments as Array<Record<string, unknown>>) : []\n const directCard = payments.some(\n (payment) =>\n payment?.status === 'succeeded' &&\n CARD_METHODS.has(payment.method as OrderPaymentMethod) &&\n payment.chargeModel === 'direct',\n )\n return directCard ? 'direct' : null\n}\n\n/**\n * A register sale's settled tenders as the order event names them (AGL-3614).\n * An order from before the split-tender ledger is one payment, inferred the\n * way the register's own reader infers it, with the order's tip and fee.\n */\nexport function orderPaymentsView(data: Record<string, any>): Array<{\n method: OrderPaymentMethod\n amountCents: number\n tipCents: number\n feeCents: number\n}> {\n if (data?.channel !== 'pos') return []\n const whole = (value: unknown) => Math.max(0, Math.round(Number(value ?? 0)) || 0)\n return orderPayments(data)\n .filter((payment) => payment.status === 'succeeded')\n .map((payment) => {\n const legacy = payment.id === 'legacy'\n return {\n method: payment.method,\n amountCents: whole(payment.amountCents),\n tipCents: whole(legacy ? data.totals?.tipCents : payment.tipCents),\n // The application fee Stripe took from this payment; a tender Stripe\n // never saw carried none.\n feeCents: legacy\n ? CARD_METHODS.has(payment.method) ? whole(data.totals?.feeCents ?? data.feeCents) : 0\n : whole(payment.feeCents),\n }\n })\n}\n"],"names":["serialize","fulfillmentLineQuantities","fulfillmentTrackingUrl","orderTaxEngineView","orderIsTestMode","orderPayments","orderViewFromData","id","data","totals","legacyTotal","Number","amountCents","NaN","totalCents","isFinite","legacyFee","feeCents","object","number","status","channel","currency","customerEmail","customerName","lineItems","itemsCents","shippingCents","taxCents","discountCents","extrasCents","tipCents","Math","max","round","payments","orderPaymentsView","giftCardRedeemedCents","extras","Array","isArray","filter","entry","map","String","pluginId","key","label","quoteRef","credits","orderCreditsView","refundedCents","livemode","checkoutSessionId","$id","taxMode","chargeModel","orderChargeModelView","taxEngine","disputed","Boolean","dispute","shippingAddress","couponCode","fulfillments","atMs","lineItemIds","lines","carrier","trackingNumber","trackingUrl","labelUrl","at","Date","toISOString","created","createdAt","online","providerId","split","reference","last4","trunc","appliedAs","register","payment","method","creditProviderId","creditReference","creditLabel","credit","CARD_METHODS","Set","directCard","some","has","whole","value","legacy"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,6CAA4C;AACtE,SAASC,yBAAyB,QAAQ,mCAA+B;AACzE,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SAASC,eAAe,QAAQ,iCAA6B;AAC7D,SAASC,aAAa,QAAiC,8BAA0B;AAEjF;;;;CAIC,GACD,OAAO,SAASC,kBAAkBC,EAAU,EAAEC,IAAyB;QACrDA,cACWA,mBAMFA,gBAKdA,cACCA,eAEKA,qBACDA,oBACOA,iBAEAC,oBACGA,uBACLA,kBACKA,uBAYFA,qBAEoBA,kBAQWD,6BAoB/BA,qBA4BLR,YACLQ,kBAqCHR;IA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