@aglyn/plugins-commerce 1.16.0 → 1.18.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/pos-cellular-control.component.d.ts +5 -0
- package/src/lib/components/console/pos-cellular-control.component.js +29 -15
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/product-grid.js +2 -1
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-name-lines.d.ts +37 -0
- package/src/lib/components/product-name-lines.js +36 -0
- package/src/lib/components/product-name-lines.js.map +1 -0
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/model/pos-cellular.d.ts +31 -4
- package/src/lib/model/pos-cellular.js +39 -4
- package/src/lib/model/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.d.ts +4 -3
- package/src/lib/server/pos-cellular-billing.js +22 -11
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular.js +43 -28
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-readers.js +8 -2
- package/src/lib/server/pos-readers.js.map +1 -1
- package/src/lib/server/quote.d.ts +3 -0
- package/src/lib/server/quote.js +54 -2
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server.d.ts +15 -0
- package/src/lib/server.js +28 -1
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-readers.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { authorizePosStaff, posRequestBody, type PosStaff } from './pos-auth'\nimport { revokePosDisplays } from './pos-display'\nimport { parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport { parsePosCellularConfig, posCellularView, type PosCellularView } from '../model/pos-cellular'\nimport { posStripe, posStripeErrorMessage, posStripeTestMode, posTerminalAvailable } from './pos-stripe'\nimport {\n ensurePosTerminalLocation,\n ownedTerminalReader,\n posReaderAccount,\n posTerminalAccount,\n refreshPosReaderStatus,\n type PosTerminalAddress,\n type PosTerminalReader,\n} from './pos-terminal'\n\n/**\n * `POST /api/commerce/pos-readers` (AGL-3607): the site's Stripe Terminal\n * card readers, from the \"Card readers\" settings card, and the server-side\n * removal of a register.\n *\n * Every action names a reader by id, and every one reads that reader under\n * the CALLER's site first (`ownedTerminalReader`): a reader id copied from\n * another store is \"not on this site\", whatever Stripe would say about it.\n */\nexport const posReadersHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n // Listing the readers is the register's; adding, renaming and removing one\n // is setting it up (AGL-4047).\n const gate = await authorizePosStaff(req, hostId, action === 'list' ? undefined : 'posDevices')\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n try {\n switch (action) {\n case 'list':\n return res.status(200).json(await listReaders(staff, body['refresh'] === true))\n case 'register':\n return await registerReader(staff, body, res)\n case 'update':\n return await updateReader(staff, body, res)\n case 'remove':\n return await removeReader(staff, body, res)\n case 'remove-register':\n return await removeRegister(staff, body, res)\n case 'cellular': {\n // 4G for the store's S710s (AGL-4038): set up like the readers, so\n // \"Registers and devices\" on the store.\n const answer = await (await import('./pos-cellular')).setPosStoreCellular(staff, body)\n return res.status(answer.status).json(answer.body)\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-readers]', action, error)\n return res.status(500).json({ error: 'Card readers could not be updated' })\n }\n}\n\n/**\n * The 4G row for the card (AGL-4038), or nothing: with why this viewer may\n * not turn it on, since it is charged to the workspace (\"Manage billing\"),\n * asked only where the row shows.\n */\nasync function cellularFor(\n staff: PosStaff,\n terminal: Record<string, unknown> | undefined,\n readers: ReadonlyArray<{ deviceType?: unknown }>,\n): Promise<{ cellular?: PosCellularView }> {\n const config = parsePosCellularConfig(process.env)\n if (!posCellularView(config, terminal, readers)) return {}\n const { mayTurnOnPosCellular, POS_CELLULAR_BILLING_REFUSAL } = await import('./pos-cellular')\n const turnOnBlocked = (await mayTurnOnPosCellular(staff.uid, staff.hostId)) ? null : POS_CELLULAR_BILLING_REFUSAL\n const cellular = posCellularView(config, terminal, readers, { turnOnBlocked })\n return cellular ? { cellular } : {}\n}\n\nfunction readersRef(hostId: string) {\n return firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('terminalReaders')\n}\n\nasync function listReaders(staff: PosStaff, refresh: boolean) {\n const available = posTerminalAvailable()\n const snapshot = await readersRef(staff.hostId).limit(50).get()\n const readers = snapshot.docs.map((doc: any) => ({\n id: doc.id as string,\n ...(doc.data() as PosTerminalReader),\n }))\n if (available && refresh) {\n await Promise.all(\n readers.map(async (reader: PosTerminalReader & { id: string }) => {\n const fresh = await refreshPosReaderStatus(staff.hostId, reader.id, posReaderAccount(reader)).catch(\n () => null,\n )\n if (fresh) reader.status = fresh.status\n }),\n )\n }\n // A reader registered on another account than the store sells on now (the\n // platform, before the store moved to its own Stripe account) cannot take\n // its cards: it is flagged so it can be removed and registered again.\n const account = readers.length ? await posTerminalAccount(staff.hostId, staff.org) : null\n const config = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(staff.hostId)\n .collection('terminal')\n .doc('config')\n .get()\n return {\n available,\n testMode: posStripeTestMode(),\n locationReady: Boolean(config.get('stripeLocationId')),\n // 4G for the store's S710s (AGL-4038), only where it is offered and the\n // store has one; absent otherwise, so the card shows nothing of it.\n ...(available ? await cellularFor(staff, config.data(), readers) : {}),\n readers: readers.map((reader: PosTerminalReader & { id: string }) => ({\n id: reader.id,\n label: reader.label,\n registerId: reader.registerId ?? null,\n deviceType: reader.deviceType ?? null,\n serialNumber: reader.serialNumber ?? null,\n status: reader.status ?? 'offline',\n livemode: reader.livemode,\n ...(posReaderAccount(reader) !== account ? { registerAgain: true } : {}),\n })),\n }\n}\n\nasync function registerExists(hostId: string, registerId: string): Promise<boolean> {\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(registerId)) return false\n return (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('registers')\n .doc(registerId)\n .get()\n ).exists\n}\n\nasync function registerReader(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const registerId = String(body['registerId'] ?? '')\n if (registerId && !(await registerExists(staff.hostId, registerId))) {\n return res.status(404).json({ error: 'Unknown register' })\n }\n const registered = await registerPosTerminalReader({\n hostId: staff.hostId,\n orgId: staff.orgId,\n uid: staff.uid,\n registrationCode: body['registrationCode'],\n label: body['label'],\n ...(registerId ? { registerId } : {}),\n ...(body['address'] ? { address: body['address'] as PosTerminalAddress } : {}),\n })\n if ('error' in registered) return res.status(registered.status).json({ error: registered.error })\n return res.status(200).json({ reader: { id: registered.id, ...registered.reader } })\n}\n\n/**\n * Registers a reader to a store by the code it shows: the store's Stripe\n * Terminal Location (made from `address` when the store has none), the\n * reader at Stripe, and `hosts/{hostId}/terminalReaders/{id}`. The POS\n * devices card's Add card reader, and the platform's own register setting a\n * reader up for the store of the person who just bought it (AGL-4038).\n *\n * A reader whose serial number was taken when it was sold in person is\n * found on its hardware order, which moves on to Set up (AGL-4038,\n * `pos-hardware-readers.ts`); that never fails the registration.\n */\nexport async function registerPosTerminalReader(input: {\n hostId: string\n orgId: string\n uid: string\n registrationCode: unknown\n label?: unknown\n registerId?: string\n address?: PosTerminalAddress\n}): Promise<\n { ok: true; id: string; reader: PosTerminalReader } | { ok: false; status: number; error: string }\n> {\n if (!posTerminalAvailable()) {\n return { ok: false, status: 409, error: 'Card readers are not available yet.' }\n }\n const registrationCode = String(input.registrationCode ?? '').trim()\n if (!/^[A-Za-z0-9-]{3,64}$/.test(registrationCode)) {\n return { ok: false, status: 400, error: 'Enter the code the reader shows on its screen.' }\n }\n const label = String(input.label ?? '').trim().slice(0, 60) || 'Card reader'\n const registerId = input.registerId ?? ''\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(input.hostId).get()\n const address = input.address\n // The account the reader is registered on: the store's own for a\n // direct-charge store (ToS v24 section 10.2(a)), the platform otherwise.\n const account = await posTerminalAccount(input.hostId)\n const location = await ensurePosTerminalLocation({\n account,\n hostId: input.hostId,\n orgId: input.orgId,\n displayName: String(host.get('name') ?? host.get('title') ?? 'Store'),\n ...(address\n ? {\n address: {\n line1: String(address.line1 ?? '').slice(0, 200),\n ...(address.line2 ? { line2: String(address.line2).slice(0, 200) } : {}),\n city: String(address.city ?? '').slice(0, 100),\n ...(address.state ? { state: String(address.state).slice(0, 100) } : {}),\n postalCode: String(address.postalCode ?? '').slice(0, 20),\n country: String(address.country ?? '').toUpperCase().slice(0, 2),\n },\n }\n : {}),\n })\n if ('error' in location) return { ok: false, status: location.status, error: location.error }\n // Not keyed: a registration code is single-use at Stripe, which is the\n // dedupe — a second press with the same code is refused there, and no\n // other store can ever register a reader this one already holds.\n const created = await posStripe('POST', 'terminal/readers', {\n params: {\n registration_code: registrationCode,\n label,\n location: location.locationId,\n 'metadata[orgId]': input.orgId,\n 'metadata[hostId]': input.hostId,\n ...(registerId ? { 'metadata[registerId]': registerId } : {}),\n // Lets the Connect delivery of this reader's events through the\n // webhook's direct-sale gate (`connectEventIsForDirectSale`).\n ...(account ? { 'metadata[chargeModel]': 'direct' } : {}),\n },\n ...(account ? { stripeAccount: account } : {}),\n })\n if (!created.ok || !created.body?.id) {\n return {\n ok: false,\n status: 400,\n error: posStripeErrorMessage(\n created.body,\n 'That code did not register a reader. Check the code on the reader and try again.',\n ),\n }\n }\n const reader: PosTerminalReader = {\n label,\n ...(registerId ? { registerId } : {}),\n stripeLocationId: location.locationId,\n ...(created.body.device_type ? { deviceType: String(created.body.device_type) } : {}),\n ...(created.body.serial_number ? { serialNumber: String(created.body.serial_number) } : {}),\n status: String(created.body.status ?? 'offline'),\n livemode: Boolean(created.body.livemode),\n createdAtMs: Date.now(),\n createdBy: input.uid,\n ...(account ? { stripeAccount: account } : {}),\n }\n const id = String(created.body.id)\n await readersRef(input.hostId).doc(id).set(reader)\n await syncCellular(input.hostId, input.orgId)\n if (reader.serialNumber && parsePosHardwareInPersonConfig(process.env)) {\n try {\n await (await import('./pos-hardware-readers')).matchRegisteredPosHardwareReader({\n hostId: input.hostId,\n orgId: input.orgId,\n uid: input.uid,\n readerId: id,\n serialNumber: reader.serialNumber,\n })\n } catch (error) {\n console.error('[pos-readers] the hardware order was not matched', id, error)\n }\n }\n return { ok: true, id, reader }\n}\n\nasync function updateReader(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const reader = await ownedTerminalReader(staff.hostId, body['readerId'])\n if (!reader) return res.status(404).json({ error: 'That card reader is not on this site.' })\n const patch: Record<string, unknown> = {}\n if (typeof body['label'] === 'string') {\n patch['label'] = body['label'].trim().slice(0, 60) || reader.label\n }\n if ('registerId' in body) {\n const registerId = String(body['registerId'] ?? '')\n if (registerId && !(await registerExists(staff.hostId, registerId))) {\n return res.status(404).json({ error: 'Unknown register' })\n }\n patch['registerId'] = registerId || firebaseAdmin.firestore.FieldValue.delete()\n }\n const readerAccount = posReaderAccount(reader)\n const updated = await posStripe('POST', `terminal/readers/${reader.id}`, {\n ...(readerAccount ? { stripeAccount: readerAccount } : {}),\n params: {\n ...(patch['label'] ? { label: String(patch['label']) } : {}),\n ...('registerId' in body ? { 'metadata[registerId]': String(body['registerId'] ?? '') } : {}),\n },\n })\n if (!updated.ok) {\n return res.status(502).json({ error: posStripeErrorMessage(updated.body, 'The reader could not be updated.') })\n }\n await readersRef(staff.hostId).doc(reader.id).set(patch, { merge: true })\n return res.status(200).json({ ok: true })\n}\n\nasync function removeReader(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const reader = await ownedTerminalReader(staff.hostId, body['readerId'])\n if (!reader) return res.status(404).json({ error: 'That card reader is not on this site.' })\n // Removed where it is registered: a reader from before the store moved to\n // its own account is freed on the platform, so it can be registered again.\n const readerAccount = posReaderAccount(reader)\n const removed = await posStripe(\n 'DELETE',\n `terminal/readers/${reader.id}`,\n readerAccount ? { stripeAccount: readerAccount } : {},\n )\n // Already gone at Stripe is the outcome asked for; anything else is not.\n if (!removed.ok && removed.status !== 404) {\n return res.status(502).json({ error: posStripeErrorMessage(removed.body, 'The reader could not be removed.') })\n }\n await readersRef(staff.hostId).doc(reader.id).delete()\n await syncCellular(staff.hostId, staff.orgId)\n return res.status(200).json({ ok: true })\n}\n\n/**\n * A reader added to or removed from a store with 4G (AGL-4038) starts or\n * stops counting toward its monthly charge. Never fails the reader's own\n * change; the next turn-on, turn-off or reader change heals a miss.\n */\nasync function syncCellular(hostId: string, orgId: string): Promise<void> {\n try {\n await (await import('./pos-cellular')).syncPosCellularReaders({ hostId, orgId })\n } catch (error) {\n console.error('[pos-readers] the 4G record was not updated', hostId, error)\n }\n}\n\n/**\n * Removes a register on the server (AGL-3617). The settings card deleted it\n * with a client `deleteDoc`, which the Firestore rules refuse for everyone but\n * staff (`registers` is server-owned since AGL-1775), so a merchant's Remove\n * button failed with a permission error. Removing it here also signs out its\n * customer displays and unbinds its readers.\n */\nasync function removeRegister(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const registerId = String(body['registerId'] ?? '')\n if (!(await registerExists(staff.hostId, registerId))) {\n return res.status(404).json({ error: 'Unknown register' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const registerRef = firestore\n .collection('hosts')\n .doc(staff.hostId)\n .collection('registers')\n .doc(registerId)\n await revokePosDisplays(staff.hostId, registerId)\n await registerRef.delete()\n const bound = await readersRef(staff.hostId).where('registerId', '==', registerId).limit(50).get()\n await Promise.all(\n bound.docs.map((doc: any) =>\n doc.ref.set({ registerId: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true }),\n ),\n )\n return res.status(200).json({ ok: true })\n}\n"],"names":["firebaseAdmin","authorizePosStaff","posRequestBody","revokePosDisplays","parsePosHardwareInPersonConfig","parsePosCellularConfig","posCellularView","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","ensurePosTerminalLocation","ownedTerminalReader","posReaderAccount","posTerminalAccount","refreshPosReaderStatus","posReadersHandler","req","res","body","method","status","json","error","hostId","String","action","gate","undefined","staff","listReaders","registerReader","updateReader","removeReader","removeRegister","answer","setPosStoreCellular","console","cellularFor","terminal","readers","config","process","env","mayTurnOnPosCellular","POS_CELLULAR_BILLING_REFUSAL","turnOnBlocked","uid","cellular","readersRef","app","firestore","collection","doc","refresh","available","snapshot","limit","get","docs","map","id","data","Promise","all","reader","fresh","catch","account","length","org","testMode","locationReady","Boolean","label","registerId","deviceType","serialNumber","livemode","registerAgain","registerExists","test","exists","registered","registerPosTerminalReader","orgId","registrationCode","address","input","host","created","ok","trim","slice","location","displayName","line1","line2","city","state","postalCode","country","toUpperCase","params","registration_code","locationId","stripeAccount","stripeLocationId","device_type","serial_number","createdAtMs","Date","now","createdBy","set","syncCellular","matchRegisteredPosHardwareReader","readerId","patch","FieldValue","delete","readerAccount","updated","merge","removed","syncPosCellularReaders","registerRef","bound","where","ref"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AAExD,SAASC,iBAAiB,EAAEC,cAAc,QAAuB,gBAAY;AAC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E;AACF;AAEA;;;;;;CAMC,GACD,eAAeW,eACbL,KAAe,EACfV,IAAyB,EACzBD,GAAoC;QAEVC;IAA1B,MAAMwD,aAAalD,QAAON,mBAAAA,IAAI,CAAC,aAAa,YAAlBA,mBAAsB;IAChD,IAAI,CAAE,MAAM6D,eAAenD,MAAML,MAAM,EAAEmD,aAAc;QACrD,OAAOzD,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAmB;IAC1D;IACA,MAAM4B,YAAYnD,cAAckD,GAAG,GAAGC,SAAS;IAC/C,MAAM2E,cAAc3E,UACjBC,UAAU,CAAC,SACXC,GAAG,CAACxB,MAAML,MAAM,EAChB4B,UAAU,CAAC,aACXC,GAAG,CAACsB;IACP,MAAMxE,kBAAkB0B,MAAML,MAAM,EAAEmD;IACtC,MAAMmD,YAAYN,MAAM;IACxB,MAAMO,QAAQ,MAAM9E,WAAWpB,MAAML,MAAM,EAAEwG,KAAK,CAAC,cAAc,MAAMrD,YAAYlB,KAAK,CAAC,IAAIC,GAAG;IAChG,MAAMK,QAAQC,GAAG,CACf+D,MAAMpE,IAAI,CAACC,GAAG,CAAC,CAACP,MACdA,IAAI4E,GAAG,CAACf,GAAG,CAAC;YAAEvC,YAAY3E,cAAcmD,SAAS,CAACoE,UAAU,CAACC,MAAM;QAAG,GAAG;YAAEG,OAAO;QAAK;IAG3F,OAAOzG,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEqE,IAAI;IAAK;AACzC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-readers.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { authorizePosStaff, posRequestBody, type PosStaff } from './pos-auth'\nimport { revokePosDisplays } from './pos-display'\nimport { parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport { parsePosCellularConfig, posCellularView, type PosCellularView } from '../model/pos-cellular'\nimport { posStripe, posStripeErrorMessage, posStripeTestMode, posTerminalAvailable } from './pos-stripe'\nimport {\n ensurePosTerminalLocation,\n ownedTerminalReader,\n posReaderAccount,\n posTerminalAccount,\n refreshPosReaderStatus,\n type PosTerminalAddress,\n type PosTerminalReader,\n} from './pos-terminal'\n\n/**\n * `POST /api/commerce/pos-readers` (AGL-3607): the site's Stripe Terminal\n * card readers, from the \"Card readers\" settings card, and the server-side\n * removal of a register.\n *\n * Every action names a reader by id, and every one reads that reader under\n * the CALLER's site first (`ownedTerminalReader`): a reader id copied from\n * another store is \"not on this site\", whatever Stripe would say about it.\n */\nexport const posReadersHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n // Listing the readers is the register's; adding, renaming and removing one\n // is setting it up (AGL-4047).\n const gate = await authorizePosStaff(req, hostId, action === 'list' ? undefined : 'posDevices')\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n try {\n switch (action) {\n case 'list':\n return res.status(200).json(await listReaders(staff, body['refresh'] === true))\n case 'register':\n return await registerReader(staff, body, res)\n case 'update':\n return await updateReader(staff, body, res)\n case 'remove':\n return await removeReader(staff, body, res)\n case 'remove-register':\n return await removeRegister(staff, body, res)\n case 'cellular': {\n // 4G for the store's S710s (AGL-4038): set up like the readers, so\n // \"Registers and devices\" on the store.\n const answer = await (await import('./pos-cellular')).setPosStoreCellular(staff, body)\n return res.status(answer.status).json(answer.body)\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-readers]', action, error)\n return res.status(500).json({ error: 'Card readers could not be updated' })\n }\n}\n\n/**\n * The 4G row for the card (AGL-4038), or nothing: with why this viewer may\n * not turn it on, since it is charged to the workspace (\"Manage billing\"),\n * asked only where the row shows and the store is not on its own Stripe\n * account (which Stripe bills directly, so the workspace's billing key is not\n * asked for).\n */\nasync function cellularFor(\n staff: PosStaff,\n terminal: Record<string, unknown> | undefined,\n readers: ReadonlyArray<{ deviceType?: unknown }>,\n): Promise<{ cellular?: PosCellularView }> {\n const config = parsePosCellularConfig(process.env)\n const row = posCellularView(config, terminal, readers)\n if (!row) return {}\n if (row.ownAccount) return { cellular: row }\n const { mayTurnOnPosCellular, POS_CELLULAR_BILLING_REFUSAL } = await import('./pos-cellular')\n const turnOnBlocked = (await mayTurnOnPosCellular(staff.uid, staff.hostId)) ? null : POS_CELLULAR_BILLING_REFUSAL\n const cellular = posCellularView(config, terminal, readers, { turnOnBlocked })\n return cellular ? { cellular } : {}\n}\n\nfunction readersRef(hostId: string) {\n return firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('terminalReaders')\n}\n\nasync function listReaders(staff: PosStaff, refresh: boolean) {\n const available = posTerminalAvailable()\n const snapshot = await readersRef(staff.hostId).limit(50).get()\n const readers = snapshot.docs.map((doc: any) => ({\n id: doc.id as string,\n ...(doc.data() as PosTerminalReader),\n }))\n if (available && refresh) {\n await Promise.all(\n readers.map(async (reader: PosTerminalReader & { id: string }) => {\n const fresh = await refreshPosReaderStatus(staff.hostId, reader.id, posReaderAccount(reader)).catch(\n () => null,\n )\n if (fresh) reader.status = fresh.status\n }),\n )\n }\n // A reader registered on another account than the store sells on now (the\n // platform, before the store moved to its own Stripe account) cannot take\n // its cards: it is flagged so it can be removed and registered again.\n const account = readers.length ? await posTerminalAccount(staff.hostId, staff.org) : null\n const config = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(staff.hostId)\n .collection('terminal')\n .doc('config')\n .get()\n return {\n available,\n testMode: posStripeTestMode(),\n locationReady: Boolean(config.get('stripeLocationId')),\n // 4G for the store's S710s (AGL-4038), only where it is offered and the\n // store has one; absent otherwise, so the card shows nothing of it.\n ...(available ? await cellularFor(staff, config.data(), readers) : {}),\n readers: readers.map((reader: PosTerminalReader & { id: string }) => ({\n id: reader.id,\n label: reader.label,\n registerId: reader.registerId ?? null,\n deviceType: reader.deviceType ?? null,\n serialNumber: reader.serialNumber ?? null,\n status: reader.status ?? 'offline',\n livemode: reader.livemode,\n ...(posReaderAccount(reader) !== account ? { registerAgain: true } : {}),\n })),\n }\n}\n\nasync function registerExists(hostId: string, registerId: string): Promise<boolean> {\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(registerId)) return false\n return (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('registers')\n .doc(registerId)\n .get()\n ).exists\n}\n\nasync function registerReader(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const registerId = String(body['registerId'] ?? '')\n if (registerId && !(await registerExists(staff.hostId, registerId))) {\n return res.status(404).json({ error: 'Unknown register' })\n }\n const registered = await registerPosTerminalReader({\n hostId: staff.hostId,\n orgId: staff.orgId,\n uid: staff.uid,\n registrationCode: body['registrationCode'],\n label: body['label'],\n ...(registerId ? { registerId } : {}),\n ...(body['address'] ? { address: body['address'] as PosTerminalAddress } : {}),\n })\n if ('error' in registered) return res.status(registered.status).json({ error: registered.error })\n return res.status(200).json({ reader: { id: registered.id, ...registered.reader } })\n}\n\n/**\n * Registers a reader to a store by the code it shows: the store's Stripe\n * Terminal Location (made from `address` when the store has none), the\n * reader at Stripe, and `hosts/{hostId}/terminalReaders/{id}`. The POS\n * devices card's Add card reader, and the platform's own register setting a\n * reader up for the store of the person who just bought it (AGL-4038).\n *\n * A reader whose serial number was taken when it was sold in person is\n * found on its hardware order, which moves on to Set up (AGL-4038,\n * `pos-hardware-readers.ts`); that never fails the registration.\n */\nexport async function registerPosTerminalReader(input: {\n hostId: string\n orgId: string\n uid: string\n registrationCode: unknown\n label?: unknown\n registerId?: string\n address?: PosTerminalAddress\n}): Promise<\n { ok: true; id: string; reader: PosTerminalReader } | { ok: false; status: number; error: string }\n> {\n if (!posTerminalAvailable()) {\n return { ok: false, status: 409, error: 'Card readers are not available yet.' }\n }\n const registrationCode = String(input.registrationCode ?? '').trim()\n if (!/^[A-Za-z0-9-]{3,64}$/.test(registrationCode)) {\n return { ok: false, status: 400, error: 'Enter the code the reader shows on its screen.' }\n }\n const label = String(input.label ?? '').trim().slice(0, 60) || 'Card reader'\n const registerId = input.registerId ?? ''\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(input.hostId).get()\n const address = input.address\n // The account the reader is registered on: the store's own for a\n // direct-charge store (ToS v24 section 10.2(a)), the platform otherwise.\n const account = await posTerminalAccount(input.hostId)\n const location = await ensurePosTerminalLocation({\n account,\n hostId: input.hostId,\n orgId: input.orgId,\n displayName: String(host.get('name') ?? host.get('title') ?? 'Store'),\n ...(address\n ? {\n address: {\n line1: String(address.line1 ?? '').slice(0, 200),\n ...(address.line2 ? { line2: String(address.line2).slice(0, 200) } : {}),\n city: String(address.city ?? '').slice(0, 100),\n ...(address.state ? { state: String(address.state).slice(0, 100) } : {}),\n postalCode: String(address.postalCode ?? '').slice(0, 20),\n country: String(address.country ?? '').toUpperCase().slice(0, 2),\n },\n }\n : {}),\n })\n if ('error' in location) return { ok: false, status: location.status, error: location.error }\n // Not keyed: a registration code is single-use at Stripe, which is the\n // dedupe — a second press with the same code is refused there, and no\n // other store can ever register a reader this one already holds.\n const created = await posStripe('POST', 'terminal/readers', {\n params: {\n registration_code: registrationCode,\n label,\n location: location.locationId,\n 'metadata[orgId]': input.orgId,\n 'metadata[hostId]': input.hostId,\n ...(registerId ? { 'metadata[registerId]': registerId } : {}),\n // Lets the Connect delivery of this reader's events through the\n // webhook's direct-sale gate (`connectEventIsForDirectSale`).\n ...(account ? { 'metadata[chargeModel]': 'direct' } : {}),\n },\n ...(account ? { stripeAccount: account } : {}),\n })\n if (!created.ok || !created.body?.id) {\n return {\n ok: false,\n status: 400,\n error: posStripeErrorMessage(\n created.body,\n 'That code did not register a reader. Check the code on the reader and try again.',\n ),\n }\n }\n const reader: PosTerminalReader = {\n label,\n ...(registerId ? { registerId } : {}),\n stripeLocationId: location.locationId,\n ...(created.body.device_type ? { deviceType: String(created.body.device_type) } : {}),\n ...(created.body.serial_number ? { serialNumber: String(created.body.serial_number) } : {}),\n status: String(created.body.status ?? 'offline'),\n livemode: Boolean(created.body.livemode),\n createdAtMs: Date.now(),\n createdBy: input.uid,\n ...(account ? { stripeAccount: account } : {}),\n }\n const id = String(created.body.id)\n await readersRef(input.hostId).doc(id).set(reader)\n await syncCellular(input.hostId, input.orgId)\n if (reader.serialNumber && parsePosHardwareInPersonConfig(process.env)) {\n try {\n await (await import('./pos-hardware-readers')).matchRegisteredPosHardwareReader({\n hostId: input.hostId,\n orgId: input.orgId,\n uid: input.uid,\n readerId: id,\n serialNumber: reader.serialNumber,\n })\n } catch (error) {\n console.error('[pos-readers] the hardware order was not matched', id, error)\n }\n }\n return { ok: true, id, reader }\n}\n\nasync function updateReader(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const reader = await ownedTerminalReader(staff.hostId, body['readerId'])\n if (!reader) return res.status(404).json({ error: 'That card reader is not on this site.' })\n const patch: Record<string, unknown> = {}\n if (typeof body['label'] === 'string') {\n patch['label'] = body['label'].trim().slice(0, 60) || reader.label\n }\n if ('registerId' in body) {\n const registerId = String(body['registerId'] ?? '')\n if (registerId && !(await registerExists(staff.hostId, registerId))) {\n return res.status(404).json({ error: 'Unknown register' })\n }\n patch['registerId'] = registerId || firebaseAdmin.firestore.FieldValue.delete()\n }\n const readerAccount = posReaderAccount(reader)\n const updated = await posStripe('POST', `terminal/readers/${reader.id}`, {\n ...(readerAccount ? { stripeAccount: readerAccount } : {}),\n params: {\n ...(patch['label'] ? { label: String(patch['label']) } : {}),\n ...('registerId' in body ? { 'metadata[registerId]': String(body['registerId'] ?? '') } : {}),\n },\n })\n if (!updated.ok) {\n return res.status(502).json({ error: posStripeErrorMessage(updated.body, 'The reader could not be updated.') })\n }\n await readersRef(staff.hostId).doc(reader.id).set(patch, { merge: true })\n return res.status(200).json({ ok: true })\n}\n\nasync function removeReader(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const reader = await ownedTerminalReader(staff.hostId, body['readerId'])\n if (!reader) return res.status(404).json({ error: 'That card reader is not on this site.' })\n // Removed where it is registered: a reader from before the store moved to\n // its own account is freed on the platform, so it can be registered again.\n const readerAccount = posReaderAccount(reader)\n const removed = await posStripe(\n 'DELETE',\n `terminal/readers/${reader.id}`,\n readerAccount ? { stripeAccount: readerAccount } : {},\n )\n // Already gone at Stripe is the outcome asked for; anything else is not.\n if (!removed.ok && removed.status !== 404) {\n return res.status(502).json({ error: posStripeErrorMessage(removed.body, 'The reader could not be removed.') })\n }\n await readersRef(staff.hostId).doc(reader.id).delete()\n await syncCellular(staff.hostId, staff.orgId)\n return res.status(200).json({ ok: true })\n}\n\n/**\n * A reader added to or removed from a store with 4G (AGL-4038) starts or\n * stops counting toward its monthly charge. Never fails the reader's own\n * change; the next turn-on, turn-off or reader change heals a miss.\n */\nasync function syncCellular(hostId: string, orgId: string): Promise<void> {\n try {\n await (await import('./pos-cellular')).syncPosCellularReaders({ hostId, orgId })\n } catch (error) {\n console.error('[pos-readers] the 4G record was not updated', hostId, error)\n }\n}\n\n/**\n * Removes a register on the server (AGL-3617). The settings card deleted it\n * with a client `deleteDoc`, which the Firestore rules refuse for everyone but\n * staff (`registers` is server-owned since AGL-1775), so a merchant's Remove\n * button failed with a permission error. Removing it here also signs out its\n * customer displays and unbinds its readers.\n */\nasync function removeRegister(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n) {\n const registerId = String(body['registerId'] ?? '')\n if (!(await registerExists(staff.hostId, registerId))) {\n return res.status(404).json({ error: 'Unknown register' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const registerRef = firestore\n .collection('hosts')\n .doc(staff.hostId)\n .collection('registers')\n .doc(registerId)\n await revokePosDisplays(staff.hostId, registerId)\n await registerRef.delete()\n const bound = await readersRef(staff.hostId).where('registerId', '==', registerId).limit(50).get()\n await Promise.all(\n bound.docs.map((doc: any) =>\n doc.ref.set({ registerId: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true }),\n ),\n )\n return res.status(200).json({ ok: true })\n}\n"],"names":["firebaseAdmin","authorizePosStaff","posRequestBody","revokePosDisplays","parsePosHardwareInPersonConfig","parsePosCellularConfig","posCellularView","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","ensurePosTerminalLocation","ownedTerminalReader","posReaderAccount","posTerminalAccount","refreshPosReaderStatus","posReadersHandler","req","res","body","method","status","json","error","hostId","String","action","gate","undefined","staff","listReaders","registerReader","updateReader","removeReader","removeRegister","answer","setPosStoreCellular","console","cellularFor","terminal","readers","config","process","env","row","ownAccount","cellular","mayTurnOnPosCellular","POS_CELLULAR_BILLING_REFUSAL","turnOnBlocked","uid","readersRef","app","firestore","collection","doc","refresh","available","snapshot","limit","get","docs","map","id","data","Promise","all","reader","fresh","catch","account","length","org","testMode","locationReady","Boolean","label","registerId","deviceType","serialNumber","livemode","registerAgain","registerExists","test","exists","registered","registerPosTerminalReader","orgId","registrationCode","address","input","host","created","ok","trim","slice","location","displayName","line1","line2","city","state","postalCode","country","toUpperCase","params","registration_code","locationId","stripeAccount","stripeLocationId","device_type","serial_number","createdAtMs","Date","now","createdBy","set","syncCellular","matchRegisteredPosHardwareReader","readerId","patch","FieldValue","delete","readerAccount","updated","merge","removed","syncPosCellularReaders","registerRef","bound","where","ref"],"mappings":";AAAA;;;;;;;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PersonRecord, type PluginPersonSearchRequest } from '@aglyn/aglyn/plugin-manager/plugin-person-records';
|
|
19
19
|
import { type PluginRecordFactsRead, type PluginRecordFactsRequest } from '@aglyn/aglyn/plugin-manager/plugin-record-facts';
|
|
20
|
+
import { type PaymentMode } from '@aglyn/tenant-data-admin/server/payment-provider';
|
|
20
21
|
import { type SaleTaxEngineRequest, type SaleTaxEngineResult } from './tax-engine-quote';
|
|
21
22
|
import { type CheckoutSessionExpiry } from './checkout-session-expiry';
|
|
22
23
|
import type { quotePdfFile } from './commerce-pdf';
|
|
@@ -70,6 +71,8 @@ export interface QuoteDeps {
|
|
|
70
71
|
}): Promise<{
|
|
71
72
|
id: string;
|
|
72
73
|
} | null>;
|
|
74
|
+
/** This deployment's payment mode, from its own credential; absent, the provider's answer. */
|
|
75
|
+
platformMode?(): PaymentMode | undefined;
|
|
73
76
|
now(): number;
|
|
74
77
|
}
|
|
75
78
|
export declare function defaultQuoteDeps(): QuoteDeps;
|
package/src/lib/server/quote.js
CHANGED
|
@@ -23,6 +23,7 @@ import { searchPluginPeople } from "@aglyn/aglyn/plugin-manager/plugin-person-re
|
|
|
23
23
|
import { pluginRecordFactsReader } from "@aglyn/aglyn/plugin-manager/plugin-record-facts";
|
|
24
24
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
25
25
|
import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
26
|
+
import { merchantAccountReadiness, paymentProvider } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
26
27
|
import * as CommerceModel from "../model/index.js";
|
|
27
28
|
import { commerceSitePermissionRefusal } from "../model/plugin-permissions.js";
|
|
28
29
|
import { holdsCommerceSiteKey } from "./commerce-site-keys.js";
|
|
@@ -56,6 +57,7 @@ export function defaultQuoteDeps() {
|
|
|
56
57
|
return (_ref = await ((_pluginRecordFactsReader = pluginRecordFactsReader(CommerceModel.QUOTE_REQUEST_FACTS_RESOURCE)) == null ? void 0 : _pluginRecordFactsReader.reader.read(request))) != null ? _ref : null;
|
|
57
58
|
},
|
|
58
59
|
customerAccount: async (input)=>(await import("./quote-pay.js")).readQuoteCustomerAccount(input),
|
|
60
|
+
platformMode: ()=>paymentProvider().platformMode(),
|
|
59
61
|
now: ()=>Date.now()
|
|
60
62
|
};
|
|
61
63
|
}
|
|
@@ -247,6 +249,25 @@ const SEND_ACTIONS = new Set([
|
|
|
247
249
|
shipping: input.shipping
|
|
248
250
|
};
|
|
249
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Whether the site's workspace can take card payments, for an app's "Customers can't pay this quote online yet."
|
|
254
|
+
* notice (AGL-4162). It reads the workspace OWNER's profile, as the console's `useMerchantPayments` and every money
|
|
255
|
+
* route do, and answers with `merchantAccountReadiness`, the check the console's copy has to agree with. The server
|
|
256
|
+
* knows this deployment's payment mode, which an app cannot, so a live deployment's unverified account answers
|
|
257
|
+
* `mode-unverified` here exactly as it does in the console.
|
|
258
|
+
*/ async function ownerPaymentsReadiness(deps, hostId) {
|
|
259
|
+
var _owner_org;
|
|
260
|
+
const owner = await deps.orgForHost(hostId);
|
|
261
|
+
const ownerUid = owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.ownerUid;
|
|
262
|
+
if (typeof ownerUid !== 'string' || !ownerUid) return 'not-connected';
|
|
263
|
+
const profile = await deps.firestore().collection('profiles').doc(ownerUid).get();
|
|
264
|
+
return merchantAccountReadiness({
|
|
265
|
+
accountId: profile.get('stripeAccountId'),
|
|
266
|
+
chargesEnabled: profile.get('stripeChargesEnabled'),
|
|
267
|
+
accountLivemode: profile.get('stripeAccountLivemode'),
|
|
268
|
+
platformMode: deps.platformMode ? deps.platformMode() : paymentProvider().platformMode()
|
|
269
|
+
});
|
|
270
|
+
}
|
|
250
271
|
export async function handleQuote(deps, req) {
|
|
251
272
|
var _body_hostId, _body_action, _body_quoteId, _body_from, _ref;
|
|
252
273
|
if (req.method !== 'POST') return refuse(405, 'Method not allowed');
|
|
@@ -273,6 +294,14 @@ export async function handleQuote(deps, req) {
|
|
|
273
294
|
return refuse(403, commerceSitePermissionRefusal(key));
|
|
274
295
|
}
|
|
275
296
|
const actor = String(decoded.email || decoded.uid);
|
|
297
|
+
if (action === 'payments-readiness') {
|
|
298
|
+
return {
|
|
299
|
+
status: 200,
|
|
300
|
+
body: {
|
|
301
|
+
state: await ownerPaymentsReadiness(deps, hostId)
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
276
305
|
if (action === 'pay-link' || action === 'replace-link') {
|
|
277
306
|
var _body_quoteId1, _host_data;
|
|
278
307
|
const quoteId = String((_body_quoteId1 = body['quoteId']) != null ? _body_quoteId1 : '');
|
|
@@ -519,8 +548,11 @@ export async function handleQuote(deps, req) {
|
|
|
519
548
|
"closeSession"
|
|
520
549
|
]);
|
|
521
550
|
await closeOpenSession(deps, closeSession, 'quote deleted', hostId);
|
|
522
|
-
// Its proofs
|
|
523
|
-
if (outcome.status === 200)
|
|
551
|
+
// Its proofs, anything the customer sent and its conversation go with it.
|
|
552
|
+
if (outcome.status === 200) {
|
|
553
|
+
await removeQuoteFiles(deps, hostId, quoteId);
|
|
554
|
+
await removeQuoteMessages(ref);
|
|
555
|
+
}
|
|
524
556
|
return outcome;
|
|
525
557
|
}
|
|
526
558
|
if (action !== 'create' && action !== 'update') return refuse(400, 'Unknown action');
|
|
@@ -787,6 +819,26 @@ export async function handleQuote(deps, req) {
|
|
|
787
819
|
file: kept.file
|
|
788
820
|
};
|
|
789
821
|
}
|
|
822
|
+
/** How many of a deleted quote's messages one read removes. */ const QUOTE_MESSAGES_DELETE_PAGE = 200;
|
|
823
|
+
/**
|
|
824
|
+
* Deletes a quote's conversation (AGL-4207), which lives under the order and
|
|
825
|
+
* so outlives it otherwise: a draft that was never sent can still hold
|
|
826
|
+
* replies, since it has the customer's address. Never throws.
|
|
827
|
+
*/ async function removeQuoteMessages(orderRef) {
|
|
828
|
+
try {
|
|
829
|
+
const messages = orderRef.collection('messages');
|
|
830
|
+
for(;;){
|
|
831
|
+
const page = await messages.limit(QUOTE_MESSAGES_DELETE_PAGE).get();
|
|
832
|
+
if (!page.docs.length) return;
|
|
833
|
+
await Promise.all(page.docs.map((message)=>messages.doc(message.id).delete()));
|
|
834
|
+
}
|
|
835
|
+
} catch (error) {
|
|
836
|
+
console.error('quote messages were not removed', {
|
|
837
|
+
orderPath: orderRef.path,
|
|
838
|
+
error
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
}
|
|
790
842
|
/** Deletes a quote's kept files, its proofs and the customer's artwork; never throws. */ async function removeQuoteFiles(deps, hostId, quoteId) {
|
|
791
843
|
try {
|
|
792
844
|
const uploads = await deps.uploads();
|