@aglyn/plugins-commerce 1.12.0 → 1.14.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 (79) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/catalog-organization-card.component.js +1 -1
  3. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  4. package/src/lib/components/console/host-quotes-card.component.js +3 -2
  5. package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
  6. package/src/lib/components/console/order-detail-dialog.component.js +1 -1
  7. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +1 -1
  9. package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -1
  10. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  11. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  12. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +1 -1
  13. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
  14. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +1 -1
  15. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -1
  16. package/src/lib/components/console/pos-reader-splash-setting.component.js +1 -1
  17. package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -1
  18. package/src/lib/components/console/quote-editor-dialog.component.d.ts +5 -0
  19. package/src/lib/components/console/quote-editor-dialog.component.js +104 -16
  20. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  21. package/src/lib/components/console/quote-pay-link.component.d.ts +4 -1
  22. package/src/lib/components/console/quote-pay-link.component.js +23 -12
  23. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  24. package/src/lib/components/console/quote-proofs.component.d.ts +3 -2
  25. package/src/lib/components/console/quote-proofs.component.js +73 -5
  26. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  27. package/src/lib/components/console/quote-send.component.js +9 -6
  28. package/src/lib/components/console/quote-send.component.js.map +1 -1
  29. package/src/lib/components/console/site-member-purchases.component.js +1 -1
  30. package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
  31. package/src/lib/components/quote-page-body.js +14 -8
  32. package/src/lib/components/quote-page-body.js.map +1 -1
  33. package/src/lib/model/commerce-invoices.d.ts +1 -1
  34. package/src/lib/model/commerce-invoices.js +4 -1
  35. package/src/lib/model/commerce-invoices.js.map +1 -1
  36. package/src/lib/model/commerce-quote-email.d.ts +7 -6
  37. package/src/lib/model/commerce-quote-email.js +11 -6
  38. package/src/lib/model/commerce-quote-email.js.map +1 -1
  39. package/src/lib/model/commerce-quote-pay.d.ts +6 -1
  40. package/src/lib/model/commerce-quote-pay.js +18 -8
  41. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  42. package/src/lib/model/commerce-quote-proofs.d.ts +28 -1
  43. package/src/lib/model/commerce-quote-proofs.js +58 -2
  44. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  45. package/src/lib/model/commerce-quotes.d.ts +22 -1
  46. package/src/lib/model/commerce-quotes.js +25 -5
  47. package/src/lib/model/commerce-quotes.js.map +1 -1
  48. package/src/lib/model/plugin-permissions.d.ts +1 -1
  49. package/src/lib/model/plugin-permissions.js +10 -0
  50. package/src/lib/model/plugin-permissions.js.map +1 -1
  51. package/src/lib/server/commerce-pdf.d.ts +1 -1
  52. package/src/lib/server/commerce-pdf.js +1 -1
  53. package/src/lib/server/commerce-pdf.js.map +1 -1
  54. package/src/lib/server/paid-media-delivery.js +1 -1
  55. package/src/lib/server/paid-media-delivery.js.map +1 -1
  56. package/src/lib/server/quote-email.js +29 -25
  57. package/src/lib/server/quote-email.js.map +1 -1
  58. package/src/lib/server/quote-pay.js +6 -2
  59. package/src/lib/server/quote-pay.js.map +1 -1
  60. package/src/lib/server/quote-proof-media.d.ts +63 -0
  61. package/src/lib/server/quote-proof-media.js +96 -0
  62. package/src/lib/server/quote-proof-media.js.map +1 -0
  63. package/src/lib/server/quote-proofs.js +9 -5
  64. package/src/lib/server/quote-proofs.js.map +1 -1
  65. package/src/lib/server/quote-uploads.d.ts +3 -1
  66. package/src/lib/server/quote-uploads.js +2 -1
  67. package/src/lib/server/quote-uploads.js.map +1 -1
  68. package/src/lib/server/quote.d.ts +3 -0
  69. package/src/lib/server/quote.js +127 -20
  70. package/src/lib/server/quote.js.map +1 -1
  71. package/src/lib/tenant-emails.js +16 -9
  72. package/src/lib/tenant-emails.js.map +1 -1
  73. package/src/lib/transfer/gift-cards.server.js +9 -11
  74. package/src/lib/transfer/gift-cards.server.js.map +1 -1
  75. package/src/lib/utils/commerce-document-pdf.js +12 -9
  76. package/src/lib/utils/commerce-document-pdf.js.map +1 -1
  77. package/src/lib/utils/quote-email-content.d.ts +2 -0
  78. package/src/lib/utils/quote-email-content.js +20 -10
  79. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -279,6 +279,18 @@ export declare function isUnpaidQuote(order: {
279
279
  } | null | undefined): boolean;
280
280
  /** `Quote #1042`; an order number until it is paid. */
281
281
  export declare function formatQuoteNumber(order: Pick<HostOrder, 'number'>, docId?: string): string;
282
+ /**
283
+ * Whether a quote is PROOF ONLY (AGL-4184): it has no lines, so it shows its
284
+ * customer a proof to answer and no price. A design proof often goes out before
285
+ * pricing. This is read off the lines rather than stored, so there is nothing
286
+ * to switch: the save that adds a line makes it a normal quote, and removing
287
+ * every line from a quote with a proof makes it proof only again.
288
+ *
289
+ * Only a stored quote says this, one whose lines are an empty list. Pass a quote.
290
+ */
291
+ export declare function quoteIsProofOnly(order: Partial<Pick<HostOrder, 'lineItems'>> | null | undefined): boolean;
292
+ /** `Proof #1042`: {@link formatQuoteNumber} for a proof only quote. */
293
+ export declare function formatProofNumber(order: Pick<HostOrder, 'number'>, docId?: string): string;
282
294
  /** A quote's status as its list shows it: its stage until it is paid. */
