@aglyn/plugins-commerce 1.15.1 → 1.16.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.
- package/README.md +1 -1
- package/package.json +13 -13
- package/src/lib/components/cart.js +2 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +6 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +5 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
- package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
- package/src/lib/components/console/product-builder-fields.component.js +195 -0
- package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
- package/src/lib/components/console/product-editor-dialog.component.js +35 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-messages.component.d.ts +21 -0
- package/src/lib/components/console/quote-messages.component.js +185 -0
- package/src/lib/components/console/quote-messages.component.js.map +1 -0
- package/src/lib/components/console/quote-pay-link.component.js +1 -1
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.js +30 -3
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
- package/src/lib/components/console/quote-settings-card.component.js +154 -24
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/product-builder-context.d.ts +22 -0
- package/src/lib/components/product-builder-context.js +21 -0
- package/src/lib/components/product-builder-context.js.map +1 -0
- package/src/lib/components/product-builder-mockup.d.ts +42 -0
- package/src/lib/components/product-builder-mockup.js +120 -0
- package/src/lib/components/product-builder-mockup.js.map +1 -0
- package/src/lib/components/product-builder-sample.d.ts +63 -0
- package/src/lib/components/product-builder-sample.js +96 -0
- package/src/lib/components/product-builder-sample.js.map +1 -0
- package/src/lib/components/product-choice-cards.d.ts +51 -0
- package/src/lib/components/product-choice-cards.js +311 -0
- package/src/lib/components/product-choice-cards.js.map +1 -0
- package/src/lib/components/product-detail-panels.d.ts +42 -0
- package/src/lib/components/product-detail-panels.js +185 -0
- package/src/lib/components/product-detail-panels.js.map +1 -0
- package/src/lib/components/product-detail.d.ts +20 -12
- package/src/lib/components/product-detail.js +136 -221
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +7 -0
- package/src/lib/components/product-grid.js +11 -8
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-options-field-body.d.ts +9 -8
- package/src/lib/components/product-options-field-body.js +152 -3
- package/src/lib/components/product-options-field-body.js.map +1 -1
- package/src/lib/components/product-options-field.js +1 -1
- package/src/lib/components/product-options-field.js.map +1 -1
- package/src/lib/components/product-photo-fit.d.ts +49 -0
- package/src/lib/components/product-photo-fit.js +58 -0
- package/src/lib/components/product-photo-fit.js.map +1 -0
- package/src/lib/components/product-restock-notify.d.ts +12 -0
- package/src/lib/components/product-restock-notify.js +86 -0
- package/src/lib/components/product-restock-notify.js.map +1 -0
- package/src/lib/components/quote-messages-panel.d.ts +21 -0
- package/src/lib/components/quote-messages-panel.js +191 -0
- package/src/lib/components/quote-messages-panel.js.map +1 -0
- package/src/lib/components/quote-page-body.js +15 -1
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/quote-proof-panel.d.ts +6 -3
- package/src/lib/components/quote-proof-panel.js +139 -14
- package/src/lib/components/quote-proof-panel.js.map +1 -1
- package/src/lib/components/related-products.d.ts +7 -0
- package/src/lib/components/related-products.js +8 -6
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/constants/quote-page.d.ts +8 -0
- package/src/lib/constants/quote-page.js +11 -0
- package/src/lib/constants/quote-page.js.map +1 -1
- package/src/lib/model/commerce-cart.d.ts +6 -1
- package/src/lib/model/commerce-cart.js +5 -1
- package/src/lib/model/commerce-cart.js.map +1 -1
- package/src/lib/model/commerce-invoices.js +5 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-pos-ops.d.ts +3 -0
- package/src/lib/model/commerce-pos-ops.js +3 -0
- package/src/lib/model/commerce-pos-ops.js.map +1 -1
- package/src/lib/model/commerce-pos.d.ts +8 -0
- package/src/lib/model/commerce-pos.js.map +1 -1
- package/src/lib/model/commerce-quote-messages.d.ts +106 -0
- package/src/lib/model/commerce-quote-messages.js +146 -0
- package/src/lib/model/commerce-quote-messages.js.map +1 -0
- package/src/lib/model/commerce-quote-pay.d.ts +31 -2
- package/src/lib/model/commerce-quote-pay.js +31 -7
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
- package/src/lib/model/commerce-quote-proofs.js +73 -18
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +14 -4
- package/src/lib/model/commerce-quote-request.js +25 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +56 -3
- package/src/lib/model/commerce-quotes.js +47 -2
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce.d.ts +12 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/pos-cellular.d.ts +5 -0
- package/src/lib/model/pos-cellular.js.map +1 -1
- package/src/lib/model/product-card-rules.d.ts +41 -0
- package/src/lib/model/product-card-rules.js +90 -0
- package/src/lib/model/product-card-rules.js.map +1 -0
- package/src/lib/model/product-modifiers.d.ts +11 -0
- package/src/lib/model/product-modifiers.js +10 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/server/billing-webhook.js +6 -2
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +15 -0
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/channel-order-updates.js +15 -1
- package/src/lib/server/channel-order-updates.js.map +1 -1
- package/src/lib/server/channel-orders.js +20 -0
- package/src/lib/server/channel-orders.js.map +1 -1
- package/src/lib/server/checkout.js +1 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/local-fulfillment.js +1 -1
- package/src/lib/server/local-fulfillment.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.d.ts +1 -1
- package/src/lib/server/pos-cellular-billing.js +2 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular.d.ts +3 -1
- package/src/lib/server/pos-cellular.js +15 -8
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +3 -3
- package/src/lib/server/pos-offline-sync.js +17 -4
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-order.js +17 -6
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-payment.js +27 -11
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-reader-splash.js +10 -5
- package/src/lib/server/pos-reader-splash.js.map +1 -1
- package/src/lib/server/pos-readers.js +34 -10
- package/src/lib/server/pos-readers.js.map +1 -1
- package/src/lib/server/pos-return.js +19 -3
- package/src/lib/server/pos-return.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +14 -0
- package/src/lib/server/pos-stripe.js +6 -2
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal-connection-token.js +23 -9
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +80 -14
- package/src/lib/server/pos-terminal.js +393 -123
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/product-drafts.d.ts +1 -1
- package/src/lib/server/product-drafts.js +4 -3
- package/src/lib/server/product-drafts.js.map +1 -1
- package/src/lib/server/product-writer.js +5 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/product.d.ts +11 -0
- package/src/lib/server/product.js +18 -3
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +4 -3
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/quote-email.d.ts +26 -0
- package/src/lib/server/quote-email.js +73 -7
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-messages.d.ts +72 -0
- package/src/lib/server/quote-messages.js +356 -0
- package/src/lib/server/quote-messages.js.map +1 -0
- package/src/lib/server/quote-pay.d.ts +42 -0
- package/src/lib/server/quote-pay.js +81 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.d.ts +1 -1
- package/src/lib/server/quote-proofs.js +63 -19
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote.d.ts +12 -0
- package/src/lib/server/quote.js +44 -14
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +3 -1
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/reserve-stock.js +9 -0
- package/src/lib/server/reserve-stock.js.map +1 -1
- package/src/lib/server/returns.js +15 -1
- package/src/lib/server/returns.js.map +1 -1
- package/src/lib/server/reviews.js +15 -0
- package/src/lib/server/reviews.js.map +1 -1
- package/src/lib/server/sold-out-drop.d.ts +58 -0
- package/src/lib/server/sold-out-drop.js +81 -0
- package/src/lib/server/sold-out-drop.js.map +1 -0
- package/src/lib/server/stock-levels.js +9 -0
- package/src/lib/server/stock-levels.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +7 -0
- package/src/lib/server/stripe-refund.js +26 -7
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server.js +2 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/tenant-emails.js +85 -2
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
- package/src/lib/testing/fake-seller-payment-account.js +40 -0
- package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
- package/src/lib/transfer/product-transfer.js +6 -5
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +4 -3
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +6 -0
- package/src/lib/utils/quote-email-content.js +6 -3
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/products-write.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 { createHash } from 'node:crypto'\nimport { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n type EditedProduct,\n liftLegacyProduct,\n productCollectionIds,\n productDuplicateFields,\n productDuplicateName,\n productDuplicateSlugBase,\n productEditWrite,\n productMembershipInput,\n productSaveFields,\n smartCollectionRulesOf,\n stockAdjustmentWrite,\n validateProduct,\n variantMatrixProblem,\n type InventoryAdjustmentReason,\n} from '../model'\nimport { planRefusal, roomRefusal } from './product-drafts'\n\n/*\n * `POST /api/commerce/products/save` and `POST /api/commerce/products/stock`\n * (AGL-3652): the console product editor's save and its Adjust stock dialog,\n * for the native apps.\n *\n * The console makes both writes from the browser, computing derived fields\n * first (search keys, stock verdict, price, image, smart-collection\n * membership). These routes run THAT computation (`model/product-write.ts`,\n * which the console imports too) and make the same writes, under the gate\n * the Firestore rules put on them: a verified member with a write role on the\n * site (`canWriteHostContent`), or staff, while the site, its org and the\n * platform are not frozen (`hostWritesFrozen`). A new product also meets the\n * create path's own door: the plan's `commerce` entitlement and its\n * `productsPerHost` quota, counted in the same transaction as the create.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const ROLE_REFUSAL = siteKeyRefusal('site.edit')\nconst MAX_BODY_BYTES = 256_000\n\n/** The reasons the Adjust stock dialog offers. */\nexport const STOCK_ADJUST_REASONS: readonly InventoryAdjustmentReason[] = ['restock', 'correction', 'damage', 'refund']\n\nexport interface ProductsWriteDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n orgForHost?: (hostId: string) => Promise<{ org: Record<string, unknown> } | null>\n lockdown?: (options: Parameters<typeof getLockdownVerdict>[0]) => Promise<unknown>\n dropCache?: typeof dropPluginSiteCache\n now?: () => number\n}\n\ntype Reply = Parameters<PluginApiHandler>[1]\n\nexport function bodyOf(req: Parameters<PluginApiHandler>[0]): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n if (raw.length > MAX_BODY_BYTES) return {}\n try {\n return JSON.parse(raw || '{}')\n } catch {\n return {}\n }\n }\n return (raw ?? {}) as Record<string, unknown>\n}\n\nexport const validId = (value: unknown): value is string =>\n typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value)\n\nexport interface Gate {\n uid: string\n /** The caller's address, for an activity line; null when the token has none. */\n email: string | null\n staff: boolean\n host: FirebaseFirestore.DocumentSnapshot\n org: Record<string, unknown>\n}\n\n/**\n * The permission a route built on {@link gate} checks instead of the site\n * role (AGL-4047): a key whose preset is the site role, that preset (the\n * declaring plugin's own table, so the answer does not depend on which\n * plugins this process loaded), and the refusal naming it.\n */\nexport interface GatePermission {\n key: string\n presetFor: Readonly<Record<HostAccessRole, boolean>>\n refusal: string\n}\n\n/**\n * Who may write this site's products, as the rules decide it. Answers the\n * caller's reply on a refusal and returns null.\n *\n * A route that is not about products names the key it checks instead\n * (`permission`, AGL-4047): the walk-in and the guests change ask their\n * reservation key, read as the rules read it, from the site's\n * `memberPermissions` stamp, else the preset of the member's `memberRoles`\n * entry, so the route and the rules give one answer. Without it, the\n * product routes ask \"Edit site content\" (`site.edit`) the same way.\n */\nexport async function gate(\n req: Parameters<PluginApiHandler>[0],\n res: Reply,\n hostId: string,\n deps: Required<ProductsWriteDeps>,\n options: { permission?: GatePermission } = {},\n): Promise<Gate | null> {\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return void res.status(401).json({ error: 'Unauthenticated' }), null\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return void res.status(401).json({ error: 'Sign in again to continue' }), null\n }\n const staff = decoded['staff'] === true\n if (!staff && decoded['email_verified'] !== true && !isImpersonationSession(decoded as never)) {\n return void res.status(403).json({ error: 'Verify your email address to make changes' }), null\n }\n const host = await deps.firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return void res.status(404).json({ error: 'Unknown site' }), null\n if (!staff) {\n const { permission } = options\n const allowed = permission\n ? hostStampedSitePermission(host.data(), decoded.uid, permission.key, permission.presetFor)\n : holdsSiteKey(host, decoded.uid, 'site.edit')\n if (!allowed) return void res.status(403).json({ error: permission?.refusal ?? ROLE_REFUSAL }), null\n }\n const org = ((await deps.orgForHost(hostId))?.org ?? {}) as Record<string, unknown>\n const locked = await deps.lockdown({ staff, uid: decoded.uid, org: org as never, host: host.data() as never, request: { method: 'POST' } as never })\n if (locked) return void res.status(423).json({ error: 'This site is not accepting changes right now' }), null\n const email = typeof decoded['email'] === 'string' ? decoded['email'] : null\n return { uid: decoded.uid, email, staff, host, org }\n}\n\n/** The site-wide cache drop a product change is owed (AGL-3386): an outbox entry in the write, then the drop. */\nexport function outboxEntry(firestore: Firestore, hostId: string) {\n return {\n ref: firestore.collection('publishOutbox').doc(createResourceUid()),\n data: { hostId, paths: ['/'], createdAt: FieldValue.serverTimestamp(), attempts: 0, entireHost: true },\n }\n}\n\nexport async function settleCache(deps: Required<ProductsWriteDeps>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string) {\n const dropped = await deps.dropCache({ hostIds: [hostId], reason }).catch(() => ({ complete: false }))\n if (dropped.complete) await entry.delete().catch(() => undefined)\n}\n\nexport function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps> {\n return {\n firestore: deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore),\n verifyIdToken: deps.verifyIdToken ?? ((token) => firebaseAdmin.app().auth().verifyIdToken(token) as never),\n orgForHost: deps.orgForHost ?? ((hostId) => getOrgForHost(hostId) as never),\n lockdown: deps.lockdown ?? ((options) => getLockdownVerdict(options)),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n now: deps.now ?? (() => Date.now()),\n }\n}\n\n/**\n * Saves a product as the console editor does. `create: true` makes a new\n * product under the client-minted `productId` (a retry finds its own product\n * and answers `replayed`); otherwise it replaces the live product, keeping\n * its live stock holds.\n */\nexport function createProductSaveHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const product = body['product'] as EditedProduct | undefined\n if (!validId(hostId) || !validId(productId) || !product || typeof product !== 'object' || !Array.isArray(product.variants)) {\n return res.status(400).json({ error: 'Missing site, product or its variants' })\n }\n if (typeof product.name !== 'string' || !product.name.trim()) return res.status(400).json({ error: 'Product name is required' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const nowMs = deps.now()\n const fields = productSaveFields(product, nowMs)\n // More combinations than a product holds is refused with the count\n // (AGL-4100), never saved short of the options it names.\n const problem = variantMatrixProblem(fields.options) ?? validateProduct(fields as never)\n if (problem) return res.status(400).json({ error: problem })\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(productId)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const create = body['create'] === true\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart] = await Promise.all([tx.get(productRef), tx.get(smartQuery)])\n const membership = {\n collectionIds: productCollectionIds(\n productMembershipInput(fields, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n ),\n }\n if (create) {\n if (existing.exists) return { status: 200, body: { ok: true, id: productId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n tx.create(productRef, {\n ...fields,\n ...membership,\n createdAtMs: nowMs,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n } else {\n if (!existing.exists || existing.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n tx.set(productRef, {\n ...storedTimestamps(existing.data() ?? {}, product as unknown as Record<string, unknown>),\n ...productEditWrite(fields, existing.get('stockHolds')),\n ...membership,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: productId, replayed: false } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product saved from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/save]', error)\n return res.status(500).json({ error: 'The product could not be saved' })\n }\n }\n}\n\n/**\n * The stored timestamps an edit keeps. The console's replace writes back the\n * Timestamps its seed carried (`createdAt`, a publish time); a client's JSON\n * cannot carry one, so each stored Timestamp field the request does not name\n * is kept as stored.\n */\nexport function storedTimestamps(stored: Record<string, unknown>, asked: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(stored).filter(\n ([key, value]) => !(key in asked) && typeof (value as { toDate?: unknown } | null)?.toDate === 'function',\n ),\n )\n}\n\n/** The ledger row id one attempt owns: the same key from the same member is the same row. */\nexport function stockAttemptId(uid: string, key: string): string {\n return 'app-' + createHash('sha256').update(`${uid}:${key}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Adjusts one variant's stock as the Adjust stock dialog does: the variants\n * and stock fields on the product, and one `inventoryAdjustments` row, in one\n * transaction. The Idempotency-Key names that row, so a retried attempt finds\n * it and moves nothing twice.\n */\nexport function createProductStockHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const variantId = body['variantId']\n const key = String(req.headers['idempotency-key'] ?? '').trim().slice(0, 200)\n const reason = body['reason'] as InventoryAdjustmentReason\n const delta = Math.round(Number(body['delta']))\n const locationId = typeof body['locationId'] === 'string' && body['locationId'] ? body['locationId'] : undefined\n if (!validId(hostId) || !validId(productId) || typeof variantId !== 'string' || !variantId) {\n return res.status(400).json({ error: 'Missing site, product or variant' })\n }\n if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!STOCK_ADJUST_REASONS.includes(reason)) return res.status(400).json({ error: 'Unknown reason' })\n if (!Number.isFinite(delta) || delta === 0) return res.status(400).json({ error: 'Enter a number of units' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const productRef = hostRef.collection('products').doc(productId)\n const ledgerRef = hostRef.collection('inventoryAdjustments').doc(stockAttemptId(door.uid, key))\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [ledger, stored] = await Promise.all([tx.get(ledgerRef), tx.get(productRef)])\n if (ledger.exists) {\n return { status: 200, body: { ok: true, replayed: true, inventory: stored.get('inventory') ?? null } }\n }\n if (!stored.exists || stored.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n const product = stored.data() as never as Parameters<typeof stockAdjustmentWrite>[0]\n if (!(product.variants ?? []).some((variant) => variant.id === variantId)) {\n return { status: 404, body: { error: 'That variant is no longer on this product' } }\n }\n const write = stockAdjustmentWrite(product, productId, { variantId, delta, reason, locationId }, deps.now())\n if (!write) return { status: 400, body: { error: 'Enter a number of units' } }\n tx.update(productRef, write.update)\n tx.create(ledgerRef, write.ledger)\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, replayed: false, inventory: (write.update as { inventory?: unknown }).inventory ?? null } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'stock adjusted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/stock]', error)\n return res.status(500).json({ error: 'Stock could not be adjusted' })\n }\n }\n}\n\n/**\n * The first slug in `base`, `base-2`, `base-3`… no product of the site holds,\n * as the console's slug ledger claims one (`product-slugs.ts`): a second\n * Duplicate of the same product does not mint a second `-copy` (AGL-3321).\n */\nexport async function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string> {\n for (let suffix = 1; suffix < 1000; suffix += 1) {\n const candidate = suffix < 2 ? base : `${base}-${suffix}`\n const held = await products.where('slug', '==', candidate).limit(1).get()\n if (held.empty) return candidate\n }\n return `${base}-${Date.now()}`\n}\n\n/**\n * `POST /api/commerce/products/duplicate` (AGL-3841): the products list's\n * Duplicate for the native apps. The console builds the copy in the browser\n * (`productDuplicateFields`, its slug ledger, the copy's smart collections)\n * and creates it through the quota-enforcing resources route; this runs the\n * same model over the stored product and creates it under the save route's\n * create door (the plan's commerce entitlement and its product quota, counted\n * in the same transaction). `newProductId` is the client's, so a retry finds\n * its own copy and answers `replayed`.\n */\nexport function createProductDuplicateHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId, newProductId } = body\n if (!validId(hostId) || !validId(productId) || !validId(newProductId) || productId === newProductId) {\n return res.status(400).json({ error: 'Missing site or product' })\n }\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const copyRef = products.doc(newProductId)\n const already = await copyRef.get()\n if (already.exists) return res.status(200).json({ ok: true, id: newProductId, replayed: true })\n const source = await products.doc(productId).get()\n if (!source.exists || source.get('deletedAt')) return res.status(404).json({ error: 'This product was deleted' })\n const product = liftLegacyProduct((source.data() ?? {}) as never)\n const slug = await claimProductSlug(products, productDuplicateSlugBase(product.slug, product.name))\n const nowMs = deps.now()\n const fields = productDuplicateFields(product, slug, nowMs)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart] = await Promise.all([tx.get(copyRef), tx.get(smartQuery)])\n if (existing.exists) return { status: 200, body: { ok: true, id: newProductId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n // The COPY's smart collections: its name differs from the source's.\n const collectionIds = productCollectionIds(\n productMembershipInput({ name: productDuplicateName(product.name) }, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n )\n tx.create(copyRef, {\n ...fields,\n collectionIds,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: newProductId, replayed: false, slug } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product duplicated from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/duplicate]', error)\n return res.status(500).json({ error: 'Could not duplicate product' })\n }\n }\n}\n\n/**\n * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete\n * for the native apps, the console's write (`deletedAt` on the product, which\n * stops it being purchasable) with the site-wide cache drop, under the save\n * route's gate. Deleting a deleted product answers `already`.\n */\nexport function createProductDeleteHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId } = body\n if (!validId(hostId) || !validId(productId)) return res.status(400).json({ error: 'Missing site or product' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const stored = await tx.get(productRef)\n if (!stored.exists) return { status: 404, body: { error: 'This product no longer exists' } }\n if (stored.get('deletedAt')) return { status: 200, body: { ok: true, already: true } }\n tx.update(productRef, { deletedAt: FieldValue.serverTimestamp() })\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, already: false } }\n })\n if (answer.status === 200 && !(answer.body as { already?: boolean }).already) {\n await settleCache(deps, hostId, outbox.ref, 'product deleted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/delete]', error)\n return res.status(500).json({ error: 'Could not delete product' })\n }\n }\n}\n\nexport const productSaveHandler = createProductSaveHandler()\nexport const productStockHandler = createProductStockHandler()\nexport const productDuplicateHandler = createProductDuplicateHandler()\nexport const productDeleteHandler = createProductDeleteHandler()\n"],"names":["createHash","holdsSiteKey","hostStampedSitePermission","siteKeyRefusal","isRefusedIdToken","createResourceUid","countLiveDocuments","dropPluginSiteCache","firebaseAdmin","getLockdownVerdict","getOrgForHost","isImpersonationSession","FieldValue","liftLegacyProduct","productCollectionIds","productDuplicateFields","productDuplicateName","productDuplicateSlugBase","productEditWrite","productMembershipInput","productSaveFields","smartCollectionRulesOf","stockAdjustmentWrite","validateProduct","variantMatrixProblem","planRefusal","roomRefusal","ROLE_REFUSAL","MAX_BODY_BYTES","STOCK_ADJUST_REASONS","bodyOf","req","raw","body","length","JSON","parse","validId","value","test","gate","res","hostId","deps","options","authorization","String","headers","token","startsWith","slice","status","json","error","decoded","verifyIdToken","staff","host","firestore","collection","doc","get","exists","permission","allowed","data","uid","key","presetFor","refusal","org","orgForHost","locked","lockdown","request","method","email","outboxEntry","ref","paths","createdAt","serverTimestamp","attempts","entireHost","settleCache","entry","reason","dropped","dropCache","hostIds","catch","complete","delete","undefined","resolved","app","auth","now","Date","createProductSaveHandler","productId","product","Array","isArray","variants","name","trim","door","nowMs","fields","problem","db","hostRef","products","productRef","smartQuery","where","outbox","create","answer","runTransaction","tx","existing","smart","Promise","all","membership","collectionIds","docs","map","id","ok","replayed","early","used","aggregate","room","Number","createdAtMs","deletedAt","updatedAt","createdBy","set","storedTimestamps","console","stored","asked","Object","fromEntries","entries","filter","toDate","stockAttemptId","update","digest","createProductStockHandler","variantId","delta","Math","round","locationId","includes","isFinite","ledgerRef","ledger","inventory","some","variant","write","claimProductSlug","base","suffix","candidate","held","limit","empty","createProductDuplicateHandler","newProductId","source","copyRef","already","slug","createProductDeleteHandler","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,YAAY,EAAEC,yBAAyB,EAAEC,cAAc,QAAQ,0CAAyC;AACjH,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AACnH,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAEEC,iBAAiB,EACjBC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,wBAAwB,EACxBC,gBAAgB,EAChBC,sBAAsB,EACtBC,iBAAiB,EACjBC,sBAAsB,EACtBC,oBAAoB,EACpBC,eAAe,EACfC,oBAAoB,QAEf,oBAAU;AACjB,SAASC,WAAW,EAAEC,WAAW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AY;oBAAEyB,WAAW/H,WAAWqE,eAAe;gBAAG;gBAChEwC,GAAGqB,GAAG,CAACzB,OAAOvC,GAAG,EAAEuC,OAAOpD,IAAI;gBAC9B,OAAO;oBAAEd,QAAQ;oBAAKlB,MAAM;wBAAEkG,IAAI;wBAAMiD,SAAS;oBAAM;gBAAE;YAC3D;YACA,IAAI7D,OAAOpE,MAAM,KAAK,OAAO,CAAC,AAACoE,OAAOtF,IAAI,CAA2BmJ,OAAO,EAAE;gBAC5E,MAAMhG,YAAYzC,MAAMD,QAAQ2E,OAAOvC,GAAG,EAAE;YAC9C;YACA,OAAOrC,IAAIU,MAAM,CAACoE,OAAOpE,MAAM,EAAEC,IAAI,CAACmE,OAAOtF,IAAI;QACnD,EAAE,OAAOoB,OAAO;YACd2F,QAAQ3F,KAAK,CAAC,8BAA8BA;YAC5C,OAAOZ,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA2B;QAClE;IACF;AACF;AAEA,OAAO,MAAMkI,qBAAqBpF,2BAA0B;AAC5D,OAAO,MAAMqF,sBAAsB7B,4BAA2B;AAC9D,OAAO,MAAM8B,0BAA0BT,gCAA+B;AACtE,OAAO,MAAMU,uBAAuBJ,6BAA4B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/products-write.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 { validateProductForSave } from '../model/product-card-rules'\nimport { createHash } from 'node:crypto'\nimport { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n type EditedProduct,\n liftLegacyProduct,\n productCollectionIds,\n productDuplicateFields,\n productDuplicateName,\n productDuplicateSlugBase,\n productEditWrite,\n productMembershipInput,\n productSaveFields,\n smartCollectionRulesOf,\n stockAdjustmentWrite,\n variantMatrixProblem,\n type InventoryAdjustmentReason,\n} from '../model'\nimport { planRefusal, roomRefusal } from './product-drafts'\n\n/*\n * `POST /api/commerce/products/save` and `POST /api/commerce/products/stock`\n * (AGL-3652): the console product editor's save and its Adjust stock dialog,\n * for the native apps.\n *\n * The console makes both writes from the browser, computing derived fields\n * first (search keys, stock verdict, price, image, smart-collection\n * membership). These routes run THAT computation (`model/product-write.ts`,\n * which the console imports too) and make the same writes, under the gate\n * the Firestore rules put on them: a verified member with a write role on the\n * site (`canWriteHostContent`), or staff, while the site, its org and the\n * platform are not frozen (`hostWritesFrozen`). A new product also meets the\n * create path's own door: the plan's `commerce` entitlement and its\n * `productsPerHost` quota, counted in the same transaction as the create.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const ROLE_REFUSAL = siteKeyRefusal('site.edit')\nconst MAX_BODY_BYTES = 256_000\n\n/** The reasons the Adjust stock dialog offers. */\nexport const STOCK_ADJUST_REASONS: readonly InventoryAdjustmentReason[] = ['restock', 'correction', 'damage', 'refund']\n\nexport interface ProductsWriteDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n orgForHost?: (hostId: string) => Promise<{ org: Record<string, unknown> } | null>\n lockdown?: (options: Parameters<typeof getLockdownVerdict>[0]) => Promise<unknown>\n dropCache?: typeof dropPluginSiteCache\n now?: () => number\n}\n\ntype Reply = Parameters<PluginApiHandler>[1]\n\nexport function bodyOf(req: Parameters<PluginApiHandler>[0]): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n if (raw.length > MAX_BODY_BYTES) return {}\n try {\n return JSON.parse(raw || '{}')\n } catch {\n return {}\n }\n }\n return (raw ?? {}) as Record<string, unknown>\n}\n\nexport const validId = (value: unknown): value is string =>\n typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value)\n\nexport interface Gate {\n uid: string\n /** The caller's address, for an activity line; null when the token has none. */\n email: string | null\n staff: boolean\n host: FirebaseFirestore.DocumentSnapshot\n org: Record<string, unknown>\n}\n\n/**\n * The permission a route built on {@link gate} checks instead of the site\n * role (AGL-4047): a key whose preset is the site role, that preset (the\n * declaring plugin's own table, so the answer does not depend on which\n * plugins this process loaded), and the refusal naming it.\n */\nexport interface GatePermission {\n key: string\n presetFor: Readonly<Record<HostAccessRole, boolean>>\n refusal: string\n}\n\n/**\n * Who may write this site's products, as the rules decide it. Answers the\n * caller's reply on a refusal and returns null.\n *\n * A route that is not about products names the key it checks instead\n * (`permission`, AGL-4047): the walk-in and the guests change ask their\n * reservation key, read as the rules read it, from the site's\n * `memberPermissions` stamp, else the preset of the member's `memberRoles`\n * entry, so the route and the rules give one answer. Without it, the\n * product routes ask \"Edit site content\" (`site.edit`) the same way.\n */\nexport async function gate(\n req: Parameters<PluginApiHandler>[0],\n res: Reply,\n hostId: string,\n deps: Required<ProductsWriteDeps>,\n options: { permission?: GatePermission } = {},\n): Promise<Gate | null> {\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return void res.status(401).json({ error: 'Unauthenticated' }), null\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return void res.status(401).json({ error: 'Sign in again to continue' }), null\n }\n const staff = decoded['staff'] === true\n if (!staff && decoded['email_verified'] !== true && !isImpersonationSession(decoded as never)) {\n return void res.status(403).json({ error: 'Verify your email address to make changes' }), null\n }\n const host = await deps.firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return void res.status(404).json({ error: 'Unknown site' }), null\n if (!staff) {\n const { permission } = options\n const allowed = permission\n ? hostStampedSitePermission(host.data(), decoded.uid, permission.key, permission.presetFor)\n : holdsSiteKey(host, decoded.uid, 'site.edit')\n if (!allowed) return void res.status(403).json({ error: permission?.refusal ?? ROLE_REFUSAL }), null\n }\n const org = ((await deps.orgForHost(hostId))?.org ?? {}) as Record<string, unknown>\n const locked = await deps.lockdown({ staff, uid: decoded.uid, org: org as never, host: host.data() as never, request: { method: 'POST' } as never })\n if (locked) return void res.status(423).json({ error: 'This site is not accepting changes right now' }), null\n const email = typeof decoded['email'] === 'string' ? decoded['email'] : null\n return { uid: decoded.uid, email, staff, host, org }\n}\n\n/** The site-wide cache drop a product change is owed (AGL-3386): an outbox entry in the write, then the drop. */\nexport function outboxEntry(firestore: Firestore, hostId: string) {\n return {\n ref: firestore.collection('publishOutbox').doc(createResourceUid()),\n data: { hostId, paths: ['/'], createdAt: FieldValue.serverTimestamp(), attempts: 0, entireHost: true },\n }\n}\n\nexport async function settleCache(deps: Required<ProductsWriteDeps>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string) {\n const dropped = await deps.dropCache({ hostIds: [hostId], reason }).catch(() => ({ complete: false }))\n if (dropped.complete) await entry.delete().catch(() => undefined)\n}\n\nexport function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps> {\n return {\n firestore: deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore),\n verifyIdToken: deps.verifyIdToken ?? ((token) => firebaseAdmin.app().auth().verifyIdToken(token) as never),\n orgForHost: deps.orgForHost ?? ((hostId) => getOrgForHost(hostId) as never),\n lockdown: deps.lockdown ?? ((options) => getLockdownVerdict(options)),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n now: deps.now ?? (() => Date.now()),\n }\n}\n\n/**\n * Saves a product as the console editor does. `create: true` makes a new\n * product under the client-minted `productId` (a retry finds its own product\n * and answers `replayed`); otherwise it replaces the live product, keeping\n * its live stock holds.\n */\nexport function createProductSaveHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const product = body['product'] as EditedProduct | undefined\n if (!validId(hostId) || !validId(productId) || !product || typeof product !== 'object' || !Array.isArray(product.variants)) {\n return res.status(400).json({ error: 'Missing site, product or its variants' })\n }\n if (typeof product.name !== 'string' || !product.name.trim()) return res.status(400).json({ error: 'Product name is required' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const nowMs = deps.now()\n const fields = productSaveFields(product, nowMs)\n // More combinations than a product holds is refused with the count\n // (AGL-4100), never saved short of the options it names.\n const problem = variantMatrixProblem(fields.options) ?? validateProductForSave(fields as never)\n if (problem) return res.status(400).json({ error: problem })\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(productId)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const create = body['create'] === true\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart] = await Promise.all([tx.get(productRef), tx.get(smartQuery)])\n const membership = {\n collectionIds: productCollectionIds(\n productMembershipInput(fields, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n ),\n }\n if (create) {\n if (existing.exists) return { status: 200, body: { ok: true, id: productId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n tx.create(productRef, {\n ...fields,\n ...membership,\n createdAtMs: nowMs,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n } else {\n if (!existing.exists || existing.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n tx.set(productRef, {\n ...storedTimestamps(existing.data() ?? {}, product as unknown as Record<string, unknown>),\n ...productEditWrite(fields, existing.get('stockHolds')),\n ...membership,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: productId, replayed: false } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product saved from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/save]', error)\n return res.status(500).json({ error: 'The product could not be saved' })\n }\n }\n}\n\n/**\n * The stored timestamps an edit keeps. The console's replace writes back the\n * Timestamps its seed carried (`createdAt`, a publish time); a client's JSON\n * cannot carry one, so each stored Timestamp field the request does not name\n * is kept as stored.\n */\nexport function storedTimestamps(stored: Record<string, unknown>, asked: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(stored).filter(\n ([key, value]) => !(key in asked) && typeof (value as { toDate?: unknown } | null)?.toDate === 'function',\n ),\n )\n}\n\n/** The ledger row id one attempt owns: the same key from the same member is the same row. */\nexport function stockAttemptId(uid: string, key: string): string {\n return 'app-' + createHash('sha256').update(`${uid}:${key}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Adjusts one variant's stock as the Adjust stock dialog does: the variants\n * and stock fields on the product, and one `inventoryAdjustments` row, in one\n * transaction. The Idempotency-Key names that row, so a retried attempt finds\n * it and moves nothing twice.\n */\nexport function createProductStockHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const variantId = body['variantId']\n const key = String(req.headers['idempotency-key'] ?? '').trim().slice(0, 200)\n const reason = body['reason'] as InventoryAdjustmentReason\n const delta = Math.round(Number(body['delta']))\n const locationId = typeof body['locationId'] === 'string' && body['locationId'] ? body['locationId'] : undefined\n if (!validId(hostId) || !validId(productId) || typeof variantId !== 'string' || !variantId) {\n return res.status(400).json({ error: 'Missing site, product or variant' })\n }\n if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!STOCK_ADJUST_REASONS.includes(reason)) return res.status(400).json({ error: 'Unknown reason' })\n if (!Number.isFinite(delta) || delta === 0) return res.status(400).json({ error: 'Enter a number of units' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const productRef = hostRef.collection('products').doc(productId)\n const ledgerRef = hostRef.collection('inventoryAdjustments').doc(stockAttemptId(door.uid, key))\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [ledger, stored] = await Promise.all([tx.get(ledgerRef), tx.get(productRef)])\n if (ledger.exists) {\n return { status: 200, body: { ok: true, replayed: true, inventory: stored.get('inventory') ?? null } }\n }\n if (!stored.exists || stored.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n const product = stored.data() as never as Parameters<typeof stockAdjustmentWrite>[0]\n if (!(product.variants ?? []).some((variant) => variant.id === variantId)) {\n return { status: 404, body: { error: 'That variant is no longer on this product' } }\n }\n const write = stockAdjustmentWrite(product, productId, { variantId, delta, reason, locationId }, deps.now())\n if (!write) return { status: 400, body: { error: 'Enter a number of units' } }\n tx.update(productRef, write.update)\n tx.create(ledgerRef, write.ledger)\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, replayed: false, inventory: (write.update as { inventory?: unknown }).inventory ?? null } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'stock adjusted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/stock]', error)\n return res.status(500).json({ error: 'Stock could not be adjusted' })\n }\n }\n}\n\n/**\n * The first slug in `base`, `base-2`, `base-3`… no product of the site holds,\n * as the console's slug ledger claims one (`product-slugs.ts`): a second\n * Duplicate of the same product does not mint a second `-copy` (AGL-3321).\n */\nexport async function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string> {\n for (let suffix = 1; suffix < 1000; suffix += 1) {\n const candidate = suffix < 2 ? base : `${base}-${suffix}`\n const held = await products.where('slug', '==', candidate).limit(1).get()\n if (held.empty) return candidate\n }\n return `${base}-${Date.now()}`\n}\n\n/**\n * `POST /api/commerce/products/duplicate` (AGL-3841): the products list's\n * Duplicate for the native apps. The console builds the copy in the browser\n * (`productDuplicateFields`, its slug ledger, the copy's smart collections)\n * and creates it through the quota-enforcing resources route; this runs the\n * same model over the stored product and creates it under the save route's\n * create door (the plan's commerce entitlement and its product quota, counted\n * in the same transaction). `newProductId` is the client's, so a retry finds\n * its own copy and answers `replayed`.\n */\nexport function createProductDuplicateHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId, newProductId } = body\n if (!validId(hostId) || !validId(productId) || !validId(newProductId) || productId === newProductId) {\n return res.status(400).json({ error: 'Missing site or product' })\n }\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const copyRef = products.doc(newProductId)\n const already = await copyRef.get()\n if (already.exists) return res.status(200).json({ ok: true, id: newProductId, replayed: true })\n const source = await products.doc(productId).get()\n if (!source.exists || source.get('deletedAt')) return res.status(404).json({ error: 'This product was deleted' })\n const product = liftLegacyProduct((source.data() ?? {}) as never)\n const slug = await claimProductSlug(products, productDuplicateSlugBase(product.slug, product.name))\n const nowMs = deps.now()\n const fields = productDuplicateFields(product, slug, nowMs)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart] = await Promise.all([tx.get(copyRef), tx.get(smartQuery)])\n if (existing.exists) return { status: 200, body: { ok: true, id: newProductId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n // The COPY's smart collections: its name differs from the source's.\n const collectionIds = productCollectionIds(\n productMembershipInput({ name: productDuplicateName(product.name) }, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n )\n tx.create(copyRef, {\n ...fields,\n collectionIds,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: newProductId, replayed: false, slug } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product duplicated from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/duplicate]', error)\n return res.status(500).json({ error: 'Could not duplicate product' })\n }\n }\n}\n\n/**\n * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete\n * for the native apps, the console's write (`deletedAt` on the product, which\n * stops it being purchasable) with the site-wide cache drop, under the save\n * route's gate. Deleting a deleted product answers `already`.\n */\nexport function createProductDeleteHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId } = body\n if (!validId(hostId) || !validId(productId)) return res.status(400).json({ error: 'Missing site or product' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const stored = await tx.get(productRef)\n if (!stored.exists) return { status: 404, body: { error: 'This product no longer exists' } }\n if (stored.get('deletedAt')) return { status: 200, body: { ok: true, already: true } }\n tx.update(productRef, { deletedAt: FieldValue.serverTimestamp() })\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, already: false } }\n })\n if (answer.status === 200 && !(answer.body as { already?: boolean }).already) {\n await settleCache(deps, hostId, outbox.ref, 'product deleted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/delete]', error)\n return res.status(500).json({ error: 'Could not delete product' })\n }\n }\n}\n\nexport const productSaveHandler = createProductSaveHandler()\nexport const productStockHandler = createProductStockHandler()\nexport const productDuplicateHandler = createProductDuplicateHandler()\nexport const productDeleteHandler = createProductDeleteHandler()\n"],"names":["validateProductForSave","createHash","holdsSiteKey","hostStampedSitePermission","siteKeyRefusal","isRefusedIdToken","createResourceUid","countLiveDocuments","dropPluginSiteCache","firebaseAdmin","getLockdownVerdict","getOrgForHost","isImpersonationSession","FieldValue","liftLegacyProduct","productCollectionIds","productDuplicateFields","productDuplicateName","productDuplicateSlugBase","productEditWrite","productMembershipInput","productSaveFields","smartCollectionRulesOf","stockAdjustmentWrite","variantMatrixProblem","planRefusal","roomRefusal","ROLE_REFUSAL","MAX_BODY_BYTES","STOCK_ADJUST_REASONS","bodyOf","req","raw","body","length","JSON","parse","validId","value","test","gate","res","hostId","deps","options","authorization","String","headers","token","startsWith","slice","status","json","error","decoded","verifyIdToken","staff","host","firestore","collection","doc","get","exists","permission","allowed","data","uid","key","presetFor","refusal","org","orgForHost","locked","lockdown","request","method","email","outboxEntry","ref","paths","createdAt","serverTimestamp","attempts","entireHost","settleCache","entry","reason","dropped","dropCache","hostIds","catch","complete","delete","undefined","resolved","app","auth","now","Date","createProductSaveHandler","productId","product","Array","isArray","variants","name","trim","door","nowMs","fields","problem","db","hostRef","products","productRef","smartQuery","where","outbox","create","answer","runTransaction","tx","existing","smart","Promise","all","membership","collectionIds","docs","map","id","ok","replayed","early","used","aggregate","room","Number","createdAtMs","deletedAt","updatedAt","createdBy","set","storedTimestamps","console","stored","asked","Object","fromEntries","entries","filter","toDate","stockAttemptId","update","digest","createProductStockHandler","variantId","delta","Math","round","locationId","includes","isFinite","ledgerRef","ledger","inventory","some","variant","write","claimProductSlug","base","suffix","candidate","held","limit","empty","createProductDuplicateHandler","newProductId","source","copyRef","already","slug","createProductDeleteHandler","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,YAAY,EAAEC,yBAAyB,EAAEC,cAAc,QAAQ,0CAAyC;AACjH,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AACnH,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAEEC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;oBAAKlB,MAAM;wBAAEoB,OAAO;oBAAgC;gBAAE;gBAC3F,IAAI4F,OAAOpF,GAAG,CAAC,cAAc,OAAO;oBAAEV,QAAQ;oBAAKlB,MAAM;wBAAEkG,IAAI;wBAAMiD,SAAS;oBAAK;gBAAE;gBACrF3D,GAAGgC,MAAM,CAACvC,YAAY;oBAAEyB,WAAW9H,WAAWoE,eAAe;gBAAG;gBAChEwC,GAAGqB,GAAG,CAACzB,OAAOvC,GAAG,EAAEuC,OAAOpD,IAAI;gBAC9B,OAAO;oBAAEd,QAAQ;oBAAKlB,MAAM;wBAAEkG,IAAI;wBAAMiD,SAAS;oBAAM;gBAAE;YAC3D;YACA,IAAI7D,OAAOpE,MAAM,KAAK,OAAO,CAAC,AAACoE,OAAOtF,IAAI,CAA2BmJ,OAAO,EAAE;gBAC5E,MAAMhG,YAAYzC,MAAMD,QAAQ2E,OAAOvC,GAAG,EAAE;YAC9C;YACA,OAAOrC,IAAIU,MAAM,CAACoE,OAAOpE,MAAM,EAAEC,IAAI,CAACmE,OAAOtF,IAAI;QACnD,EAAE,OAAOoB,OAAO;YACd2F,QAAQ3F,KAAK,CAAC,8BAA8BA;YAC5C,OAAOZ,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA2B;QAClE;IACF;AACF;AAEA,OAAO,MAAMkI,qBAAqBpF,2BAA0B;AAC5D,OAAO,MAAMqF,sBAAsB7B,4BAA2B;AAC9D,OAAO,MAAM8B,0BAA0BT,gCAA+B;AACtE,OAAO,MAAMU,uBAAuBJ,6BAA4B"}
|
|
@@ -36,6 +36,8 @@ export interface QuoteDeliveryInput {
|
|
|
36
36
|
message: string;
|
|
37
37
|
payUrl: string;
|
|
38
38
|
proofUrl: (proofId: string) => string | null;
|
|
39
|
+
/** The customer signs in to their account on the site to see the proof (AGL-4206): no pictures of it go. */
|
|
40
|
+
signInFirst?: boolean;
|
|
39
41
|
linkReplaced: boolean;
|
|
40
42
|
/** The sending member's email: the Reply-To when the site has no contact email. */
|
|
41
43
|
senderEmail: string | null;
|
|
@@ -68,11 +70,35 @@ export interface QuoteMailerDeps {
|
|
|
68
70
|
suppression(email: string): Promise<'suppressed-platform' | null>;
|
|
69
71
|
}
|
|
70
72
|
export declare function defaultQuoteMailerDeps(): QuoteMailerDeps;
|
|
73
|
+
/** What a reply from the quote hands over (AGL-4207). */
|
|
74
|
+
export interface QuoteMessageDeliveryInput {
|
|
75
|
+
hostId: string;
|
|
76
|
+
quoteId: string;
|
|
77
|
+
order: CommerceModel.HostOrder;
|
|
78
|
+
host: Record<string, unknown>;
|
|
79
|
+
owner: {
|
|
80
|
+
id?: string;
|
|
81
|
+
org?: unknown;
|
|
82
|
+
} | null;
|
|
83
|
+
to: string;
|
|
84
|
+
/** The message as typed. */
|
|
85
|
+
body: string;
|
|
86
|
+
/** The quote's link at its current version. */
|
|
87
|
+
url: string;
|
|
88
|
+
senderEmail: string | null;
|
|
89
|
+
atMs: number;
|
|
90
|
+
}
|
|
71
91
|
/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */
|
|
72
92
|
export interface QuoteMailer {
|
|
73
93
|
configured(): boolean;
|
|
74
94
|
suppression(email: string): Promise<'suppressed-platform' | null>;
|
|
75
95
|
deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>;
|
|
96
|
+
/**
|
|
97
|
+
* A reply from the quote (AGL-4207): the `quote-message` catalog email, in
|
|
98
|
+
* the quote's conversation under its subject, answering to the site as the
|
|
99
|
+
* quote email does. No PDF goes with it.
|
|
100
|
+
*/
|
|
101
|
+
deliverMessage(input: QuoteMessageDeliveryInput): Promise<QuoteDeliveryResult>;
|
|
76
102
|
}
|
|
77
103
|
/** The business's name as its documents print it. */
|
|
78
104
|
export declare function quoteBusinessName(host: Record<string, unknown>): string;
|
|
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { siteContactEmail, resolveHostToken } from "@aglyn/aglyn/app-utils/host-tokens";
|
|
18
18
|
import { resolveBrandingProfile } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
19
|
-
import { emailThreadAfterSend, isEmailConfigured, mintEmailMessageId, nextThreadHeaders, PLATFORM_EMAIL_PALETTE, readEmailThread, resolveEmailColor, sendEmail } from "@aglyn/shared-util-email";
|
|
19
|
+
import { emailThreadAfterSend, emailThreadSubject, isEmailConfigured, mintEmailMessageId, nextThreadHeaders, PLATFORM_EMAIL_PALETTE, readEmailThread, resolveEmailColor, sendEmail } from "@aglyn/shared-util-email";
|
|
20
20
|
import { firebaseAdmin, hostSendingIdentity, meterHostEmail, renderHostEmailWithTokens, siteEmailFrame, transactionalAddressSuppression } from "@aglyn/tenant-data-admin";
|
|
21
21
|
import * as CommerceModel from "../model/index.js";
|
|
22
22
|
import { QUOTE_EMAIL_KEY, quoteEmailContent } from "../utils/quote-email-content.js";
|
|
@@ -60,12 +60,13 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
60
60
|
muted: read('text.secondary')
|
|
61
61
|
};
|
|
62
62
|
}
|
|
63
|
-
/** A refused send in the words the console shows. */ function refusalOf(result) {
|
|
63
|
+
/** A refused send in the words the console shows, for the quote email or a reply from the quote (AGL-4207). */ function refusalOf(result, what = 'quote') {
|
|
64
|
+
const notSent = what === 'quote' ? 'the quote wasn’t sent' : 'the reply wasn’t sent';
|
|
64
65
|
switch(result.reason){
|
|
65
66
|
case 'unconfigured':
|
|
66
67
|
return {
|
|
67
68
|
status: 503,
|
|
68
|
-
error:
|
|
69
|
+
error: `Email isn’t set up here, so ${notSent}.`
|
|
69
70
|
};
|
|
70
71
|
case 'rate-limited':
|
|
71
72
|
return {
|
|
@@ -76,17 +77,17 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
76
77
|
case 'undeliverable':
|
|
77
78
|
return {
|
|
78
79
|
status: 409,
|
|
79
|
-
error: 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.'
|
|
80
|
+
error: what === 'quote' ? 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.' : 'This address can’t receive email, so the reply wasn’t sent.'
|
|
80
81
|
};
|
|
81
82
|
case 'unverified-domain':
|
|
82
83
|
return {
|
|
83
84
|
status: 409,
|
|
84
|
-
error:
|
|
85
|
+
error: `This site’s sending domain isn’t verified, so ${notSent}. Check Email settings.`
|
|
85
86
|
};
|
|
86
87
|
case 'suspended':
|
|
87
88
|
return {
|
|
88
89
|
status: 423,
|
|
89
|
-
error:
|
|
90
|
+
error: `This site can’t send email right now, so ${notSent}.`
|
|
90
91
|
};
|
|
91
92
|
case 'held-for-review':
|
|
92
93
|
return {
|
|
@@ -96,7 +97,7 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
96
97
|
default:
|
|
97
98
|
return {
|
|
98
99
|
status: 502,
|
|
99
|
-
error: 'The quote email could not be sent. Try again.'
|
|
100
|
+
error: what === 'quote' ? 'The quote email could not be sent. Try again.' : 'The reply could not be sent. Try again.'
|
|
100
101
|
};
|
|
101
102
|
}
|
|
102
103
|
}
|
|
@@ -123,6 +124,7 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
123
124
|
message: input.message,
|
|
124
125
|
payUrl: input.payUrl,
|
|
125
126
|
proofUrl: input.proofUrl,
|
|
127
|
+
signInFirst: input.signInFirst === true,
|
|
126
128
|
linkReplaced: input.linkReplaced,
|
|
127
129
|
colors: proofColors(theme),
|
|
128
130
|
radius: theme == null ? void 0 : theme.buttonRadius,
|
|
@@ -209,6 +211,70 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
209
211
|
subject
|
|
210
212
|
})
|
|
211
213
|
};
|
|
214
|
+
},
|
|
215
|
+
deliverMessage: async (input)=>{
|
|
216
|
+
var _host_cname, _result_id;
|
|
217
|
+
var _order_quote, _input_owner;
|
|
218
|
+
const { hostId, quoteId, order, host } = input;
|
|
219
|
+
const businessName = quoteBusinessName(host);
|
|
220
|
+
const thread = readEmailThread((_order_quote = order.quote) == null ? void 0 : _order_quote.emailThread);
|
|
221
|
+
// The conversation's own subject, so the reply lands in it; a quote never emailed takes the quote email's.
|
|
222
|
+
const subject = emailThreadSubject(thread, CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId));
|
|
223
|
+
const content = CommerceModel.quoteMessageEmailTokens({
|
|
224
|
+
order,
|
|
225
|
+
quoteId,
|
|
226
|
+
businessName,
|
|
227
|
+
subject,
|
|
228
|
+
body: input.body,
|
|
229
|
+
url: input.url
|
|
230
|
+
});
|
|
231
|
+
const [identity, rendered] = await Promise.all([
|
|
232
|
+
deps.sendingIdentity(hostId),
|
|
233
|
+
deps.render(hostId, CommerceModel.QUOTE_MESSAGE_EMAIL_KEY, content.tokens)
|
|
234
|
+
]);
|
|
235
|
+
const siteHost = String((_host_cname = host['cname']) != null ? _host_cname : '').trim() || null;
|
|
236
|
+
const messageId = mintEmailMessageId([
|
|
237
|
+
identity == null ? void 0 : identity.domain,
|
|
238
|
+
identity == null ? void 0 : identity.from,
|
|
239
|
+
siteHost
|
|
240
|
+
], {
|
|
241
|
+
label: 'quote-message',
|
|
242
|
+
atMs: input.atMs
|
|
243
|
+
});
|
|
244
|
+
const replyTo = quoteReplyTo(host, input.senderEmail);
|
|
245
|
+
const result = await deps.send(_extends({
|
|
246
|
+
to: input.to,
|
|
247
|
+
subject,
|
|
248
|
+
text: (rendered == null ? void 0 : rendered.text) || content.text
|
|
249
|
+
}, (rendered == null ? void 0 : rendered.html) ? {
|
|
250
|
+
html: rendered.html
|
|
251
|
+
} : {}, {
|
|
252
|
+
headers: nextThreadHeaders(thread, messageId)
|
|
253
|
+
}, replyTo ? {
|
|
254
|
+
replyTo
|
|
255
|
+
} : {}, {
|
|
256
|
+
fromName: resolveBrandingProfile((_input_owner = input.owner) == null ? void 0 : _input_owner.org).fromName,
|
|
257
|
+
sendingIdentity: identity,
|
|
258
|
+
audience: 'tenant',
|
|
259
|
+
context: 'quote'
|
|
260
|
+
}));
|
|
261
|
+
if (!result.sent) {
|
|
262
|
+
return _extends({
|
|
263
|
+
sent: false
|
|
264
|
+
}, refusalOf(result, 'reply'));
|
|
265
|
+
}
|
|
266
|
+
await deps.meter(hostId).catch((error)=>console.error('[commerce/quote-email] not metered', error));
|
|
267
|
+
return {
|
|
268
|
+
sent: true,
|
|
269
|
+
messageId,
|
|
270
|
+
providerId: (_result_id = result.id) != null ? _result_id : null,
|
|
271
|
+
subject,
|
|
272
|
+
replyTo,
|
|
273
|
+
thread: emailThreadAfterSend(thread, {
|
|
274
|
+
messageId,
|
|
275
|
+
subject
|
|
276
|
+
})
|
|
277
|
+
};
|
|
212
278
|
}
|
|
213
279
|
};
|
|
214
280
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-email.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 { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n PLATFORM_EMAIL_PALETTE,\n readEmailThread,\n resolveEmailColor,\n sendEmail,\n type EmailTheme,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n siteEmailFrame,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { QUOTE_EMAIL_KEY, quoteEmailContent, type QuoteEmailColors } from '../utils/quote-email-content'\nimport type { quotePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\n\n/*==========================================\n * SENDING THE QUOTE EMAIL (AGL-4097). Loaded only by the console's Send\n * quote (`POST commerce/quote { action: 'send' }`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `quote-sent` catalog key in the site's theme and its header\n * and footer (or the site's own design of it), with the quote's PDF attached:\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), else the email of the person sending, so a reply reaches the\n * business either way, as an inbox reply's does;\n * - IN THE CUSTOMER'S CONVERSATION: a `Message-ID` minted on the sending\n * domain, and, when the quote already has a conversation (an earlier\n * send, or a request's confirmation), `In-Reply-To` and `References`\n * from it, else the root of the one it starts in `References`\n * (`nextThreadHeaders`). The provider's own id is returned beside ours,\n * because a provider may replace a caller's `Message-ID` (in production\n * one does), and a replaced one can then be traced;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam (`transactionalAddressSuppression`): the customer asked for the\n * quote, so an unsubscribe from the site's newsletter does not stop it,\n * as it does not stop a receipt (AGL-4098).\n *\n * The route decides everything about the quote (who may send, the link, the\n * stage); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface QuoteDeliveryInput {\n hostId: string\n quoteId: string\n /** The quote as it stands, after any pay link replacement this send made. */\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n payUrl: string\n proofUrl: (proofId: string) => string | null\n linkReplaced: boolean\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type QuoteDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface QuoteMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The site's email theme, for the colors the composed proof markup draws with. */\n theme(hostId: string): Promise<EmailTheme | null>\n /** The quote's PDF; loads the PDF writer and sharp only here. */\n quotePdf(input: Parameters<typeof quotePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: a quote is mail the customer asked for. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultQuoteMailerDeps(): QuoteMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n theme: async (hostId) => (await siteEmailFrame(firestore(), hostId, QUOTE_EMAIL_KEY)).theme,\n quotePdf: async (input) => (await import('./commerce-pdf')).quotePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface QuoteMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The business's name as its documents print it. */\nexport function quoteBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['name'] ?? '').trim()\n}\n\n/**\n * Who a reply reaches: the site's contact email, else the person sending, as\n * an inbox reply answers to them. Null only when neither is an address.\n */\nexport function quoteReplyTo(host: Record<string, unknown>, senderEmail: string | null | undefined): string | null {\n const contact = siteContactEmail(host as never)\n if (contact && EMAIL.test(contact)) return contact\n const sender = String(senderEmail ?? '').trim()\n return EMAIL.test(sender) ? sender : null\n}\n\n/** The theme's colors for the composed proof markup, the platform's where the site's cannot answer. */\nfunction proofColors(theme: EmailTheme | null): QuoteEmailColors {\n const read = (token: string) =>\n resolveEmailColor(token, theme?.palette) ?? resolveEmailColor(token, PLATFORM_EMAIL_PALETTE) ?? 'inherit'\n return { border: read('divider'), muted: read('text.secondary') }\n}\n\n/** A refused send in the words the console shows. */\nfunction refusalOf(result: Extract<SendEmailResult, { sent: false }>): { status: number; error: string } {\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: 'Email isn’t set up here, so the quote wasn’t sent.' }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return { status: 409, error: 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the quote wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the quote wasn’t sent.' }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: 'The quote email could not be sent. Try again.' }\n }\n}\n\n/** The quote email, said and sent. */\nexport function quoteMailer(deps: QuoteMailerDeps = defaultQuoteMailerDeps()): QuoteMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId)\n const [identity, theme] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.theme(hostId).catch(() => null),\n ])\n\n const content = quoteEmailContent({\n order,\n quoteId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n proofUrl: input.proofUrl,\n linkReplaced: input.linkReplaced,\n colors: proofColors(theme),\n radius: theme?.buttonRadius,\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n\n // The PDF is what the email says is attached; without it nothing goes. A\n // proof with no price yet says no such thing: its proof is the whole of it.\n let pdf: CommercePdfFile | null = null\n if (!content.proofOnly) {\n try {\n pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/quote-email] the PDF could not be made', { hostId, quoteId, error })\n return { sent: false, status: 500, error: 'The quote’s PDF could not be made, so nothing was sent. Try again.' }\n }\n }\n\n const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(order.quote?.emailThread)\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'quote',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n ...(pdf\n ? {\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n }\n : {}),\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n }\n}\n"],"names":["siteContactEmail","resolveHostToken","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","PLATFORM_EMAIL_PALETTE","readEmailThread","resolveEmailColor","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","siteEmailFrame","transactionalAddressSuppression","CommerceModel","QUOTE_EMAIL_KEY","quoteEmailContent","defaultQuoteMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","theme","quotePdf","input","quotePdfFile","send","options","meter","suppression","email","EMAIL","quoteBusinessName","host","named","String","trim","quoteReplyTo","senderEmail","contact","test","sender","proofColors","read","token","palette","border","muted","refusalOf","result","reason","status","error","detail","quoteMailer","deps","deliver","order","quoteId","businessName","subject","quoteEmailDefaultSubject","identity","Promise","all","catch","content","currency","store","message","payUrl","proofUrl","linkReplaced","colors","radius","buttonRadius","payLinkStoreOf","pdf","proofOnly","owner","console","sent","rendered","thread","quote","emailThread","siteHost","messageId","domain","from","label","atMs","replyTo","to","text","html","headers","fromName","org","audience","context","attachments","filename","contentType","Buffer","bytes","toString","providerId","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,EACfC,iBAAiB,EACjBC,SAAS,QAMJ,2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AAoD2D,EAAE,YAAvD,aAA2D;gBACvEhD;gBACAgC;gBACAT,QAAQvF,qBAAqBuF,QAAQ;oBAAEI;oBAAW3B;gBAAQ;YAC5D;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-email.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 { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n emailThreadSubject,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n PLATFORM_EMAIL_PALETTE,\n readEmailThread,\n resolveEmailColor,\n sendEmail,\n type EmailTheme,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n siteEmailFrame,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { QUOTE_EMAIL_KEY, quoteEmailContent, type QuoteEmailColors } from '../utils/quote-email-content'\nimport type { quotePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\n\n/*==========================================\n * SENDING THE QUOTE EMAIL (AGL-4097). Loaded only by the console's Send\n * quote (`POST commerce/quote { action: 'send' }`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `quote-sent` catalog key in the site's theme and its header\n * and footer (or the site's own design of it), with the quote's PDF attached:\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), else the email of the person sending, so a reply reaches the\n * business either way, as an inbox reply's does;\n * - IN THE CUSTOMER'S CONVERSATION: a `Message-ID` minted on the sending\n * domain, and, when the quote already has a conversation (an earlier\n * send, or a request's confirmation), `In-Reply-To` and `References`\n * from it, else the root of the one it starts in `References`\n * (`nextThreadHeaders`). The provider's own id is returned beside ours,\n * because a provider may replace a caller's `Message-ID` (in production\n * one does), and a replaced one can then be traced;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam (`transactionalAddressSuppression`): the customer asked for the\n * quote, so an unsubscribe from the site's newsletter does not stop it,\n * as it does not stop a receipt (AGL-4098).\n *\n * The route decides everything about the quote (who may send, the link, the\n * stage); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface QuoteDeliveryInput {\n hostId: string\n quoteId: string\n /** The quote as it stands, after any pay link replacement this send made. */\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n payUrl: string\n proofUrl: (proofId: string) => string | null\n /** The customer signs in to their account on the site to see the proof (AGL-4206): no pictures of it go. */\n signInFirst?: boolean\n linkReplaced: boolean\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type QuoteDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface QuoteMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The site's email theme, for the colors the composed proof markup draws with. */\n theme(hostId: string): Promise<EmailTheme | null>\n /** The quote's PDF; loads the PDF writer and sharp only here. */\n quotePdf(input: Parameters<typeof quotePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: a quote is mail the customer asked for. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultQuoteMailerDeps(): QuoteMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n theme: async (hostId) => (await siteEmailFrame(firestore(), hostId, QUOTE_EMAIL_KEY)).theme,\n quotePdf: async (input) => (await import('./commerce-pdf')).quotePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What a reply from the quote hands over (AGL-4207). */\nexport interface QuoteMessageDeliveryInput {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The message as typed. */\n body: string\n /** The quote's link at its current version. */\n url: string\n senderEmail: string | null\n atMs: number\n}\n\n/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface QuoteMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>\n /**\n * A reply from the quote (AGL-4207): the `quote-message` catalog email, in\n * the quote's conversation under its subject, answering to the site as the\n * quote email does. No PDF goes with it.\n */\n deliverMessage(input: QuoteMessageDeliveryInput): Promise<QuoteDeliveryResult>\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The business's name as its documents print it. */\nexport function quoteBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['name'] ?? '').trim()\n}\n\n/**\n * Who a reply reaches: the site's contact email, else the person sending, as\n * an inbox reply answers to them. Null only when neither is an address.\n */\nexport function quoteReplyTo(host: Record<string, unknown>, senderEmail: string | null | undefined): string | null {\n const contact = siteContactEmail(host as never)\n if (contact && EMAIL.test(contact)) return contact\n const sender = String(senderEmail ?? '').trim()\n return EMAIL.test(sender) ? sender : null\n}\n\n/** The theme's colors for the composed proof markup, the platform's where the site's cannot answer. */\nfunction proofColors(theme: EmailTheme | null): QuoteEmailColors {\n const read = (token: string) =>\n resolveEmailColor(token, theme?.palette) ?? resolveEmailColor(token, PLATFORM_EMAIL_PALETTE) ?? 'inherit'\n return { border: read('divider'), muted: read('text.secondary') }\n}\n\n/** A refused send in the words the console shows, for the quote email or a reply from the quote (AGL-4207). */\nfunction refusalOf(\n result: Extract<SendEmailResult, { sent: false }>,\n what: 'quote' | 'reply' = 'quote',\n): { status: number; error: string } {\n const notSent = what === 'quote' ? 'the quote wasn’t sent' : 'the reply wasn’t sent'\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: `Email isn’t set up here, so ${notSent}.` }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return {\n status: 409,\n error:\n what === 'quote'\n ? 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.'\n : 'This address can’t receive email, so the reply wasn’t sent.',\n }\n case 'unverified-domain':\n return { status: 409, error: `This site’s sending domain isn’t verified, so ${notSent}. Check Email settings.` }\n case 'suspended':\n return { status: 423, error: `This site can’t send email right now, so ${notSent}.` }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: what === 'quote' ? 'The quote email could not be sent. Try again.' : 'The reply could not be sent. Try again.' }\n }\n}\n\n/** The quote email, said and sent. */\nexport function quoteMailer(deps: QuoteMailerDeps = defaultQuoteMailerDeps()): QuoteMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId)\n const [identity, theme] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.theme(hostId).catch(() => null),\n ])\n\n const content = quoteEmailContent({\n order,\n quoteId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n proofUrl: input.proofUrl,\n signInFirst: input.signInFirst === true,\n linkReplaced: input.linkReplaced,\n colors: proofColors(theme),\n radius: theme?.buttonRadius,\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n\n // The PDF is what the email says is attached; without it nothing goes. A\n // proof with no price yet says no such thing: its proof is the whole of it.\n let pdf: CommercePdfFile | null = null\n if (!content.proofOnly) {\n try {\n pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/quote-email] the PDF could not be made', { hostId, quoteId, error })\n return { sent: false, status: 500, error: 'The quote’s PDF could not be made, so nothing was sent. Try again.' }\n }\n }\n\n const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(order.quote?.emailThread)\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'quote',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n ...(pdf\n ? {\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n }\n : {}),\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n deliverMessage: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const thread = readEmailThread(order.quote?.emailThread)\n // The conversation's own subject, so the reply lands in it; a quote never emailed takes the quote email's.\n const subject = emailThreadSubject(thread, CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId))\n const content = CommerceModel.quoteMessageEmailTokens({ order, quoteId, businessName, subject, body: input.body, url: input.url })\n const [identity, rendered] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.render(hostId, CommerceModel.QUOTE_MESSAGE_EMAIL_KEY, content.tokens),\n ])\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], { label: 'quote-message', atMs: input.atMs })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n const result = await deps.send({\n to: input.to,\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n })\n if (!result.sent) {\n return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>, 'reply') }\n }\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n }\n}\n"],"names":["siteContactEmail","resolveHostToken","resolveBrandingProfile","emailThreadAfterSend","emailThreadSubject","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","PLATFORM_EMAIL_PALETTE","readEmailThread","resolveEmailColor","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","siteEmailFrame","transactionalAddressSuppression","CommerceModel","QUOTE_EMAIL_KEY","quoteEmailContent","defaultQuoteMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","theme","quotePdf","input","quotePdfFile","send","options","meter","suppression","email","EMAIL","quoteBusinessName","host","named","String","trim","quoteReplyTo","senderEmail","contact","test","sender","proofColors","read","token","palette","border","muted","refusalOf","result","what","notSent","reason","status","error","detail","quoteMailer","deps","deliver","order","quoteId","businessName","subject","quoteEmailDefaultSubject","identity","Promise","all","catch","content","currency","store","message","payUrl","proofUrl","signInFirst","linkReplaced","colors","radius","buttonRadius","payLinkStoreOf","pdf","proofOnly","owner","console","sent","rendered","thread","quote","emailThread","siteHost","messageId","domain","from","label","atMs","replyTo","to","text","html","headers","fromName","org","audience","context","attachments","filename","contentType","Buffer","bytes","toString","providerId","id","deliverMessage","quoteMessageEmailTokens","body","url","QUOTE_MESSAGE_EMAIL_KEY"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,EACfC,iBAAiB,EACjBC,SAAS,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B,4BAAAA,SAAU4B,IAAI;gBAAEH;aAAS,EAAE;gBAAEI,OAAO;gBAAiBC,MAAMtE,MAAMsE,IAAI;YAAC;YAC9H,MAAMC,UAAU1D,aAAaJ,MAAMT,MAAMc,WAAW;YACpD,MAAMW,SAAS,MAAMQ,KAAK/B,IAAI,CAAC;gBAC7BsE,IAAIxE,MAAMwE,EAAE;gBACZlC;gBACAmC,MAAMZ,CAAAA,4BAAAA,SAAUY,IAAI,KAAI7B,QAAQ6B,IAAI;eAChCZ,CAAAA,4BAAAA,SAAUa,IAAI,IAAG;gBAAEA,MAAMb,SAASa,IAAI;YAAC,IAAI,CAAC;gBAChDC,SAASpG,kBAAkBuF,QAAQI;eAC/BK,UAAU;gBAAEA;YAAQ,IAAI,CAAC;gBAC7BK,UAAU1G,wBAAuB8B,eAAAA,MAAM0D,KAAK,qBAAX1D,aAAa6E,GAAG,EAAWD,QAAQ;gBACpEnF,iBAAiB+C;gBACjBsC,UAAU;gBACVC,SAAS;;YAEX,IAAI,CAACtD,OAAOmC,IAAI,EAAE;gBAChB,OAAO;oBAAEA,MAAM;mBAAUpC,UAAUC,QAAqD;YAC1F;YACA,MAAMQ,KAAK7B,KAAK,CAACV,QAAQiD,KAAK,CAAC,CAACb,QAAU6B,QAAQ7B,KAAK,CAAC,sCAAsCA;YAC9F,OAAO;gBACL8B,MAAM;gBACNM;gBACAoB,UAAU,GAAE,aAAA,AAAC7D,OAAoD8D,EAAE,YAAvD,aAA2D;gBACvEjD;gBACAiC;gBACAT,QAAQ3F,qBAAqB2F,QAAQ;oBAAEI;oBAAW5B;gBAAQ;YAC5D;QACF;IACF;AACF"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server';
|
|
18
|
+
import * as CommerceModel from '../model';
|
|
19
|
+
import type { QuoteDeps } from './quote';
|
|
20
|
+
import { type QuoteLinkOutcome } from './quote-pay';
|
|
21
|
+
import { type QuoteProofDeps } from './quote-proofs';
|
|
22
|
+
type Outcome = {
|
|
23
|
+
status: number;
|
|
24
|
+
body: Record<string, unknown>;
|
|
25
|
+
};
|
|
26
|
+
/** Messages the customer may send per address per site, per ten minutes. */
|
|
27
|
+
export declare const QUOTE_MESSAGES_PER_WINDOW = 20;
|
|
28
|
+
/** The quote's messages, newest {@link CommerceModel.QUOTE_MESSAGES_SHOWN}, as stored (the page's view reads the same, in `payLinkPageView`). */
|
|
29
|
+
export declare function readQuoteMessages(orderRef: FirebaseFirestore.DocumentReference): Promise<Array<{
|
|
30
|
+
id: string;
|
|
31
|
+
data: Partial<CommerceModel.QuoteMessage>;
|
|
32
|
+
}>>;
|
|
33
|
+
export declare function handleQuoteMessagesAction(deps: QuoteDeps, context: {
|
|
34
|
+
action: 'messages' | 'reply';
|
|
35
|
+
req: PluginApiRequest;
|
|
36
|
+
body: Record<string, unknown>;
|
|
37
|
+
hostId: string;
|
|
38
|
+
quoteId: string;
|
|
39
|
+
hostRef: FirebaseFirestore.DocumentReference;
|
|
40
|
+
host: Record<string, unknown>;
|
|
41
|
+
actor: string;
|
|
42
|
+
senderEmail: string | null;
|
|
43
|
+
}): Promise<Outcome>;
|
|
44
|
+
/** The managers' notice of a customer's message: who, which quote, what they said, and how to answer. */
|
|
45
|
+
export declare function quoteMessageNotice(input: {
|
|
46
|
+
hostId: string;
|
|
47
|
+
quoteId: string;
|
|
48
|
+
order: CommerceModel.HostOrder;
|
|
49
|
+
body: string;
|
|
50
|
+
}): {
|
|
51
|
+
payload: {
|
|
52
|
+
type: "content.order";
|
|
53
|
+
level: "info";
|
|
54
|
+
label: string;
|
|
55
|
+
actionLabel: string;
|
|
56
|
+
title: string;
|
|
57
|
+
body: string;
|
|
58
|
+
link: string;
|
|
59
|
+
};
|
|
60
|
+
options: {
|
|
61
|
+
replyTo?: string;
|
|
62
|
+
emailDetails: {
|
|
63
|
+
label: string;
|
|
64
|
+
value: string;
|
|
65
|
+
}[];
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
/** `POST /api/commerce/quote-message`: the customer writes to the business on the quote page. */
|
|
69
|
+
export declare function handleQuoteMessage(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome>;
|
|
70
|
+
/** `POST /api/commerce/quote-message`. */
|
|
71
|
+
export declare const quoteMessageHandler: PluginApiHandler;
|
|
72
|
+
export {};
|