@aglyn/plugins-commerce 1.4.0 → 1.6.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/package.json +13 -13
- package/src/lib/components/console/catalog-organization-card.component.js +14 -8
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +4 -2
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +4 -2
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.d.ts +3 -0
- package/src/lib/components/console/product-editor-dialog.component.js +4 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +5 -2
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +4 -2
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +5 -3
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +4 -2
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +5 -3
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +5 -3
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +4 -2
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +5 -3
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/server/commerce-pdf.d.ts +5 -3
- package/src/lib/server/commerce-pdf.js +5 -3
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/membership-register.js +3 -3
- package/src/lib/server/membership-register.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/tax-settings-card.component.tsx"],"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'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\n\nexport interface TaxSettingsCardProps {\n hostId: string\n}\n\n/**\n * Tax settings (AGL-285): manual per-region rates (most-specific wins)\n * or Stripe Tax automatic calculation, stored on\n * `hosts/{hostId}/settings/store` under `tax`. The legacy quick-buy\n * checkout taxes by the store origin; Checkout v2 taxes by destination.\n */\nexport function TaxSettingsCard(props: TaxSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? store?.tax ?? {mode: 'manual'}` and\n * the save writes `{tax: current}`, so `merge: true` protects the doc's\n * other maps and nothing inside this one. `mode` is the field that costs\n * money: a cached seed flipping `stripe` back to `manual` stops automatic\n * tax calculation — `resolveTaxRate` returns null in stripe mode — and\n * the store under-collects with nothing anywhere reporting it.\n */\n fromCache: storeFromCache,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const [draft, setDraft] = useState<CommerceModel.TaxSettings | null>(null)\n const current: CommerceModel.TaxSettings = draft ?? store?.tax ?? { mode: 'manual' }\n /**\n * Whether anyone has ever answered the tax question for this store\n * (AGL-1999). Read from the SAVED document, never from `current` — the\n * `{ mode: 'manual' }` seed above is local state that has never reached\n * Firestore, and it is exactly what made this invisible: the card looked\n * configured while the server saw `mode: undefined`, took no branch, and\n * sold untaxed. Every storefront path now refuses that state, so the card\n * has to show it rather than paper over it.\n */\n const decided =\n storeStatus !== 'loading' && typeof store?.tax?.mode === 'string'\n const update = (patch: Partial<CommerceModel.TaxSettings>) =>\n setDraft({ ...current, ...patch })\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.TaxRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else rates[index] = { country: '', pct: 0, ...rates[index], ...patch }\n update({ rates })\n }\n /**\n * One of the flat, per-regime rates (AGL-1969 lodging, AGL-2028 services).\n *\n * A blank field clears the rate rather than storing `NaN`: clearing is how a\n * merchant turns the regime back off, and `Number('')` is 0 while\n * `Number(' ')` is also 0 — neither of which should ever reach the document\n * as a \"rate\".\n */\n const updateFlat = (\n key: 'lodging' | 'service',\n patch: Partial<CommerceModel.FlatTaxRate>,\n ) => update({ [key]: { ...current[key], ...patch } })\n const flatPctText = (key: 'lodging' | 'service') => {\n const pct = current[key]?.pct\n return pct === undefined || pct === null ? '' : String(pct)\n }\n /**\n * Shown under a typed rate this will NOT apply. Silence here would be the\n * failure: `resolveFlatTaxCents` treats an out-of-range percentage as off,\n * so a decimal-point typo would otherwise save cleanly and collect nothing.\n */\n const flatPctProblem = (key: 'lodging' | 'service'): string | null => {\n const raw = current[key]?.pct\n if (raw === undefined || raw === null || String(raw) === '') return null\n if (Number(raw) === 0) return null\n return CommerceModel.isUsableFlatTaxPct(raw)\n ? null\n : `Enter a percentage between 0 and ${CommerceModel.FLAT_TAX_MAX_PCT}. ` +\n 'This rate is not being applied.'\n }\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * No create path to exempt: this is a FIXED document path, so the\n * `{mode: 'manual'}` default produced when the cache has never seen the\n * map is not the harmless blank a fresh uid would be — writing it turns\n * automatic tax calculation off on a store that had it on.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'tax settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n { tax: current },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps every typed rate on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Tax settings saved', { variant: 'success', persist: false })\n }, [current, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache])\n\n return (\n <CardDisplay\n // Another plugin's card scrolls here (the tax service's \"Go to Taxes\",\n // AGL-3693), restating this id rather than importing this package.\n id=\"commerce-store-taxes\"\n header={'Taxes'}\n help={pluginDocsHelp('commerce', { anchor: '#tax-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n {decided ? null : (\n // The store is not selling. Saying so here is the whole point: the\n // silent version of this state charged shoppers an untaxed total.\n <Alert severity=\"warning\">\n {'Choose how this store handles sales tax and save. Until you ' +\n 'do, checkout is turned off — we won’t take an order we can’t ' +\n 'tax correctly.'}\n </Alert>\n )}\n <TextField\n label=\"Calculation\"\n value={current.mode ?? 'manual'}\n onChange={(event) =>\n update({\n mode: event.target.value as 'manual' | 'stripe' | 'none',\n })\n }\n size=\"small\"\n select\n sx={{ maxWidth: 280 }}\n >\n <MenuItem value=\"manual\">{'Manual rates (below)'}</MenuItem>\n <MenuItem value=\"stripe\">{'Stripe Tax (automatic)'}</MenuItem>\n {/* An explicit decision, not an omission (AGL-1999) — the option a\n merchant under a nexus threshold, or selling non-taxable goods,\n needs in order to sell at all. */}\n <MenuItem value=\"none\">{'Don’t collect sales tax'}</MenuItem>\n </TextField>\n {current.mode === 'none' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This store adds no sales tax to any order. Orders still go ' +\n 'through — the decision is recorded, not the tax.'}\n </Typography>\n ) : current.mode === 'stripe' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Stripe Tax calculates per buyer location at checkout. ' +\n 'Activate Stripe Tax in your Stripe dashboard first.'}\n </Typography>\n ) : (\n <>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.pricesIncludeTax)}\n onChange={(event) =>\n update({ pricesIncludeTax: event.target.checked })\n }\n />\n }\n label=\"Prices include tax (VAT-style)\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Origin country\"\n value={current.origin?.country ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n country: event.target.value.toUpperCase().slice(0, 2),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"US\"\n />\n <TextField\n label=\"Origin state\"\n value={current.origin?.state ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n state: event.target.value.toUpperCase().slice(0, 3),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"TX\"\n />\n </Stack>\n {/* Which of the product's three addresses this is. A merchant\n who reads an unlabeled origin as \"our address\" may set it\n from the wrong one: the address the workspace pays Aglyn\n from is a different jurisdiction question, and the payout\n identity is a third. Naming the two it is NOT costs a line\n and prevents a mis-taxed order. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Where this store ships or sells FROM — the jurisdiction the ' +\n 'manual rates below are applied from. Not the address your ' +\n 'workspace is billed at by Aglyn, and not where your payouts ' +\n 'are sent.'}\n </Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n label=\"Country\"\n value={rate.country}\n onChange={(event) =>\n updateRate(index, {\n country: event.target.value.toUpperCase().slice(0, 2),\n })\n }\n size=\"small\"\n sx={{ width: 90 }}\n />\n <TextField\n label=\"State\"\n value={rate.state ?? ''}\n onChange={(event) =>\n updateRate(index, {\n state:\n event.target.value.toUpperCase().slice(0, 3) ||\n undefined,\n })\n }\n size=\"small\"\n sx={{ width: 80 }}\n />\n <TextField\n label=\"%\"\n value={rate.pct}\n onChange={(event) =>\n updateRate(index, { pct: Number(event.target.value) || 0 })\n }\n size=\"small\"\n sx={{ width: 80 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={rate.label ?? ''}\n onChange={(event) =>\n updateRate(index, { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Sales tax\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n </>\n )}\n {/*\n LODGING TAX (AGL-1969) — deliberately OUTSIDE the calculation branch\n above, and deliberately not a `rates[]` row.\n\n The setting above is a goods SALES rate resolved against an address.\n Occupancy tax is a different regime with its own rates, registration\n and return, and it applies to reservations, which sell nights rather\n than goods. Nesting it under \"Manual rates\" would have said the two\n are the same machinery; putting it here says a store on Stripe Tax —\n which cannot compute occupancy tax from these sessions at all — can\n still set one.\n\n It is off until the merchant fills it in, so nothing an existing\n store charges moves.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Lodging tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on reservations, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because occupancy tax is its own regime with its own rates ' +\n 'and its own return. Leave it blank to charge none — that is ' +\n 'the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('lodging')}\n onChange={(event) =>\n updateFlat('lodging', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('lodging'))}\n helperText={flatPctProblem('lodging') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.lodging?.label ?? ''}\n onChange={(event) =>\n updateFlat('lodging', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Occupancy tax\"\n helperText=\"Shown to the guest on the receipt\"\n />\n </Stack>\n {/*\n MECHANISM ONLY, AND NO REMITTANCE DETERMINATION.\n\n Whether a jurisdiction imposes occupancy tax, who must register for\n it and who must remit it are legal conclusions that attach by\n operation of law (AGL-1904/AGL-1956) and are the merchant's under\n the Terms. This copy says what the software DOES and what it does\n not do, and stops there — including the deposit basis, which is a\n real limitation rather than an answer this product has taken.\n */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'On a reservation that takes a deposit, the rate is applied to ' +\n 'the deposit — the amount actually charged here — not to the ' +\n 'whole stay. If tax is due on the full stay, collect the ' +\n 'difference the same way you collect the rest of the balance.'}\n </Typography>\n </Stack>\n {/*\n SERVICE TAX (AGL-2028) — the bookings sibling of the block above,\n and here for the same reason it is not in the bookings plugin's own\n settings: this is the one card a merchant comes to with a tax\n question, and a second tax surface elsewhere is how one of them ends\n up unanswered.\n\n Its EXISTENCE is also the opt-in AGL-2000 wanted. That issue\n declined to apply the goods rate to an appointment partly because\n nothing said the merchant meant these settings to cover bookings; a\n field labelled for services, blank until they fill it in, is them\n saying so.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Service tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on paid bookings, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because whether a service is taxable is often a different ' +\n 'question from whether goods are. Leave it blank to charge ' +\n 'none — that is the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('service')}\n onChange={(event) =>\n updateFlat('service', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('service'))}\n helperText={flatPctProblem('service') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.service?.label ?? ''}\n onChange={(event) =>\n updateFlat('service', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Service tax\"\n helperText=\"Shown to the client on the receipt\"\n />\n </Stack>\n {/* MECHANISM ONLY, AND NO REMITTANCE DETERMINATION — see the\n lodging block above. */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n </Stack>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n // An undecided store saves the choice on screen as it stands. The\n // select fires no change for the option already shown, so waiting\n // for an edit left \"Manual rates\" unsaveable and checkout off.\n disabled={storeStatus === 'loading' || (decided && !draft)}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save tax settings'}\n </Button>\n </Stack>\n </CardDisplay>\n )\n}\nTaxSettingsCard.displayName = 'TaxSettingsCard'\n\nexport default TaxSettingsCard\n"],"names":["CommerceModel","PLATFORM_BRAND_NAME","CardDisplay","useSnackbar","Alert","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","setDoc","useCallback","useState","useFirestore","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","TaxSettingsCard","props","draft","current","flatPctProblem","store","hostId","firestore","enqueueSnackbar","data","status","storeStatus","fromCache","storeFromCache","setDraft","tax","mode","decided","update","patch","updateRate","index","rates","splice","country","pct","updateFlat","key","flatPctText","undefined","String","raw","Number","isUsableFlatTaxPct","FLAT_TAX_MAX_PCT","handleSave","verdict","subject","unreadable","merge","ok","message","variant","persist","id","header","help","anchor","contentGutterX","contentGutterY","spacing","severity","label","value","onChange","event","target","size","select","sx","maxWidth","color","control","checked","Boolean","pricesIncludeTax","direction","origin","toUpperCase","slice","width","placeholder","state","map","rate","slotProps","htmlInput","inputMode","flex","onClick","alignSelf","length","my","error","helperText","lodging","service","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SAC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C8D,OAAM;oCACNC,KAAK,YAAElD,mBAAAA,QAAQmF,OAAO,qBAAfnF,iBAAiBiD,KAAK,oBAAI;oCACjCE,UAAU,CAACC,QACT7B,WAAW,WAAW;4CAAE0B,OAAOG,MAAMC,MAAM,CAACH,KAAK;wCAAC;oCAEpDI,MAAK;oCACLE,IAAI;wCAAEmB,MAAM;oCAAE;oCACdP,aAAY;oCACZa,YAAW;;;;sCAKf,KAACrG;4BAAMoE,UAAS;sCACb,GAAGvE,oBAAoB,wCAAwC,CAAC,GAC/D,8DACA,gEACA;;;;8BAGN,KAACI;oBACC0D,SAAQ;oBACRmB,OAAM;oBACNJ,MAAK;oBACL,kEAAkE;oBAClE,kEAAkE;oBAClE,+DAA+D;oBAC/D8B,UAAU5E,gBAAgB,aAAcM,WAAW,CAACf;oBACpD6E,SAAS5C;oBACTwB,IAAI;wBAAEqB,WAAW;oBAAa;8BAE7B;;;;;AAKX;AACAhF,gBAAgBwF,WAAW,GAAG;AAE9B,eAAexF,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/tax-settings-card.component.tsx"],"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'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\n\nexport interface TaxSettingsCardProps {\n hostId: string\n}\n\n/**\n * Tax settings (AGL-285): manual per-region rates (most-specific wins)\n * or Stripe Tax automatic calculation, stored on\n * `hosts/{hostId}/settings/store` under `tax`. The legacy quick-buy\n * checkout taxes by the store origin; Checkout v2 taxes by destination.\n */\nexport function TaxSettingsCard(props: TaxSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? store?.tax ?? {mode: 'manual'}` and\n * the save writes `{tax: current}`, so `merge: true` protects the doc's\n * other maps and nothing inside this one. `mode` is the field that costs\n * money: a cached seed flipping `stripe` back to `manual` stops automatic\n * tax calculation — `resolveTaxRate` returns null in stripe mode — and\n * the store under-collects with nothing anywhere reporting it.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const [draft, setDraft] = useState<CommerceModel.TaxSettings | null>(null)\n const current: CommerceModel.TaxSettings = draft ?? store?.tax ?? { mode: 'manual' }\n /**\n * Whether anyone has ever answered the tax question for this store\n * (AGL-1999). Read from the SAVED document, never from `current` — the\n * `{ mode: 'manual' }` seed above is local state that has never reached\n * Firestore, and it is exactly what made this invisible: the card looked\n * configured while the server saw `mode: undefined`, took no branch, and\n * sold untaxed. Every storefront path now refuses that state, so the card\n * has to show it rather than paper over it.\n */\n const decided =\n storeStatus !== 'loading' && typeof store?.tax?.mode === 'string'\n const update = (patch: Partial<CommerceModel.TaxSettings>) =>\n setDraft({ ...current, ...patch })\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.TaxRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else rates[index] = { country: '', pct: 0, ...rates[index], ...patch }\n update({ rates })\n }\n /**\n * One of the flat, per-regime rates (AGL-1969 lodging, AGL-2028 services).\n *\n * A blank field clears the rate rather than storing `NaN`: clearing is how a\n * merchant turns the regime back off, and `Number('')` is 0 while\n * `Number(' ')` is also 0 — neither of which should ever reach the document\n * as a \"rate\".\n */\n const updateFlat = (\n key: 'lodging' | 'service',\n patch: Partial<CommerceModel.FlatTaxRate>,\n ) => update({ [key]: { ...current[key], ...patch } })\n const flatPctText = (key: 'lodging' | 'service') => {\n const pct = current[key]?.pct\n return pct === undefined || pct === null ? '' : String(pct)\n }\n /**\n * Shown under a typed rate this will NOT apply. Silence here would be the\n * failure: `resolveFlatTaxCents` treats an out-of-range percentage as off,\n * so a decimal-point typo would otherwise save cleanly and collect nothing.\n */\n const flatPctProblem = (key: 'lodging' | 'service'): string | null => {\n const raw = current[key]?.pct\n if (raw === undefined || raw === null || String(raw) === '') return null\n if (Number(raw) === 0) return null\n return CommerceModel.isUsableFlatTaxPct(raw)\n ? null\n : `Enter a percentage between 0 and ${CommerceModel.FLAT_TAX_MAX_PCT}. ` +\n 'This rate is not being applied.'\n }\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * No create path to exempt: this is a FIXED document path, so the\n * `{mode: 'manual'}` default produced when the cache has never seen the\n * map is not the harmless blank a fresh uid would be — writing it turns\n * automatic tax calculation off on a store that had it on.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'tax settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n { tax: current },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps every typed rate on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Tax settings saved', { variant: 'success', persist: false })\n }, [current, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, storeListen])\n\n return (\n <CardDisplay\n // Another plugin's card scrolls here (the tax service's \"Go to Taxes\",\n // AGL-3693), restating this id rather than importing this package.\n id=\"commerce-store-taxes\"\n header={'Taxes'}\n help={pluginDocsHelp('commerce', { anchor: '#tax-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n {decided ? null : (\n // The store is not selling. Saying so here is the whole point: the\n // silent version of this state charged shoppers an untaxed total.\n <Alert severity=\"warning\">\n {'Choose how this store handles sales tax and save. Until you ' +\n 'do, checkout is turned off — we won’t take an order we can’t ' +\n 'tax correctly.'}\n </Alert>\n )}\n <TextField\n label=\"Calculation\"\n value={current.mode ?? 'manual'}\n onChange={(event) =>\n update({\n mode: event.target.value as 'manual' | 'stripe' | 'none',\n })\n }\n size=\"small\"\n select\n sx={{ maxWidth: 280 }}\n >\n <MenuItem value=\"manual\">{'Manual rates (below)'}</MenuItem>\n <MenuItem value=\"stripe\">{'Stripe Tax (automatic)'}</MenuItem>\n {/* An explicit decision, not an omission (AGL-1999) — the option a\n merchant under a nexus threshold, or selling non-taxable goods,\n needs in order to sell at all. */}\n <MenuItem value=\"none\">{'Don’t collect sales tax'}</MenuItem>\n </TextField>\n {current.mode === 'none' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This store adds no sales tax to any order. Orders still go ' +\n 'through — the decision is recorded, not the tax.'}\n </Typography>\n ) : current.mode === 'stripe' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Stripe Tax calculates per buyer location at checkout. ' +\n 'Activate Stripe Tax in your Stripe dashboard first.'}\n </Typography>\n ) : (\n <>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.pricesIncludeTax)}\n onChange={(event) =>\n update({ pricesIncludeTax: event.target.checked })\n }\n />\n }\n label=\"Prices include tax (VAT-style)\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Origin country\"\n value={current.origin?.country ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n country: event.target.value.toUpperCase().slice(0, 2),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"US\"\n />\n <TextField\n label=\"Origin state\"\n value={current.origin?.state ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n state: event.target.value.toUpperCase().slice(0, 3),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"TX\"\n />\n </Stack>\n {/* Which of the product's three addresses this is. A merchant\n who reads an unlabeled origin as \"our address\" may set it\n from the wrong one: the address the workspace pays Aglyn\n from is a different jurisdiction question, and the payout\n identity is a third. Naming the two it is NOT costs a line\n and prevents a mis-taxed order. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Where this store ships or sells FROM — the jurisdiction the ' +\n 'manual rates below are applied from. Not the address your ' +\n 'workspace is billed at by Aglyn, and not where your payouts ' +\n 'are sent.'}\n </Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n label=\"Country\"\n value={rate.country}\n onChange={(event) =>\n updateRate(index, {\n country: event.target.value.toUpperCase().slice(0, 2),\n })\n }\n size=\"small\"\n sx={{ width: 90 }}\n />\n <TextField\n label=\"State\"\n value={rate.state ?? ''}\n onChange={(event) =>\n updateRate(index, {\n state:\n event.target.value.toUpperCase().slice(0, 3) ||\n undefined,\n })\n }\n size=\"small\"\n sx={{ width: 80 }}\n />\n <TextField\n label=\"%\"\n value={rate.pct}\n onChange={(event) =>\n updateRate(index, { pct: Number(event.target.value) || 0 })\n }\n size=\"small\"\n sx={{ width: 80 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={rate.label ?? ''}\n onChange={(event) =>\n updateRate(index, { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Sales tax\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n </>\n )}\n {/*\n LODGING TAX (AGL-1969) — deliberately OUTSIDE the calculation branch\n above, and deliberately not a `rates[]` row.\n\n The setting above is a goods SALES rate resolved against an address.\n Occupancy tax is a different regime with its own rates, registration\n and return, and it applies to reservations, which sell nights rather\n than goods. Nesting it under \"Manual rates\" would have said the two\n are the same machinery; putting it here says a store on Stripe Tax —\n which cannot compute occupancy tax from these sessions at all — can\n still set one.\n\n It is off until the merchant fills it in, so nothing an existing\n store charges moves.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Lodging tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on reservations, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because occupancy tax is its own regime with its own rates ' +\n 'and its own return. Leave it blank to charge none — that is ' +\n 'the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('lodging')}\n onChange={(event) =>\n updateFlat('lodging', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('lodging'))}\n helperText={flatPctProblem('lodging') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.lodging?.label ?? ''}\n onChange={(event) =>\n updateFlat('lodging', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Occupancy tax\"\n helperText=\"Shown to the guest on the receipt\"\n />\n </Stack>\n {/*\n MECHANISM ONLY, AND NO REMITTANCE DETERMINATION.\n\n Whether a jurisdiction imposes occupancy tax, who must register for\n it and who must remit it are legal conclusions that attach by\n operation of law (AGL-1904/AGL-1956) and are the merchant's under\n the Terms. This copy says what the software DOES and what it does\n not do, and stops there — including the deposit basis, which is a\n real limitation rather than an answer this product has taken.\n */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'On a reservation that takes a deposit, the rate is applied to ' +\n 'the deposit — the amount actually charged here — not to the ' +\n 'whole stay. If tax is due on the full stay, collect the ' +\n 'difference the same way you collect the rest of the balance.'}\n </Typography>\n </Stack>\n {/*\n SERVICE TAX (AGL-2028) — the bookings sibling of the block above,\n and here for the same reason it is not in the bookings plugin's own\n settings: this is the one card a merchant comes to with a tax\n question, and a second tax surface elsewhere is how one of them ends\n up unanswered.\n\n Its EXISTENCE is also the opt-in AGL-2000 wanted. That issue\n declined to apply the goods rate to an appointment partly because\n nothing said the merchant meant these settings to cover bookings; a\n field labelled for services, blank until they fill it in, is them\n saying so.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Service tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on paid bookings, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because whether a service is taxable is often a different ' +\n 'question from whether goods are. Leave it blank to charge ' +\n 'none — that is the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('service')}\n onChange={(event) =>\n updateFlat('service', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('service'))}\n helperText={flatPctProblem('service') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.service?.label ?? ''}\n onChange={(event) =>\n updateFlat('service', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Service tax\"\n helperText=\"Shown to the client on the receipt\"\n />\n </Stack>\n {/* MECHANISM ONLY, AND NO REMITTANCE DETERMINATION — see the\n lodging block above. */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n </Stack>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n // An undecided store saves the choice on screen as it stands. The\n // select fires no change for the option already shown, so waiting\n // for an edit left \"Manual rates\" unsaveable and checkout off.\n disabled={storeStatus === 'loading' || (decided && !draft)}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save tax settings'}\n </Button>\n </Stack>\n </CardDisplay>\n )\n}\nTaxSettingsCard.displayName = 'TaxSettingsCard'\n\nexport default TaxSettingsCard\n"],"names":["CommerceModel","PLATFORM_BRAND_NAME","CardDisplay","useSnackbar","Alert","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","setDoc","useCallback","useState","useFirestore","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","TaxSettingsCard","props","draft","current","flatPctProblem","store","hostId","firestore","enqueueSnackbar","data","status","storeStatus","fromCache","storeFromCache","listen","storeListen","setDraft","tax","mode","decided","update","patch","updateRate","index","rates","splice","country","pct","updateFlat","key","flatPctText","undefined","String","raw","Number","isUsableFlatTaxPct","FLAT_TAX_MAX_PCT","handleSave","verdict","subject","unreadable","merge","ok","message","variant","persist","id","header","help","anchor","contentGutterX","contentGutterY","spacing","severity","label","value","onChange","event","target","size","select","sx","maxWidth","color","control","checked","Boolean","pricesIncludeTax","direction","origin","toUpperCase","slice","width","placeholder","state","map","rate","slotProps","htmlInput","inputMode","flex","onClick","alignSelf","length","my","error","helperText","lodging","service","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAM7C;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;QAuBdC,MAkH5BC,6BAqFHA,gBAyGYC,wBA6EAA;QAlXcC,YAmJjBF,iBAeAA,kBAwIFA,kBA6EAA;IAxZnB,MAAM,EAAEG,MAAM,EAAE,GAAGL;IACnB,MAAMM,YAAYX;IAClB,MAAM,EAAEY,eAAe,EAAE,GAAG1B;IAC5B,MAAM,EACJ2B,MAAMJ,KAAK,EACXK,QAAQC,WAAW,EACnB;;;;;;;;KAQC,GACDC,WAAWC,cAAc,EACzBC,QAAQC,WAAW,EACpB,GAAGlB,gBACF,IAAML,IAAIe,WAAW,SAASD,QAAQ,YAAY,UAClD;QAACC;QAAWD;KAAO;IAErB,MAAM,CAACJ,OA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gB,aAAcQ,WAAW,CAACjB;oBACpD+E,SAAS5C;oBACTwB,IAAI;wBAAEqB,WAAW;oBAAa;8BAE7B;;;;;AAKX;AACAlF,gBAAgB0F,WAAW,GAAG;AAE9B,eAAe1F,gBAAe"}
|
|
@@ -23,9 +23,11 @@ import { type CommercePdfFile } from './pdf-response';
|
|
|
23
23
|
import { type QuoteLinkOutcome, type QuotePayDeps } from './quote-pay';
|
|
24
24
|
type HostDocument = Record<string, unknown>;
|
|
25
25
|
/**
|
|
26
|
-
* The business's contact as the document prints it: its postal address (
|
|
27
|
-
*
|
|
28
|
-
* and its web address without
|
|
26
|
+
* The business's contact as the document prints it: its postal address (the
|
|
27
|
+
* one line Setup → Business profile saves, or an older one-block address a line per
|
|
28
|
+
* line), the email visitors write to, its phone, and its web address without
|
|
29
|
+
* the scheme. The address and email are the host tokens' (AGL-4136), so the
|
|
30
|
+
* document says what the site's pages and emails say.
|
|
29
31
|
*/
|
|
30
32
|
export declare function commercePdfContactLines(host: HostDocument | null | undefined): string[];
|
|
31
33
|
/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */
|
|
@@ -61,9 +61,11 @@ import { locateImageSource, readImageSourceBytes } from "./site-image-source.js"
|
|
|
61
61
|
};
|
|
62
62
|
const trimmed = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
63
63
|
/**
|
|
64
|
-
* The business's contact as the document prints it: its postal address (
|
|
65
|
-
*
|
|
66
|
-
* and its web address without
|
|
64
|
+
* The business's contact as the document prints it: its postal address (the
|
|
65
|
+
* one line Setup → Business profile saves, or an older one-block address a line per
|
|
66
|
+
* line), the email visitors write to, its phone, and its web address without
|
|
67
|
+
* the scheme. The address and email are the host tokens' (AGL-4136), so the
|
|
68
|
+
* document says what the site's pages and emails say.
|
|
67
69
|
*/ export function commercePdfContactLines(host) {
|
|
68
70
|
var _siteContactEmail;
|
|
69
71
|
var _source_seo_entity, _source_seo;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (a\n * block of text, a line per line), the email visitors write to, its phone,\n * and its web address without the scheme.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","revision","Number","quote","payUrl","filename","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,gBAAgB,QAAgC,oCAAmC;AAC5F,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,2BAA0B;AACrF,SAASC,QAAQ,QAA2B,wCAAuC;AACnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,iDAAgD;AAC1E,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,qBAAqB,EACrBC,cAAc,QAGT,oCAAgC;AACvC,SAASC,gBAAgB,QAAQ,4BAAwB;AACzD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,OAAO,QAA8B,oBAAgB;AAC9D,SAASC,eAAe,QAAQ,wBAAoB;AACpD,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,oBAAoB,QAGf,iBAAa;AACpB,SAASC,iBAAiB,EAAEC,oBAAoB,QAAQ,yBAAqB;AAE7E;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,gDAAgD,GAChD,MAAMC,wBAAwB;AAE9B,gFAAgF,GAChF,MAAMC,cAAc;IAAEC,OAAO;IAAKC,QAAQ;AAAI;AAE9C,gGAAgG,GAChG,MAAMC,sBAAsB;AAE5B,8EAA8E,GAC9E,MAAMC,wBAAwB;AAE9B,iFAAiF,GACjF,MAAMC,cAAc;IAAEC,GAAG;IAAKC,GAAG;IAAKC,GAAG;AAAI;AAI7C,MAAMC,UAAU,CAACC,QAA4B,OAA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WAAW;YACHlD,kBAKT4B;QALV,MAAMyB,MAAM,MAAM,EAACrD,mBAAAA,KAAKsD,UAAU,YAAftD,mBAAmBoC,qBAAqB;YACzDjD;YACAqC,SAASC;YACTF;YACAtF;YACA2F,KAAK,GAAGA,eAAAA,MAAM2B,IAAI,cAAV3B,eAAgB;YACxB3B,OAAOA,QAAQ;gBAAEL,IAAIK,MAAML,EAAE;gBAAEC,KAAKI,MAAMJ,GAAG;YAAC,IAAI;YAClDqC;QACF;QACA,OAAO;YAAEO,QAAQ;YAAKY;QAAI;IAC5B;IACA,MAAMA,MAAM,MAAMrD,KAAKwD,QAAQ,CAAC;QAC9BrE;QACAsC;QACAF;QACAtF;QACA2F,KAAK,GAAGA,cAAAA,MAAM2B,IAAI,cAAV3B,cAAgB;QACxB3B,OAAOA,QAAQ;YAAEL,IAAIK,MAAML,EAAE;YAAEC,KAAKI,MAAMJ,GAAG;QAAC,IAAI;QAClDqC;IACF;IACA,OAAO;QAAEO,QAAQ;QAAKY;IAAI;AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK1H;YAAuB4I,UAAUrC;YAAgBoB;QAC3F,IAAI,SAASU,SAAS,OAAOvI,QAAQgJ,KAAKT,QAAQI,GAAG;QACrD,OAAOrI,qBAAqB0I,KAAKT;IACnC,EAAE,OAAO1D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB0I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAEnD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","revision","Number","quote","payUrl","filename","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,gBAAgB,QAAgC,oCAAmC;AAC5F,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,2BAA0B;AACrF,SAASC,QAAQ,QAA2B,wCAAuC;AACnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,iDAAgD;AAC1E,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,qBAAqB,EACrBC,cAAc,QAGT,oCAAgC;AACvC,SAASC,gBAAgB,QAAQ,4BAAwB;AACzD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,OAAO,QAA8B,oBAAgB;AAC9D,SAASC,eAAe,QAAQ,wBAAoB;AACpD,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,oBAAoB,QAGf,iBAAa;AACpB,SAASC,iBAAiB,EAAEC,oBAAoB,QAAQ,yBAAqB;AAE7E;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,gDAAgD,GAChD,MAAMC,wBAAwB;AAE9B,gFAAgF,GAChF,MAAMC,cAAc;IAAEC,OAAO;IAAKC,QAAQ;AAAI;AAE9C,gGAAgG,GAChG,MAAMC,sBAAsB;AAE5B,8EAA8E,GAC9E,MAAMC,wBAAwB;AAE9B,iFAAiF,GACjF,MAAMC,cAAc;IAAEC,GAAG;IAAKC,GAAG;IAAKC,GAAG;AAAI;AAI7C,MAAMC,UAAU,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAExF;;;;;;CAMC,GACD,OAAO,SAASC,wBAAwBC,IAAqC;QAS7DtC;Q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qBAAqB;YACzDjD;YACAqC,SAASC;YACTF;YACAtF;YACA2F,KAAK,GAAGA,eAAAA,MAAM2B,IAAI,cAAV3B,eAAgB;YACxB3B,OAAOA,QAAQ;gBAAEL,IAAIK,MAAML,EAAE;gBAAEC,KAAKI,MAAMJ,GAAG;YAAC,IAAI;YAClDqC;QACF;QACA,OAAO;YAAEO,QAAQ;YAAKY;QAAI;IAC5B;IACA,MAAMA,MAAM,MAAMrD,KAAKwD,QAAQ,CAAC;QAC9BrE;QACAsC;QACAF;QACAtF;QACA2F,KAAK,GAAGA,cAAAA,MAAM2B,IAAI,cAAV3B,cAAgB;QACxB3B,OAAOA,QAAQ;YAAEL,IAAIK,MAAML,EAAE;YAAEC,KAAKI,MAAMJ,GAAG;QAAC,IAAI;QAClDqC;IACF;IACA,OAAO;QAAEO,QAAQ;QAAKY;IAAI;AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK1H;YAAuB4I,UAAUrC;YAAgBoB;QAC3F,IAAI,SAASU,SAAS,OAAOvI,QAAQgJ,KAAKT,QAAQI,GAAG;QACrD,OAAOrI,qBAAqB0I,KAAKT;IACnC,EAAE,OAAO1D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB0I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAEnD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
@@ -165,9 +165,9 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
165
165
|
// Opaque to the VISITOR, who is a stranger to this site and not our
|
|
166
166
|
// customer (AGL-1666's rules, restated in the message's own docblock).
|
|
167
167
|
// The one genuinely useful thing to hand them is a door that still
|
|
168
|
-
// opens, so the site's OWN published
|
|
169
|
-
//
|
|
170
|
-
//
|
|
168
|
+
// opens, so the site's OWN published email rides along when it has
|
|
169
|
+
// one — read through the host-token registry, which answers the email
|
|
170
|
+
// Setup → Business profile saves, else the older one-block copy (AGL-4136).
|
|
171
171
|
// Nothing else off the host document may leave the console.
|
|
172
172
|
const contact = (_HOST_TOKENS_supportEmail = HOST_TOKENS['supportEmail']) == null ? void 0 : _HOST_TOKENS_supportEmail.resolve(hostSnapshot.data());
|
|
173
173
|
return res.status(429).json(_extends({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-register.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { memberNameSearchFields, memberSearchTokens } from './member-name-search'\nimport {\n checkVisitorRecordCeiling,\n HOST_TOKENS,\n marketingConsentFieldsForHost,\n SITE_MEMBER_CEILING_CODE,\n SITE_MEMBER_UNAVAILABLE_MESSAGE,\n SITE_MEMBERS_MAX_PER_HOST,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n rearmVisitorRecordCeilingNotice,\n recordVisitorRecordCeilingTrip,\n} from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n CONVERSION_TOUCH_DETAIL,\n resolveConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport {\n hashMemberPassword,\n mintMemberSession,\n setMemberCookie,\n} from './membership'\nimport { memberCredentialRef } from './member-credentials'\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Site member sign-up (AGL-109): creates the member record and its credential\n * document (the scrypt hash, AGL-3308), doubles as a lead, and signs the\n * visitor in via the session cookie.\n */\nexport const membershipRegisterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const email = String(req.body?.email ?? '')\n .trim()\n .toLowerCase()\n const password = String(req.body?.password ?? '')\n const displayName = String(req.body?.displayName ?? '')\n .trim()\n .slice(0, 80)\n // Explicit opt-in checkbox (AGL-2499) — never inferred from signing up.\n const marketingConsent = req.body?.marketingConsent === true\n if (!hostId) return res.status(400).json({ error: 'Missing host' })\n if (!EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Enter a valid email' })\n }\n if (password.length < 8) {\n return res\n .status(400)\n .json({ error: 'Password must be at least 8 characters' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // Member accounts are UNLIMITED on every plan (AGL-889) — no seat or\n // quota check belongs here. Audience monetization happens downstream:\n // contact bands meter the CRM projection (AGL-890) and paid\n // memberships carry the plan's digital transaction fee (AGL-892).\n //\n // `SITE_MEMBERS_MAX_PER_HOST` below is NOT that check and does not make\n // it one (AGL-1529). It is a flat PLATFORM ceiling — same number on every\n // plan, no `OrgEntitlements` key, nothing on the price list — and it\n // exists because this handler is reachable by an ANONYMOUS VISITOR, so\n // without it the collection was bounded only by a per-(host, IP) rate\n // limiter that fails soft and bounds the RATE rather than the TOTAL. An\n // abuse control is not something we sell; \"unlimited member accounts on\n // every plan\" stays literally true.\n const membersRef = hostRef.collection('siteMembers')\n const memberRef = membersRef.doc()\n /*\n * COUNT, DEDUPE AND CREATE IN ONE TRANSACTION (AGL-1529, the AGL-2231\n * treatment).\n *\n * Read-then-decide-then-`set()` is the create-time quota that laundered\n * everywhere else in this repo: N concurrent sign-ups each read the same\n * pre-count, each find room, and each land — and nothing re-counts\n * afterwards, so the extra accounts are permanent. The fix is WHEN the\n * count is evaluated, not the counting rule.\n * `Transaction.get(AggregateQuery)` serialises the count against a\n * concurrent create into this collection: the loser retries, re-reads the\n * higher count and is refused. The duplicate-email read moves inside for\n * free, which also closes the smaller race it always had — two\n * simultaneous sign-ups on one address both saw `empty` and both wrote.\n *\n * ALL READS BEFORE THE WRITE, which Firestore requires.\n *\n * The scrypt hash sits between the last read and the create ON PURPOSE.\n * It is ~100 ms of CPU and it is the most expensive thing in the request,\n * so a refused sign-up must never pay it — hashing before the transaction\n * would hand a flood a CPU amplifier on exactly the path the ceiling\n * exists to contain, and would also be a regression, since today a\n * duplicate-email refusal does not hash either. It is a pure computation,\n * not an effect, so it does not violate the \"nothing happens in a\n * transaction body\" rule the sibling routes state.\n *\n * A refusal is returned as DATA and rendered outside: a body that can run\n * several times must not be the place a response is built.\n */\n // The count the new account was judged against, for the notice re-arm.\n let usedBeforeCreate = 0\n const refusal = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(membersRef.where('email', '==', email).limit(1))\n if (!existing.empty) return { duplicate: true, ceiling: 0 }\n const used = (await tx.get(membersRef.count())).data().count\n usedBeforeCreate = used\n // Live documents only, so removing a member in the inbox frees the slot.\n const verdict = checkVisitorRecordCeiling(used, SITE_MEMBERS_MAX_PER_HOST)\n if (verdict.exceeded) return { duplicate: false, ceiling: verdict.ceiling }\n // The hash goes to the credential document, which no client can read\n // (AGL-3308), and in this transaction, so a member never exists without\n // the password they chose. The profile below is what the console lists.\n tx.set(memberCredentialRef(hostRef, memberRef.id), {\n passwordScrypt: hashMemberPassword(password),\n })\n tx.create(memberRef, {\n email,\n /*\n * `displayNameLower` is stored `null` for a member who gave no name,\n * not left out: the console's Site users list sorts by Name with an\n * `orderBy` on it, and an `orderBy` drops every document that lacks\n * the field (AGL-3680).\n */\n ...(displayName\n ? memberNameSearchFields(displayName)\n : { displayNameLower: null }),\n // The Site users list's search: the name and the address (AGL-3321).\n searchTokens: memberSearchTokens(displayName, email),\n /*\n * Stored `false`, not left out: the console's Status filter asks\n * `suspended == false` for the active members, and a query cannot\n * find a document that lacks the field. The drawer's Suspend and\n * Reactivate write `true` and `false` over it.\n */\n suspended: false,\n /*\n * The checkbox is PERSISTED on the member, not only forwarded.\n *\n * It reached the lead and the contact from the two lines below and\n * was dropped for this document, so `hosts/{hostId}/siteMembers` had\n * no consent field of any kind and `audience: 'members'` had nothing\n * for the send-time join to read — the audience could not be filtered\n * even in principle (`docs/specs/email-overhaul.md` §1d/§3f). The\n * other two documents are not a substitute: a member is deduped in\n * this transaction while leads append every time, and contacts are\n * ORG-scoped where a member is the site's own.\n *\n * Written only when ticked. Signing up is not opting in — that is why\n * the checkbox exists and why it defaults unchecked — so the omitted\n * case stores nothing and reads back as an unrecorded basis rather\n * than as a refusal.\n *\n * Under this site's key even though `siteMembers` already lives\n * beneath it, so that one reader answers for every silo — see\n * `addHostLead`, which makes the same write for the same reason.\n */\n ...(marketingConsent\n ? marketingConsentFieldsForHost(hostId, Date.now())\n : {}),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return null\n })\n if (refusal?.duplicate) {\n return res.status(409).json({ error: 'That email is already a member' })\n }\n if (refusal) {\n // Visible to the HOST — the rule that a control nobody can see in\n // the console did not ship. Durable counter + one notification.\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'siteMembers',\n ceiling: refusal.ceiling,\n })\n // Opaque to the VISITOR, who is a stranger to this site and not our\n // customer (AGL-1666's rules, restated in the message's own docblock).\n // The one genuinely useful thing to hand them is a door that still\n // opens, so the site's OWN published support address rides along when\n // it has one — read through the host-token registry, whose description\n // of this field is literally \"where visitors should write for help\".\n // Nothing else off the host document may leave the console.\n const contact = HOST_TOKENS['supportEmail']?.resolve(\n hostSnapshot.data() as any,\n )\n return res.status(429).json({\n error: SITE_MEMBER_UNAVAILABLE_MESSAGE,\n // Machine-readable, because the dispatcher's rate limiter answers 429\n // too and the status therefore discriminates nothing.\n code: SITE_MEMBER_CEILING_CODE,\n ...(contact ? { contact } : {}),\n })\n }\n // The account took a slot below the ceiling. When it took the last one,\n // the next refusal is a new crossing and is announced again (AGL-3442).\n await rearmVisitorRecordCeilingNotice({\n hostRef,\n kind: 'siteMembers',\n used: usedBeforeCreate,\n ceiling: SITE_MEMBERS_MAX_PER_HOST,\n })\n // Sign-ups double as leads for the site owner (AGL-109), through the one\n // writer that enforces `LEADS_MAX_PER_HOST` (AGL-1529). A refused lead\n // never fails the sign-up: the visitor asked for an account, not for a\n // lead record, and the trip is recorded for the owner either way.\n /*\n * WHERE THE VISITOR ARRIVED FROM, RESOLVED ONCE FOR THE WHOLE SIGN-UP.\n *\n * A sign-up is the identify moment for a visitor who has been anonymous\n * until now, and it writes two records an arrival can be credited with —\n * the lead and the contact. One resolve, by the plugin that credits\n * outcomes, and the two cannot end up credited to different arrivals.\n *\n * The MEMBER record itself is not attributed. A member is an account the\n * visitor holds and the lead is the site's record of the same act, so\n * crediting both would count one sign-up twice under two names.\n */\n const signedUpAtMs = Date.now()\n const arrival = await resolveConversionTouch({\n hostId,\n wire: req.body?.campaignTouch,\n email,\n atMs: signedUpAtMs,\n })\n /*\n * Contacts ingestion (AGL-197), reported to whichever plugin keeps people\n * rather than written by this one (AGL-3080). Commerce knows it just met\n * somebody; what a person record is belongs to the plugin that models it,\n * and a workspace that keeps none is a quiet, correct answer here.\n */\n /*\n * A member account is a RELATIONSHIP (AGL-3232): the person is a\n * contact from this moment, and an open lead the site held for the\n * address is closed as converted onto that contact by the record\n * system — a sign-up files no lead of its own any more, the way a\n * portal user is a contact and not a lead in Salesforce.\n */\n void recordCapturedContact({\n /*\n * Not resolved here. The record system keys a person on the SITE they\n * were met on, so this costs the capture nothing — and resolving it\n * would put a Firestore read in front of the writer, which is the one\n * thing `recordCapturedContact` asks a door not to do.\n */\n orgId: '',\n hostId,\n identity: { email, name: displayName || undefined },\n interaction: {\n source: 'member',\n refId: memberRef.id,\n summary: 'Joined as a member',\n },\n surface: 'relationship',\n // An account is a subscription to the site, not an enquiry (AGL-2612):\n // the stage on the contact says only that the person asked to be\n // kept. A floor, so a customer who opens an account stays a customer.\n lifecycleFloor: 'subscriber',\n ...(marketingConsent ? { marketingConsent: true } : {}),\n // Where the visitor ARRIVED from — a fact about this visit and not\n // about the person, which is what `detail` carries.\n ...(arrival ? { detail: { [CONVERSION_TOUCH_DETAIL]: arrival } } : {}),\n })\n // Event trigger (AGL-128/148). A sign-up is no longer a lead (AGL-3232),\n // so the `lead` event is the lead surfaces' to emit.\n await emitHostEvent(\n hostId,\n 'memberSignUp',\n { email },\n { actor: { kind: 'visitor', email } },\n )\n setMemberCookie(res, hostId, mintMemberSession(hostId, memberRef.id))\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Sign-up failed' })\n }\n}\n"],"names":["memberNameSearchFields","memberSearchTokens","checkVisitorRecordCeiling","HOST_TOKENS","marketingConsentFieldsForHost","SITE_MEMBER_CEILING_CODE","SITE_MEMBER_UNAVAILABLE_MESSAGE","SITE_MEMBERS_MAX_PER_HOST","firebaseAdmin","rearmVisitorRecordCeilingNotice","recordVisitorRecordCeilingTrip","emitHostEvent","recordCapturedContact","CONVERSION_TOUCH_DETAIL","resolveConversionTouch","hashMemberPassword","mintMemberSession","setMemberCookie","memberCredentialRef","EMAIL_PATTERN","membershipRegisterHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","password","displayName","slice","marketingConsent","test","length","firestore","app","hostRef","collection","doc","hostSnapshot","get","exists","membersRef","memberRef","usedBeforeCreate","refusal","runTransaction","tx","existing","where","limit","empty","duplicate","ceiling","used","count","data","verdict","exceeded","set","id","passwordScrypt","create","displayNameLower","searchTokens","suspended","Date","now","createdAt","FieldValue","serverTimestamp","kind","contact","resolve","code","signedUpAtMs","arrival","wire","campaignTouch","atMs","orgId","identity","name","undefined","interaction","source","refId","summary","surface","lifecycleFloor","detail","actor","ok","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,sBAAsB,EAAEC,kBAAkB,QAAQ,0BAAsB;AACjF,SACEC,yBAAyB,EACzBC,WAAW,EACXC,6BAA6B,EAC7BC,wBAAwB,EACxBC,+BAA+B,EAC/BC,yBAAyB,QACpB,sBAAqB;AAC5B,SACEC,aAAa,EACbC,+BAA+B,EAC/BC,8BAA8B,QACzB,2BAA0B;AACjC,SAASC,aAAa,QAAQ,wBAAuB;AACrD,OAAOC,2BAA2B,sDAAqD;AACvF,SACEC,uBAAuB,EACvBC,sBAAsB,QACjB,uDAAsD;AAC7D,SACEC,kBAAkB,EAClBC,iBAAiB,EACjBC,eAAe,QACV,kBAAc;AACrB,SAASC,mBAAmB,QAAQ,0BAAsB;AAE1D,MAAMC,gBAAgB;AAEtB;;;;CAIC,GACD,OAAO,MAAMC,4BAA8C,OAAOC,KAAKC;;QAI/CD,WACDA,YAGGA,YACGA,YAIFA;IAZzB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,QAAQF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,KAAK,oBAAI,IACrCC,IAAI,GACJC,WAAW;IACd,MAAMC,WAAWL,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUY,QAAQ,oBAAI;IAC9C,MAAMC,cAAcN,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUa,WAAW,oBAAI,IACjDH,IAAI,GACJI,KAAK,CAAC,GAAG;IACZ,wEAAwE;IACxE,MAAMC,mBAAmBf,E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AOvE,OAAO;QACdwE,QAAQxE,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-register.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { memberNameSearchFields, memberSearchTokens } from './member-name-search'\nimport {\n checkVisitorRecordCeiling,\n HOST_TOKENS,\n marketingConsentFieldsForHost,\n SITE_MEMBER_CEILING_CODE,\n SITE_MEMBER_UNAVAILABLE_MESSAGE,\n SITE_MEMBERS_MAX_PER_HOST,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n rearmVisitorRecordCeilingNotice,\n recordVisitorRecordCeilingTrip,\n} from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n CONVERSION_TOUCH_DETAIL,\n resolveConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport {\n hashMemberPassword,\n mintMemberSession,\n setMemberCookie,\n} from './membership'\nimport { memberCredentialRef } from './member-credentials'\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Site member sign-up (AGL-109): creates the member record and its credential\n * document (the scrypt hash, AGL-3308), doubles as a lead, and signs the\n * visitor in via the session cookie.\n */\nexport const membershipRegisterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const email = String(req.body?.email ?? '')\n .trim()\n .toLowerCase()\n const password = String(req.body?.password ?? '')\n const displayName = String(req.body?.displayName ?? '')\n .trim()\n .slice(0, 80)\n // Explicit opt-in checkbox (AGL-2499) — never inferred from signing up.\n const marketingConsent = req.body?.marketingConsent === true\n if (!hostId) return res.status(400).json({ error: 'Missing host' })\n if (!EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Enter a valid email' })\n }\n if (password.length < 8) {\n return res\n .status(400)\n .json({ error: 'Password must be at least 8 characters' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // Member accounts are UNLIMITED on every plan (AGL-889) — no seat or\n // quota check belongs here. Audience monetization happens downstream:\n // contact bands meter the CRM projection (AGL-890) and paid\n // memberships carry the plan's digital transaction fee (AGL-892).\n //\n // `SITE_MEMBERS_MAX_PER_HOST` below is NOT that check and does not make\n // it one (AGL-1529). It is a flat PLATFORM ceiling — same number on every\n // plan, no `OrgEntitlements` key, nothing on the price list — and it\n // exists because this handler is reachable by an ANONYMOUS VISITOR, so\n // without it the collection was bounded only by a per-(host, IP) rate\n // limiter that fails soft and bounds the RATE rather than the TOTAL. An\n // abuse control is not something we sell; \"unlimited member accounts on\n // every plan\" stays literally true.\n const membersRef = hostRef.collection('siteMembers')\n const memberRef = membersRef.doc()\n /*\n * COUNT, DEDUPE AND CREATE IN ONE TRANSACTION (AGL-1529, the AGL-2231\n * treatment).\n *\n * Read-then-decide-then-`set()` is the create-time quota that laundered\n * everywhere else in this repo: N concurrent sign-ups each read the same\n * pre-count, each find room, and each land — and nothing re-counts\n * afterwards, so the extra accounts are permanent. The fix is WHEN the\n * count is evaluated, not the counting rule.\n * `Transaction.get(AggregateQuery)` serialises the count against a\n * concurrent create into this collection: the loser retries, re-reads the\n * higher count and is refused. The duplicate-email read moves inside for\n * free, which also closes the smaller race it always had — two\n * simultaneous sign-ups on one address both saw `empty` and both wrote.\n *\n * ALL READS BEFORE THE WRITE, which Firestore requires.\n *\n * The scrypt hash sits between the last read and the create ON PURPOSE.\n * It is ~100 ms of CPU and it is the most expensive thing in the request,\n * so a refused sign-up must never pay it — hashing before the transaction\n * would hand a flood a CPU amplifier on exactly the path the ceiling\n * exists to contain, and would also be a regression, since today a\n * duplicate-email refusal does not hash either. It is a pure computation,\n * not an effect, so it does not violate the \"nothing happens in a\n * transaction body\" rule the sibling routes state.\n *\n * A refusal is returned as DATA and rendered outside: a body that can run\n * several times must not be the place a response is built.\n */\n // The count the new account was judged against, for the notice re-arm.\n let usedBeforeCreate = 0\n const refusal = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(membersRef.where('email', '==', email).limit(1))\n if (!existing.empty) return { duplicate: true, ceiling: 0 }\n const used = (await tx.get(membersRef.count())).data().count\n usedBeforeCreate = used\n // Live documents only, so removing a member in the inbox frees the slot.\n const verdict = checkVisitorRecordCeiling(used, SITE_MEMBERS_MAX_PER_HOST)\n if (verdict.exceeded) return { duplicate: false, ceiling: verdict.ceiling }\n // The hash goes to the credential document, which no client can read\n // (AGL-3308), and in this transaction, so a member never exists without\n // the password they chose. The profile below is what the console lists.\n tx.set(memberCredentialRef(hostRef, memberRef.id), {\n passwordScrypt: hashMemberPassword(password),\n })\n tx.create(memberRef, {\n email,\n /*\n * `displayNameLower` is stored `null` for a member who gave no name,\n * not left out: the console's Site users list sorts by Name with an\n * `orderBy` on it, and an `orderBy` drops every document that lacks\n * the field (AGL-3680).\n */\n ...(displayName\n ? memberNameSearchFields(displayName)\n : { displayNameLower: null }),\n // The Site users list's search: the name and the address (AGL-3321).\n searchTokens: memberSearchTokens(displayName, email),\n /*\n * Stored `false`, not left out: the console's Status filter asks\n * `suspended == false` for the active members, and a query cannot\n * find a document that lacks the field. The drawer's Suspend and\n * Reactivate write `true` and `false` over it.\n */\n suspended: false,\n /*\n * The checkbox is PERSISTED on the member, not only forwarded.\n *\n * It reached the lead and the contact from the two lines below and\n * was dropped for this document, so `hosts/{hostId}/siteMembers` had\n * no consent field of any kind and `audience: 'members'` had nothing\n * for the send-time join to read — the audience could not be filtered\n * even in principle (`docs/specs/email-overhaul.md` §1d/§3f). The\n * other two documents are not a substitute: a member is deduped in\n * this transaction while leads append every time, and contacts are\n * ORG-scoped where a member is the site's own.\n *\n * Written only when ticked. Signing up is not opting in — that is why\n * the checkbox exists and why it defaults unchecked — so the omitted\n * case stores nothing and reads back as an unrecorded basis rather\n * than as a refusal.\n *\n * Under this site's key even though `siteMembers` already lives\n * beneath it, so that one reader answers for every silo — see\n * `addHostLead`, which makes the same write for the same reason.\n */\n ...(marketingConsent\n ? marketingConsentFieldsForHost(hostId, Date.now())\n : {}),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return null\n })\n if (refusal?.duplicate) {\n return res.status(409).json({ error: 'That email is already a member' })\n }\n if (refusal) {\n // Visible to the HOST — the rule that a control nobody can see in\n // the console did not ship. Durable counter + one notification.\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'siteMembers',\n ceiling: refusal.ceiling,\n })\n // Opaque to the VISITOR, who is a stranger to this site and not our\n // customer (AGL-1666's rules, restated in the message's own docblock).\n // The one genuinely useful thing to hand them is a door that still\n // opens, so the site's OWN published email rides along when it has\n // one — read through the host-token registry, which answers the email\n // Setup → Business profile saves, else the older one-block copy (AGL-4136).\n // Nothing else off the host document may leave the console.\n const contact = HOST_TOKENS['supportEmail']?.resolve(\n hostSnapshot.data() as any,\n )\n return res.status(429).json({\n error: SITE_MEMBER_UNAVAILABLE_MESSAGE,\n // Machine-readable, because the dispatcher's rate limiter answers 429\n // too and the status therefore discriminates nothing.\n code: SITE_MEMBER_CEILING_CODE,\n ...(contact ? { contact } : {}),\n })\n }\n // The account took a slot below the ceiling. When it took the last one,\n // the next refusal is a new crossing and is announced again (AGL-3442).\n await rearmVisitorRecordCeilingNotice({\n hostRef,\n kind: 'siteMembers',\n used: usedBeforeCreate,\n ceiling: SITE_MEMBERS_MAX_PER_HOST,\n })\n // Sign-ups double as leads for the site owner (AGL-109), through the one\n // writer that enforces `LEADS_MAX_PER_HOST` (AGL-1529). A refused lead\n // never fails the sign-up: the visitor asked for an account, not for a\n // lead record, and the trip is recorded for the owner either way.\n /*\n * WHERE THE VISITOR ARRIVED FROM, RESOLVED ONCE FOR THE WHOLE SIGN-UP.\n *\n * A sign-up is the identify moment for a visitor who has been anonymous\n * until now, and it writes two records an arrival can be credited with —\n * the lead and the contact. One resolve, by the plugin that credits\n * outcomes, and the two cannot end up credited to different arrivals.\n *\n * The MEMBER record itself is not attributed. A member is an account the\n * visitor holds and the lead is the site's record of the same act, so\n * crediting both would count one sign-up twice under two names.\n */\n const signedUpAtMs = Date.now()\n const arrival = await resolveConversionTouch({\n hostId,\n wire: req.body?.campaignTouch,\n email,\n atMs: signedUpAtMs,\n })\n /*\n * Contacts ingestion (AGL-197), reported to whichever plugin keeps people\n * rather than written by this one (AGL-3080). Commerce knows it just met\n * somebody; what a person record is belongs to the plugin that models it,\n * and a workspace that keeps none is a quiet, correct answer here.\n */\n /*\n * A member account is a RELATIONSHIP (AGL-3232): the person is a\n * contact from this moment, and an open lead the site held for the\n * address is closed as converted onto that contact by the record\n * system — a sign-up files no lead of its own any more, the way a\n * portal user is a contact and not a lead in Salesforce.\n */\n void recordCapturedContact({\n /*\n * Not resolved here. The record system keys a person on the SITE they\n * were met on, so this costs the capture nothing — and resolving it\n * would put a Firestore read in front of the writer, which is the one\n * thing `recordCapturedContact` asks a door not to do.\n */\n orgId: '',\n hostId,\n identity: { email, name: displayName || undefined },\n interaction: {\n source: 'member',\n refId: memberRef.id,\n summary: 'Joined as a member',\n },\n surface: 'relationship',\n // An account is a subscription to the site, not an enquiry (AGL-2612):\n // the stage on the contact says only that the person asked to be\n // kept. A floor, so a customer who opens an account stays a customer.\n lifecycleFloor: 'subscriber',\n ...(marketingConsent ? { marketingConsent: true } : {}),\n // Where the visitor ARRIVED from — a fact about this visit and not\n // about the person, which is what `detail` carries.\n ...(arrival ? { detail: { [CONVERSION_TOUCH_DETAIL]: arrival } } : {}),\n })\n // Event trigger (AGL-128/148). A sign-up is no longer a lead (AGL-3232),\n // so the `lead` event is the lead surfaces' to emit.\n await emitHostEvent(\n hostId,\n 'memberSignUp',\n { email },\n { actor: { kind: 'visitor', email } },\n )\n setMemberCookie(res, hostId, mintMemberSession(hostId, memberRef.id))\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Sign-up failed' })\n }\n}\n"],"names":["memberNameSearchFields","memberSearchTokens","checkVisitorRecordCeiling","HOST_TOKENS","marketingConsentFieldsForHost","SITE_MEMBER_CEILING_CODE","SITE_MEMBER_UNAVAILABLE_MESSAGE","SITE_MEMBERS_MAX_PER_HOST","firebaseAdmin","rearmVisitorRecordCeilingNotice","recordVisitorRecordCeilingTrip","emitHostEvent","recordCapturedContact","CONVERSION_TOUCH_DETAIL","resolveConversionTouch","hashMemberPassword","mintMemberSession","setMemberCookie","memberCredentialRef","EMAIL_PATTERN","membershipRegisterHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","password","displayName","slice","marketingConsent","test","length","firestore","app","hostRef","collection","doc","hostSnapshot","get","exists","membersRef","memberRef","usedBeforeCreate","refusal","runTransaction","tx","existing","where","limit","empty","duplicate","ceiling","used","count","data","verdict","exceeded","set","id","passwordScrypt","create","displayNameLower","searchTokens","suspended","Date","now","createdAt","FieldValue","serverTimestamp","kind","contact","resolve","code","signedUpAtMs","arrival","wire","campaignTouch","atMs","orgId","identity","name","undefined","interaction","source","refId","summary","surface","lifecycleFloor","detail","actor","ok","console"],"mappings":"AAAA;;;;;;;;;;;;;;;C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