283
295
  export declare function quoteDisplayStatus(order: {
284
296
  status?: OrderStatus | string;
@@ -383,11 +395,20 @@ export interface QuoteInput {
383
395
  /** Absent: the store's default (on create) or unchanged (on update). */
384
396
  requireProofApproval?: boolean;
385
397
  }
398
+ /** What a save with no lines and no proof is told: a quote needs one or the other. */
399
+ export declare const QUOTE_NEEDS_LINE_OR_PROOF = "Add at least one line, or a proof, to the quote.";
386
400
  /**
387
401
  * The console's quote, checked and trimmed, or what to fix. Prices on product
388
402
  * lines are not read from here: the server prices them from the product.
403
+ *
404
+ * No lines is refused unless the caller will check for a proof itself
405
+ * (`allowNoLines`, AGL-4184). With no lines there is nothing to discount or
406
+ * ship, so a discount or shipping sent with none is not kept: a quote with no
407
+ * lines always totals nothing.
389
408
  */
390
- export declare function parseQuoteInput(raw: unknown): {
409
+ export declare function parseQuoteInput(raw: unknown, options?: {
410
+ allowNoLines?: boolean;
411
+ }): {
391
412
  ok: true;
392
413
  input: QuoteInput;
393
414
  } | {
@@ -50,6 +50,20 @@ export const QUOTE_STAGE_LABELS = {
50
50
  if (order.number != null) return `Quote #${order.number}`;
51
51
  return docId ? `Quote #${docId.slice(-6).toUpperCase()}` : 'Quote';
52
52
  }
53
+ /**
54
+ * Whether a quote is PROOF ONLY (AGL-4184): it has no lines, so it shows its
55
+ * customer a proof to answer and no price. A design proof often goes out before
56
+ * pricing. This is read off the lines rather than stored, so there is nothing
57
+ * to switch: the save that adds a line makes it a normal quote, and removing
58
+ * every line from a quote with a proof makes it proof only again.
59
+ *
60
+ * Only a stored quote says this, one whose lines are an empty list. Pass a quote.
61
+ */ export function quoteIsProofOnly(order) {
62
+ return Array.isArray(order == null ? void 0 : order.lineItems) && order.lineItems.length === 0;
63
+ }
64
+ /** `Proof #1042`: {@link formatQuoteNumber} for a proof only quote. */ export function formatProofNumber(order, docId) {
65
+ return formatQuoteNumber(order, docId).replace(/^Quote\b/, 'Proof');
66
+ }
53
67
  /** A quote's status as its list shows it: its stage until it is paid. */ export function quoteDisplayStatus(order) {
54
68
  var _ref, _QUOTE_STAGE_LABELS_stage;
55
69
  var _order_quote;
@@ -302,16 +316,22 @@ function parseLine(raw, index) {
302
316
  }
303
317
  return `${at}: add a product or type an item.`;
304
318
  }
319
+ /** What a save with no lines and no proof is told: a quote needs one or the other. */ export const QUOTE_NEEDS_LINE_OR_PROOF = 'Add at least one line, or a proof, to the quote.';
305
320
  /**
306
321
  * The console's quote, checked and trimmed, or what to fix. Prices on product
307
322
  * lines are not read from here: the server prices them from the product.
308
- */ export function parseQuoteInput(raw) {
323
+ *
324
+ * No lines is refused unless the caller will check for a proof itself
325
+ * (`allowNoLines`, AGL-4184). With no lines there is nothing to discount or
326
+ * ship, so a discount or shipping sent with none is not kept: a quote with no
327
+ * lines always totals nothing.
328
+ */ export function parseQuoteInput(raw, options = {}) {
309
329
  var _customerSource_record, _source_discount, _source_shipping;
310
330
  const source = raw && typeof raw === 'object' ? raw : {};
311
331
  const rawLines = Array.isArray(source['lines']) ? source['lines'] : [];
312
- if (rawLines.length === 0) return {
332
+ if (rawLines.length === 0 && !options.allowNoLines) return {
313
333
  ok: false,
314
- error: 'Add at least one line to the quote.'
334
+ error: QUOTE_NEEDS_LINE_OR_PROOF
315
335
  };
316
336
  if (rawLines.length > QUOTE_MAX_LINES) {
317
337
  return {
@@ -353,7 +373,7 @@ function parseLine(raw, index) {
353
373
  phone: clean(customerSource['phone'], 40)
354
374
  } : {});
355
375
  let discount = null;
356
- const discountSource = (_source_discount = source['discount']) != null ? _source_discount : null;
376
+ const discountSource = lines.length ? (_source_discount = source['discount']) != null ? _source_discount : null : null;
357
377
  if ((discountSource == null ? void 0 : discountSource['kind']) === 'amount') {
358
378
  const amountCents = intIn(discountSource['amountCents'], 0, QUOTE_MAX_UNIT_CENTS);
359
379
  if (amountCents === null) return {
@@ -378,7 +398,7 @@ function parseLine(raw, index) {
378
398
  };
379
399
  }
380
400
  let shipping = null;
381
- const shippingSource = (_source_shipping = source['shipping']) != null ? _source_shipping : null;
401
+ const shippingSource = lines.length ? (_source_shipping = source['shipping']) != null ? _source_shipping : null : null;
382
402
  if (shippingSource) {
383
403
  const amountCents = intIn(shippingSource['amountCents'], 0, QUOTE_MAX_UNIT_CENTS);
384
404
  if (amountCents === null) return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quotes.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 type { HostProduct, ProductType } from './commerce'\nimport type { QuoteRequestRef } from './commerce-quote-request'\nimport { liftLegacyProduct, variantHasPrice } from './commerce'\nimport type {\n HostOrder,\n OrderAddress,\n OrderLineItem,\n OrderStatus,\n OrderTotals,\n} from './commerce-orders'\nimport { computeTaxCents, resolveTaxRate, type TaxSettings } from './commerce-tax'\nimport { storefrontTaxDecision, type StorefrontTaxMode } from './commerce-tax-decision'\nimport { allocateCentsByWeight } from './commerce-tax-engine'\nimport {\n lineLabelWithModifiers,\n resolveLineModifiers,\n type ModifierSelection,\n} from './product-modifiers'\n\n/*==========================================\n * QUOTES (AGL-4093).\n *\n * A quote is an order that has not been paid yet: a document in\n * `hosts/{hostId}/orders` with `channel: 'quote'`, `status: 'pending'` and a\n * `quote` section holding what only a quote has (the customer it is for, its\n * notes and terms, its discount and shipping, where it stands with the\n * business). Its `number` comes from the store's order counter, so the quote\n * and the order it becomes are one number and one document: paying it flips\n * `status` the way a paid draft order flips.\n *\n * WHAT KEEPS AN UNPAID QUOTE OUT OF EVERY ORDER LIST. A quote document\n * carries none of the fields the order readers ask their queries about:\n * no `createdAtMs` (the Orders list, its filters, the money tiles, the\n * analytics, the exports and the reports all order or range on it), none of\n * the list fields `withOrderListFields` stamps (`customerEmailLower`, the\n * search tokens, `requiresShipping`, `productIds`), and no top-level\n * `customerEmail`, `shippingAddress` or `billingAddress` (the customer's\n * account page, gated content and reviews look orders up by the buyer's\n * address). The customer lives in `quote.customer` until the quote is paid,\n * and whatever pays it writes those order fields then. `isUnpaidQuote` is the\n * test for the few readers that reach orders some other way (by number, by\n * document id, or by a header sort on `status`, `channel` or `number`).\n *\n * Pure: the console's live totals, the server's stored totals, and later the\n * quote's PDF and pay page all come from `computeQuoteTotals`.\n *=========================================*/\n\n/** Where a quote stands with the business. The customer side has no states. */\nexport type QuoteStage = 'draft' | 'sent' | 'changes_requested' | 'approved'\n\nexport const QUOTE_STAGE_LABELS: Record<QuoteStage, string> = {\n draft: 'Draft',\n sent: 'Sent',\n changes_requested: 'Changes requested',\n approved: 'Approved',\n}\n\n/** The person a quote is for: a record the workspace keeps, typed details, or both. */\nexport interface QuoteCustomer {\n /** The person record, as the person-records seam names it (`contact`, …). */\n record?: { kind: string; id: string } | null\n name?: string\n company?: string\n email?: string\n /** `email` lower-cased: what a person erasure finds the quote by. */\n emailLower?: string\n phone?: string\n}\n\n/** Money off the whole quote: an amount, or a percentage of the charged lines. */\nexport interface QuoteDiscount {\n kind: 'amount' | 'percent'\n /** With `amount`: the cents off. */\n amountCents?: number\n /** With `percent`: the percentage off. */\n pct?: number\n}\n\n/** Shipping the business prices by hand. */\nexport interface QuoteShipping {\n amountCents: number\n}\n\n/** Why a quote carries no tax. */\nexport type QuoteNoTaxReason =\n | 'not-collected'\n | 'prices-include-tax'\n | 'no-rate'\n | 'undecided'\n\n/** Where a quote's tax comes from. */\nexport type QuoteTaxKind = 'rate' | 'service' | 'at-payment' | 'none'\n\n/**\n * How a quote's tax was worked out, stored beside the figure so the quote can\n * say it: one of the store's own rates (`rate`, with `pct` and its `label`),\n * its connected tax service's answer (`service`, with `taxCents` and\n * `providerLabel`), Stripe Tax at payment (`at-payment`), or no tax and why\n * (`none`, with `reason`). One flat shape, so the apps can read it as is.\n */\nexport interface QuoteTaxBasis {\n kind: QuoteTaxKind\n pct?: number\n label?: string\n taxCents?: number\n providerLabel?: string\n reason?: QuoteNoTaxReason\n}\n\n/** A proof attached to one revision of a quote: what names it, and the revision it is for. */\nexport interface QuoteProofRef {\n id: string\n revision: number\n}\n\n/**\n * A proof the business attached to a revision (AGL-4096): an image or a\n * design file in the site's private storage, under the quote.\n */\nexport interface QuoteProof extends QuoteProofRef {\n name: string\n contentType: string\n size: number\n /** The private Storage object. Never sent to the customer. */\n path: string\n addedAtMs: number\n /** Who attached it: an email, else a uid. */\n addedBy: string\n}\n\n/** A file the customer sent with a response. */\nexport interface QuoteResponseFile {\n id: string\n name: string\n contentType: string\n size: number\n /** The private Storage object. Never sent to the customer. */\n path: string\n}\n\n/**\n * The customer's answer to a revision's proofs (AGL-4096): approved under a\n * typed name, or changes asked for in a comment, with artwork if they had\n * some. The address and browser are kept as the record of who answered.\n */\nexport interface QuoteCustomerResponse {\n action: 'approve' | 'changes'\n revision: number\n atMs: number\n /** With `approve`: the name they typed. */\n name?: string\n /** With `changes`: what to change. */\n comment?: string\n /** With `changes`: files they sent. */\n files?: QuoteResponseFile[]\n ip: string | null\n userAgent: string | null\n}\n\n/** The record of a revision's approval. */\nexport interface QuoteApproval {\n revision: number\n name: string\n atMs: number\n ip: string | null\n userAgent: string | null\n}\n\n/**\n * A payment that reached a quote it could not pay: one made through a pay\n * link the business replaced or for a price it has since changed\n * (`superseded`), or one made after the quote was already paid\n * (`already-paid`). The money is in Stripe and the quote records no sale for\n * it; the business refunds it or reconciles it by hand.\n */\nexport interface QuoteUnmatchedPayment {\n sessionId: string\n paymentIntentId: string | null\n amountCents: number\n atMs: number\n reason: 'superseded' | 'already-paid'\n}\n\n/**\n * The conversation the quote's emails keep in the customer's mailbox\n * (AGL-4097): the latest message's `Message-ID`, every id in the\n * conversation oldest first, and the subject it runs under. The shape of\n * `EmailThread` (`@aglyn/shared-util-email`), spelled out so the model needs\n * no email library. Started by the first email about the quote (a request's\n * confirmation, or the quote itself); every later one replies into it.\n */\nexport interface QuoteEmailThread {\n messageId: string\n references: string[]\n subject: string\n}\n\n/** One time the quote was emailed to the customer (AGL-4097). */\nexport interface QuoteSendRecord {\n /** The revision the email carried. */\n revision: number\n to: string\n subject: string\n atMs: number\n /** Who sent it: an email, else a uid. */\n by: string\n /** The `Message-ID` the email was sent with. */\n messageId: string\n /** The mail provider's own id for the message, when it answered one. */\n providerId: string | null\n /** The pay link version the email carried. */\n linkVersion: number\n}\n\n/** One shipping rate a draft order offered (AGL-4099), as checkout's resolved rates name it. */\nexport interface OrderDraftShippingRate {\n rateId: string\n name: string\n amountCents: number\n}\n\n/** The shipping a draft order offered when it was made (AGL-4099); see `HostOrder.draftShipping`. */\nexport interface OrderDraftShipping {\n /** Where its rates ship; empty when it offers none. */\n countries: string[]\n /** The rates the buyer picks from at payment; empty when it ships nothing. */\n options: OrderDraftShippingRate[]\n}\n\n/** The lasting pay link of an order that is not a quote (AGL-4099); see `HostOrder.payLink`. */\nexport interface OrderPayLink {\n /** The link's version, absent reading as 1. */\n version?: number\n /** Payments through the link the order could not take, as a quote records them. */\n unmatchedPayments?: QuoteUnmatchedPayment[]\n}\n\n/** One time an order's (or a quote's) invoice was emailed to the customer (AGL-4099). */\nexport interface OrderInvoiceSendRecord {\n to: string\n subject: string\n atMs: number\n /** Who sent it: an email, else a uid. */\n by: string\n /** The `Message-ID` the email was sent with. */\n messageId: string\n /** The mail provider's own id for the message, when it answered one. */\n providerId: string | null\n /** The invoice said it was paid (the record), rather than asking for payment. */\n paid: boolean\n /** The pay link version an unpaid invoice carried; null on a paid one. */\n linkVersion: number | null\n /** The total the invoice showed. */\n totalCents: number\n}\n\n/** What only a quote has, on its order document. */\nexport interface OrderQuote {\n stage: QuoteStage\n /** Which version of the quote this is; versions are what proofs and approvals name. */\n revision: number\n customer: QuoteCustomer\n billTo?: OrderAddress | null\n shipTo?: OrderAddress | null\n notes?: string\n terms?: string\n discount?: QuoteDiscount | null\n shipping?: QuoteShipping | null\n tax: QuoteTaxBasis\n /** The customer approves the current revision's proof before they can pay. Absent reads as off. */\n requireProofApproval?: boolean\n /** The current revision's proofs; earlier revisions keep theirs in `revisions/{n}`. */\n proofs?: QuoteProof[]\n /** The customer's answers to the current revision, oldest first; the last one counts. */\n responses?: QuoteCustomerResponse[]\n /** The current revision's approval, while its latest answer is one. */\n approval?: QuoteApproval | null\n /** The revision the customer approved, when they have. */\n approvedRevision?: number | null\n /**\n * Which pay link opens the quote: a link signed for an older version shows\n * the customer that the quote was replaced, and nothing of it. Absent reads\n * as 1. Bumped when the business replaces the link.\n */\n linkVersion?: number\n /** The conversation its emails keep in the customer's mailbox (AGL-4097). */\n emailThread?: QuoteEmailThread | null\n /** Every time it was emailed to the customer, oldest first (AGL-4097). */\n sends?: QuoteSendRecord[]\n /**\n * The request it was started from (AGL-4098): a \"Request a quote\" form's\n * submission, by id. Its files are listed on the quote as the customer's\n * ({@link requestFiles}), and its confirmation's conversation is the\n * quote's {@link emailThread} until the quote is first sent.\n */\n request?: QuoteRequestRef | null\n /** The request's files, where the request keeps them; downloaded through the quote's own route. */\n requestFiles?: QuoteResponseFile[]\n /** When the customer paid it. */\n paidAtMs?: number\n /** Payments the quote could not take; see {@link QuoteUnmatchedPayment}. */\n unmatchedPayments?: QuoteUnmatchedPayment[]\n createdAtMs: number\n updatedAtMs: number\n /** Who created and last changed it: an email, else a uid. */\n createdBy: string\n updatedBy: string\n}\n\n/** The store-wide quote defaults, at `hosts/{hostId}/settings/store` under `quotes`. */\nexport interface QuoteStoreSettings {\n /** What `requireProofApproval` a new quote starts with. Absent reads as off. */\n requireProofApproval?: boolean\n}\n\n/** Whether new quotes start out asking the customer to approve the proof first. */\nexport function quoteRequiresProofApprovalByDefault(\n settings: QuoteStoreSettings | null | undefined,\n): boolean {\n return settings?.requireProofApproval === true\n}\n\n/**\n * Whether paying waits on the customer approving the proof: the quote asks for\n * approval, its current revision has a proof, and that revision is not the\n * one the customer approved. A revision with no proof never holds a payment.\n */\nexport function quotePaymentBlockedByApproval(\n quote:\n | (Pick<OrderQuote, 'requireProofApproval' | 'revision' | 'approvedRevision'> & {\n proofs?: readonly QuoteProofRef[]\n })\n | null\n | undefined,\n): boolean {\n if (!quote || quote.requireProofApproval !== true) return false\n const revision = Number(quote.revision ?? 1)\n const proofed = (quote.proofs ?? []).some((proof) => Number(proof?.revision) === revision)\n if (!proofed) return false\n return Number(quote.approvedRevision) !== revision\n}\n\n/** Whether an order document is a quote, paid or not. */\nexport function isQuote(order: Pick<Partial<HostOrder>, 'channel'> | null | undefined): boolean {\n return order?.channel === 'quote'\n}\n\n/** Whether an order document is a quote nobody has paid yet, which no order list counts. */\nexport function isUnpaidQuote(\n order: { channel?: unknown; status?: unknown } | null | undefined,\n): boolean {\n return order?.channel === 'quote' && order?.status === 'pending'\n}\n\n/** `Quote #1042`; an order number until it is paid. */\nexport function formatQuoteNumber(order: Pick<HostOrder, 'number'>, docId?: string): string {\n if (order.number != null) return `Quote #${order.number}`\n return docId ? `Quote #${docId.slice(-6).toUpperCase()}` : 'Quote'\n}\n\n/** A quote's status as its list shows it: its stage until it is paid. */\nexport function quoteDisplayStatus(order: {\n status?: OrderStatus | string\n quote?: Pick<OrderQuote, 'stage'> | null\n}): { key: QuoteStage | 'paid' | 'cancelled' | 'refunded'; label: string } {\n if (order.status === 'cancelled') return { key: 'cancelled', label: 'Canceled' }\n if (order.status === 'refunded') return { key: 'refunded', label: 'Refunded' }\n if (order.status && order.status !== 'pending') return { key: 'paid', label: 'Paid' }\n const stage = (order.quote?.stage ?? 'draft') as QuoteStage\n return { key: stage, label: QUOTE_STAGE_LABELS[stage] ?? QUOTE_STAGE_LABELS.draft }\n}\n\n/** Chip colors for {@link quoteDisplayStatus}, as the orders list colors its statuses. */\nexport const QUOTE_STATUS_COLOR: Record<\n ReturnType<typeof quoteDisplayStatus>['key'],\n 'default' | 'success' | 'info' | 'warning' | 'error'\n> = {\n draft: 'default',\n sent: 'info',\n changes_requested: 'warning',\n approved: 'info',\n paid: 'success',\n cancelled: 'default',\n refunded: 'error',\n}\n\n/*==========================================\n * TOTALS\n *=========================================*/\n\n/** A line as the totals read it. */\nexport type QuoteTotalsLine = Pick<OrderLineItem, 'unitAmountCents' | 'quantity'> & {\n included?: boolean\n taxExempt?: boolean\n}\n\nexport interface QuoteTotalsInput {\n lines: readonly QuoteTotalsLine[]\n discount?: QuoteDiscount | null\n shippingCents?: number\n tax: QuoteTaxBasis\n}\n\n/** A quote's totals: the order's, plus what the tax was computed on. */\nexport interface QuoteTotals extends OrderTotals {\n /** The taxable lines after their share of the discount. */\n taxableCents: number\n /** Stripe Tax works the tax out when the customer pays; `taxCents` is 0 until then. */\n taxAtPayment: boolean\n}\n\nconst whole = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/** One line's charge: nothing for an included line. */\nexport function quoteLineCents(line: QuoteTotalsLine): number {\n if (line.included) return 0\n return whole(line.unitAmountCents) * whole(line.quantity)\n}\n\n/** The discount in cents on `itemsCents`, never more than it. */\nexport function quoteDiscountCents(\n itemsCents: number,\n discount: QuoteDiscount | null | undefined,\n): number {\n const items = whole(itemsCents)\n if (!discount) return 0\n if (discount.kind === 'amount') return Math.min(items, whole(discount.amountCents))\n if (discount.kind !== 'percent') return 0\n const pct = Math.min(100, Math.max(0, Number(discount.pct) || 0))\n return Math.min(items, Math.round((items * pct) / 100))\n}\n\n/**\n * Each line's charge, its share of the discount (in proportion to the\n * charges, as a checkout spreads a coupon) and what is left: the amounts a tax\n * service is asked about, line by line.\n */\nexport function quoteLineAmounts(\n lines: readonly QuoteTotalsLine[],\n discount: QuoteDiscount | null | undefined,\n): { grossCents: number[]; discountCents: number[]; netCents: number[]; itemsCents: number; totalDiscountCents: number } {\n const grossCents = lines.map(quoteLineCents)\n const itemsCents = grossCents.reduce((sum, cents) => sum + cents, 0)\n const totalDiscountCents = quoteDiscountCents(itemsCents, discount)\n const discountCents = allocateCentsByWeight(totalDiscountCents, grossCents)\n return {\n grossCents,\n discountCents,\n netCents: grossCents.map((cents, index) => cents - discountCents[index]),\n itemsCents,\n totalDiscountCents,\n }\n}\n\n/**\n * A quote's totals. The discount comes off before tax; a store rate taxes the\n * taxable lines (not shipping, as a draft order's rate does); a tax service's\n * answer is taken as given; Stripe Tax and no-tax add nothing now.\n */\nexport function computeQuoteTotals(input: QuoteTotalsInput): QuoteTotals {\n const amounts = quoteLineAmounts(input.lines, input.discount)\n const taxableCents = amounts.netCents.reduce(\n (sum, cents, index) => sum + (input.lines[index]?.taxExempt ? 0 : cents),\n 0,\n )\n const shippingCents = whole(input.shippingCents)\n const tax = input.tax\n const taxCents =\n tax.kind === 'rate'\n ? computeTaxCents(taxableCents, Number(tax.pct) || 0)\n : tax.kind === 'service'\n ? whole(tax.taxCents)\n : 0\n return {\n itemsCents: amounts.itemsCents,\n discountCents: amounts.totalDiscountCents,\n shippingCents,\n taxCents,\n // The platform fee is set when a payment is created, from what it charges.\n feeCents: 0,\n totalCents: amounts.itemsCents - amounts.totalDiscountCents + shippingCents + taxCents,\n taxableCents,\n taxAtPayment: tax.kind === 'at-payment',\n }\n}\n\n/** The order totals a quote document stores. */\nexport function quoteOrderTotals(totals: QuoteTotals): OrderTotals {\n return {\n itemsCents: totals.itemsCents,\n discountCents: totals.discountCents,\n shippingCents: totals.shippingCents,\n taxCents: totals.taxCents,\n feeCents: totals.feeCents,\n totalCents: totals.totalCents,\n }\n}\n\n/*==========================================\n * TAX\n *=========================================*/\n\n/**\n * The tax basis the store's own settings give a quote, before any tax service\n * is asked: Stripe Tax at payment, no tax (and why), or the store's rate for\n * where the quote ships — its ship-to when it has a country, else the store's\n * own address, as the storefront taxes a sale it cannot see the destination of.\n */\nexport function quoteTaxBasisFromSettings(\n settings: TaxSettings | null | undefined,\n shipTo: Pick<OrderAddress, 'country' | 'state'> | null | undefined,\n): QuoteTaxBasis {\n const decision = storefrontTaxDecision({ settings })\n if (decision.kind === 'undecided') return { kind: 'none', reason: 'undecided' }\n if (decision.kind === 'stripe-automatic') return { kind: 'at-payment' }\n if (decision.kind !== 'manual') return { kind: 'none', reason: 'not-collected' }\n if (settings?.pricesIncludeTax) return { kind: 'none', reason: 'prices-include-tax' }\n const address = String(shipTo?.country ?? '').trim()\n ? { country: shipTo?.country, state: shipTo?.state }\n : (settings?.origin ?? {})\n const rate = resolveTaxRate(settings ?? undefined, address)\n if (!rate || !(Number(rate.pct) > 0)) return { kind: 'none', reason: 'no-rate' }\n return { kind: 'rate', pct: Number(rate.pct), ...(rate.label ? { label: rate.label } : {}) }\n}\n\n/** The tax line's label on a quote. */\nexport function describeQuoteTax(basis: QuoteTaxBasis | null | undefined): string {\n if (!basis) return 'Tax'\n switch (basis.kind) {\n case 'rate':\n return basis.label ? `${basis.label} (${basis.pct ?? 0}%)` : `Tax (${basis.pct ?? 0}%)`\n case 'service':\n return basis.providerLabel ? `Tax (${basis.providerLabel})` : 'Tax'\n case 'at-payment':\n return 'Tax is added at payment'\n case 'none':\n return basis.reason === 'prices-include-tax'\n ? 'Prices include tax'\n : basis.reason === 'no-rate'\n ? 'No tax rate for this address'\n : basis.reason === 'undecided'\n ? 'Sales tax is not set up'\n : 'No sales tax'\n default:\n return 'Tax'\n }\n}\n\n/** The order's `taxMode` for a quote's basis; absent while nobody has decided. */\nexport function quoteTaxMode(basis: QuoteTaxBasis, taxCents: number): StorefrontTaxMode | undefined {\n if (basis.kind === 'at-payment') return 'stripe-automatic'\n if (basis.kind === 'none' && basis.reason === 'undecided') return undefined\n return taxCents > 0 ? 'manual' : 'none'\n}\n\n/*==========================================\n * WHAT THE CONSOLE SENDS\n *=========================================*/\n\nexport const QUOTE_MAX_LINES = 100\nexport const QUOTE_MAX_QUANTITY = 9_999\n/** $1,000,000 a unit: the most a typed line may cost. */\nexport const QUOTE_MAX_UNIT_CENTS = 100_000_000\nexport const QUOTE_MAX_TEXT = 5_000\nconst SHORT_TEXT = 200\n\n/** A product line as the console asks for it: what it is, never what it costs. */\nexport interface QuoteCatalogLineRequest {\n kind: 'catalog'\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n included?: boolean\n description?: string\n}\n\n/** A line typed on the quote, which no product stands behind. */\nexport interface QuoteCustomLineRequest {\n kind: 'custom'\n name: string\n description?: string\n sku?: string\n unitAmountCents: number\n quantity: number\n /** Whether it is something to ship (else a service, which never ships). */\n ships?: boolean\n included?: boolean\n}\n\nexport type QuoteLineRequest = QuoteCatalogLineRequest | QuoteCustomLineRequest\n\n/** Everything a business edits on a quote. */\nexport interface QuoteInput {\n lines: QuoteLineRequest[]\n customer: QuoteCustomer\n billTo: OrderAddress | null\n shipTo: OrderAddress | null\n notes: string\n terms: string\n discount: QuoteDiscount | null\n shipping: QuoteShipping | null\n /** Absent: the store's default (on create) or unchanged (on update). */\n requireProofApproval?: boolean\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nconst clean = (value: unknown, max = SHORT_TEXT): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\nconst intIn = (value: unknown, min: number, max: number): number | null => {\n const number = Number(value)\n return Number.isInteger(number) && number >= min && number <= max ? number : null\n}\n\nfunction parseAddress(raw: unknown): OrderAddress | null {\n if (!raw || typeof raw !== 'object') return null\n const source = raw as Record<string, unknown>\n const address: OrderAddress = {}\n for (const key of ['name', 'line1', 'line2', 'city', 'state', 'postalCode', 'phone'] as const) {\n const value = clean(source[key])\n if (value) address[key] = value\n }\n const country = clean(source['country'], 2).toUpperCase()\n if (/^[A-Z]{2}$/.test(country)) address.country = country\n return Object.keys(address).length ? address : null\n}\n\nfunction parseLine(raw: unknown, index: number): QuoteLineRequest | string {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const at = `Line ${index + 1}`\n const quantity = intIn(source['quantity'], 1, QUOTE_MAX_QUANTITY)\n if (quantity === null) return `${at}: enter a quantity from 1 to ${QUOTE_MAX_QUANTITY.toLocaleString('en-US')}.`\n const included = source['included'] === true\n const description = clean(source['description'], QUOTE_MAX_TEXT)\n if (source['kind'] === 'catalog') {\n const productId = clean(source['productId'])\n if (!DOC_ID.test(productId)) return `${at}: choose a product.`\n const variantId = clean(source['variantId'])\n const modifiers = Array.isArray(source['modifiers'])\n ? (source['modifiers'] as unknown[]).slice(0, 200).map((entry) => {\n const pick = (entry ?? {}) as Record<string, unknown>\n return { groupId: clean(pick['groupId']), optionId: clean(pick['optionId']) }\n })\n : []\n return {\n kind: 'catalog',\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n ...(included ? { included } : {}),\n ...(description ? { description } : {}),\n }\n }\n if (source['kind'] === 'custom') {\n const name = clean(source['name'])\n if (!name) return `${at}: name the item.`\n const unitAmountCents = included ? 0 : intIn(source['unitAmountCents'], 0, QUOTE_MAX_UNIT_CENTS)\n if (unitAmountCents === null) return `${at}: enter a price from $0 to $1,000,000.`\n const sku = clean(source['sku'], 100)\n return {\n kind: 'custom',\n name,\n ...(description ? { description } : {}),\n ...(sku ? { sku } : {}),\n unitAmountCents,\n quantity,\n ships: source['ships'] !== false,\n ...(included ? { included } : {}),\n }\n }\n return `${at}: add a product or type an item.`\n}\n\n/**\n * The console's quote, checked and trimmed, or what to fix. Prices on product\n * lines are not read from here: the server prices them from the product.\n */\nexport function parseQuoteInput(raw: unknown): { ok: true; input: QuoteInput } | { ok: false; error: string } {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const rawLines = Array.isArray(source['lines']) ? (source['lines'] as unknown[]) : []\n if (rawLines.length === 0) return { ok: false, error: 'Add at least one line to the quote.' }\n if (rawLines.length > QUOTE_MAX_LINES) {\n return { ok: false, error: `A quote holds up to ${QUOTE_MAX_LINES} lines.` }\n }\n const lines: QuoteLineRequest[] = []\n for (const [index, entry] of rawLines.entries()) {\n const line = parseLine(entry, index)\n if (typeof line === 'string') return { ok: false, error: line }\n lines.push(line)\n }\n\n const customerSource = (source['customer'] && typeof source['customer'] === 'object'\n ? source['customer']\n : {}) as Record<string, unknown>\n const email = clean(customerSource['email'])\n if (email && !EMAIL.test(email)) return { ok: false, error: 'Enter a valid email for the customer.' }\n const recordSource = (customerSource['record'] ?? null) as Record<string, unknown> | null\n const recordKind = clean(recordSource?.['kind'], 40)\n const recordId = clean(recordSource?.['id'])\n const customer: QuoteCustomer = {\n ...(recordKind && DOC_ID.test(recordId) ? { record: { kind: recordKind, id: recordId } } : {}),\n ...(clean(customerSource['name']) ? { name: clean(customerSource['name']) } : {}),\n ...(clean(customerSource['company']) ? { company: clean(customerSource['company']) } : {}),\n ...(email ? { email, emailLower: email.toLowerCase() } : {}),\n ...(clean(customerSource['phone'], 40) ? { phone: clean(customerSource['phone'], 40) } : {}),\n }\n\n let discount: QuoteDiscount | null = null\n const discountSource = (source['discount'] ?? null) as Record<string, unknown> | null\n if (discountSource?.['kind'] === 'amount') {\n const amountCents = intIn(discountSource['amountCents'], 0, QUOTE_MAX_UNIT_CENTS)\n if (amountCents === null) return { ok: false, error: 'Enter a discount from $0 to $1,000,000.' }\n if (amountCents > 0) discount = { kind: 'amount', amountCents }\n } else if (discountSource?.['kind'] === 'percent') {\n const pct = Number(discountSource['pct'])\n if (!Number.isFinite(pct) || pct < 0 || pct > 100) {\n return { ok: false, error: 'Enter a discount from 0% to 100%.' }\n }\n if (pct > 0) discount = { kind: 'percent', pct: Math.round(pct * 100) / 100 }\n }\n\n let shipping: QuoteShipping | null = null\n const shippingSource = (source['shipping'] ?? null) as Record<string, unknown> | null\n if (shippingSource) {\n const amountCents = intIn(shippingSource['amountCents'], 0, QUOTE_MAX_UNIT_CENTS)\n if (amountCents === null) return { ok: false, error: 'Enter shipping from $0 to $1,000,000.' }\n shipping = { amountCents }\n }\n\n return {\n ok: true,\n input: {\n lines,\n customer,\n billTo: parseAddress(source['billTo']),\n shipTo: parseAddress(source['shipTo']),\n notes: clean(source['notes'], QUOTE_MAX_TEXT),\n terms: clean(source['terms'], QUOTE_MAX_TEXT),\n discount,\n shipping,\n ...(typeof source['requireProofApproval'] === 'boolean'\n ? { requireProofApproval: source['requireProofApproval'] }\n : {}),\n },\n }\n}\n\n/** A priced quote line, and whether its product is tax-exempt. */\nexport type PricedQuoteLine = OrderLineItem & { taxExempt?: boolean }\n\n/** The variant's label as order lines print it: its option values, or nothing for a default. */\nfunction variantOptionsLabel(options: Record<string, string> | undefined): string | undefined {\n return options && Object.keys(options).length ? Object.values(options).join(' / ') : undefined\n}\n\n/**\n * A product line priced from the PRODUCT: its variant's price plus the chosen\n * add-ons, as the register prices one. An included line keeps what it is and\n * charges nothing.\n */\nexport function priceQuoteCatalogLine(\n rawProduct: Partial<HostProduct> | null | undefined,\n request: QuoteCatalogLineRequest,\n): { ok: true; line: PricedQuoteLine } | { ok: false; error: string } {\n if (!rawProduct || rawProduct.deletedAt) {\n return { ok: false, error: 'A product on this quote no longer exists. Remove it and add it again.' }\n }\n const product = liftLegacyProduct(rawProduct)\n const variant = request.variantId\n ? product.variants.find((entry) => entry.id === request.variantId)\n : product.variants[0]\n if (!variant) return { ok: false, error: `Choose an option of ${product.name} that still exists.` }\n if (!request.included && !variantHasPrice(variant)) {\n return { ok: false, error: `Set a price for ${product.name} before quoting it.` }\n }\n const chosen = resolveLineModifiers(product, request.modifiers, variant.id)\n if (!chosen.ok) return { ok: false, error: chosen.error ?? `Check the choices on ${product.name}.` }\n const variantLabel = lineLabelWithModifiers(variantOptionsLabel(variant.options), chosen.modifiers)\n return {\n ok: true,\n line: {\n productId: request.productId,\n ...(variant.id !== 'default' ? { variantId: variant.id } : {}),\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: (product.type ?? 'physical') as ProductType,\n quantity: request.quantity,\n unitAmountCents: request.included\n ? 0\n : Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(chosen.modifiers.length ? { modifiers: chosen.modifiers } : {}),\n ...(request.included ? { included: true } : {}),\n ...(request.description ? { description: request.description } : {}),\n ...(product.taxExempt ? { taxExempt: true } : {}),\n },\n }\n}\n\n/** A typed line: no product, so nothing reads stock, a supplier or a download for it. */\nexport function priceQuoteCustomLine(request: QuoteCustomLineRequest): PricedQuoteLine {\n return {\n productId: '',\n custom: true,\n name: request.name,\n ...(request.sku ? { sku: request.sku } : {}),\n productType: request.ships === false ? 'service' : 'physical',\n quantity: request.quantity,\n unitAmountCents: request.included ? 0 : request.unitAmountCents,\n ...(request.included ? { included: true } : {}),\n ...(request.description ? { description: request.description } : {}),\n }\n}\n\n/** The request a stored line is edited as: what the console sends back on a save. */\nexport function quoteLineRequestFromLine(line: OrderLineItem): QuoteLineRequest {\n if (line.custom || !line.productId) {\n return {\n kind: 'custom',\n name: line.name,\n ...(line.description ? { description: line.description } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n unitAmountCents: line.unitAmountCents,\n quantity: line.quantity,\n ships: line.productType !== 'service' && line.productType !== 'digital',\n ...(line.included ? { included: true } : {}),\n }\n }\n return {\n kind: 'catalog',\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n quantity: line.quantity,\n ...(line.modifiers?.length\n ? { modifiers: line.modifiers.map(({ groupId, optionId }) => ({ groupId, optionId })) }\n : {}),\n ...(line.included ? { included: true } : {}),\n ...(line.description ? { description: line.description } : {}),\n }\n}\n"],"names":["liftLegacyProduct","variantHasPrice","computeTaxCents","resolveTaxRate","storefrontTaxDecision","allocateCentsByWeight","lineLabelWithModifiers","resolveLineModifiers","QUOTE_STAGE_LABELS","draft","sent","changes_requested","approved","quoteRequiresProofApprovalByDefault","settings","requireProofApproval","quotePaymentBlockedByApproval","quote","revision","Number","proofed","proofs","some","proof","approvedRevision","isQuote","order","channel","isUnpaidQuote","status","formatQuoteNumber","docId","number","slice","toUpperCase","quoteDisplayStatus","key","label","stage","QUOTE_STATUS_COLOR","paid","cancelled","refunded","whole","value","Math","round","isFinite","quoteLineCents","line","included","unitAmountCents","quantity","quoteDiscountCents","itemsCents","discount","items","kind","min","amountCents","pct","max","quoteLineAmounts","lines","grossCents","map","reduce","sum","cents","totalDiscountCents","discountCents","netCents","index","computeQuoteTotals","input","amounts","taxableCents","taxExempt","shippingCents","tax","taxCents","feeCents","totalCents","taxAtPayment","quoteOrderTotals","totals","quoteTaxBasisFromSettings","shipTo","decision","reason","pricesIncludeTax","address","String","country","trim","state","origin","rate","undefined","describeQuoteTax","basis","providerLabel","quoteTaxMode","QUOTE_MAX_LINES","QUOTE_MAX_QUANTITY","QUOTE_MAX_UNIT_CENTS","QUOTE_MAX_TEXT","SHORT_TEXT","EMAIL","DOC_ID","clean","intIn","isInteger","parseAddress","raw","source","test","Object","keys","length","parseLine","at","toLocaleString","description","productId","variantId","modifiers","Array","isArray","entry","pick","groupId","optionId","name","sku","ships","parseQuoteInput","customerSource","rawLines","ok","error","entries","push","email","recordSource","recordKind","recordId","customer","record","id","company","emailLower","toLowerCase","phone","discountSource","shipping","shippingSource","billTo","notes","terms","variantOptionsLabel","options","values","join","priceQuoteCatalogLine","rawProduct","request","chosen","product","deletedAt","variant","variants","find","variantLabel","productType","type","priceUsd","extraCents","priceQuoteCustomLine","custom","quoteLineRequestFromLine"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SAASA,iBAAiB,EAAEC,eAAe,QAAQ,gBAAY;AAQ/D,SAASC,eAAe,EAAEC,cAAc,QAA0B,oBAAgB;AAClF,SAASC,qBAAqB,QAAgC,6BAAyB;AACvF,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SACEC,sBAAsB,EACtBC,oBAAoB,QAEf,yBAAqB;AAiC5B,OAAO,MAAMC,qBAAiD;IAC5DC,OAAO;IACPC,MAAM;IACNC,mBAAmB;IACnBC,UAAU;AACZ,EAAC;AAoQD,iFAAiF,GACjF,OAAO,SAASC,oCACdC,QAA+C;IAE/C,OAAOA,CAAAA,4BAAAA,SAAUC,oBAAoB,MAAK;AAC5C;AAEA;;;;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ACDnF,KAAKC,QAAQ,GAAG;QAAEA,UAAU;IAAK,IAAI,CAAC,GACtCD,KAAK0E,WAAW,GAAG;QAAEA,aAAa1E,KAAK0E,WAAW;IAAC,IAAI,CAAC;AAEhE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quotes.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 type { HostProduct, ProductType } from './commerce'\nimport type { QuoteRequestRef } from './commerce-quote-request'\nimport { liftLegacyProduct, variantHasPrice } from './commerce'\nimport type {\n HostOrder,\n OrderAddress,\n OrderLineItem,\n OrderStatus,\n OrderTotals,\n} from './commerce-orders'\nimport { computeTaxCents, resolveTaxRate, type TaxSettings } from './commerce-tax'\nimport { storefrontTaxDecision, type StorefrontTaxMode } from './commerce-tax-decision'\nimport { allocateCentsByWeight } from './commerce-tax-engine'\nimport {\n lineLabelWithModifiers,\n resolveLineModifiers,\n type ModifierSelection,\n} from './product-modifiers'\n\n/*==========================================\n * QUOTES (AGL-4093).\n *\n * A quote is an order that has not been paid yet: a document in\n * `hosts/{hostId}/orders` with `channel: 'quote'`, `status: 'pending'` and a\n * `quote` section holding what only a quote has (the customer it is for, its\n * notes and terms, its discount and shipping, where it stands with the\n * business). Its `number` comes from the store's order counter, so the quote\n * and the order it becomes are one number and one document: paying it flips\n * `status` the way a paid draft order flips.\n *\n * WHAT KEEPS AN UNPAID QUOTE OUT OF EVERY ORDER LIST. A quote document\n * carries none of the fields the order readers ask their queries about:\n * no `createdAtMs` (the Orders list, its filters, the money tiles, the\n * analytics, the exports and the reports all order or range on it), none of\n * the list fields `withOrderListFields` stamps (`customerEmailLower`, the\n * search tokens, `requiresShipping`, `productIds`), and no top-level\n * `customerEmail`, `shippingAddress` or `billingAddress` (the customer's\n * account page, gated content and reviews look orders up by the buyer's\n * address). The customer lives in `quote.customer` until the quote is paid,\n * and whatever pays it writes those order fields then. `isUnpaidQuote` is the\n * test for the few readers that reach orders some other way (by number, by\n * document id, or by a header sort on `status`, `channel` or `number`).\n *\n * Pure: the console's live totals, the server's stored totals, and later the\n * quote's PDF and pay page all come from `computeQuoteTotals`.\n *=========================================*/\n\n/** Where a quote stands with the business. The customer side has no states. */\nexport type QuoteStage = 'draft' | 'sent' | 'changes_requested' | 'approved'\n\nexport const QUOTE_STAGE_LABELS: Record<QuoteStage, string> = {\n draft: 'Draft',\n sent: 'Sent',\n changes_requested: 'Changes requested',\n approved: 'Approved',\n}\n\n/** The person a quote is for: a record the workspace keeps, typed details, or both. */\nexport interface QuoteCustomer {\n /** The person record, as the person-records seam names it (`contact`, …). */\n record?: { kind: string; id: string } | null\n name?: string\n company?: string\n email?: string\n /** `email` lower-cased: what a person erasure finds the quote by. */\n emailLower?: string\n phone?: string\n}\n\n/** Money off the whole quote: an amount, or a percentage of the charged lines. */\nexport interface QuoteDiscount {\n kind: 'amount' | 'percent'\n /** With `amount`: the cents off. */\n amountCents?: number\n /** With `percent`: the percentage off. */\n pct?: number\n}\n\n/** Shipping the business prices by hand. */\nexport interface QuoteShipping {\n amountCents: number\n}\n\n/** Why a quote carries no tax. */\nexport type QuoteNoTaxReason =\n | 'not-collected'\n | 'prices-include-tax'\n | 'no-rate'\n | 'undecided'\n\n/** Where a quote's tax comes from. */\nexport type QuoteTaxKind = 'rate' | 'service' | 'at-payment' | 'none'\n\n/**\n * How a quote's tax was worked out, stored beside the figure so the quote can\n * say it: one of the store's own rates (`rate`, with `pct` and its `label`),\n * its connected tax service's answer (`service`, with `taxCents` and\n * `providerLabel`), Stripe Tax at payment (`at-payment`), or no tax and why\n * (`none`, with `reason`). One flat shape, so the apps can read it as is.\n */\nexport interface QuoteTaxBasis {\n kind: QuoteTaxKind\n pct?: number\n label?: string\n taxCents?: number\n providerLabel?: string\n reason?: QuoteNoTaxReason\n}\n\n/** A proof attached to one revision of a quote: what names it, and the revision it is for. */\nexport interface QuoteProofRef {\n id: string\n revision: number\n}\n\n/**\n * A proof the business attached to a revision (AGL-4096): an image or a\n * design file in the site's private storage, under the quote.\n */\nexport interface QuoteProof extends QuoteProofRef {\n name: string\n contentType: string\n size: number\n /** The private Storage object. Never sent to the customer. */\n path: string\n addedAtMs: number\n /** Who attached it: an email, else a uid. */\n addedBy: string\n}\n\n/** A file the customer sent with a response. */\nexport interface QuoteResponseFile {\n id: string\n name: string\n contentType: string\n size: number\n /** The private Storage object. Never sent to the customer. */\n path: string\n}\n\n/**\n * The customer's answer to a revision's proofs (AGL-4096): approved under a\n * typed name, or changes asked for in a comment, with artwork if they had\n * some. The address and browser are kept as the record of who answered.\n */\nexport interface QuoteCustomerResponse {\n action: 'approve' | 'changes'\n revision: number\n atMs: number\n /** With `approve`: the name they typed. */\n name?: string\n /** With `changes`: what to change. */\n comment?: string\n /** With `changes`: files they sent. */\n files?: QuoteResponseFile[]\n ip: string | null\n userAgent: string | null\n}\n\n/** The record of a revision's approval. */\nexport interface QuoteApproval {\n revision: number\n name: string\n atMs: number\n ip: string | null\n userAgent: string | null\n}\n\n/**\n * A payment that reached a quote it could not pay: one made through a pay\n * link the business replaced or for a price it has since changed\n * (`superseded`), or one made after the quote was already paid\n * (`already-paid`). The money is in Stripe and the quote records no sale for\n * it; the business refunds it or reconciles it by hand.\n */\nexport interface QuoteUnmatchedPayment {\n sessionId: string\n paymentIntentId: string | null\n amountCents: number\n atMs: number\n reason: 'superseded' | 'already-paid'\n}\n\n/**\n * The conversation the quote's emails keep in the customer's mailbox\n * (AGL-4097): the latest message's `Message-ID`, every id in the\n * conversation oldest first, and the subject it runs under. The shape of\n * `EmailThread` (`@aglyn/shared-util-email`), spelled out so the model needs\n * no email library. Started by the first email about the quote (a request's\n * confirmation, or the quote itself); every later one replies into it.\n */\nexport interface QuoteEmailThread {\n messageId: string\n references: string[]\n subject: string\n}\n\n/** One time the quote was emailed to the customer (AGL-4097). */\nexport interface QuoteSendRecord {\n /** The revision the email carried. */\n revision: number\n to: string\n subject: string\n atMs: number\n /** Who sent it: an email, else a uid. */\n by: string\n /** The `Message-ID` the email was sent with. */\n messageId: string\n /** The mail provider's own id for the message, when it answered one. */\n providerId: string | null\n /** The pay link version the email carried. */\n linkVersion: number\n}\n\n/** One shipping rate a draft order offered (AGL-4099), as checkout's resolved rates name it. */\nexport interface OrderDraftShippingRate {\n rateId: string\n name: string\n amountCents: number\n}\n\n/** The shipping a draft order offered when it was made (AGL-4099); see `HostOrder.draftShipping`. */\nexport interface OrderDraftShipping {\n /** Where its rates ship; empty when it offers none. */\n countries: string[]\n /** The rates the buyer picks from at payment; empty when it ships nothing. */\n options: OrderDraftShippingRate[]\n}\n\n/** The lasting pay link of an order that is not a quote (AGL-4099); see `HostOrder.payLink`. */\nexport interface OrderPayLink {\n /** The link's version, absent reading as 1. */\n version?: number\n /** Payments through the link the order could not take, as a quote records them. */\n unmatchedPayments?: QuoteUnmatchedPayment[]\n}\n\n/** One time an order's (or a quote's) invoice was emailed to the customer (AGL-4099). */\nexport interface OrderInvoiceSendRecord {\n to: string\n subject: string\n atMs: number\n /** Who sent it: an email, else a uid. */\n by: string\n /** The `Message-ID` the email was sent with. */\n messageId: string\n /** The mail provider's own id for the message, when it answered one. */\n providerId: string | null\n /** The invoice said it was paid (the record), rather than asking for payment. */\n paid: boolean\n /** The pay link version an unpaid invoice carried; null on a paid one. */\n linkVersion: number | null\n /** The total the invoice showed. */\n totalCents: number\n}\n\n/** What only a quote has, on its order document. */\nexport interface OrderQuote {\n stage: QuoteStage\n /** Which version of the quote this is; versions are what proofs and approvals name. */\n revision: number\n customer: QuoteCustomer\n billTo?: OrderAddress | null\n shipTo?: OrderAddress | null\n notes?: string\n terms?: string\n discount?: QuoteDiscount | null\n shipping?: QuoteShipping | null\n tax: QuoteTaxBasis\n /** The customer approves the current revision's proof before they can pay. Absent reads as off. */\n requireProofApproval?: boolean\n /** The current revision's proofs; earlier revisions keep theirs in `revisions/{n}`. */\n proofs?: QuoteProof[]\n /** The customer's answers to the current revision, oldest first; the last one counts. */\n responses?: QuoteCustomerResponse[]\n /** The current revision's approval, while its latest answer is one. */\n approval?: QuoteApproval | null\n /** The revision the customer approved, when they have. */\n approvedRevision?: number | null\n /**\n * Which pay link opens the quote: a link signed for an older version shows\n * the customer that the quote was replaced, and nothing of it. Absent reads\n * as 1. Bumped when the business replaces the link.\n */\n linkVersion?: number\n /** The conversation its emails keep in the customer's mailbox (AGL-4097). */\n emailThread?: QuoteEmailThread | null\n /** Every time it was emailed to the customer, oldest first (AGL-4097). */\n sends?: QuoteSendRecord[]\n /**\n * The request it was started from (AGL-4098): a \"Request a quote\" form's\n * submission, by id. Its files are listed on the quote as the customer's\n * ({@link requestFiles}), and its confirmation's conversation is the\n * quote's {@link emailThread} until the quote is first sent.\n */\n request?: QuoteRequestRef | null\n /** The request's files, where the request keeps them; downloaded through the quote's own route. */\n requestFiles?: QuoteResponseFile[]\n /** When the customer paid it. */\n paidAtMs?: number\n /** Payments the quote could not take; see {@link QuoteUnmatchedPayment}. */\n unmatchedPayments?: QuoteUnmatchedPayment[]\n createdAtMs: number\n updatedAtMs: number\n /** Who created and last changed it: an email, else a uid. */\n createdBy: string\n updatedBy: string\n}\n\n/** The store-wide quote defaults, at `hosts/{hostId}/settings/store` under `quotes`. */\nexport interface QuoteStoreSettings {\n /** What `requireProofApproval` a new quote starts with. Absent reads as off. */\n requireProofApproval?: boolean\n}\n\n/** Whether new quotes start out asking the customer to approve the proof first. */\nexport function quoteRequiresProofApprovalByDefault(\n settings: QuoteStoreSettings | null | undefined,\n): boolean {\n return settings?.requireProofApproval === true\n}\n\n/**\n * Whether paying waits on the customer approving the proof: the quote asks for\n * approval, its current revision has a proof, and that revision is not the\n * one the customer approved. A revision with no proof never holds a payment.\n */\nexport function quotePaymentBlockedByApproval(\n quote:\n | (Pick<OrderQuote, 'requireProofApproval' | 'revision' | 'approvedRevision'> & {\n proofs?: readonly QuoteProofRef[]\n })\n | null\n | undefined,\n): boolean {\n if (!quote || quote.requireProofApproval !== true) return false\n const revision = Number(quote.revision ?? 1)\n const proofed = (quote.proofs ?? []).some((proof) => Number(proof?.revision) === revision)\n if (!proofed) return false\n return Number(quote.approvedRevision) !== revision\n}\n\n/** Whether an order document is a quote, paid or not. */\nexport function isQuote(order: Pick<Partial<HostOrder>, 'channel'> | null | undefined): boolean {\n return order?.channel === 'quote'\n}\n\n/** Whether an order document is a quote nobody has paid yet, which no order list counts. */\nexport function isUnpaidQuote(\n order: { channel?: unknown; status?: unknown } | null | undefined,\n): boolean {\n return order?.channel === 'quote' && order?.status === 'pending'\n}\n\n/** `Quote #1042`; an order number until it is paid. */\nexport function formatQuoteNumber(order: Pick<HostOrder, 'number'>, docId?: string): string {\n if (order.number != null) return `Quote #${order.number}`\n return docId ? `Quote #${docId.slice(-6).toUpperCase()}` : 'Quote'\n}\n\n/**\n * Whether a quote is PROOF ONLY (AGL-4184): it has no lines, so it shows its\n * customer a proof to answer and no price. A design proof often goes out before\n * pricing. This is read off the lines rather than stored, so there is nothing\n * to switch: the save that adds a line makes it a normal quote, and removing\n * every line from a quote with a proof makes it proof only again.\n *\n * Only a stored quote says this, one whose lines are an empty list. Pass a quote.\n */\nexport function quoteIsProofOnly(order: Partial<Pick<HostOrder, 'lineItems'>> | null | undefined): boolean {\n return Array.isArray(order?.lineItems) && order.lineItems.length === 0\n}\n\n/** `Proof #1042`: {@link formatQuoteNumber} for a proof only quote. */\nexport function formatProofNumber(order: Pick<HostOrder, 'number'>, docId?: string): string {\n return formatQuoteNumber(order, docId).replace(/^Quote\\b/, 'Proof')\n}\n\n/** A quote's status as its list shows it: its stage until it is paid. */\nexport function quoteDisplayStatus(order: {\n status?: OrderStatus | string\n quote?: Pick<OrderQuote, 'stage'> | null\n}): { key: QuoteStage | 'paid' | 'cancelled' | 'refunded'; label: string } {\n if (order.status === 'cancelled') return { key: 'cancelled', label: 'Canceled' }\n if (order.status === 'refunded') return { key: 'refunded', label: 'Refunded' }\n if (order.status && order.status !== 'pending') return { key: 'paid', label: 'Paid' }\n const stage = (order.quote?.stage ?? 'draft') as QuoteStage\n return { key: stage, label: QUOTE_STAGE_LABELS[stage] ?? QUOTE_STAGE_LABELS.draft }\n}\n\n/** Chip colors for {@link quoteDisplayStatus}, as the orders list colors its statuses. */\nexport const QUOTE_STATUS_COLOR: Record<\n ReturnType<typeof quoteDisplayStatus>['key'],\n 'default' | 'success' | 'info' | 'warning' | 'error'\n> = {\n draft: 'default',\n sent: 'info',\n changes_requested: 'warning',\n approved: 'info',\n paid: 'success',\n cancelled: 'default',\n refunded: 'error',\n}\n\n/*==========================================\n * TOTALS\n *=========================================*/\n\n/** A line as the totals read it. */\nexport type QuoteTotalsLine = Pick<OrderLineItem, 'unitAmountCents' | 'quantity'> & {\n included?: boolean\n taxExempt?: boolean\n}\n\nexport interface QuoteTotalsInput {\n lines: readonly QuoteTotalsLine[]\n discount?: QuoteDiscount | null\n shippingCents?: number\n tax: QuoteTaxBasis\n}\n\n/** A quote's totals: the order's, plus what the tax was computed on. */\nexport interface QuoteTotals extends OrderTotals {\n /** The taxable lines after their share of the discount. */\n taxableCents: number\n /** Stripe Tax works the tax out when the customer pays; `taxCents` is 0 until then. */\n taxAtPayment: boolean\n}\n\nconst whole = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/** One line's charge: nothing for an included line. */\nexport function quoteLineCents(line: QuoteTotalsLine): number {\n if (line.included) return 0\n return whole(line.unitAmountCents) * whole(line.quantity)\n}\n\n/** The discount in cents on `itemsCents`, never more than it. */\nexport function quoteDiscountCents(\n itemsCents: number,\n discount: QuoteDiscount | null | undefined,\n): number {\n const items = whole(itemsCents)\n if (!discount) return 0\n if (discount.kind === 'amount') return Math.min(items, whole(discount.amountCents))\n if (discount.kind !== 'percent') return 0\n const pct = Math.min(100, Math.max(0, Number(discount.pct) || 0))\n return Math.min(items, Math.round((items * pct) / 100))\n}\n\n/**\n * Each line's charge, its share of the discount (in proportion to the\n * charges, as a checkout spreads a coupon) and what is left: the amounts a tax\n * service is asked about, line by line.\n */\nexport function quoteLineAmounts(\n lines: readonly QuoteTotalsLine[],\n discount: QuoteDiscount | null | undefined,\n): { grossCents: number[]; discountCents: number[]; netCents: number[]; itemsCents: number; totalDiscountCents: number } {\n const grossCents = lines.map(quoteLineCents)\n const itemsCents = grossCents.reduce((sum, cents) => sum + cents, 0)\n const totalDiscountCents = quoteDiscountCents(itemsCents, discount)\n const discountCents = allocateCentsByWeight(totalDiscountCents, grossCents)\n return {\n grossCents,\n discountCents,\n netCents: grossCents.map((cents, index) => cents - discountCents[index]),\n itemsCents,\n totalDiscountCents,\n }\n}\n\n/**\n * A quote's totals. The discount comes off before tax; a store rate taxes the\n * taxable lines (not shipping, as a draft order's rate does); a tax service's\n * answer is taken as given; Stripe Tax and no-tax add nothing now.\n */\nexport function computeQuoteTotals(input: QuoteTotalsInput): QuoteTotals {\n const amounts = quoteLineAmounts(input.lines, input.discount)\n const taxableCents = amounts.netCents.reduce(\n (sum, cents, index) => sum + (input.lines[index]?.taxExempt ? 0 : cents),\n 0,\n )\n const shippingCents = whole(input.shippingCents)\n const tax = input.tax\n const taxCents =\n tax.kind === 'rate'\n ? computeTaxCents(taxableCents, Number(tax.pct) || 0)\n : tax.kind === 'service'\n ? whole(tax.taxCents)\n : 0\n return {\n itemsCents: amounts.itemsCents,\n discountCents: amounts.totalDiscountCents,\n shippingCents,\n taxCents,\n // The platform fee is set when a payment is created, from what it charges.\n feeCents: 0,\n totalCents: amounts.itemsCents - amounts.totalDiscountCents + shippingCents + taxCents,\n taxableCents,\n taxAtPayment: tax.kind === 'at-payment',\n }\n}\n\n/** The order totals a quote document stores. */\nexport function quoteOrderTotals(totals: QuoteTotals): OrderTotals {\n return {\n itemsCents: totals.itemsCents,\n discountCents: totals.discountCents,\n shippingCents: totals.shippingCents,\n taxCents: totals.taxCents,\n feeCents: totals.feeCents,\n totalCents: totals.totalCents,\n }\n}\n\n/*==========================================\n * TAX\n *=========================================*/\n\n/**\n * The tax basis the store's own settings give a quote, before any tax service\n * is asked: Stripe Tax at payment, no tax (and why), or the store's rate for\n * where the quote ships — its ship-to when it has a country, else the store's\n * own address, as the storefront taxes a sale it cannot see the destination of.\n */\nexport function quoteTaxBasisFromSettings(\n settings: TaxSettings | null | undefined,\n shipTo: Pick<OrderAddress, 'country' | 'state'> | null | undefined,\n): QuoteTaxBasis {\n const decision = storefrontTaxDecision({ settings })\n if (decision.kind === 'undecided') return { kind: 'none', reason: 'undecided' }\n if (decision.kind === 'stripe-automatic') return { kind: 'at-payment' }\n if (decision.kind !== 'manual') return { kind: 'none', reason: 'not-collected' }\n if (settings?.pricesIncludeTax) return { kind: 'none', reason: 'prices-include-tax' }\n const address = String(shipTo?.country ?? '').trim()\n ? { country: shipTo?.country, state: shipTo?.state }\n : (settings?.origin ?? {})\n const rate = resolveTaxRate(settings ?? undefined, address)\n if (!rate || !(Number(rate.pct) > 0)) return { kind: 'none', reason: 'no-rate' }\n return { kind: 'rate', pct: Number(rate.pct), ...(rate.label ? { label: rate.label } : {}) }\n}\n\n/** The tax line's label on a quote. */\nexport function describeQuoteTax(basis: QuoteTaxBasis | null | undefined): string {\n if (!basis) return 'Tax'\n switch (basis.kind) {\n case 'rate':\n return basis.label ? `${basis.label} (${basis.pct ?? 0}%)` : `Tax (${basis.pct ?? 0}%)`\n case 'service':\n return basis.providerLabel ? `Tax (${basis.providerLabel})` : 'Tax'\n case 'at-payment':\n return 'Tax is added at payment'\n case 'none':\n return basis.reason === 'prices-include-tax'\n ? 'Prices include tax'\n : basis.reason === 'no-rate'\n ? 'No tax rate for this address'\n : basis.reason === 'undecided'\n ? 'Sales tax is not set up'\n : 'No sales tax'\n default:\n return 'Tax'\n }\n}\n\n/** The order's `taxMode` for a quote's basis; absent while nobody has decided. */\nexport function quoteTaxMode(basis: QuoteTaxBasis, taxCents: number): StorefrontTaxMode | undefined {\n if (basis.kind === 'at-payment') return 'stripe-automatic'\n if (basis.kind === 'none' && basis.reason === 'undecided') return undefined\n return taxCents > 0 ? 'manual' : 'none'\n}\n\n/*==========================================\n * WHAT THE CONSOLE SENDS\n *=========================================*/\n\nexport const QUOTE_MAX_LINES = 100\nexport const QUOTE_MAX_QUANTITY = 9_999\n/** $1,000,000 a unit: the most a typed line may cost. */\nexport const QUOTE_MAX_UNIT_CENTS = 100_000_000\nexport const QUOTE_MAX_TEXT = 5_000\nconst SHORT_TEXT = 200\n\n/** A product line as the console asks for it: what it is, never what it costs. */\nexport interface QuoteCatalogLineRequest {\n kind: 'catalog'\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n included?: boolean\n description?: string\n}\n\n/** A line typed on the quote, which no product stands behind. */\nexport interface QuoteCustomLineRequest {\n kind: 'custom'\n name: string\n description?: string\n sku?: string\n unitAmountCents: number\n quantity: number\n /** Whether it is something to ship (else a service, which never ships). */\n ships?: boolean\n included?: boolean\n}\n\nexport type QuoteLineRequest = QuoteCatalogLineRequest | QuoteCustomLineRequest\n\n/** Everything a business edits on a quote. */\nexport interface QuoteInput {\n lines: QuoteLineRequest[]\n customer: QuoteCustomer\n billTo: OrderAddress | null\n shipTo: OrderAddress | null\n notes: string\n terms: string\n discount: QuoteDiscount | null\n shipping: QuoteShipping | null\n /** Absent: the store's default (on create) or unchanged (on update). */\n requireProofApproval?: boolean\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nconst clean = (value: unknown, max = SHORT_TEXT): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\nconst intIn = (value: unknown, min: number, max: number): number | null => {\n const number = Number(value)\n return Number.isInteger(number) && number >= min && number <= max ? number : null\n}\n\nfunction parseAddress(raw: unknown): OrderAddress | null {\n if (!raw || typeof raw !== 'object') return null\n const source = raw as Record<string, unknown>\n const address: OrderAddress = {}\n for (const key of ['name', 'line1', 'line2', 'city', 'state', 'postalCode', 'phone'] as const) {\n const value = clean(source[key])\n if (value) address[key] = value\n }\n const country = clean(source['country'], 2).toUpperCase()\n if (/^[A-Z]{2}$/.test(country)) address.country = country\n return Object.keys(address).length ? address : null\n}\n\nfunction parseLine(raw: unknown, index: number): QuoteLineRequest | string {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const at = `Line ${index + 1}`\n const quantity = intIn(source['quantity'], 1, QUOTE_MAX_QUANTITY)\n if (quantity === null) return `${at}: enter a quantity from 1 to ${QUOTE_MAX_QUANTITY.toLocaleString('en-US')}.`\n const included = source['included'] === true\n const description = clean(source['description'], QUOTE_MAX_TEXT)\n if (source['kind'] === 'catalog') {\n const productId = clean(source['productId'])\n if (!DOC_ID.test(productId)) return `${at}: choose a product.`\n const variantId = clean(source['variantId'])\n const modifiers = Array.isArray(source['modifiers'])\n ? (source['modifiers'] as unknown[]).slice(0, 200).map((entry) => {\n const pick = (entry ?? {}) as Record<string, unknown>\n return { groupId: clean(pick['groupId']), optionId: clean(pick['optionId']) }\n })\n : []\n return {\n kind: 'catalog',\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n ...(included ? { included } : {}),\n ...(description ? { description } : {}),\n }\n }\n if (source['kind'] === 'custom') {\n const name = clean(source['name'])\n if (!name) return `${at}: name the item.`\n const unitAmountCents = included ? 0 : intIn(source['unitAmountCents'], 0, QUOTE_MAX_UNIT_CENTS)\n if (unitAmountCents === null) return `${at}: enter a price from $0 to $1,000,000.`\n const sku = clean(source['sku'], 100)\n return {\n kind: 'custom',\n name,\n ...(description ? { description } : {}),\n ...(sku ? { sku } : {}),\n unitAmountCents,\n quantity,\n ships: source['ships'] !== false,\n ...(included ? { included } : {}),\n }\n }\n return `${at}: add a product or type an item.`\n}\n\n/** What a save with no lines and no proof is told: a quote needs one or the other. */\nexport const QUOTE_NEEDS_LINE_OR_PROOF = 'Add at least one line, or a proof, to the quote.'\n\n/**\n * The console's quote, checked and trimmed, or what to fix. Prices on product\n * lines are not read from here: the server prices them from the product.\n *\n * No lines is refused unless the caller will check for a proof itself\n * (`allowNoLines`, AGL-4184). With no lines there is nothing to discount or\n * ship, so a discount or shipping sent with none is not kept: a quote with no\n * lines always totals nothing.\n */\nexport function parseQuoteInput(\n raw: unknown,\n options: { allowNoLines?: boolean } = {},\n): { ok: true; input: QuoteInput } | { ok: false; error: string } {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const rawLines = Array.isArray(source['lines']) ? (source['lines'] as unknown[]) : []\n if (rawLines.length === 0 && !options.allowNoLines) return { ok: false, error: QUOTE_NEEDS_LINE_OR_PROOF }\n if (rawLines.length > QUOTE_MAX_LINES) {\n return { ok: false, error: `A quote holds up to ${QUOTE_MAX_LINES} lines.` }\n }\n const lines: QuoteLineRequest[] = []\n for (const [index, entry] of rawLines.entries()) {\n const line = parseLine(entry, index)\n if (typeof line === 'string') return { ok: false, error: line }\n lines.push(line)\n }\n\n const customerSource = (source['customer'] && typeof source['customer'] === 'object'\n ? source['customer']\n : {}) as Record<string, unknown>\n const email = clean(customerSource['email'])\n if (email && !EMAIL.test(email)) return { ok: false, error: 'Enter a valid email for the customer.' }\n const recordSource = (customerSource['record'] ?? null) as Record<string, unknown> | null\n const recordKind = clean(recordSource?.['kind'], 40)\n const recordId = clean(recordSource?.['id'])\n const customer: QuoteCustomer = {\n ...(recordKind && DOC_ID.test(recordId) ? { record: { kind: recordKind, id: recordId } } : {}),\n ...(clean(customerSource['name']) ? { name: clean(customerSource['name']) } : {}),\n ...(clean(customerSource['company']) ? { company: clean(customerSource['company']) } : {}),\n ...(email ? { email, emailLower: email.toLowerCase() } : {}),\n ...(clean(customerSource['phone'], 40) ? { phone: clean(customerSource['phone'], 40) } : {}),\n }\n\n let discount: QuoteDiscount | null = null\n const discountSource = (lines.length ? source['discount'] ?? null : null) as Record<string, unknown> | null\n if (discountSource?.['kind'] === 'amount') {\n const amountCents = intIn(discountSource['amountCents'], 0, QUOTE_MAX_UNIT_CENTS)\n if (amountCents === null) return { ok: false, error: 'Enter a discount from $0 to $1,000,000.' }\n if (amountCents > 0) discount = { kind: 'amount', amountCents }\n } else if (discountSource?.['kind'] === 'percent') {\n const pct = Number(discountSource['pct'])\n if (!Number.isFinite(pct) || pct < 0 || pct > 100) {\n return { ok: false, error: 'Enter a discount from 0% to 100%.' }\n }\n if (pct > 0) discount = { kind: 'percent', pct: Math.round(pct * 100) / 100 }\n }\n\n let shipping: QuoteShipping | null = null\n const shippingSource = (lines.length ? source['shipping'] ?? null : null) as Record<string, unknown> | null\n if (shippingSource) {\n const amountCents = intIn(shippingSource['amountCents'], 0, QUOTE_MAX_UNIT_CENTS)\n if (amountCents === null) return { ok: false, error: 'Enter shipping from $0 to $1,000,000.' }\n shipping = { amountCents }\n }\n\n return {\n ok: true,\n input: {\n lines,\n customer,\n billTo: parseAddress(source['billTo']),\n shipTo: parseAddress(source['shipTo']),\n notes: clean(source['notes'], QUOTE_MAX_TEXT),\n terms: clean(source['terms'], QUOTE_MAX_TEXT),\n discount,\n shipping,\n ...(typeof source['requireProofApproval'] === 'boolean'\n ? { requireProofApproval: source['requireProofApproval'] }\n : {}),\n },\n }\n}\n\n/** A priced quote line, and whether its product is tax-exempt. */\nexport type PricedQuoteLine = OrderLineItem & { taxExempt?: boolean }\n\n/** The variant's label as order lines print it: its option values, or nothing for a default. */\nfunction variantOptionsLabel(options: Record<string, string> | undefined): string | undefined {\n return options && Object.keys(options).length ? Object.values(options).join(' / ') : undefined\n}\n\n/**\n * A product line priced from the PRODUCT: its variant's price plus the chosen\n * add-ons, as the register prices one. An included line keeps what it is and\n * charges nothing.\n */\nexport function priceQuoteCatalogLine(\n rawProduct: Partial<HostProduct> | null | undefined,\n request: QuoteCatalogLineRequest,\n): { ok: true; line: PricedQuoteLine } | { ok: false; error: string } {\n if (!rawProduct || rawProduct.deletedAt) {\n return { ok: false, error: 'A product on this quote no longer exists. Remove it and add it again.' }\n }\n const product = liftLegacyProduct(rawProduct)\n const variant = request.variantId\n ? product.variants.find((entry) => entry.id === request.variantId)\n : product.variants[0]\n if (!variant) return { ok: false, error: `Choose an option of ${product.name} that still exists.` }\n if (!request.included && !variantHasPrice(variant)) {\n return { ok: false, error: `Set a price for ${product.name} before quoting it.` }\n }\n const chosen = resolveLineModifiers(product, request.modifiers, variant.id)\n if (!chosen.ok) return { ok: false, error: chosen.error ?? `Check the choices on ${product.name}.` }\n const variantLabel = lineLabelWithModifiers(variantOptionsLabel(variant.options), chosen.modifiers)\n return {\n ok: true,\n line: {\n productId: request.productId,\n ...(variant.id !== 'default' ? { variantId: variant.id } : {}),\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: (product.type ?? 'physical') as ProductType,\n quantity: request.quantity,\n unitAmountCents: request.included\n ? 0\n : Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(chosen.modifiers.length ? { modifiers: chosen.modifiers } : {}),\n ...(request.included ? { included: true } : {}),\n ...(request.description ? { description: request.description } : {}),\n ...(product.taxExempt ? { taxExempt: true } : {}),\n },\n }\n}\n\n/** A typed line: no product, so nothing reads stock, a supplier or a download for it. */\nexport function priceQuoteCustomLine(request: QuoteCustomLineRequest): PricedQuoteLine {\n return {\n productId: '',\n custom: true,\n name: request.name,\n ...(request.sku ? { sku: request.sku } : {}),\n productType: request.ships === false ? 'service' : 'physical',\n quantity: request.quantity,\n unitAmountCents: request.included ? 0 : request.unitAmountCents,\n ...(request.included ? { included: true } : {}),\n ...(request.description ? { description: request.description } : {}),\n }\n}\n\n/** The request a stored line is edited as: what the console sends back on a save. */\nexport function quoteLineRequestFromLine(line: OrderLineItem): QuoteLineRequest {\n if (line.custom || !line.productId) {\n return {\n kind: 'custom',\n name: line.name,\n ...(line.description ? { description: line.description } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n unitAmountCents: line.unitAmountCents,\n quantity: line.quantity,\n ships: line.productType !== 'service' && line.productType !== 'digital',\n ...(line.included ? { included: true } : {}),\n }\n }\n return {\n kind: 'catalog',\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n quantity: line.quantity,\n ...(line.modifiers?.length\n ? { modifiers: line.modifiers.map(({ groupId, optionId }) => ({ groupId, optionId })) }\n : {}),\n ...(line.included ? { included: true } : {}),\n ...(line.description ? { description: line.description } : {}),\n }\n}\n"],"names":["liftLegacyProduct","variantHasPrice","computeTaxCents","resolveTaxRate","storefrontTaxDecision","allocateCentsByWeight","lineLabelWithModifiers","resolveLineModifiers","QUOTE_STAGE_LABELS","draft","sent","changes_requested","approved","quoteRequiresProofApprovalByDefault","settings","requireProofApproval","quotePaymentBlockedByApproval","quote","revision","Number","proofed","proofs","some","proof","approvedRevision","isQuote","order","channel","isUnpaidQuote","status","formatQuoteNumber","docId","number","slice","toUpperCase","quoteIsProofOnly","Array","isArray","lineItems","length","formatProofNumber","replace","quoteDisplayStatus","key","label","stage","QUOTE_STATUS_COLOR","paid","cancelled","refunded","whole","value","Math","round","isFinite","quoteLineCents","line","included","unitAmountCents","quantity","quoteDiscountCents","itemsCents","discount","items","kind","min","amountCents","pct","max","quoteLineAmounts","lines","grossCents","map","reduce","sum","cents","totalDiscountCents","discountCents","netCents","index","computeQuoteTotals","input","amounts","taxableCents","taxExempt","shippingCents","tax","taxCents","feeCents","totalCents","taxAtPayment","quoteOrderTotals","totals","quoteTaxBasisFromSettings","shipTo","decision","reason","pricesIncludeTax","address","String","country","trim","state","origin","rate","undefined","describeQuoteTax","basis","providerLabel","quoteTaxMode","QUOTE_MAX_LINES","QUOTE_MAX_QUANTITY","QUOTE_MAX_UNIT_CENTS","QUOTE_MAX_TEXT","SHORT_TEXT","EMAIL","DOC_ID","clean","intIn","isInteger","parseAddress","raw","source","test","Object","keys","parseLine","at","toLocaleString","description","productId","variantId","modifiers","entry","pick","groupId","optionId","name","sku","ships","QUOTE_NEEDS_LINE_OR_PROOF","parseQuoteInput","options","customerSource","rawLines","allowNoLines","ok","error","entries","push","email","recordSource","recordKind","recordId","customer","record","id","company","emailLower","toLowerCase","phone","discountSource","shipping","shippingSource","billTo","notes","terms","variantOptionsLabel","values","join","priceQuoteCatalogLine","rawProduct","request","chosen","product","deletedAt","variant","variants","find","variantLabel","productType","type","priceUsd","extraCents","priceQuoteCustomLine","custom","quoteLineRequestFromLine"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SAASA,iBAAiB,EAAEC,eAAe,QAAQ,gBAAY;AAQ/D,SAASC,eAAe,EAAEC,cAAc,QAA0B,oBAAgB;AAClF,SAASC,qBAAqB,QAAgC,6BAAyB;AACvF,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SACEC,sBAAsB,EACtBC,oBAAoB,QAEf,yBAAqB;AAiC5B,OAAO,MAAMC,qBAAiD;IAC5DC,OAAO;IACPC,MAAM;IACNC,mBAAmB;IACnBC,UAAU;AACZ,EAAC;AAoQD,iFAAiF,GACjF,OAAO,SAASC,oCACdC,QAA+C;IAE/C,OAAOA,CAAAA,4BAAAA,SAAUC,oBAAoB,MAAK;AAC5C;AAEA;;;;CAIC,GACD,OAAO,SAASC,8BACdC,KAKa;QAGWA,iBACPA;IAFjB,IAAI,CAACA,SAASA,MAAMF,oBAAoB,KAAK,MAAM,OAAO;IAC1D,MAAMG,WAAWC,QAAOF,kBAAAA,MAAMC,QAAQ,YAAdD,kBAAkB;IAC1C,MAAMG,UAAU,EAACH,gBAAAA,MAAMI,MAAM,YAAZJ,gBAAgB,EAAE,EAAEK,IAAI,CAAC,CAACC,QAAUJ,OAAOI,yBAAAA,MAAOL,QAAQ,MAAMA;IACjF,IAAI,CAACE,SAAS,OAA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GAAG,CAAC,CAAC,EAAE+D,OAAO,EAAEC,QAAQ,EAAE,GAAM,CAAA;gBAAED;gBAASC;YAAS,CAAA;IAAI,IACpF,CAAC,GACDhF,KAAKC,QAAQ,GAAG;QAAEA,UAAU;IAAK,IAAI,CAAC,GACtCD,KAAKyE,WAAW,GAAG;QAAEA,aAAazE,KAAKyE,WAAW;IAAC,IAAI,CAAC;AAEhE"}
@@ -63,7 +63,7 @@ export declare function posPermissionRefusal(permission: PosPermission): string;
63
63
  /** The reservation keys. */
64
64
  export type ReservationPermission = 'commerce.reservations' | 'commerce.walkIns';
65
65
  /** Commerce's keys whose preset is the site role (AGL-4047). */
66
- export type CommerceSitePermission = ReservationPermission | 'commerce.orders' | 'commerce.quotes' | 'commerce.quotes.send' | 'commerce.giftCards' | 'commerce.paymentMethods' | 'commerce.shippingConnections';
66
+ export type CommerceSitePermission = ReservationPermission | 'commerce.orders' | 'commerce.quotes' | 'commerce.quotes.send' | 'commerce.giftCards' | 'commerce.giftCards.import' | 'commerce.paymentMethods' | 'commerce.shippingConnections';
67
67
  /** Who held reservations on a site before they were keys: Admin, Editor and Author. */
68
68
  export declare const RESERVATION_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>>;
69
69
  /**
@@ -233,6 +233,16 @@
233
233
  groupLabel: 'Commerce',
234
234
  presetFromSiteRole: true
235
235
  },
236
+ {
237
+ key: 'commerce.giftCards.import',
238
+ label: 'Import gift cards',
239
+ description: 'Import gift cards from a file, which issues each one as spendable money. Also takes "Manage data". Follows the site role unless a role or member sets it.',
240
+ roleDefaults: _extends({}, STORE_SETTINGS_ORG_ROLE_PRESET),
241
+ hostRoleDefaults: _extends({}, STORE_SETTINGS_SITE_ROLE_PRESET),
242
+ group: 'commerce',
243
+ groupLabel: 'Commerce',
244
+ presetFromSiteRole: true
245
+ },
236
246
  {
237
247
  key: 'commerce.paymentMethods',
238
248
  label: 'Manage payment methods',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/plugin-permissions.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 type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\n\n/**\n * The register's finer permissions (AGL-4047), each a part of `managePos`\n * (Use the point of sale). Each REFINES it: never held without it, and,\n * where no custom role or override sets one, it follows `managePos` — so a\n * member keeps exactly the register they had until somebody narrows it.\n */\nexport type PosRegisterPermission =\n | 'posSell'\n | 'posRefund'\n | 'posDiscount'\n | 'posCashDrawer'\n | 'posDevices'\n\n/**\n * The register's keys and `posBuyHardware`, which stands on its own\n * (AGL-4047): it FOLLOWS `managePos` where no custom role or override sets\n * it, so every member keeps the hardware shop they had, but it may be\n * granted without the register — a bookkeeper who orders the store's readers\n * and never rings a sale.\n */\nexport type PosPermission = PosRegisterPermission | 'posBuyHardware'\n\n/** The tier defaults `managePos` has, which every finer key mirrors. */\nconst POS_TIER_DEFAULTS = { admin: true, editor: true, viewer: false } as const\n\n/*\n * The register is a site's own (AGL-4047): `managePos` and its five finer\n * keys are `narrowsPerSite`, so an editor of the whole workspace given Viewer\n * or Author access to one site does not work that site's register unless the\n * site grants it to them. `posBuyHardware` is not: the hardware shop spends\n * the workspace's money, and its verdict is the workspace's on every site.\n */\n\n/**\n * Commerce's plugin-declared permissions (AGL-435) — the reference\n * adopter. Pure data: the client barrel and /server entry both register\n * it, so console gating and API-side resolution agree.\n */\nexport const COMMERCE_PERMISSIONS: readonly PluginPermission[] = [\n {\n key: 'managePos',\n pluginId: 'commerce',\n label: 'Use the point of sale',\n description:\n 'Open the point of sale. Each point of sale permission below follows this one unless a role or member sets it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n },\n {\n key: 'posSell',\n pluginId: 'commerce',\n label: 'Sell at the register',\n description: 'Ring up sales and take payment at the register, the kiosk and the point of sale apps.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posRefund',\n pluginId: 'commerce',\n label: 'Refunds and returns',\n description: 'Refund point of sale orders at the register, up to its refund limit, and take returns and exchanges.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDiscount',\n pluginId: 'commerce',\n label: 'Give discounts at the register',\n description:\n 'Take a discount off a sale at the register. A shopper’s discount code and the store’s own promotions apply without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posCashDrawer',\n pluginId: 'commerce',\n label: 'Cash drawer and shifts',\n description: 'Open and close shifts, record cash in and out, print shift reports and open the drawer without a sale.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDevices',\n pluginId: 'commerce',\n label: 'Registers and devices',\n description: 'Add, change and remove card readers, receipt printers and customer displays, and set the reader screen.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posBuyHardware',\n pluginId: 'commerce',\n label: 'Buy point of sale hardware',\n description:\n 'Order card readers and other hardware from the hardware shop. Follows \"Use the point of sale\" unless a role or member sets it, and may be allowed without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n follows: 'managePos',\n },\n]\n\n/** One finer register key's label, for a refusal or a disabled control's reason. */\nexport function posPermissionLabel(permission: PosPermission): string {\n return COMMERCE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/**\n * Whether a resolved permission map allows one of the register's finer\n * actions (AGL-4047): `managePos`, and the finer key not refused. A map\n * that does not carry the finer key at all follows `managePos` — the\n * resolvers always carry it once commerce has registered, so an absent key\n * is a map built before that, which keeps the register it had.\n *\n * `posBuyHardware` stands on its own: its own verdict when the map carries\n * one, granted with or without `managePos`, and `managePos`'s when it does\n * not.\n */\nexport function holdsPosPermission(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n permission: PosPermission,\n): boolean {\n if (permission === 'posBuyHardware') {\n const own = permissions?.[permission]\n return typeof own === 'boolean' ? own : permissions?.['managePos'] === true\n }\n return permissions?.['managePos'] === true && permissions?.[permission] !== false\n}\n\n/**\n * Whether a member may open the hardware shop at all (AGL-4047): see what\n * it offers and what the store ordered. Whoever works the register, and\n * whoever may buy hardware without working it.\n */\nexport function mayVisitPosHardwareShop(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n): boolean {\n return permissions?.['managePos'] === true || holdsPosPermission(permissions, 'posBuyHardware')\n}\n\n/** The refusal a register route answers when a finer key is not held. */\nexport function posPermissionRefusal(permission: PosPermission): string {\n return `Your role does not include \"${posPermissionLabel(permission)}\" — ask an organization admin`\n}\n\n/*\n * RESERVATIONS (AGL-4047).\n *\n * A site's stays and what they book were decided by the member's role ON THE\n * SITE: Admin, Editor and Author could book a walk-in, change a stay's guests\n * and edit or cancel stays, and a Viewer could not (`canWriteHostContent` in\n * the rules, the same three roles at the routes). Those are now keys whose\n * preset is that site role (`presetFromSiteRole`), so every member keeps\n * exactly the access they had, and a custom role, a member's own permissions\n * or a site's toggle can grant or refuse either one: the window's staff can\n * be allowed walk-ins without editing anyone's booking.\n */\n\n/** The reservation keys. */\nexport type ReservationPermission = 'commerce.reservations' | 'commerce.walkIns'\n\n/** Commerce's keys whose preset is the site role (AGL-4047). */\nexport type CommerceSitePermission =\n | ReservationPermission\n | 'commerce.orders'\n | 'commerce.quotes'\n | 'commerce.quotes.send'\n | 'commerce.giftCards'\n | 'commerce.paymentMethods'\n | 'commerce.shippingConnections'\n\n/** Who held reservations on a site before they were keys: Admin, Editor and Author. */\nexport const RESERVATION_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: true,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nconst RESERVATION_ORG_ROLE_PRESET = { owner: true, admin: true, editor: true, viewer: false } as const\n\n/**\n * Who worked a site's orders and gift cards before they were keys: the site's\n * Admin and Editor (an Author edits the catalog and never touched an order).\n */\nexport const ORDERS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/**\n * Who changed a site's payment methods and its shipping app connections\n * before they were keys: the site's Admin alone (an Editor could see them, as\n * whoever works the orders still can).\n */\nexport const STORE_SETTINGS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: false,\n author: false,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nexport const STORE_SETTINGS_ORG_ROLE_PRESET = { owner: true, admin: true, editor: false, viewer: false } as const\n\n/**\n * The reservation keys as commerce declares them into the org permission\n * catalog (AGL-4047), registered beside `COMMERCE_PERMISSIONS`.\n */\nexport const COMMERCE_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'commerce.reservations',\n label: 'Manage reservations',\n description:\n 'Edit, cancel and check out stays, and add, change and remove what can be booked. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.walkIns',\n label: 'Book walk-ins and change guests',\n description:\n 'Book a walk-in stay and change how many guests a stay is for. Follows \"Manage reservations\" unless a role or member sets it, and may be allowed without it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n follows: 'commerce.reservations',\n },\n {\n key: 'commerce.orders',\n label: 'Manage orders',\n description:\n 'Fulfill, cancel and print orders, resend receipts, build draft orders, take returns and record shipments. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes',\n label: 'Create and edit quotes',\n description:\n 'Create, edit and delete quotes for customers. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes.send',\n label: 'Send quotes and invoices to customers',\n description:\n 'Copy a quote’s pay link to send to the customer, and replace it so the old link stops working. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.giftCards',\n label: 'Issue gift cards',\n description: 'Issue, adjust and void the store’s gift cards. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.paymentMethods',\n label: 'Manage payment methods',\n description:\n 'Turn the store’s payment methods on and off. Anyone with \"Manage orders\" sees them. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.shippingConnections',\n label: 'Connect shipping apps',\n description:\n 'Connect, sync and disconnect ShipStation and ShippingEasy, and show or replace their credentials. Anyone with \"Manage orders\" sees whether they are connected. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a door answers when a commerce site key is not held: names the permission. */\nexport function commerceSitePermissionRefusal(key: CommerceSitePermission): string {\n const label = COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === key)?.label ?? key\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/** One reservation key's label, for a refusal. */\nexport function reservationPermissionLabel(permission: ReservationPermission): string {\n return COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/** The refusal a reservation route answers when its key is not held; names the permission, never a role. */\nexport function reservationPermissionRefusal(permission: ReservationPermission): string {\n return commerceSitePermissionRefusal(permission)\n}\n"],"names":["POS_TIER_DEFAULTS","admin","editor","viewer","COMMERCE_PERMISSIONS","key","pluginId","label","description","defaults","groupLabel","narrowsPerSite","refines","follows","posPermissionLabel","permission","find","entry","holdsPosPermission","permissions","own","mayVisitPosHardwareShop","posPermissionRefusal","RESERVATION_SITE_ROLE_PRESET","author","RESERVATION_ORG_ROLE_PRESET","owner","ORDERS_SITE_ROLE_PRESET","STORE_SETTINGS_SITE_ROLE_PRESET","STORE_SETTINGS_ORG_ROLE_PRESET","COMMERCE_SITE_PERMISSIONS","roleDefaults","hostRoleDefaults","group","presetFromSiteRole","commerceSitePermissionRefusal","reservationPermissionLabel","reservationPermissionRefusal"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AA4BD,sEAAsE,GACtE,MAAMA,oBAAoB;IAAEC,OAAO;IAAMC,QAAQ;IAAMC,QAAQ;AAAM;AAErE;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,uBAAoD;IAC/D;QACEC,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;IAClB;IACA;QACEN,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZG,SAAS;IACX;CACD,CAAA;AAED,kFAAkF,GAClF,OAAO,SAASC,mBAAmBC,UAAyB;;QACnDX;IAAP,gBAAOA,6BAAAA,qBAAqBY,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKU,gCAAnD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B,KAAK,mBAAIF;IACrF,OAAO,CAAC,4BAA4B,EAAEE,MAAM,6BAA6B,CAAC;AAC5E;AAEA,gDAAgD,GAChD,OAAO,SAAS6B,2BAA2BrB,UAAiC;;QACnEe;IAAP,gBAAOA,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKU,gCAAxDe,gCAAqEvB,KAAK,mBAAIQ;AACvF;AAEA,0GAA0G,GAC1G,OAAO,SAASsB,6BAA6BtB,UAAiC;IAC5E,OAAOoB,8BAA8BpB;AACvC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/plugin-permissions.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 type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\n\n/**\n * The register's finer permissions (AGL-4047), each a part of `managePos`\n * (Use the point of sale). Each REFINES it: never held without it, and,\n * where no custom role or override sets one, it follows `managePos` — so a\n * member keeps exactly the register they had until somebody narrows it.\n */\nexport type PosRegisterPermission =\n | 'posSell'\n | 'posRefund'\n | 'posDiscount'\n | 'posCashDrawer'\n | 'posDevices'\n\n/**\n * The register's keys and `posBuyHardware`, which stands on its own\n * (AGL-4047): it FOLLOWS `managePos` where no custom role or override sets\n * it, so every member keeps the hardware shop they had, but it may be\n * granted without the register — a bookkeeper who orders the store's readers\n * and never rings a sale.\n */\nexport type PosPermission = PosRegisterPermission | 'posBuyHardware'\n\n/** The tier defaults `managePos` has, which every finer key mirrors. */\nconst POS_TIER_DEFAULTS = { admin: true, editor: true, viewer: false } as const\n\n/*\n * The register is a site's own (AGL-4047): `managePos` and its five finer\n * keys are `narrowsPerSite`, so an editor of the whole workspace given Viewer\n * or Author access to one site does not work that site's register unless the\n * site grants it to them. `posBuyHardware` is not: the hardware shop spends\n * the workspace's money, and its verdict is the workspace's on every site.\n */\n\n/**\n * Commerce's plugin-declared permissions (AGL-435) — the reference\n * adopter. Pure data: the client barrel and /server entry both register\n * it, so console gating and API-side resolution agree.\n */\nexport const COMMERCE_PERMISSIONS: readonly PluginPermission[] = [\n {\n key: 'managePos',\n pluginId: 'commerce',\n label: 'Use the point of sale',\n description:\n 'Open the point of sale. Each point of sale permission below follows this one unless a role or member sets it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n },\n {\n key: 'posSell',\n pluginId: 'commerce',\n label: 'Sell at the register',\n description: 'Ring up sales and take payment at the register, the kiosk and the point of sale apps.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posRefund',\n pluginId: 'commerce',\n label: 'Refunds and returns',\n description: 'Refund point of sale orders at the register, up to its refund limit, and take returns and exchanges.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDiscount',\n pluginId: 'commerce',\n label: 'Give discounts at the register',\n description:\n 'Take a discount off a sale at the register. A shopper’s discount code and the store’s own promotions apply without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posCashDrawer',\n pluginId: 'commerce',\n label: 'Cash drawer and shifts',\n description: 'Open and close shifts, record cash in and out, print shift reports and open the drawer without a sale.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDevices',\n pluginId: 'commerce',\n label: 'Registers and devices',\n description: 'Add, change and remove card readers, receipt printers and customer displays, and set the reader screen.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posBuyHardware',\n pluginId: 'commerce',\n label: 'Buy point of sale hardware',\n description:\n 'Order card readers and other hardware from the hardware shop. Follows \"Use the point of sale\" unless a role or member sets it, and may be allowed without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n follows: 'managePos',\n },\n]\n\n/** One finer register key's label, for a refusal or a disabled control's reason. */\nexport function posPermissionLabel(permission: PosPermission): string {\n return COMMERCE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/**\n * Whether a resolved permission map allows one of the register's finer\n * actions (AGL-4047): `managePos`, and the finer key not refused. A map\n * that does not carry the finer key at all follows `managePos` — the\n * resolvers always carry it once commerce has registered, so an absent key\n * is a map built before that, which keeps the register it had.\n *\n * `posBuyHardware` stands on its own: its own verdict when the map carries\n * one, granted with or without `managePos`, and `managePos`'s when it does\n * not.\n */\nexport function holdsPosPermission(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n permission: PosPermission,\n): boolean {\n if (permission === 'posBuyHardware') {\n const own = permissions?.[permission]\n return typeof own === 'boolean' ? own : permissions?.['managePos'] === true\n }\n return permissions?.['managePos'] === true && permissions?.[permission] !== false\n}\n\n/**\n * Whether a member may open the hardware shop at all (AGL-4047): see what\n * it offers and what the store ordered. Whoever works the register, and\n * whoever may buy hardware without working it.\n */\nexport function mayVisitPosHardwareShop(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n): boolean {\n return permissions?.['managePos'] === true || holdsPosPermission(permissions, 'posBuyHardware')\n}\n\n/** The refusal a register route answers when a finer key is not held. */\nexport function posPermissionRefusal(permission: PosPermission): string {\n return `Your role does not include \"${posPermissionLabel(permission)}\" — ask an organization admin`\n}\n\n/*\n * RESERVATIONS (AGL-4047).\n *\n * A site's stays and what they book were decided by the member's role ON THE\n * SITE: Admin, Editor and Author could book a walk-in, change a stay's guests\n * and edit or cancel stays, and a Viewer could not (`canWriteHostContent` in\n * the rules, the same three roles at the routes). Those are now keys whose\n * preset is that site role (`presetFromSiteRole`), so every member keeps\n * exactly the access they had, and a custom role, a member's own permissions\n * or a site's toggle can grant or refuse either one: the window's staff can\n * be allowed walk-ins without editing anyone's booking.\n */\n\n/** The reservation keys. */\nexport type ReservationPermission = 'commerce.reservations' | 'commerce.walkIns'\n\n/** Commerce's keys whose preset is the site role (AGL-4047). */\nexport type CommerceSitePermission =\n | ReservationPermission\n | 'commerce.orders'\n | 'commerce.quotes'\n | 'commerce.quotes.send'\n | 'commerce.giftCards'\n | 'commerce.giftCards.import'\n | 'commerce.paymentMethods'\n | 'commerce.shippingConnections'\n\n/** Who held reservations on a site before they were keys: Admin, Editor and Author. */\nexport const RESERVATION_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: true,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nconst RESERVATION_ORG_ROLE_PRESET = { owner: true, admin: true, editor: true, viewer: false } as const\n\n/**\n * Who worked a site's orders and gift cards before they were keys: the site's\n * Admin and Editor (an Author edits the catalog and never touched an order).\n */\nexport const ORDERS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/**\n * Who changed a site's payment methods and its shipping app connections\n * before they were keys: the site's Admin alone (an Editor could see them, as\n * whoever works the orders still can).\n */\nexport const STORE_SETTINGS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: false,\n author: false,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nexport const STORE_SETTINGS_ORG_ROLE_PRESET = { owner: true, admin: true, editor: false, viewer: false } as const\n\n/**\n * The reservation keys as commerce declares them into the org permission\n * catalog (AGL-4047), registered beside `COMMERCE_PERMISSIONS`.\n */\nexport const COMMERCE_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'commerce.reservations',\n label: 'Manage reservations',\n description:\n 'Edit, cancel and check out stays, and add, change and remove what can be booked. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.walkIns',\n label: 'Book walk-ins and change guests',\n description:\n 'Book a walk-in stay and change how many guests a stay is for. Follows \"Manage reservations\" unless a role or member sets it, and may be allowed without it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n follows: 'commerce.reservations',\n },\n {\n key: 'commerce.orders',\n label: 'Manage orders',\n description:\n 'Fulfill, cancel and print orders, resend receipts, build draft orders, take returns and record shipments. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes',\n label: 'Create and edit quotes',\n description:\n 'Create, edit and delete quotes for customers. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes.send',\n label: 'Send quotes and invoices to customers',\n description:\n 'Copy a quote’s pay link to send to the customer, and replace it so the old link stops working. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.giftCards',\n label: 'Issue gift cards',\n description: 'Issue, adjust and void the store’s gift cards. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.giftCards.import',\n label: 'Import gift cards',\n description:\n 'Import gift cards from a file, which issues each one as spendable money. Also takes \"Manage data\". Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.paymentMethods',\n label: 'Manage payment methods',\n description:\n 'Turn the store’s payment methods on and off. Anyone with \"Manage orders\" sees them. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.shippingConnections',\n label: 'Connect shipping apps',\n description:\n 'Connect, sync and disconnect ShipStation and ShippingEasy, and show or replace their credentials. Anyone with \"Manage orders\" sees whether they are connected. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a door answers when a commerce site key is not held: names the permission. */\nexport function commerceSitePermissionRefusal(key: CommerceSitePermission): string {\n const label = COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === key)?.label ?? key\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/** One reservation key's label, for a refusal. */\nexport function reservationPermissionLabel(permission: ReservationPermission): string {\n return COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/** The refusal a reservation route answers when its key is not held; names the permission, never a role. */\nexport function reservationPermissionRefusal(permission: ReservationPermission): string {\n return commerceSitePermissionRefusal(permission)\n}\n"],"names":["POS_TIER_DEFAULTS","admin","editor","viewer","COMMERCE_PERMISSIONS","key","pluginId","label","description","defaults","groupLabel","narrowsPerSite","refines","follows","posPermissionLabel","permission","find","entry","holdsPosPermission","permissions","own","mayVisitPosHardwareShop","posPermissionRefusal","RESERVATION_SITE_ROLE_PRESET","author","RESERVATION_ORG_ROLE_PRESET","owner","ORDERS_SITE_ROLE_PRESET","STORE_SETTINGS_SITE_ROLE_PRESET","STORE_SETTINGS_ORG_ROLE_PRESET","COMMERCE_SITE_PERMISSIONS","roleDefaults","hostRoleDefaults","group","presetFromSiteRole","commerceSitePermissionRefusal","reservationPermissionLabel","reservationPermissionRefusal"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AA4BD,sEAAsE,GACtE,MAAMA,oBAAoB;IAAEC,OAAO;IAAMC,QAAQ;IAAMC,QAAQ;AAAM;AAErE;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,uBAAoD;IAC/D;QACEC,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;IAClB;IACA;QACEN,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAA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ACnBO,kBAAkB,aAAKL;QACvBM,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aAAa;QACbuB,cAAc,aAAKN;QACnBO,kBAAkB,aAAKL;QACvBM,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aACE;QACFuB,cAAc,aAAKF;QACnBG,kBAAkB,aAAKJ;QACvBK,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aACE;QACFuB,cAAc,aAAKF;QACnBG,kBAAkB,aAAKJ;QACvBK,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aACE;QACFuB,cAAc,aAAKF;QACnBG,kBAAkB,aAAKJ;QACvBK,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;CACD,CAAA;AAED,2FAA2F,GAC3F,OAAO,SAASC,8BAA8B9B,GAA2B;;QACzDyB;IAAd,MAAMvB,iBAAQuB,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKA,yBAAxDyB,gCAA8DvB,KAAK,mBAAIF;IACrF,OAAO,CAAC,4BAA4B,EAAEE,MAAM,6BAA6B,CAAC;AAC5E;AAEA,gDAAgD,GAChD,OAAO,SAAS6B,2BAA2BrB,UAAiC;;QACnEe;IAAP,gBAAOA,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKU,gCAAxDe,gCAAqEvB,KAAK,mBAAIQ;AACvF;AAEA,0GAA0G,GAC1G,OAAO,SAASsB,6BAA6BtB,UAAiC;IAC5E,OAAOoB,8BAA8BpB;AACvC"}
@@ -61,7 +61,7 @@ export declare function loadCommercePdfBrand(input: {
61
61
  } | null;
62
62
  }, deps?: CommercePdfBrandDeps): Promise<CommercePdfBrand>;
63
63
  /** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */
64
- export declare function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string;
64
+ export declare function commercePdfFilename(businessName: string, document: 'quote' | 'proof' | 'invoice', number: unknown, docId: string): string;
65
65
  /** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */
66
66
  export declare function quotePdfFile(input: {
67
67
  hostId: string;
@@ -202,7 +202,7 @@ export function defaultCommercePdfBrandDeps() {
202
202
  revision: Number((_input_order_quote = input.order.quote) == null ? void 0 : _input_order_quote.revision) || 1,
203
203
  payUrl: input.payUrl
204
204
  }),
205
- filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId)
205
+ filename: commercePdfFilename(brand.businessName, view.proofOnly ? 'proof' : 'quote', input.order.number, input.quoteId)
206
206
  };
207
207
  }
208
208
  /** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */ export async function orderInvoicePdfFile(input, deps) {