@aglyn/plugins-marketing 1.0.0-beta.172 → 1.0.0-beta.174
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/package.json +15 -15
- package/src/lib/components/campaign-detail-card.d.ts +12 -1
- package/src/lib/components/campaign-detail-card.js +146 -35
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-edit-drawer.d.ts +13 -0
- package/src/lib/components/campaign-edit-drawer.js +56 -4
- package/src/lib/components/campaign-edit-drawer.js.map +1 -1
- package/src/lib/components/campaign-glance-card.component.js +10 -2
- package/src/lib/components/campaign-glance-card.component.js.map +1 -1
- package/src/lib/components/campaign-members-section.d.ts +6 -0
- package/src/lib/components/campaign-members-section.js +2 -2
- package/src/lib/components/campaign-members-section.js.map +1 -1
- package/src/lib/components/campaign-queries.d.ts +58 -0
- package/src/lib/components/campaign-queries.js +72 -0
- package/src/lib/components/campaign-queries.js.map +1 -0
- package/src/lib/components/campaign-reach-sections.d.ts +21 -7
- package/src/lib/components/campaign-reach-sections.js +20 -17
- package/src/lib/components/campaign-reach-sections.js.map +1 -1
- package/src/lib/components/campaign-report-card.d.ts +8 -1
- package/src/lib/components/campaign-report-card.js +33 -16
- package/src/lib/components/campaign-report-card.js.map +1 -1
- package/src/lib/components/campaigns-card.d.ts +10 -1
- package/src/lib/components/campaigns-card.js +102 -19
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/email-compose-card.d.ts +3 -2
- package/src/lib/components/email-compose-card.js +18 -7
- package/src/lib/components/email-compose-card.js.map +1 -1
- package/src/lib/components/email-detail.d.ts +11 -2
- package/src/lib/components/email-detail.js +50 -23
- package/src/lib/components/email-detail.js.map +1 -1
- package/src/lib/components/emails-list-card.d.ts +10 -1
- package/src/lib/components/emails-list-card.js +129 -23
- package/src/lib/components/emails-list-card.js.map +1 -1
- package/src/lib/components/host-marketing-summary-card.component.js +9 -1
- package/src/lib/components/host-marketing-summary-card.component.js.map +1 -1
- package/src/lib/components/marketing-console-page.js +81 -4
- package/src/lib/components/marketing-console-page.js.map +1 -1
- package/src/lib/components/marketing-console-sections.d.ts +16 -1
- package/src/lib/components/marketing-console-sections.js +25 -2
- package/src/lib/components/marketing-console-sections.js.map +1 -1
- package/src/lib/components/marketing-org-mount.d.ts +71 -0
- package/src/lib/components/marketing-org-mount.js +84 -0
- package/src/lib/components/marketing-org-mount.js.map +1 -0
- package/src/lib/components/use-campaign-send-api.d.ts +2 -2
- package/src/lib/components/use-campaign-send-api.js +22 -6
- package/src/lib/components/use-campaign-send-api.js.map +1 -1
- package/src/lib/components/use-emails-hub-path.d.ts +13 -3
- package/src/lib/components/use-emails-hub-path.js +25 -4
- package/src/lib/components/use-emails-hub-path.js.map +1 -1
- package/src/lib/components/use-marketing-hub-path.d.ts +19 -16
- package/src/lib/components/use-marketing-hub-path.js +6 -32
- package/src/lib/components/use-marketing-hub-path.js.map +1 -1
- package/src/lib/model/marketing-record-routes.js +11 -4
- package/src/lib/model/marketing-record-routes.js.map +1 -1
- package/src/lib/plugin.js +31 -1
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/campaign-manage.d.ts +31 -2
- package/src/lib/server/campaign-manage.js +365 -137
- package/src/lib/server/campaign-manage.js.map +1 -1
- package/src/lib/server/campaign-org-refs.d.ts +45 -0
- package/src/lib/server/campaign-org-refs.js +83 -0
- package/src/lib/server/campaign-org-refs.js.map +1 -0
- package/src/lib/server/campaign-process-scheduled.d.ts +32 -2
- package/src/lib/server/campaign-process-scheduled.js +79 -9
- package/src/lib/server/campaign-process-scheduled.js.map +1 -1
- package/src/lib/server/campaign-recipients.js +18 -4
- package/src/lib/server/campaign-recipients.js.map +1 -1
- package/src/lib/server/campaign-send.js +139 -55
- package/src/lib/server/campaign-send.js.map +1 -1
- package/src/lib/server/email-campaign-reach.d.ts +6 -5
- package/src/lib/server/email-campaign-reach.js +14 -14
- package/src/lib/server/email-campaign-reach.js.map +1 -1
- package/src/lib/server/email-events.js +48 -17
- package/src/lib/server/email-events.js.map +1 -1
- package/src/lib/server/marketing-figures.js +12 -1
- package/src/lib/server/marketing-figures.js.map +1 -1
- package/src/lib/server.js +7 -3
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-manage.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\n/**\n * TAKING SOMETHING AWAY: a campaign container, and an abandoned draft.\n *\n * Both are removals, and neither may take a delivered message with it. That\n * is the whole reason this file is small and the comments are long.\n *\n * ## Why these two are not client writes\n *\n * The console creates and edits a campaign CONTAINER with the client SDK —\n * `hosts/{hostId}/emailCampaigns` is deliberately outside the rules'\n * server-only exclusion list, because a container holds no counter, no\n * consent record and no entitlement input.\n *\n * The SEND collection is the opposite: `hosts/{hostId}/campaigns` is excluded\n * from client create, update AND delete, because each document is the record\n * of what a merchant mailed and to whom they were allowed to mail it. Both\n * operations here have to touch it — one to detach sends from the container\n * being removed, the other to remove a draft outright — so both run on the\n * Admin SDK behind the same site-role check the send route uses.\n *\n * ## What deleting a campaign MEANS\n *\n * The container goes; every email inside it stays, and reads afterwards as a\n * single send.\n *\n * It cannot mean anything else. A send id is cited by mail already delivered\n * — every unsubscribe footer carries `cid={sendId}` inside its own HMAC, and\n * `/marketing/campaigns/{sendId}` is a URL merchants paste into their own\n * messages — so deleting a container that destroyed its sends would break\n * opt-out links that must go on resolving forever, which is a compliance\n * failure rather than a broken page.\n *\n * Nor may the sends simply be left pointing at a container that is gone.\n * `campaignListRows` groups sends by the container they name and draws one\n * row per container; a send naming a container that no longer exists is in\n * neither half of that — not a container row, and not an orphan the list\n * adopts — so it would vanish from the campaigns table while remaining\n * perfectly deliverable. Detaching is what puts it back in the list, as the\n * \"Single send\" the product already models and the table already draws.\n *\n * Deleting a campaign is therefore NOT a way to stop its mail. A scheduled\n * email inside it keeps its send time and still goes out, because a\n * container is a grouping and cancelling somebody's mail is `cancel`'s job.\n * The console says so before it asks.\n *\n * ## The same rule for everything else the campaign held\n *\n * A campaign also groups forms, screens and contacts, each of which names it\n * from its OWN document. They are detached on exactly the argument the sends\n * are: a form left naming a container nobody can read has not been freed, it\n * has been made unreadable — its page draws a dead id where a campaign name\n * belongs, and the campaigns table can no longer find it. The record itself\n * is never touched. Deleting a campaign deletes a campaign.\n */\n\n/*\n * The MODULE, not the barrel. `@aglyn/tenant-data-admin`'s index reaches\n * `render-cache`, which imports `next/cache` and therefore the whole Next\n * server pipeline — everything this file needs from the admin SDK is one\n * default export, and taking it from the leaf keeps that pipeline out of the\n * graph.\n */\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { logResourceDuplicated } from '@aglyn/tenant-data-admin/server/duplicate-activity'\nimport {\n DUPLICATE_BUSY_MESSAGE,\n duplicateDisplayName,\n uniqueDuplicateName,\n} from '@aglyn/aglyn/app-utils/duplicate-resource'\nimport { claimAttempt, createResourceUid } from '@aglyn/aglyn/server'\n/*\n * The MODULES again, for the same reason: `consentGroupForSite` and\n * `orgDataCollectionForHost` are what the contact pass needs, and taking them\n * from `@aglyn/tenant-data-admin`'s index would pull the whole Next server\n * pipeline back into this file's graph.\n */\nimport {\n consentGroupForSite,\n orgDataCollectionForHost,\n resolveOrgIdForHost,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport {\n CAMPAIGN_MEMBER_HOST_COLLECTIONS,\n CAMPAIGN_MEMBERSHIP_FIELD,\n contactCampaignFieldPath,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n CAMPAIGN_SEND_CONTAINER_FIELD,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport { SCREEN_KIND_EMAIL } from '@aglyn/aglyn/app-utils/screen-route'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { runPluginMembershipDetachers } from '@aglyn/aglyn/plugin-manager/plugin-membership-detach'\n\n/**\n * Sends detached in one write.\n *\n * Under Firestore's 500-operation batch limit with room to spare rather than\n * at it: a batch that is refused for being one over has done nothing, and the\n * margin costs one extra round trip on a campaign of exactly this size.\n */\nconst DETACH_BATCH = 400\n\n/**\n * How many batches one request will run.\n *\n * A ceiling on the REQUEST, not on the campaign. The loop below terminates on\n * its own — each pass clears the very field it queries on, so a detached send\n * is not returned again — but a request that runs unbounded is a request that\n * eventually exceeds the platform's own timeout with no idea how far it got.\n *\n * Stopping early is safe and is why this is a ceiling rather than a refusal\n * up front: detaching is idempotent and partial progress is a consistent\n * state — the sends already detached read as single sends, the rest still\n * read under the campaign — so the answer to hitting it is to ask again.\n */\nconst DETACH_PASSES = 25\n\n/** What one `campaigns/manage` call answered with. */\ninterface ManageResult {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Clears {@link CAMPAIGN_SEND_CONTAINER_FIELD} from every send in a campaign.\n *\n * Equality on one field with a `limit` — no `orderBy` — which Firestore's\n * automatic single-field index serves. Ordering would need a composite index\n * for a walk whose order does not matter: every match is being written, so\n * which order they come back in cannot change the outcome.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachSends(\n hostRef: FirebaseFirestore.DocumentReference,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n const firestore = hostRef.firestore\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await hostRef\n .collection('campaigns')\n .where(CAMPAIGN_SEND_CONTAINER_FIELD, '==', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const send of page.docs) {\n /*\n * The FIELD is removed, not set to an empty string. `campaignListRows`\n * adopts a send whose container id is falsy, so an empty string would\n * work by accident today — but the field is also what the campaign\n * detail page's `where` clause matches, and an equality query on `''`\n * is a different query from the absence the pre-container sends have.\n * One shape for \"belongs to no campaign\" is what keeps those two\n * readers agreeing.\n */\n batch.update(send.ref, {\n [CAMPAIGN_SEND_CONTAINER_FIELD]:\n firebaseAdmin.firestore.FieldValue.delete(),\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Clears one campaign id out of a membership array, wherever it is held.\n *\n * The same walk {@link detachSends} makes, over an ARRAY field rather than a\n * scalar one: `array-contains` matches on Firestore's automatic single-field\n * index, and `arrayRemove` takes out the one id without touching the other\n * campaigns a form or a screen is in. That is the whole reason the membership\n * is an array here and a `FieldValue.delete()` on a send — a send is in one\n * campaign and a landing page is in several, so removing one must not be\n * removing all of them.\n *\n * `query` rather than a collection ref, because the contact pass hands in a\n * path this file cannot build for itself.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachMembership(\n firestore: FirebaseFirestore.Firestore,\n collectionRef: FirebaseFirestore.CollectionReference,\n fieldPath: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await collectionRef\n .where(fieldPath, 'array-contains', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const member of page.docs) {\n batch.update(member.ref, {\n [fieldPath]: firebaseAdmin.firestore.FieldValue.arrayRemove(campaignId),\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Clears the campaign off every form, screen, lead and contact holding it,\n * and then off every record a plugin keeps about it (AGL-3254).\n *\n * ## Why the campaign is not simply deleted over the top of them\n *\n * A campaign that went away leaving members naming it is the same failure the\n * send detach exists to prevent, one collection over: the campaign's own page\n * finds its forms and screens with `array-contains`, and a form still naming\n * a container nobody can read is in neither half of that — not a member of\n * any campaign the console can draw, and not free of one either. Its own page\n * would render the dead id as a chip with no name.\n *\n * ## The contacts are reached by a different path, on purpose\n *\n * A contact lives on the ORG (`orgs/{orgId}/contacts`) and is shared by every\n * site in it, so the membership sits inside this site's consent-group facet\n * rather than at the top of the document. The field PATH is therefore the\n * scope: only rows this group filed under the campaign match it, and no other\n * holder's filing is touched. The unscoped collection ref is what the walk\n * runs on precisely because the path already carries the boundary — the\n * `visibleTo` filter `orgDataQueryForHost` adds would spend the query's one\n * array-contains slot and leave none for the membership.\n *\n * A group that cannot be resolved answers as the site alone, which is\n * {@link consentGroupForSite}'s documented failure direction and the safe one\n * here too: the pass then clears the site's own facet and no other.\n *\n * ## A plugin's members are the plugin's to clear\n *\n * A sequence and its enrollments name the campaign from documents under the\n * org, in collections this plugin does not know (AGL-3254). Every plugin\n * with a membership detacher registered on the core's seam is asked, with\n * the campaign's id and the field it is held in, after the site's own\n * records, and a detacher that reports records\n * remaining — or threw, which is reported as `null` — holds the container\n * exactly as this pass's own `remaining` does. A plugin that failed is a\n * plugin whose records may still name the campaign, and the deletion has\n * no way to tell that apart from one that has more than a request clears.\n */\nasync function detachMembers(\n hostId: string,\n hostRef: FirebaseFirestore.DocumentReference,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n const firestore = hostRef.firestore\n let detached = 0\n let remaining = false\n for (const collectionName of CAMPAIGN_MEMBER_HOST_COLLECTIONS) {\n const pass = await detachMembership(\n firestore,\n hostRef.collection(collectionName),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n )\n detached += pass.detached\n remaining = remaining || pass.remaining\n }\n /*\n * NO ORG, NO ORG CONTACTS — and that is a skip rather than a failure.\n *\n * Contacts live at `orgs/{orgId}/contacts`, so a site whose `hostIndex`\n * entry names no org holds none of them and there is nothing here to\n * detach. Resolving it first is what separates that from a read that FAILED:\n * `orgDataCollectionForHost` throws for both, and swallowing both would let\n * a transient Firestore error delete the campaign with contacts still\n * naming it. A thrown read reaches the handler's 500 and the container\n * survives, which is the direction a failure here has to fall.\n */\n const orgId = await resolveOrgIdForHost(hostId)\n const plugins = await runPluginMembershipDetachers({\n hostId,\n orgId: orgId ?? '',\n field: CAMPAIGN_MEMBERSHIP_FIELD,\n id: campaignId,\n })\n for (const report of Object.values(plugins)) {\n detached += report?.detached ?? 0\n remaining = remaining || report === null || report.remaining\n }\n if (!orgId) return { detached, remaining }\n const group = await consentGroupForSite(hostId)\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n const contactPass = await detachMembership(\n firestore,\n contacts,\n contactCampaignFieldPath(group.groupId),\n campaignId,\n )\n return {\n detached: detached + contactPass.detached,\n remaining: remaining || contactPass.remaining,\n }\n}\n\n/**\n * Removes a campaign container, leaving its emails standing.\n *\n * Detach first, delete second, and the order is the point: stopping between\n * them leaves a container whose emails are already single sends, which the\n * list draws correctly and a second run finishes. Deleting first would leave\n * sends naming a container nobody can read, which is the state that loses\n * them from the table.\n */\nasync function deleteCampaign(\n hostId: string,\n hostRef: FirebaseFirestore.DocumentReference,\n campaignId: string,\n): Promise<ManageResult> {\n const ref = hostRef.collection('emailCampaigns').doc(campaignId)\n const snapshot = await ref.get()\n /*\n * A 404 rather than a silent success. The id in a campaign URL may name a\n * container OR a single send — that ambiguity is what keeps every link\n * minted before containers existed resolving — so \"no container here\" is\n * very often \"this is a send\", and answering it as a completed deletion\n * would tell the console it had removed something it never touched.\n */\n if (!snapshot.exists) {\n return { status: 404, body: { error: 'Unknown campaign' } }\n }\n const { detached, remaining } = await detachSends(hostRef, campaignId)\n if (remaining) {\n return {\n status: 409,\n body: {\n detached,\n error:\n `This campaign holds more emails than one request can detach. ` +\n `${detached.toLocaleString()} of them now read as single sends and ` +\n 'the campaign is still here — run the delete again to finish it.',\n },\n }\n }\n /*\n * The MEMBERS come off before the container does, for the reason the sends\n * do: a partial run leaves records that are already out of the campaign,\n * which every surface draws correctly, while deleting first would leave\n * forms, screens and contacts naming an id nothing can resolve.\n *\n * Their own 409 rather than a shared one. \"More emails than one request can\n * detach\" is a sentence about the campaign's mail, and a merchant reading\n * it about a campaign of two emails and four thousand contacts would go\n * looking for emails that are not the problem.\n */\n const members = await detachMembers(hostId, hostRef, campaignId)\n if (members.remaining) {\n return {\n status: 409,\n body: {\n detached,\n detachedMembers: members.detached,\n error:\n 'This campaign is on more records than one request can clear. ' +\n `${members.detached.toLocaleString()} of them are already out of ` +\n 'it and the campaign is still here — run the delete again to ' +\n 'finish it.',\n },\n }\n }\n await ref.delete()\n return {\n status: 200,\n body: {\n campaignId,\n detached,\n detachedMembers: members.detached,\n deleted: true,\n },\n }\n}\n\n/**\n * Discards a DRAFT email, and refuses anything else.\n *\n * The state check is inside the transaction as well as being the reason for\n * it. `sendNow` claims a draft by moving it to `sending` in a transaction of\n * its own, so a check made against an earlier read could delete a record\n * while the send path was mailing from it — the merchant would receive a\n * report for an email that no longer exists, and its `cid` would stop\n * resolving with the message already in inboxes.\n *\n * Only `draft`. A scheduled email is withdrawn with `cancel`, which leaves\n * the record and its report standing; a sent one has reached people, and\n * nothing on this surface may remove the evidence of that.\n */\nasync function discardDraft(\n hostRef: FirebaseFirestore.DocumentReference,\n emailId: string,\n): Promise<ManageResult> {\n const ref = hostRef.collection('campaigns').doc(emailId)\n const firestore = hostRef.firestore\n const refusal = (state: string): string => {\n if (state === 'sent') {\n return 'This email has already been sent, so it cannot be discarded. ' +\n 'Its report and its unsubscribe links have to go on resolving.'\n }\n if (state === 'scheduled') {\n return 'This email is scheduled. Cancel the send first — cancelling ' +\n 'keeps the email and takes it off the clock.'\n }\n if (state === 'sending') {\n return 'This email is being sent right now.'\n }\n return 'Only a draft can be discarded.'\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult> => {\n const fresh = await transaction.get(ref)\n if (!fresh.exists) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const state = String(fresh.get('status') ?? '')\n if (state !== 'draft') {\n return { status: 409, body: { error: refusal(state) } }\n }\n /*\n * A plain delete, with nothing recursive under it. The one\n * subcollection a message grows is `reports/links`, written by the\n * delivery webhook — an email that has never been sent has no\n * deliveries, so there is nothing beneath a draft to leave behind.\n */\n transaction.delete(ref)\n return { status: 200, body: { emailId, discarded: true } }\n },\n )\n return outcome\n}\n\n/**\n * Campaign management API: removing a campaign, and discarding a draft.\n *\n * Separate from `campaigns/send` because nothing here sends, reserves\n * allowance or moves a meter, and because both operations are about a record\n * ceasing to exist — which is the one class of change that has to be read\n * against what a merchant has already mailed. Same authorization as the send\n * route: a site admin or editor, proven by a Firebase ID token.\n *\n * Editing a campaign is deliberately NOT here. The container is client-\n * writable by the same roles, its create already runs on the client SDK, and\n * a second door to the same document would be a second place for the two to\n * disagree about what a campaign may hold.\n */\n/**\n * The fields a copy of a message carries (AGL-2936): what was written and\n * how it is sent — never who it goes to or when. The audience, list,\n * segment, addresses, schedule and experiment are the decisions a person\n * makes about THIS send, and a copy that inherited them would be one click\n * from mailing the same people twice.\n */\nconst DUPLICATED_MESSAGE_FIELDS = [\n 'subject',\n 'body',\n 'fromName',\n 'replyTo',\n 'senderId',\n 'templateScreenId',\n 'plainText',\n 'plainTextVersionId',\n 'topicId',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n] as const\n\n/**\n * Copies a message as a new draft (AGL-2936). Any status can be copied —\n * a sent email is the usual source — and the copy is always `draft`, with\n * the name the person gave it made unique among the site's messages.\n */\nasync function duplicateMessage(\n hostId: string,\n hostRef: FirebaseFirestore.DocumentReference,\n emailId: string,\n requestedName: string,\n actor: { uid: string; email: string | null; orgId: string },\n): Promise<ManageResult> {\n const messages = hostRef.collection('campaigns')\n const firestore = hostRef.firestore\n const id = createResourceUid()\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult & { name?: string; sourceName?: string }> => {\n const [source, siblings] = await Promise.all([\n transaction.get(messages.doc(emailId)),\n transaction.get(messages.select('displayName', 'subject')),\n ])\n if (!source.exists) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const data = (source.data() ?? {}) as Record<string, unknown>\n const sourceName = String(data['displayName'] ?? data['subject'] ?? '').trim()\n const name = uniqueDuplicateName(\n requestedName.trim() || duplicateDisplayName(sourceName),\n siblings.docs.map((row) => String(row.get('displayName') ?? row.get('subject') ?? '')),\n )\n const copy: Record<string, unknown> = {}\n for (const field of DUPLICATED_MESSAGE_FIELDS) {\n if (data[field] !== undefined && data[field] !== null) copy[field] = data[field]\n }\n const nowMs = Date.now()\n transaction.create(messages.doc(id), {\n ...copy,\n displayName: name,\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: new Date(nowMs),\n draftedBy: actor.uid,\n })\n return { status: 200, body: { emailId: id, name }, name, sourceName }\n },\n )\n if (outcome.status === 200) {\n await logResourceDuplicated(\n 'campaign',\n { uid: actor.uid, email: actor.email },\n {\n orgId: actor.orgId,\n hostId,\n source: { id: emailId, name: outcome.sourceName ?? '' },\n target: { id, name: outcome.name ?? '' },\n },\n )\n }\n return { status: outcome.status, body: outcome.body }\n}\n\n/*==========================================\n * A CAMPAIGN THAT EXISTS BEFORE ANYBODY CHOSE WHO GETS IT (AGL-2912).\n *\n * The draft writer this plugin registers for the `campaign` resource on the\n * core's resource-drafts seam. Another plugin that produces a campaign — a\n * generator working from a brief, an importer bringing campaigns over from\n * another tool — asks for it by name, and gets exactly two documents:\n *\n * - the CONTAINER at `emailCampaigns/{id}`, written as the campaigns list's\n * create drawer writes one, aimed at no list;\n * - ONE EMAIL inside it at `campaigns/{id}-email`, `status: 'draft'`, naming\n * the email design it sends and holding its subject, preheader and the\n * alternatives to them.\n *\n * ## What a drafted email never holds\n *\n * An audience, a list, a segment, addresses, a topic, a sender, a send time or\n * an experiment. Those are the decisions a person makes about a send — the\n * duplicate above strips the same ones for the same reason — and a draft that\n * arrived holding any of them would be one click from mailing people nobody\n * chose. So the writer has no field for them to arrive in.\n *\n * ## Why a draft cannot escape\n *\n * Nothing here reserves an allowance, claims a budget or calls the send path,\n * and the scheduled processor queries `status == 'scheduled'`, which a draft\n * never is. `performCampaignSend` is the only thing that mails a draft, behind\n * the send route's own authorization, when a member asks.\n *\n * The id of the email is derived from the campaign's rather than minted, so a\n * write asked again finds the email it made — and differs from it, because a\n * campaign URL names a container OR a send, and one id naming both would read\n * as either.\n *=========================================*/\n\n/** The resource name the campaign draft writer is registered under. */\nexport const CAMPAIGN_DRAFT_RESOURCE = 'campaign'\n\n/** The id `plugins.config.json` registers this plugin under. */\nconst MARKETING_PLUGIN_ID = 'marketing'\n\n/** A drafted campaign's name when the caller asks for none. */\nexport const CAMPAIGN_DRAFT_DEFAULT_NAME = 'Untitled campaign'\n\n/** The longest subject or preheader a drafted email stores: the send route's header cap. */\nexport const CAMPAIGN_DRAFT_HEADER_MAX_CHARS = 200\n\n/** The most alternative subject lines or preheaders a drafted email keeps. */\nexport const CAMPAIGN_DRAFT_MAX_VARIANTS = 10\n\n/** The site roles that may compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLES = ['admin', 'editor'] as const\n/** The send route's refusal for a member who may not compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLE_REFUSAL = 'Not a site admin or editor'\n\n/** The id of the one email inside a drafted campaign. */\nexport function campaignDraftEmailId(campaignId: string): string {\n return `${campaignId}-email`\n}\n\n/** Every field a drafted email is written with, and so every field it can hold. */\nexport const CAMPAIGN_DRAFT_EMAIL_FIELDS = [\n 'subject',\n 'preheader',\n 'templateScreenId',\n 'subjectVariants',\n 'preheaderVariants',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n 'status',\n 'createdAtMs',\n 'draftedAt',\n 'draftedBy',\n] as const\n\n/** What a caller sends as `content`. */\nexport interface CampaignDraftContent {\n /** The email design the email sends: a `kind: 'email'` screen on the site. */\n templateScreenId: string\n subject: string\n preheader: string\n subjectVariants: string[]\n preheaderVariants: string[]\n}\n\n/** A header value on one line: controls and runs of space folded to one space. */\nfunction draftHeaderLine(value: unknown): string {\n return String(value ?? '').replace(/[\\p{Cc}\\s]+/gu, ' ').trim()\n}\n\nfunction draftVariants(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const seen = new Set<string>()\n const lines: string[] = []\n for (const raw of value) {\n const line = draftHeaderLine(raw)\n if (!line || seen.has(line.toLowerCase())) continue\n seen.add(line.toLowerCase())\n lines.push(line)\n }\n return lines.slice(0, CAMPAIGN_DRAFT_MAX_VARIANTS)\n}\n\nexport function readCampaignDraftContent(\n content: Readonly<Record<string, unknown>>,\n): { ok: true; value: CampaignDraftContent } | { ok: false; problems: string[] } {\n const value: CampaignDraftContent = {\n templateScreenId: String(content['templateScreenId'] ?? ''),\n subject: draftHeaderLine(content['subject']),\n preheader: draftHeaderLine(content['preheader']),\n subjectVariants: draftVariants(content['subjectVariants']),\n preheaderVariants: draftVariants(content['preheaderVariants']),\n }\n const problems: string[] = []\n if (!isDocumentId(value.templateScreenId)) {\n problems.push('A drafted campaign needs the email design it sends')\n }\n if (!value.subject) problems.push('A drafted campaign needs a subject line')\n const long = (lines: string[]) =>\n lines.some((line) => line.length > CAMPAIGN_DRAFT_HEADER_MAX_CHARS)\n if (long([value.subject, ...value.subjectVariants])) {\n problems.push(`A subject line is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n if (long([value.preheader, ...value.preheaderVariants])) {\n problems.push(`A preheader is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n return problems.length ? { ok: false, problems } : { ok: true, value }\n}\n\nfunction campaignDraftRoleRefusal(\n host: FirebaseFirestore.DocumentSnapshot,\n uid: string,\n): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return CAMPAIGN_DRAFT_ROLES.includes(role)\n ? null\n : { status: 403, error: CAMPAIGN_DRAFT_ROLE_REFUSAL }\n}\n\nfunction campaignDraftRecord(campaign: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n return {\n id: campaign.id,\n name: String(campaign.get('name') ?? ''),\n versionId: null,\n facts: { emailId: campaignDraftEmailId(campaign.id) },\n }\n}\n\nexport interface CampaignDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => FirebaseFirestore.Firestore\n}\n\nexport function createCampaignDraftWriter(\n deps: CampaignDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore =\n deps.firestore ??\n (() => firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore)\n return {\n refusal: async ({ hostId, uid }) => {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n return campaignDraftRoleRefusal(host, uid)\n },\n\n check: (content) => {\n const read = readCampaignDraftContent(content)\n return read.ok === false\n ? read\n : { ok: true, facts: { fields: [...CAMPAIGN_DRAFT_EMAIL_FIELDS] } }\n },\n\n read: async ({ hostId, id }) => {\n if (!isDocumentId(id)) return null\n const campaign = await firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('emailCampaigns')\n .doc(id)\n .get()\n return campaign.exists ? campaignDraftRecord(campaign) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCampaignDraftContent(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n if (!isDocumentId(request.id)) return { ok: false, status: 400, error: 'Invalid campaignId' }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const campaignRef = hostRef.collection('emailCampaigns').doc(request.id)\n const emailId = campaignDraftEmailId(request.id)\n const emailRef = hostRef.collection('campaigns').doc(emailId)\n const designRef = hostRef.collection('screens').doc(read.value.templateScreenId)\n return db.runTransaction(async (transaction): Promise<PluginDraftWrite> => {\n const [host, campaign, email, design] = await Promise.all([\n transaction.get(hostRef),\n transaction.get(campaignRef),\n transaction.get(emailRef),\n transaction.get(designRef),\n ])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (campaign.exists) {\n return { ok: true, replayed: true, ...campaignDraftRecord(campaign) }\n }\n const refusal = campaignDraftRoleRefusal(host, request.uid)\n if (refusal) return { ok: false, ...refusal }\n if (\n !design.exists ||\n design.get('deletedAt') != null ||\n design.get('kind') !== SCREEN_KIND_EMAIL\n ) {\n return { ok: false, status: 400, error: 'Unknown email design' }\n }\n if (email.exists) return { ok: false, status: 409, error: 'That email already exists' }\n const name = draftHeaderLine(request.name) || CAMPAIGN_DRAFT_DEFAULT_NAME\n const nowMs = request.now.getTime()\n // The create drawer's own document: a name, no dates, no lists.\n transaction.create(campaignRef, {\n name,\n listIds: [],\n createdAtMs: nowMs,\n createdBy: request.uid,\n })\n const { value } = read\n transaction.create(emailRef, {\n subject: value.subject,\n ...(value.preheader ? { preheader: value.preheader } : {}),\n templateScreenId: value.templateScreenId,\n ...(value.subjectVariants.length ? { subjectVariants: value.subjectVariants } : {}),\n ...(value.preheaderVariants.length ? { preheaderVariants: value.preheaderVariants } : {}),\n [CAMPAIGN_SEND_CONTAINER_FIELD]: request.id,\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: request.now,\n draftedBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: { emailId },\n }\n })\n },\n }\n}\n\nexport const campaignDraftWriter = createCampaignDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerCampaignDraftWriter(): void {\n registerPluginResourceDraftWriter(CAMPAIGN_DRAFT_RESOURCE, campaignDraftWriter, {\n pluginId: MARKETING_PLUGIN_ID,\n })\n}\n\nexport const campaignManageHandler: 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 action = String(req.body?.action ?? '')\n const targetId = String(req.body?.campaignId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n if (!isDocumentId(targetId)) {\n return res.status(400).json({ error: 'Invalid campaignId' })\n }\n if (\n action !== 'deleteCampaign' &&\n action !== 'discardEmail' &&\n action !== 'duplicate'\n ) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\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 const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n if (action === 'duplicate') {\n // One attempt key, one copy (AGL-2936): a double click on Duplicate\n // replays the first answer rather than drafting the message twice.\n const attemptKey = String(req.body?.attemptKey ?? '').trim().slice(0, 200)\n const orgId = (await resolveOrgIdForHost(hostId)) ?? ''\n const claimed = attemptKey\n ? await claimAttempt(firestore as never, {\n kind: 'duplicate-campaign',\n scopeId: `${hostId}:${targetId}`,\n orgId,\n key: attemptKey,\n busyMessage: DUPLICATE_BUSY_MESSAGE,\n })\n : null\n if (claimed && 'replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n const claim = claimed && 'claim' in claimed ? claimed.claim : null\n const copied = await duplicateMessage(\n hostId,\n hostRef,\n targetId,\n String(req.body?.name ?? ''),\n { uid: decoded.uid, email: decoded.email ?? null, orgId },\n )\n if (copied.status === 200) await claim?.record(copied.status, copied.body)\n else await claim?.release()\n return res.status(copied.status).json(copied.body)\n }\n const result =\n action === 'deleteCampaign'\n ? await deleteCampaign(hostId, hostRef, targetId)\n : await discardDraft(hostRef, targetId)\n return res.status(result.status).json(result.body)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'The request could not be completed' })\n }\n}\n"],"names":["firebaseAdmin","isDocumentId","logResourceDuplicated","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","claimAttempt","createResourceUid","consentGroupForSite","orgDataCollectionForHost","resolveOrgIdForHost","CAMPAIGN_MEMBER_HOST_COLLECTIONS","CAMPAIGN_MEMBERSHIP_FIELD","contactCampaignFieldPath","CAMPAIGN_SEND_CONTAINER_FIELD","SCREEN_KIND_EMAIL","registerPluginResourceDraftWriter","runPluginMembershipDetachers","DETACH_BATCH","DETACH_PASSES","detachSends","hostRef","campaignId","firestore","detached","pass","page","collection","where","limit","get","empty","remaining","batch","send","docs","update","ref","FieldValue","delete","commit","size","detachMembership","collectionRef","fieldPath","member","arrayRemove","detachMembers","hostId","collectionName","orgId","plugins","field","id","report","Object","values","group","contacts","contactPass","groupId","deleteCampaign","doc","snapshot","exists","status","body","error","toLocaleString","members","detachedMembers","deleted","discardDraft","emailId","refusal","state","outcome","runTransaction","transaction","fresh","String","discarded","DUPLICATED_MESSAGE_FIELDS","duplicateMessage","requestedName","actor","messages","source","data","siblings","Promise","all","select","sourceName","trim","name","map","row","copy","undefined","nowMs","Date","now","create","displayName","createdAtMs","draftedAt","draftedBy","uid","email","target","CAMPAIGN_DRAFT_RESOURCE","MARKETING_PLUGIN_ID","CAMPAIGN_DRAFT_DEFAULT_NAME","CAMPAIGN_DRAFT_HEADER_MAX_CHARS","CAMPAIGN_DRAFT_MAX_VARIANTS","CAMPAIGN_DRAFT_ROLES","CAMPAIGN_DRAFT_ROLE_REFUSAL","campaignDraftEmailId","CAMPAIGN_DRAFT_EMAIL_FIELDS","draftHeaderLine","value","replace","draftVariants","Array","isArray","seen","Set","lines","raw","line","has","toLowerCase","add","push","slice","readCampaignDraftContent","content","templateScreenId","subject","preheader","subjectVariants","preheaderVariants","problems","long","some","length","ok","campaignDraftRoleRefusal","host","role","includes","campaignDraftRecord","campaign","versionId","facts","createCampaignDraftWriter","deps","app","check","read","fields","write","request","db","campaignRef","emailRef","designRef","design","replayed","getTime","listIds","createdBy","campaignDraftWriter","registerCampaignDraftWriter","pluginId","campaignManageHandler","req","res","method","json","action","targetId","authorization","headers","idToken","startsWith","hostSnapshot","decoded","auth","verifyIdToken","memberRole","attemptKey","claimed","kind","scopeId","key","busyMessage","replay","claim","copied","record","release","result","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GAED;;;;;;CAMC,GACD,OAAOA,mBAAmB,iDAAgD;AAC1E,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,sBAAqB;AACrE;;;;;CAKC,GACD,SACEC,mBAAmB,EACnBC,wBAAwB,EACxBC,mBAAmB,QACd,gDAA+C;AACtD,SACEC,gCAAgC,EAChCC,yBAAyB,EACzBC,wBAAwB,QAEnB,sBAAqB;AAC5B,SACEC,6BAA6B,QACxB,yCAAwC;AAC/C,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,iCAAiC,QAK5B,qDAAoD;AAC3D,SAASC,4BAA4B,QAAQ,uDAAsD;AAEnG;;;;;;CAMC,GACD,MAAMC,eAAe;AAErB;;;;;;;;;;;;CAYC,GACD,MAAMC,gBAAgB;AAQtB;;;;;;;;;CASC,GACD,eAAeC,YACbC,OAA4C,EAC5CC,UAAkB;IAElB,MAAMC,YAAYF,QAAQE,SAAS;IACnC,IAAIC,WAAW;IACf,IAAK,IAA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E;YACA,MAAMqI,QAAQN,WAAW,WAAWA,UAAUA,QAAQM,KAAK,GAAG;YAC9D,MAAMC,SAAS,MAAMrH,iBACnBnC,QACA3B,SACAiK,UACAtG,iBAAOiG,aAAAA,IAAI/G,IAAI,qBAAR+G,WAAUlF,IAAI,oBAAI,KACzB;gBAAEa,KAAKgF,QAAQhF,GAAG;gBAAEC,KAAK,GAAE+E,iBAAAA,QAAQ/E,KAAK,YAAb+E,iBAAiB;gBAAM1I;YAAM;YAE1D,IAAIsJ,OAAOvI,MAAM,KAAK,KAAK,OAAMsI,yBAAAA,MAAOE,MAAM,CAACD,OAAOvI,MAAM,EAAEuI,OAAOtI,IAAI;iBACpE,OAAMqI,yBAAAA,MAAOG,OAAO;YACzB,OAAOxB,IAAIjH,MAAM,CAACuI,OAAOvI,MAAM,EAAEmH,IAAI,CAACoB,OAAOtI,IAAI;QACnD;QACA,MAAMyI,SACJtB,WAAW,mBACP,MAAMxH,eAAeb,QAAQ3B,SAASiK,YACtC,MAAM9G,aAAanD,SAASiK;QAClC,OAAOJ,IAAIjH,MAAM,CAAC0I,OAAO1I,MAAM,EAAEmH,IAAI,CAACuB,OAAOzI,IAAI;IACnD,EAAE,OAAOC,OAAO;QACdyI,QAAQzI,KAAK,CAACA;QACd,OAAO+G,IAAIjH,MAAM,CAAC,KAAKmH,IAAI,CAAC;YAAEjH,OAAO;QAAqC;IAC5E;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-manage.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\n/**\n * TAKING SOMETHING AWAY: a campaign container, and an abandoned draft.\n *\n * Both are removals, and neither may take a delivered message with it. That\n * is the whole reason this file is small and the comments are long.\n *\n * ## Why these two are not client writes\n *\n * The console creates and edits a campaign CONTAINER with the client SDK —\n * `orgs/{orgId}/emailCampaigns` is client-writable, because a container holds\n * no counter, no consent record and no entitlement input. It is not\n * client-DELETABLE: removing one has to detach everything that names it\n * first, across every site in the organization, which no rule can express.\n *\n * The SEND collection is the opposite: `orgs/{orgId}/campaigns` is excluded\n * from client create, update AND delete, because each document is the record\n * of what a merchant mailed and to whom they were allowed to mail it. Both\n * operations here have to touch it — one to detach sends from the container\n * being removed, the other to remove a draft outright — so both run on the\n * Admin SDK behind a role check.\n *\n * ## Two doors: a site, and the organization\n *\n * A campaign belongs to the organization and may be placed on several of its\n * sites. A request from a SITE hub names the site (`hostId`) and is\n * authorized by the caller's role there, as the send route is — and it acts\n * only on what that site holds: a send sent as another site, or a campaign\n * not placed on this one, answers as if it did not exist. A request from the\n * ORGANIZATION hub names the org (`orgId`) and no site, and is authorized by\n * the caller's org-wide membership; for an email it acts in the name of the\n * site the email is sent as.\n *\n * ## What deleting a campaign MEANS\n *\n * The container goes; every email inside it stays, and reads afterwards as a\n * single send.\n *\n * It cannot mean anything else. A send id is cited by mail already delivered\n * — every unsubscribe footer carries `cid={sendId}` inside its own HMAC, and\n * `/marketing/campaigns/{sendId}` is a URL merchants paste into their own\n * messages — so deleting a container that destroyed its sends would break\n * opt-out links that must go on resolving forever, which is a compliance\n * failure rather than a broken page.\n *\n * Nor may the sends simply be left pointing at a container that is gone.\n * `campaignListRows` groups sends by the container they name and draws one\n * row per container; a send naming a container that no longer exists is in\n * neither half of that — not a container row, and not an orphan the list\n * adopts — so it would vanish from the campaigns table while remaining\n * perfectly deliverable. Detaching is what puts it back in the list, as the\n * \"Single send\" the product already models and the table already draws.\n *\n * Deleting a campaign is therefore NOT a way to stop its mail. A scheduled\n * email inside it keeps its send time and still goes out, because a\n * container is a grouping and cancelling somebody's mail is `cancel`'s job.\n * The console says so before it asks.\n *\n * ## The same rule for everything else the campaign held\n *\n * A campaign also groups forms, screens and contacts, each of which names it\n * from its OWN document. They are detached on exactly the argument the sends\n * are: a form left naming a container nobody can read has not been freed, it\n * has been made unreadable — its page draws a dead id where a campaign name\n * belongs, and the campaigns table can no longer find it. The record itself\n * is never touched. Deleting a campaign deletes a campaign.\n */\n\n/*\n * The MODULE, not the barrel. `@aglyn/tenant-data-admin`'s index reaches\n * `render-cache`, which imports `next/cache` and therefore the whole Next\n * server pipeline — everything this file needs from the admin SDK is one\n * default export, and taking it from the leaf keeps that pipeline out of the\n * graph.\n */\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { logResourceDuplicated } from '@aglyn/tenant-data-admin/server/duplicate-activity'\nimport {\n DUPLICATE_BUSY_MESSAGE,\n duplicateDisplayName,\n uniqueDuplicateName,\n} from '@aglyn/aglyn/app-utils/duplicate-resource'\nimport { claimAttempt, createResourceUid } from '@aglyn/aglyn/server'\n/*\n * The MODULES again, for the same reason: the org and membership reads here\n * are what the contact pass and the organization door need, and taking them\n * from `@aglyn/tenant-data-admin`'s index would pull the whole Next server\n * pipeline back into this file's graph.\n */\nimport {\n consentGroupForSite,\n getOrgDoc,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport {\n CAMPAIGN_MEMBER_HOST_COLLECTIONS,\n CAMPAIGN_MEMBERSHIP_FIELD,\n contactCampaignFieldPath,\n isOrgWideMember,\n type AglynOrgMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n} from '@aglyn/aglyn/server'\nimport {\n CAMPAIGN_SEND_CONTAINER_FIELD,\n CAMPAIGN_SEND_HOST_FIELD,\n campaignPlacedOnHost,\n campaignSiteIds,\n campaignVisibleTo,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport {\n campaignSendSiteStamp,\n orgCampaignSends,\n orgEmailCampaigns,\n sendHostId,\n sendIsOnHost,\n} from './campaign-org-refs'\nimport { SCREEN_KIND_EMAIL } from '@aglyn/aglyn/app-utils/screen-route'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { runPluginMembershipDetachers } from '@aglyn/aglyn/plugin-manager/plugin-membership-detach'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\n\n/**\n * Sends detached in one write.\n *\n * Under Firestore's 500-operation batch limit with room to spare rather than\n * at it: a batch that is refused for being one over has done nothing, and the\n * margin costs one extra round trip on a campaign of exactly this size.\n */\nconst DETACH_BATCH = 400\n\n/**\n * How many batches one request will run.\n *\n * A ceiling on the REQUEST, not on the campaign. The loop below terminates on\n * its own — each pass clears the very field it queries on, so a detached send\n * is not returned again — but a request that runs unbounded is a request that\n * eventually exceeds the platform's own timeout with no idea how far it got.\n *\n * Stopping early is safe and is why this is a ceiling rather than a refusal\n * up front: detaching is idempotent and partial progress is a consistent\n * state — the sends already detached read as single sends, the rest still\n * read under the campaign — so the answer to hitting it is to ask again.\n */\nconst DETACH_PASSES = 25\n\n/**\n * The most sites one deletion walks for members.\n *\n * A campaign is the organization's, so its forms, screens and consent-group\n * facets may be on any of its sites. An organization past this has more\n * sites than one request should sweep, and the deletion refuses rather than\n * removing a container some sites' records would still name.\n */\nconst ORG_SITES_MAX = 200\n\n/** What one `campaigns/manage` call answered with. */\ninterface ManageResult {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Clears {@link CAMPAIGN_SEND_CONTAINER_FIELD} from every send in a campaign.\n *\n * Equality on one field with a `limit` — no `orderBy` — which Firestore's\n * automatic single-field index serves. Ordering would need a composite index\n * for a walk whose order does not matter: every match is being written, so\n * which order they come back in cannot change the outcome.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachSends(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await orgCampaignSends(firestore, orgId)\n .where(CAMPAIGN_SEND_CONTAINER_FIELD, '==', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const send of page.docs) {\n /*\n * The FIELD is removed, not set to an empty string. `campaignListRows`\n * adopts a send whose container id is falsy, so an empty string would\n * work by accident today — but the field is also what the campaign\n * detail page's `where` clause matches, and an equality query on `''`\n * is a different query from the absence the pre-container sends have.\n * One shape for \"belongs to no campaign\" is what keeps those two\n * readers agreeing.\n */\n batch.update(send.ref, {\n [CAMPAIGN_SEND_CONTAINER_FIELD]:\n firebaseAdmin.firestore.FieldValue.delete(),\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Clears one campaign id out of a membership array, wherever it is held.\n *\n * The same walk {@link detachSends} makes, over an ARRAY field rather than a\n * scalar one: `array-contains` matches on Firestore's automatic single-field\n * index, and `arrayRemove` takes out the one id without touching the other\n * campaigns a form or a screen is in. That is the whole reason the membership\n * is an array here and a `FieldValue.delete()` on a send — a send is in one\n * campaign and a landing page is in several, so removing one must not be\n * removing all of them.\n *\n * `query` rather than a collection ref, because the contact pass hands in a\n * path this file cannot build for itself.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachMembership(\n firestore: FirebaseFirestore.Firestore,\n collectionRef: FirebaseFirestore.CollectionReference,\n fieldPath: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await collectionRef\n .where(fieldPath, 'array-contains', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const member of page.docs) {\n batch.update(member.ref, {\n [fieldPath]: firebaseAdmin.firestore.FieldValue.arrayRemove(campaignId),\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Every site of the organization, by id — the sites a campaign's members may\n * be on. One equality on the `hostIndex` mirror, the same document\n * `resolveOrgIdForHost` reads to put a site in an org.\n *\n * @returns the ids, and whether the org has more than {@link ORG_SITES_MAX}.\n */\nasync function orgSiteIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<{ hostIds: string[]; truncated: boolean }> {\n const page = await firestore\n .collection('hostIndex')\n .where('orgId', '==', orgId)\n .limit(ORG_SITES_MAX + 1)\n .get()\n const hostIds = page.docs.map((doc) => String(doc.id))\n return {\n hostIds: hostIds.slice(0, ORG_SITES_MAX),\n truncated: hostIds.length > ORG_SITES_MAX,\n }\n}\n\n/**\n * Clears the campaign off every form, screen, lead and contact holding it,\n * on every site of the organization, and then off every record a plugin\n * keeps about it (AGL-3254).\n *\n * ## Why the campaign is not simply deleted over the top of them\n *\n * A campaign that went away leaving members naming it is the same failure the\n * send detach exists to prevent, one collection over: the campaign's own page\n * finds its forms and screens with `array-contains`, and a form still naming\n * a container nobody can read is in neither half of that — not a member of\n * any campaign the console can draw, and not free of one either. Its own page\n * would render the dead id as a chip with no name.\n *\n * ## Every site, not the one that asked\n *\n * The campaign is the organization's, and a site it has since been taken off\n * may still hold forms and screens filed under it. So the walk covers every\n * site in the org regardless of which door the deletion came through.\n *\n * ## Leads and contacts are reached on the organization\n *\n * A lead lives at `orgs/{orgId}/leads` and carries the field at the top of\n * its document, like a form. The site `leads` collection is walked as well,\n * as part of each site's own collections: records captured before leads\n * moved to the org are still read there.\n *\n * A contact lives at `orgs/{orgId}/contacts` and is shared by every site, so\n * the membership sits inside a consent group's facet rather than at the top\n * of the document. The field PATH is therefore the scope, and the walk runs\n * once per distinct group of the org's sites — two sites declared as one\n * sender share a facet, and clearing it twice would find nothing the second\n * time. The unscoped collection ref is what the walk runs on precisely\n * because the path already carries the boundary — a `visibleTo` filter would\n * spend the query's one array-contains slot and leave none for the\n * membership.\n *\n * ## A plugin's members are the plugin's to clear\n *\n * A sequence and its enrollments name the campaign from documents under the\n * org, in collections this plugin does not know (AGL-3254). Every plugin\n * with a membership detacher registered on the core's seam is asked, once\n * per site, with the campaign's id and the field it is held in, and a\n * detacher that reports records remaining — or threw, which is reported as\n * `null` — holds the container exactly as this pass's own `remaining` does.\n * A plugin that failed is a plugin whose records may still name the\n * campaign, and the deletion has no way to tell that apart from one that has\n * more than a request clears.\n */\nasync function detachMembers(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n let remaining = false\n const take = (pass: { detached: number; remaining: boolean }) => {\n detached += pass.detached\n remaining = remaining || pass.remaining\n }\n const { hostIds, truncated } = await orgSiteIds(firestore, orgId)\n if (truncated) remaining = true\n for (const hostId of hostIds) {\n const hostRef = firestore.collection('hosts').doc(hostId)\n for (const collectionName of CAMPAIGN_MEMBER_HOST_COLLECTIONS) {\n take(\n await detachMembership(\n firestore,\n hostRef.collection(collectionName),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n ),\n )\n }\n }\n const orgRef = firestore.collection('orgs').doc(orgId)\n take(\n await detachMembership(\n firestore,\n orgRef.collection('leads'),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n ),\n )\n /*\n * An org with no sites still has plugins that may hold the campaign, so\n * the seam is asked once with no site rather than not at all.\n */\n for (const hostId of hostIds.length ? hostIds : ['']) {\n const plugins = await runPluginMembershipDetachers({\n hostId,\n orgId,\n field: CAMPAIGN_MEMBERSHIP_FIELD,\n id: campaignId,\n })\n for (const report of Object.values(plugins)) {\n detached += report?.detached ?? 0\n remaining = remaining || report === null || report.remaining\n }\n }\n /*\n * One read of the org document serves every site's group: with it in\n * hand, `consentGroupForSite` resolves from the declaration without a\n * lookup per site. A missing document answers every site as a group of\n * one, which is `consentGroupForSite`'s documented failure direction and\n * the safe one here — each site's own facet is cleared, and no other.\n */\n const org = ((await getOrgDoc(orgId)) ?? {}) as Record<string, unknown>\n const groupIds = new Set<string>()\n for (const hostId of hostIds) {\n groupIds.add((await consentGroupForSite(hostId, org)).groupId)\n }\n const contacts = orgRef.collection('contacts')\n for (const groupId of groupIds) {\n take(\n await detachMembership(\n firestore,\n contacts,\n contactCampaignFieldPath(groupId),\n campaignId,\n ),\n )\n }\n return { detached, remaining }\n}\n\n/** Who is deleting, and through which door. */\ninterface DeleteAccess {\n /** The site hub the request came from, or `''` from the organization hub. */\n hostId: string\n /** The caller, for the site door's reach check. */\n uid: string\n}\n\n/**\n * Removes a campaign container, leaving its emails standing.\n *\n * Detach first, delete second, and the order is the point: stopping between\n * them leaves a container whose emails are already single sends, which the\n * list draws correctly and a second run finishes. Deleting first would leave\n * sends naming a container nobody can read, which is the state that loses\n * them from the table.\n *\n * ## What a site hub may delete\n *\n * A campaign placed on this site and on no other — the one a site hub\n * creates. A campaign that is not placed here is not this site's to see, so\n * it answers 404 as a missing one would. A campaign also placed on other\n * sites is refused unless the caller is an org-wide member: deleting it\n * takes it off those sites too, which is the same reach change the rules\n * reserve for org-wide members when a campaign is edited.\n */\nasync function deleteCampaign(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n access: DeleteAccess,\n): Promise<ManageResult> {\n const ref = orgEmailCampaigns(firestore, orgId).doc(campaignId)\n const snapshot = await ref.get()\n /*\n * A 404 rather than a silent success. The id in a campaign URL may name a\n * container OR a single send — that ambiguity is what keeps every link\n * minted before containers existed resolving — so \"no container here\" is\n * very often \"this is a send\", and answering it as a completed deletion\n * would tell the console it had removed something it never touched.\n */\n const placement = {\n visibleTo: snapshot.exists\n ? (snapshot.get('visibleTo') as string[] | undefined)\n : undefined,\n }\n if (\n !snapshot.exists ||\n (access.hostId && !campaignPlacedOnHost(placement, access.hostId))\n ) {\n return { status: 404, body: { error: 'Unknown campaign' } }\n }\n if (access.hostId) {\n const sites = campaignSiteIds(placement)\n const onlyHere = sites !== null && sites.every((id) => id === access.hostId)\n if (!onlyHere) {\n const membership = await resolveOrgMembership(access.uid, orgId)\n if (!isOrgWideMember(membership?.member)) {\n return {\n status: 403,\n body: {\n error:\n 'This campaign is on other sites too, so deleting it would take ' +\n 'it off them as well. An organization admin can delete it from ' +\n 'the organization’s campaigns.',\n },\n }\n }\n }\n }\n const { detached, remaining } = await detachSends(firestore, orgId, campaignId)\n if (remaining) {\n return {\n status: 409,\n body: {\n detached,\n error:\n `This campaign holds more emails than one request can detach. ` +\n `${detached.toLocaleString()} of them now read as single sends and ` +\n 'the campaign is still here — run the delete again to finish it.',\n },\n }\n }\n /*\n * The MEMBERS come off before the container does, for the reason the sends\n * do: a partial run leaves records that are already out of the campaign,\n * which every surface draws correctly, while deleting first would leave\n * forms, screens and contacts naming an id nothing can resolve.\n *\n * Their own 409 rather than a shared one. \"More emails than one request can\n * detach\" is a sentence about the campaign's mail, and a merchant reading\n * it about a campaign of two emails and four thousand contacts would go\n * looking for emails that are not the problem.\n */\n const members = await detachMembers(firestore, orgId, campaignId)\n if (members.remaining) {\n return {\n status: 409,\n body: {\n detached,\n detachedMembers: members.detached,\n error:\n 'This campaign is on more records than one request can clear. ' +\n `${members.detached.toLocaleString()} of them are already out of ` +\n 'it and the campaign is still here — run the delete again to ' +\n 'finish it.',\n },\n }\n }\n await ref.delete()\n return {\n status: 200,\n body: {\n campaignId,\n detached,\n detachedMembers: members.detached,\n deleted: true,\n },\n }\n}\n\n/**\n * Discards a DRAFT email, and refuses anything else.\n *\n * The state check is inside the transaction as well as being the reason for\n * it. `sendNow` claims a draft by moving it to `sending` in a transaction of\n * its own, so a check made against an earlier read could delete a record\n * while the send path was mailing from it — the merchant would receive a\n * report for an email that no longer exists, and its `cid` would stop\n * resolving with the message already in inboxes.\n *\n * Only `draft`. A scheduled email is withdrawn with `cancel`, which leaves\n * the record and its report standing; a sent one has reached people, and\n * nothing on this surface may remove the evidence of that.\n *\n * `hostId` is the site hub the request came from, and a draft sent as a\n * different site is refused as unknown; from the organization hub it is\n * `''` and any site's draft may be discarded.\n */\nasync function discardDraft(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n emailId: string,\n hostId: string,\n): Promise<ManageResult> {\n const ref = orgCampaignSends(firestore, orgId).doc(emailId)\n const refusal = (state: string): string => {\n if (state === 'sent') {\n return 'This email has already been sent, so it cannot be discarded. ' +\n 'Its report and its unsubscribe links have to go on resolving.'\n }\n if (state === 'scheduled') {\n return 'This email is scheduled. Cancel the send first — cancelling ' +\n 'keeps the email and takes it off the clock.'\n }\n if (state === 'sending') {\n return 'This email is being sent right now.'\n }\n return 'Only a draft can be discarded.'\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult> => {\n const fresh = await transaction.get(ref)\n if (!fresh.exists || (hostId && !sendIsOnHost(fresh, hostId))) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const state = String(fresh.get('status') ?? '')\n if (state !== 'draft') {\n return { status: 409, body: { error: refusal(state) } }\n }\n /*\n * A plain delete, with nothing recursive under it. The one\n * subcollection a message grows is `reports/links`, written by the\n * delivery webhook — an email that has never been sent has no\n * deliveries, so there is nothing beneath a draft to leave behind.\n */\n transaction.delete(ref)\n return { status: 200, body: { emailId, discarded: true } }\n },\n )\n return outcome\n}\n\n/**\n * The fields a copy of a message carries (AGL-2936): what was written and\n * how it is sent — never who it goes to or when. The audience, list,\n * segment, addresses, schedule and experiment are the decisions a person\n * makes about THIS send, and a copy that inherited them would be one click\n * from mailing the same people twice.\n */\nconst DUPLICATED_MESSAGE_FIELDS = [\n 'subject',\n 'body',\n 'fromName',\n 'replyTo',\n 'senderId',\n 'templateScreenId',\n 'plainText',\n 'plainTextVersionId',\n 'topicId',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n] as const\n\n/**\n * Copies a message as a new draft (AGL-2936). Any status can be copied —\n * a sent email is the usual source — and the copy is always `draft`, with\n * the name the person gave it made unique among its site's messages.\n *\n * The copy is sent as the same site as its source: the sender, the design\n * and the consent it would mail under are all that site's. From a site hub\n * that is the requesting site, and a source sent as another site is refused\n * as unknown; from the organization hub (`hostId` `''`) it is whichever site\n * the source records, and a source that records none cannot be copied,\n * because the copy would be an email that can never be sent.\n */\nasync function duplicateMessage(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n hostId: string,\n emailId: string,\n requestedName: string,\n actor: { uid: string; email: string | null },\n): Promise<ManageResult> {\n const messages = orgCampaignSends(firestore, orgId)\n const id = createResourceUid()\n /*\n * The source is read once outside the transaction to learn its site, which\n * decides which siblings the name must be unique among; the transaction\n * reads it again, so a source changed in between is copied as it stands.\n */\n const peek = await messages.doc(emailId).get()\n if (!peek.exists || (hostId && !sendIsOnHost(peek, hostId))) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const siteId = hostId || sendHostId(peek)\n if (!siteId) {\n return {\n status: 409,\n body: {\n error:\n 'This email does not record which site it is sent from, so it ' +\n 'cannot be copied from here. Open it from its site instead.',\n },\n }\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult & { name?: string; sourceName?: string }> => {\n const [source, siblings] = await Promise.all([\n transaction.get(messages.doc(emailId)),\n transaction.get(\n messages\n .select('displayName', 'subject')\n .where(CAMPAIGN_SEND_HOST_FIELD, '==', siteId),\n ),\n ])\n if (!source.exists) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const data = (source.data() ?? {}) as Record<string, unknown>\n const sourceName = String(data['displayName'] ?? data['subject'] ?? '').trim()\n const name = uniqueDuplicateName(\n requestedName.trim() || duplicateDisplayName(sourceName),\n siblings.docs.map((row) => String(row.get('displayName') ?? row.get('subject') ?? '')),\n )\n const copy: Record<string, unknown> = {}\n for (const field of DUPLICATED_MESSAGE_FIELDS) {\n if (data[field] !== undefined && data[field] !== null) copy[field] = data[field]\n }\n const nowMs = Date.now()\n transaction.create(messages.doc(id), {\n ...copy,\n ...campaignSendSiteStamp(siteId),\n displayName: name,\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: new Date(nowMs),\n draftedBy: actor.uid,\n })\n return { status: 200, body: { emailId: id, name }, name, sourceName }\n },\n )\n if (outcome.status === 200) {\n await logResourceDuplicated(\n 'campaign',\n { uid: actor.uid, email: actor.email },\n {\n orgId,\n hostId: siteId,\n source: { id: emailId, name: outcome.sourceName ?? '' },\n target: { id, name: outcome.name ?? '' },\n },\n )\n }\n return { status: outcome.status, body: outcome.body }\n}\n\n/*==========================================\n * A CAMPAIGN THAT EXISTS BEFORE ANYBODY CHOSE WHO GETS IT (AGL-2912).\n *\n * The draft writer this plugin registers for the `campaign` resource on the\n * core's resource-drafts seam. Another plugin that produces a campaign — a\n * generator working from a brief, an importer bringing campaigns over from\n * another tool — asks for it by name, and gets exactly two documents:\n *\n * - the CONTAINER at `orgs/{orgId}/emailCampaigns/{id}`, written as a site\n * hub's create drawer writes one: aimed at no list, placed on the site\n * the draft was asked for;\n * - ONE EMAIL inside it at `orgs/{orgId}/campaigns/{id}-email`,\n * `status: 'draft'`, sent as that site, naming the email design it sends\n * and holding its subject, preheader and the alternatives to them.\n *\n * ## What a drafted email never holds\n *\n * An audience, a list, a segment, addresses, a topic, a sender, a send time or\n * an experiment. Those are the decisions a person makes about a send — the\n * duplicate above strips the same ones for the same reason — and a draft that\n * arrived holding any of them would be one click from mailing people nobody\n * chose. So the writer has no field for them to arrive in.\n *\n * ## Why a draft cannot escape\n *\n * Nothing here reserves an allowance, claims a budget or calls the send path,\n * and the scheduled processor queries `status == 'scheduled'`, which a draft\n * never is. `performCampaignSend` is the only thing that mails a draft, behind\n * the send route's own authorization, when a member asks.\n *\n * The id of the email is derived from the campaign's rather than minted, so a\n * write asked again finds the email it made — and differs from it, because a\n * campaign URL names a container OR a send, and one id naming both would read\n * as either.\n *=========================================*/\n\n/** The resource name the campaign draft writer is registered under. */\nexport const CAMPAIGN_DRAFT_RESOURCE = 'campaign'\n\n/** The id `plugins.config.json` registers this plugin under. */\nconst MARKETING_PLUGIN_ID = 'marketing'\n\n/** A drafted campaign's name when the caller asks for none. */\nexport const CAMPAIGN_DRAFT_DEFAULT_NAME = 'Untitled campaign'\n\n/** The longest subject or preheader a drafted email stores: the send route's header cap. */\nexport const CAMPAIGN_DRAFT_HEADER_MAX_CHARS = 200\n\n/** The most alternative subject lines or preheaders a drafted email keeps. */\nexport const CAMPAIGN_DRAFT_MAX_VARIANTS = 10\n\n/** The site roles that may compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLES = ['admin', 'editor'] as const\n/** The send route's refusal for a member who may not compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLE_REFUSAL = 'Not a site admin or editor'\n\n/** The id of the one email inside a drafted campaign. */\nexport function campaignDraftEmailId(campaignId: string): string {\n return `${campaignId}-email`\n}\n\n/** Every field a drafted email is written with, and so every field it can hold. */\nexport const CAMPAIGN_DRAFT_EMAIL_FIELDS = [\n 'subject',\n 'preheader',\n 'templateScreenId',\n 'subjectVariants',\n 'preheaderVariants',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n CAMPAIGN_SEND_HOST_FIELD,\n 'visibleTo',\n 'status',\n 'createdAtMs',\n 'draftedAt',\n 'draftedBy',\n] as const\n\n/** What a caller sends as `content`. */\nexport interface CampaignDraftContent {\n /** The email design the email sends: a `kind: 'email'` screen on the site. */\n templateScreenId: string\n subject: string\n preheader: string\n subjectVariants: string[]\n preheaderVariants: string[]\n}\n\n/** A header value on one line: controls and runs of space folded to one space. */\nfunction draftHeaderLine(value: unknown): string {\n return String(value ?? '').replace(/[\\p{Cc}\\s]+/gu, ' ').trim()\n}\n\nfunction draftVariants(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const seen = new Set<string>()\n const lines: string[] = []\n for (const raw of value) {\n const line = draftHeaderLine(raw)\n if (!line || seen.has(line.toLowerCase())) continue\n seen.add(line.toLowerCase())\n lines.push(line)\n }\n return lines.slice(0, CAMPAIGN_DRAFT_MAX_VARIANTS)\n}\n\nexport function readCampaignDraftContent(\n content: Readonly<Record<string, unknown>>,\n): { ok: true; value: CampaignDraftContent } | { ok: false; problems: string[] } {\n const value: CampaignDraftContent = {\n templateScreenId: String(content['templateScreenId'] ?? ''),\n subject: draftHeaderLine(content['subject']),\n preheader: draftHeaderLine(content['preheader']),\n subjectVariants: draftVariants(content['subjectVariants']),\n preheaderVariants: draftVariants(content['preheaderVariants']),\n }\n const problems: string[] = []\n if (!isDocumentId(value.templateScreenId)) {\n problems.push('A drafted campaign needs the email design it sends')\n }\n if (!value.subject) problems.push('A drafted campaign needs a subject line')\n const long = (lines: string[]) =>\n lines.some((line) => line.length > CAMPAIGN_DRAFT_HEADER_MAX_CHARS)\n if (long([value.subject, ...value.subjectVariants])) {\n problems.push(`A subject line is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n if (long([value.preheader, ...value.preheaderVariants])) {\n problems.push(`A preheader is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n return problems.length ? { ok: false, problems } : { ok: true, value }\n}\n\nfunction campaignDraftRoleRefusal(\n host: FirebaseFirestore.DocumentSnapshot,\n uid: string,\n): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return CAMPAIGN_DRAFT_ROLES.includes(role)\n ? null\n : { status: 403, error: CAMPAIGN_DRAFT_ROLE_REFUSAL }\n}\n\nfunction campaignDraftRecord(campaign: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n return {\n id: campaign.id,\n name: String(campaign.get('name') ?? ''),\n versionId: null,\n facts: { emailId: campaignDraftEmailId(campaign.id) },\n }\n}\n\nexport interface CampaignDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => FirebaseFirestore.Firestore\n /** The site's organization, or null; specs hand in a double. */\n resolveOrgId?: (hostId: string) => Promise<string | null>\n}\n\nexport function createCampaignDraftWriter(\n deps: CampaignDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore =\n deps.firestore ??\n (() => firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore)\n /*\n * The org is resolved from the SITE rather than taken from the request's\n * context: the site is what the role check reads, so the campaign lands in\n * the organization that site belongs to and no other.\n */\n const resolveOrgId = deps.resolveOrgId ?? resolveOrgIdForHost\n return {\n refusal: async ({ hostId, uid }) => {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n return campaignDraftRoleRefusal(host, uid)\n },\n\n check: (content) => {\n const read = readCampaignDraftContent(content)\n return read.ok === false\n ? read\n : { ok: true, facts: { fields: [...CAMPAIGN_DRAFT_EMAIL_FIELDS] } }\n },\n\n read: async ({ hostId, id }) => {\n if (!isDocumentId(id)) return null\n const orgId = await resolveOrgId(hostId)\n if (!orgId) return null\n const campaign = await orgEmailCampaigns(firestore(), orgId).doc(id).get()\n return campaign.exists &&\n campaignPlacedOnHost(\n { visibleTo: campaign.get('visibleTo') as string[] | undefined },\n hostId,\n )\n ? campaignDraftRecord(campaign)\n : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCampaignDraftContent(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n if (!isDocumentId(request.id)) return { ok: false, status: 400, error: 'Invalid campaignId' }\n const db = firestore()\n const orgId = await resolveOrgId(request.hostId)\n if (!orgId) {\n return { ok: false, status: 409, error: 'This site is not part of an organization' }\n }\n const hostRef = db.collection('hosts').doc(request.hostId)\n const campaignRef = orgEmailCampaigns(db, orgId).doc(request.id)\n const emailId = campaignDraftEmailId(request.id)\n const emailRef = orgCampaignSends(db, orgId).doc(emailId)\n const designRef = hostRef.collection('screens').doc(read.value.templateScreenId)\n return db.runTransaction(async (transaction): Promise<PluginDraftWrite> => {\n const [host, campaign, email, design] = await Promise.all([\n transaction.get(hostRef),\n transaction.get(campaignRef),\n transaction.get(emailRef),\n transaction.get(designRef),\n ])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (campaign.exists) {\n /*\n * A replay answers only for a campaign this site can see: the id\n * space is the organization's, and one placed on a sibling site is\n * not this request's to report or to write over.\n */\n if (\n !campaignPlacedOnHost(\n { visibleTo: campaign.get('visibleTo') as string[] | undefined },\n request.hostId,\n )\n ) {\n return { ok: false, status: 409, error: 'That campaign already exists' }\n }\n return { ok: true, replayed: true, ...campaignDraftRecord(campaign) }\n }\n const refusal = campaignDraftRoleRefusal(host, request.uid)\n if (refusal) return { ok: false, ...refusal }\n if (\n !design.exists ||\n design.get('deletedAt') != null ||\n design.get('kind') !== SCREEN_KIND_EMAIL\n ) {\n return { ok: false, status: 400, error: 'Unknown email design' }\n }\n if (email.exists) return { ok: false, status: 409, error: 'That email already exists' }\n const name = draftHeaderLine(request.name) || CAMPAIGN_DRAFT_DEFAULT_NAME\n const nowMs = request.now.getTime()\n // A site hub's create drawer's own document: a name, no dates, no\n // lists, placed on the site it was drafted for.\n transaction.create(campaignRef, {\n name,\n listIds: [],\n visibleTo: campaignVisibleTo([request.hostId]),\n createdAtMs: nowMs,\n createdBy: request.uid,\n })\n const { value } = read\n transaction.create(emailRef, {\n subject: value.subject,\n ...(value.preheader ? { preheader: value.preheader } : {}),\n templateScreenId: value.templateScreenId,\n ...(value.subjectVariants.length ? { subjectVariants: value.subjectVariants } : {}),\n ...(value.preheaderVariants.length ? { preheaderVariants: value.preheaderVariants } : {}),\n [CAMPAIGN_SEND_CONTAINER_FIELD]: request.id,\n ...campaignSendSiteStamp(request.hostId),\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: request.now,\n draftedBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: { emailId },\n }\n })\n },\n }\n}\n\nexport const campaignDraftWriter = createCampaignDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerCampaignDraftWriter(): void {\n registerPluginResourceDraftWriter(CAMPAIGN_DRAFT_RESOURCE, campaignDraftWriter, {\n pluginId: MARKETING_PLUGIN_ID,\n })\n}\n\n/** The org roles that may manage campaigns from the organization hub. */\nconst ORG_MANAGE_ROLES = ['owner', 'admin', 'editor'] as const\n\n/**\n * The organization a `campaigns/manage` request from the organization hub is\n * for, read off its JSON body, so the dispatcher's release gate asks about the\n * right organization. Only consulted for a request that names no site.\n * Unverified, exactly as a `hostId` is: the handler refuses anyone who is not\n * an org-wide member of it.\n */\nexport async function campaignManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as { orgId?: unknown } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/**\n * Campaign management API: removing a campaign, discarding a draft, and\n * copying an email.\n *\n * Separate from `campaigns/send` because nothing here sends, reserves\n * allowance or moves a meter, and because the removals are about a record\n * ceasing to exist — which is the one class of change that has to be read\n * against what a merchant has already mailed.\n *\n * Reached through two doors — see the header. A site request carries\n * `hostId` and is authorized by the caller's admin or editor role on that\n * site; an organization request carries `orgId` and no `hostId`, and is\n * authorized by an org-wide membership as owner, admin or editor.\n *\n * Editing a campaign is deliberately NOT here. The container is client-\n * writable, its create already runs on the client SDK, and a second door to\n * the same document would be a second place for the two to disagree about\n * what a campaign may hold.\n */\nexport const campaignManageHandler: 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 requestedOrgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '')\n const targetId = String(req.body?.campaignId ?? '')\n if (!hostId && !requestedOrgId) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n if (hostId && !isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (requestedOrgId && !isDocumentId(requestedOrgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!isDocumentId(targetId)) {\n return res.status(400).json({ error: 'Invalid campaignId' })\n }\n if (\n action !== 'deleteCampaign' &&\n action !== 'discardEmail' &&\n action !== 'duplicate'\n ) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n let orgId: string\n if (hostId) {\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 const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n orgId = (await resolveOrgIdForHost(hostId)) ?? ''\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it holds no campaigns.',\n })\n }\n /*\n * A request naming both is answered for the site, and only when the\n * two agree: an org id the site does not belong to is a confused\n * caller, and acting on the site's own org instead would be a guess.\n */\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n } else {\n const membership = await resolveOrgMembership(decoded.uid, requestedOrgId)\n const member = membership?.member as Partial<AglynOrgMember> | undefined\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(ORG_MANAGE_ROLES as readonly string[]).includes(String(member.role ?? ''))\n ) {\n return res\n .status(403)\n .json({ error: 'Not an organization owner, admin or editor' })\n }\n /*\n * The site door is refused by the dispatcher when Marketing is off for\n * the site; a request naming no site reaches here past only the release\n * gate, so the organization's own switch is asked here.\n */\n if (!isPluginEnabled(await getOrgDoc(requestedOrgId), MARKETING_PLUGIN_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n orgId = requestedOrgId\n }\n\n if (action === 'duplicate') {\n // One attempt key, one copy (AGL-2936): a double click on Duplicate\n // replays the first answer rather than drafting the message twice.\n const attemptKey = String(req.body?.attemptKey ?? '').trim().slice(0, 200)\n const claimed = attemptKey\n ? await claimAttempt(firestore as never, {\n kind: 'duplicate-campaign',\n scopeId: `${hostId || `org:${orgId}`}:${targetId}`,\n orgId,\n key: attemptKey,\n busyMessage: DUPLICATE_BUSY_MESSAGE,\n })\n : null\n if (claimed && 'replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n const claim = claimed && 'claim' in claimed ? claimed.claim : null\n const copied = await duplicateMessage(\n firestore,\n orgId,\n hostId,\n targetId,\n String(req.body?.name ?? ''),\n { uid: decoded.uid, email: decoded.email ?? null },\n )\n if (copied.status === 200) await claim?.record(copied.status, copied.body)\n else await claim?.release()\n return res.status(copied.status).json(copied.body)\n }\n const result =\n action === 'deleteCampaign'\n ? await deleteCampaign(firestore, orgId, targetId, {\n hostId,\n uid: decoded.uid,\n })\n : await discardDraft(firestore, orgId, targetId, hostId)\n return res.status(result.status).json(result.body)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'The request could not be completed' })\n }\n}\n"],"names":["firebaseAdmin","isDocumentId","logResourceDuplicated","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","claimAttempt","createResourceUid","consentGroupForSite","getOrgDoc","resolveOrgIdForHost","resolveOrgMembership","CAMPAIGN_MEMBER_HOST_COLLECTIONS","CAMPAIGN_MEMBERSHIP_FIELD","contactCampaignFieldPath","isOrgWideMember","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_SEND_HOST_FIELD","campaignPlacedOnHost","campaignSiteIds","campaignVisibleTo","campaignSendSiteStamp","orgCampaignSends","orgEmailCampaigns","sendHostId","sendIsOnHost","SCREEN_KIND_EMAIL","registerPluginResourceDraftWriter","runPluginMembershipDetachers","isPluginEnabled","DETACH_BATCH","DETACH_PASSES","ORG_SITES_MAX","detachSends","firestore","orgId","campaignId","detached","pass","page","where","limit","get","empty","remaining","batch","send","docs","update","ref","FieldValue","delete","commit","size","detachMembership","collectionRef","fieldPath","member","arrayRemove","orgSiteIds","collection","hostIds","map","doc","String","id","slice","truncated","length","detachMembers","take","hostId","hostRef","collectionName","orgRef","plugins","field","report","Object","values","org","groupIds","Set","add","groupId","contacts","deleteCampaign","access","snapshot","placement","visibleTo","exists","undefined","status","body","error","sites","onlyHere","every","membership","uid","toLocaleString","members","detachedMembers","deleted","discardDraft","emailId","refusal","state","outcome","runTransaction","transaction","fresh","discarded","DUPLICATED_MESSAGE_FIELDS","duplicateMessage","requestedName","actor","messages","peek","siteId","source","data","siblings","Promise","all","select","sourceName","trim","name","row","copy","nowMs","Date","now","create","displayName","createdAtMs","draftedAt","draftedBy","email","target","CAMPAIGN_DRAFT_RESOURCE","MARKETING_PLUGIN_ID","CAMPAIGN_DRAFT_DEFAULT_NAME","CAMPAIGN_DRAFT_HEADER_MAX_CHARS","CAMPAIGN_DRAFT_MAX_VARIANTS","CAMPAIGN_DRAFT_ROLES","CAMPAIGN_DRAFT_ROLE_REFUSAL","campaignDraftEmailId","CAMPAIGN_DRAFT_EMAIL_FIELDS","draftHeaderLine","value","replace","draftVariants","Array","isArray","seen","lines","raw","line","has","toLowerCase","push","readCampaignDraftContent","content","templateScreenId","subject","preheader","subjectVariants","preheaderVariants","problems","long","some","ok","campaignDraftRoleRefusal","host","role","includes","campaignDraftRecord","campaign","versionId","facts","createCampaignDraftWriter","deps","app","resolveOrgId","check","read","fields","write","request","db","campaignRef","emailRef","designRef","design","replayed","getTime","listIds","createdBy","campaignDraftWriter","registerCampaignDraftWriter","pluginId","ORG_MANAGE_ROLES","campaignManageSubject","method","json","catch","campaignManageHandler","req","res","requestedOrgId","action","targetId","authorization","headers","idToken","startsWith","decoded","auth","verifyIdToken","hostSnapshot","memberRole","attemptKey","claimed","kind","scopeId","key","busyMessage","replay","claim","copied","record","release","result","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED;;;;;;CAMC,GACD,OAAOA,mBAAmB,iDAAgD;AAC1E,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,sBAAqB;AACrE;;;;;CAKC,GACD,SACEC,mBAAmB,EACnBC,SAAS,EACTC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SACEC,gCAAgC,EAChCC,yBAAyB,EACzBC,wBAAwB,EACxBC,eAAe,QAIV,sBAAqB;AAC5B,SACEC,6BAA6B,EAC7BC,wBAAwB,EACxBC,oBAAoB,EACpBC,eAAe,EACfC,iBAAiB,QACZ,yCAAwC;AAC/C,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,QACP,yBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,iCAAiC,QAK5B,qDAAoD;AAC3D,SAASC,4BAA4B,QAAQ,uDAAsD;AACnG,SAASC,eAAe,QAAQ,8CAA6C;AAE7E;;;;;;CAMC,GACD,MAAMC,eAAe;AAErB;;;;;;;;;;;;CAYC,GACD,MAAMC,gBAAgB;AAEtB;;;;;;;CAOC,GACD,MAAMC,gBAAgB;AAQtB;;;;;;;;;CASC,GACD,eAAeC,YACbC,SAAsC,EACtCC,KAAa,EACbC,UAAkB;IAElB,IAAIC,WAAW;IACf,IAAK,IAAIC,OAAO,GAAGA,OAAOP,eAAeO,QAAQ,EAAG;QAClD,MAAMC,OAAO,MAAMjB,iBAAi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hH,OAAO;QAAqC;IAC5E;AACF,EAAC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
type Firestore = FirebaseFirestore.Firestore;
|
|
18
|
+
/** `orgs/{orgId}/campaigns` — one document per send. */
|
|
19
|
+
export declare function orgCampaignSends(firestore: Firestore, orgId: string): FirebaseFirestore.CollectionReference;
|
|
20
|
+
/** `orgs/{orgId}/emailCampaigns` — one document per campaign container. */
|
|
21
|
+
export declare function orgEmailCampaigns(firestore: Firestore, orgId: string): FirebaseFirestore.CollectionReference;
|
|
22
|
+
/**
|
|
23
|
+
* The two fields every write that creates a send stamps: the site it is sent
|
|
24
|
+
* as, and that one site's scope token.
|
|
25
|
+
*
|
|
26
|
+
* Merged onto existing sends too. It is the same value the send already
|
|
27
|
+
* carries, or — on a send the migration has not reached — the value it is
|
|
28
|
+
* missing.
|
|
29
|
+
*/
|
|
30
|
+
export declare function campaignSendSiteStamp(hostId: string): {
|
|
31
|
+
hostId: string;
|
|
32
|
+
visibleTo: string[];
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Whether a stored send may be acted on in the name of this site. See the
|
|
36
|
+
* header for why an absent site is admitted.
|
|
37
|
+
*/
|
|
38
|
+
export declare function sendIsOnHost(snapshot: {
|
|
39
|
+
get(field: string): unknown;
|
|
40
|
+
}, hostId: string): boolean;
|
|
41
|
+
/** The site a stored send is sent as, or `''` when it records none. */
|
|
42
|
+
export declare function sendHostId(snapshot: {
|
|
43
|
+
get(field: string): unknown;
|
|
44
|
+
}): string;
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /**
|
|
17
|
+
* WHERE THIS PLUGIN'S SERVER CODE FINDS A CAMPAIGN, AND WHICH SITE A SEND IS.
|
|
18
|
+
*
|
|
19
|
+
* Containers and sends belong to the organization —
|
|
20
|
+
* `orgs/{orgId}/emailCampaigns` and `orgs/{orgId}/campaigns` — while every
|
|
21
|
+
* request that reaches this plugin arrives naming a SITE. The handlers know
|
|
22
|
+
* the org (they resolve it to check the plan and the sender), so they address
|
|
23
|
+
* the org collections directly; these helpers are the one spelling of those
|
|
24
|
+
* paths on the Admin SDK, beside the segment tuples the console uses from
|
|
25
|
+
* `campaign-container.ts`.
|
|
26
|
+
*
|
|
27
|
+
* ## Why a send is checked against the site that asks for it
|
|
28
|
+
*
|
|
29
|
+
* One org collection holds every site's sends, and a send id is not a secret:
|
|
30
|
+
* it is in every unsubscribe link and every report URL. A handler that took a
|
|
31
|
+
* site from the request and a send id from the request and acted on the pair
|
|
32
|
+
* would let an editor of one site cancel, mail or discard a sibling site's
|
|
33
|
+
* email by naming its id. So every door that addresses an existing send asks
|
|
34
|
+
* {@link sendIsOnHost} first. A send with no stored site is one written before
|
|
35
|
+
* sends recorded theirs; the migration stamps it, and until then it is
|
|
36
|
+
* admitted rather than stranded.
|
|
37
|
+
*/ import { CAMPAIGN_SEND_HOST_FIELD, CAMPAIGN_SENDS_COLLECTION, EMAIL_CAMPAIGNS_COLLECTION, campaignSendVisibleTo } from "@aglyn/shared-ui-email-campaigns/model";
|
|
38
|
+
function orgRef(firestore, orgId) {
|
|
39
|
+
/*
|
|
40
|
+
* Refused outright, not left to `.doc()`: an empty id throws there, but a
|
|
41
|
+
* `null` becomes the string `'null'` and addresses an org of that name —
|
|
42
|
+
* and nothing here is checked by the compiler for it.
|
|
43
|
+
*/ if (typeof orgId !== 'string' || !orgId) {
|
|
44
|
+
throw new Error('[marketing] a campaign path needs an organization');
|
|
45
|
+
}
|
|
46
|
+
return firestore.collection('orgs').doc(orgId);
|
|
47
|
+
}
|
|
48
|
+
/** `orgs/{orgId}/campaigns` — one document per send. */ export function orgCampaignSends(firestore, orgId) {
|
|
49
|
+
return orgRef(firestore, orgId).collection(CAMPAIGN_SENDS_COLLECTION);
|
|
50
|
+
}
|
|
51
|
+
/** `orgs/{orgId}/emailCampaigns` — one document per campaign container. */ export function orgEmailCampaigns(firestore, orgId) {
|
|
52
|
+
return orgRef(firestore, orgId).collection(EMAIL_CAMPAIGNS_COLLECTION);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The two fields every write that creates a send stamps: the site it is sent
|
|
56
|
+
* as, and that one site's scope token.
|
|
57
|
+
*
|
|
58
|
+
* Merged onto existing sends too. It is the same value the send already
|
|
59
|
+
* carries, or — on a send the migration has not reached — the value it is
|
|
60
|
+
* missing.
|
|
61
|
+
*/ export function campaignSendSiteStamp(hostId) {
|
|
62
|
+
if (typeof hostId !== 'string' || !hostId) {
|
|
63
|
+
throw new Error('[marketing] a send has to name the site it is sent as');
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
[CAMPAIGN_SEND_HOST_FIELD]: hostId,
|
|
67
|
+
visibleTo: campaignSendVisibleTo(hostId)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Whether a stored send may be acted on in the name of this site. See the
|
|
72
|
+
* header for why an absent site is admitted.
|
|
73
|
+
*/ export function sendIsOnHost(snapshot, hostId) {
|
|
74
|
+
const stored = snapshot.get(CAMPAIGN_SEND_HOST_FIELD);
|
|
75
|
+
if (stored === undefined || stored === null || stored === '') return true;
|
|
76
|
+
return stored === hostId;
|
|
77
|
+
}
|
|
78
|
+
/** The site a stored send is sent as, or `''` when it records none. */ export function sendHostId(snapshot) {
|
|
79
|
+
const stored = snapshot.get(CAMPAIGN_SEND_HOST_FIELD);
|
|
80
|
+
return typeof stored === 'string' ? stored : '';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=campaign-org-refs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-org-refs.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\n/**\n * WHERE THIS PLUGIN'S SERVER CODE FINDS A CAMPAIGN, AND WHICH SITE A SEND IS.\n *\n * Containers and sends belong to the organization —\n * `orgs/{orgId}/emailCampaigns` and `orgs/{orgId}/campaigns` — while every\n * request that reaches this plugin arrives naming a SITE. The handlers know\n * the org (they resolve it to check the plan and the sender), so they address\n * the org collections directly; these helpers are the one spelling of those\n * paths on the Admin SDK, beside the segment tuples the console uses from\n * `campaign-container.ts`.\n *\n * ## Why a send is checked against the site that asks for it\n *\n * One org collection holds every site's sends, and a send id is not a secret:\n * it is in every unsubscribe link and every report URL. A handler that took a\n * site from the request and a send id from the request and acted on the pair\n * would let an editor of one site cancel, mail or discard a sibling site's\n * email by naming its id. So every door that addresses an existing send asks\n * {@link sendIsOnHost} first. A send with no stored site is one written before\n * sends recorded theirs; the migration stamps it, and until then it is\n * admitted rather than stranded.\n */\n\nimport {\n CAMPAIGN_SEND_HOST_FIELD,\n CAMPAIGN_SENDS_COLLECTION,\n EMAIL_CAMPAIGNS_COLLECTION,\n campaignSendVisibleTo,\n} from '@aglyn/shared-ui-email-campaigns/model'\n\ntype Firestore = FirebaseFirestore.Firestore\n\nfunction orgRef(\n firestore: Firestore,\n orgId: string,\n): FirebaseFirestore.DocumentReference {\n /*\n * Refused outright, not left to `.doc()`: an empty id throws there, but a\n * `null` becomes the string `'null'` and addresses an org of that name —\n * and nothing here is checked by the compiler for it.\n */\n if (typeof orgId !== 'string' || !orgId) {\n throw new Error('[marketing] a campaign path needs an organization')\n }\n return firestore.collection('orgs').doc(orgId)\n}\n\n/** `orgs/{orgId}/campaigns` — one document per send. */\nexport function orgCampaignSends(\n firestore: Firestore,\n orgId: string,\n): FirebaseFirestore.CollectionReference {\n return orgRef(firestore, orgId).collection(CAMPAIGN_SENDS_COLLECTION)\n}\n\n/** `orgs/{orgId}/emailCampaigns` — one document per campaign container. */\nexport function orgEmailCampaigns(\n firestore: Firestore,\n orgId: string,\n): FirebaseFirestore.CollectionReference {\n return orgRef(firestore, orgId).collection(EMAIL_CAMPAIGNS_COLLECTION)\n}\n\n/**\n * The two fields every write that creates a send stamps: the site it is sent\n * as, and that one site's scope token.\n *\n * Merged onto existing sends too. It is the same value the send already\n * carries, or — on a send the migration has not reached — the value it is\n * missing.\n */\nexport function campaignSendSiteStamp(hostId: string): {\n hostId: string\n visibleTo: string[]\n} {\n if (typeof hostId !== 'string' || !hostId) {\n throw new Error('[marketing] a send has to name the site it is sent as')\n }\n return {\n [CAMPAIGN_SEND_HOST_FIELD]: hostId,\n visibleTo: campaignSendVisibleTo(hostId),\n } as { hostId: string; visibleTo: string[] }\n}\n\n/**\n * Whether a stored send may be acted on in the name of this site. See the\n * header for why an absent site is admitted.\n */\nexport function sendIsOnHost(\n snapshot: { get(field: string): unknown },\n hostId: string,\n): boolean {\n const stored = snapshot.get(CAMPAIGN_SEND_HOST_FIELD)\n if (stored === undefined || stored === null || stored === '') return true\n return stored === hostId\n}\n\n/** The site a stored send is sent as, or `''` when it records none. */\nexport function sendHostId(snapshot: { get(field: string): unknown }): string {\n const stored = snapshot.get(CAMPAIGN_SEND_HOST_FIELD)\n return typeof stored === 'string' ? stored : ''\n}\n"],"names":["CAMPAIGN_SEND_HOST_FIELD","CAMPAIGN_SENDS_COLLECTION","EMAIL_CAMPAIGNS_COLLECTION","campaignSendVisibleTo","orgRef","firestore","orgId","Error","collection","doc","orgCampaignSends","orgEmailCampaigns","campaignSendSiteStamp","hostId","visibleTo","sendIsOnHost","snapshot","stored","get","undefined","sendHostId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;CAqBC,GAED,SACEA,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,qBAAqB,QAChB,yCAAwC;AAI/C,SAASC,OACPC,SAAoB,EACpBC,KAAa;IAEb;;;;GAIC,GACD,IAAI,OAAOA,UAAU,YAAY,CAACA,OAAO;QACvC,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOF,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAACH;AAC1C;AAEA,sDAAsD,GACtD,OAAO,SAASI,iBACdL,SAAoB,EACpBC,KAAa;IAEb,OAAOF,OAAOC,WAAWC,OAAOE,UAAU,CAACP;AAC7C;AAEA,yEAAyE,GACzE,OAAO,SAASU,kBACdN,SAAoB,EACpBC,KAAa;IAEb,OAAOF,OAAOC,WAAWC,OAAOE,UAAU,CAACN;AAC7C;AAEA;;;;;;;CAOC,GACD,OAAO,SAASU,sBAAsBC,MAAc;IAIlD,IAAI,OAAOA,WAAW,YAAY,CAACA,QAAQ;QACzC,MAAM,IAAIN,MAAM;IAClB;IACA,OAAO;QACL,CAACP,yBAAyB,EAAEa;QAC5BC,WAAWX,sBAAsBU;IACnC;AACF;AAEA;;;CAGC,GACD,OAAO,SAASE,aACdC,QAAyC,EACzCH,MAAc;IAEd,MAAMI,SAASD,SAASE,GAAG,CAAClB;IAC5B,IAAIiB,WAAWE,aAAaF,WAAW,QAAQA,WAAW,IAAI,OAAO;IACrE,OAAOA,WAAWJ;AACpB;AAEA,qEAAqE,GACrE,OAAO,SAASO,WAAWJ,QAAyC;IAClE,MAAMC,SAASD,SAASE,GAAG,CAAClB;IAC5B,OAAO,OAAOiB,WAAW,WAAWA,SAAS;AAC/C"}
|
|
@@ -15,12 +15,42 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
18
|
+
/**
|
|
19
|
+
* Which site a due send is sent as, or why it is not this run's to send.
|
|
20
|
+
*
|
|
21
|
+
* `collectionGroup('campaigns')` matches every collection of that name, so
|
|
22
|
+
* the answer depends on where the document is:
|
|
23
|
+
*
|
|
24
|
+
* - `orgs/{orgId}/campaigns/{id}` — a send, whose site is its own
|
|
25
|
+
* `hostId` field. One that records none cannot be delivered, because the
|
|
26
|
+
* sender, the consent group and the unsubscribe signature are all the
|
|
27
|
+
* site's; it is skipped and logged rather than guessed at.
|
|
28
|
+
* - `hosts/{hostId}/campaigns/{id}` — a send the migration has not moved
|
|
29
|
+
* yet. NOT delivered and NOT claimed: the send core records every send
|
|
30
|
+
* under the org, so delivering this one would split it across two
|
|
31
|
+
* documents, the counters on one and the copy on the other. It stays
|
|
32
|
+
* `scheduled`, and the migration moves it with its site stamped, after
|
|
33
|
+
* which the next run delivers it.
|
|
34
|
+
* - anything else — some other collection named `campaigns`, never ours.
|
|
35
|
+
*/
|
|
36
|
+
export declare function scheduledSendSite(ref: {
|
|
37
|
+
path: string;
|
|
38
|
+
}, data: Record<string, unknown>): {
|
|
39
|
+
kind: 'send';
|
|
40
|
+
hostId: string;
|
|
41
|
+
} | {
|
|
42
|
+
kind: 'legacy';
|
|
43
|
+
} | {
|
|
44
|
+
kind: 'unsited';
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'foreign';
|
|
47
|
+
};
|
|
18
48
|
/**
|
|
19
49
|
* Scheduled-campaign processor (AGL-272): scheduler-invoked (Cloud
|
|
20
50
|
* Scheduler / cron, x-cron-secret like report-usage), it claims due
|
|
21
|
-
* `status: 'scheduled'`
|
|
51
|
+
* `status: 'scheduled'` sends across every organization and delivers them
|
|
22
52
|
* through the shared send core. A transaction flips scheduled → sending
|
|
23
|
-
* so overlapping runs never double-send; failures mark the
|
|
53
|
+
* so overlapping runs never double-send; failures mark the send
|
|
24
54
|
* `failed` with the reason instead of retrying forever.
|
|
25
55
|
*/
|
|
26
56
|
export declare const campaignProcessScheduledHandler: PluginApiHandler;
|
|
@@ -17,12 +17,61 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { writeCronBeat } from "@aglyn/aglyn/server";
|
|
18
18
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
19
19
|
import { CampaignSendDeferredError, CampaignSendError, performCampaignSend } from "./campaign-send.js";
|
|
20
|
+
/** The most sends one run delivers. */ const PROCESS_BATCH = 10;
|
|
21
|
+
/**
|
|
22
|
+
* How many due sends one run reads to find {@link PROCESS_BATCH} it may
|
|
23
|
+
* deliver.
|
|
24
|
+
*
|
|
25
|
+
* Wider than the batch because the collection-group query cannot be narrowed
|
|
26
|
+
* to one parent without a composite index, and it also returns sends still
|
|
27
|
+
* at the site path that are waiting for the migration (see
|
|
28
|
+
* {@link scheduledSendSite}). Those are skipped, so without the margin ten
|
|
29
|
+
* of them would crowd every organization's sends out of every run until the
|
|
30
|
+
* migration reached them.
|
|
31
|
+
*/ const PROCESS_READ = 30;
|
|
32
|
+
/**
|
|
33
|
+
* Which site a due send is sent as, or why it is not this run's to send.
|
|
34
|
+
*
|
|
35
|
+
* `collectionGroup('campaigns')` matches every collection of that name, so
|
|
36
|
+
* the answer depends on where the document is:
|
|
37
|
+
*
|
|
38
|
+
* - `orgs/{orgId}/campaigns/{id}` — a send, whose site is its own
|
|
39
|
+
* `hostId` field. One that records none cannot be delivered, because the
|
|
40
|
+
* sender, the consent group and the unsubscribe signature are all the
|
|
41
|
+
* site's; it is skipped and logged rather than guessed at.
|
|
42
|
+
* - `hosts/{hostId}/campaigns/{id}` — a send the migration has not moved
|
|
43
|
+
* yet. NOT delivered and NOT claimed: the send core records every send
|
|
44
|
+
* under the org, so delivering this one would split it across two
|
|
45
|
+
* documents, the counters on one and the copy on the other. It stays
|
|
46
|
+
* `scheduled`, and the migration moves it with its site stamped, after
|
|
47
|
+
* which the next run delivers it.
|
|
48
|
+
* - anything else — some other collection named `campaigns`, never ours.
|
|
49
|
+
*/ export function scheduledSendSite(ref, data) {
|
|
50
|
+
var _ref;
|
|
51
|
+
const segments = String((_ref = ref == null ? void 0 : ref.path) != null ? _ref : '').split('/');
|
|
52
|
+
const ownerCollection = segments.length === 4 ? segments[0] : '';
|
|
53
|
+
if (ownerCollection === 'orgs') {
|
|
54
|
+
const hostId = data['hostId'];
|
|
55
|
+
return typeof hostId === 'string' && hostId && !hostId.includes('/') ? {
|
|
56
|
+
kind: 'send',
|
|
57
|
+
hostId
|
|
58
|
+
} : {
|
|
59
|
+
kind: 'unsited'
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (ownerCollection === 'hosts') return {
|
|
63
|
+
kind: 'legacy'
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
kind: 'foreign'
|
|
67
|
+
};
|
|
68
|
+
}
|
|
20
69
|
/**
|
|
21
70
|
* Scheduled-campaign processor (AGL-272): scheduler-invoked (Cloud
|
|
22
71
|
* Scheduler / cron, x-cron-secret like report-usage), it claims due
|
|
23
|
-
* `status: 'scheduled'`
|
|
72
|
+
* `status: 'scheduled'` sends across every organization and delivers them
|
|
24
73
|
* through the shared send core. A transaction flips scheduled → sending
|
|
25
|
-
* so overlapping runs never double-send; failures mark the
|
|
74
|
+
* so overlapping runs never double-send; failures mark the send
|
|
26
75
|
* `failed` with the reason instead of retrying forever.
|
|
27
76
|
*/ export const campaignProcessScheduledHandler = async (req, res)=>{
|
|
28
77
|
if (req.method !== 'POST') {
|
|
@@ -52,13 +101,27 @@ import { CampaignSendDeferredError, CampaignSendError, performCampaignSend } fro
|
|
|
52
101
|
// produces exactly the same silence as a deleted schedule — so the
|
|
53
102
|
// invocation itself is the only honest thing to watch.
|
|
54
103
|
await writeCronBeat(firestore, 'campaigns-process-scheduled');
|
|
55
|
-
const due = await firestore.collectionGroup('campaigns').where('status', '==', 'scheduled').where('sendAtMs', '<=', Date.now()).limit(
|
|
104
|
+
const due = await firestore.collectionGroup('campaigns').where('status', '==', 'scheduled').where('sendAtMs', '<=', Date.now()).limit(PROCESS_READ).get();
|
|
56
105
|
const results = [];
|
|
106
|
+
/** Due sends still at a site path, left for the migration. */ let awaitingMigration = 0;
|
|
107
|
+
/** Due org sends that name no site, and so cannot be sent. */ let unsited = 0;
|
|
108
|
+
let attempted = 0;
|
|
57
109
|
for (const campaignDoc of due.docs){
|
|
58
|
-
var _ref;
|
|
110
|
+
var _campaignDoc_data, _ref;
|
|
59
111
|
var _data_resume;
|
|
60
|
-
|
|
61
|
-
|
|
112
|
+
if (attempted >= PROCESS_BATCH) break;
|
|
113
|
+
const site = scheduledSendSite(campaignDoc.ref, (_campaignDoc_data = campaignDoc.data()) != null ? _campaignDoc_data : {});
|
|
114
|
+
if (site.kind === 'legacy') {
|
|
115
|
+
awaitingMigration += 1;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (site.kind === 'unsited') {
|
|
119
|
+
unsited += 1;
|
|
120
|
+
console.error(`[campaigns] scheduled send ${campaignDoc.ref.path} names no site and was not sent`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (site.kind !== 'send') continue;
|
|
124
|
+
attempted += 1;
|
|
62
125
|
const claimed = await firestore.runTransaction(async (transaction)=>{
|
|
63
126
|
const fresh = await transaction.get(campaignDoc.ref);
|
|
64
127
|
if (fresh.get('status') !== 'scheduled') return false;
|
|
@@ -88,7 +151,7 @@ import { CampaignSendDeferredError, CampaignSendError, performCampaignSend } fro
|
|
|
88
151
|
try {
|
|
89
152
|
var _data_subject, _data_body, _data_audience, _data_segmentId, _data_listId, _data_topicId, _data_experimentId, _data_templateScreenId, _data_plainText, _data_fromName, _data_replyTo, _data_preheader, _data_emailCampaignId, _ref1, _data_scheduledBy;
|
|
90
153
|
const result = await performCampaignSend(_extends({
|
|
91
|
-
hostId:
|
|
154
|
+
hostId: site.hostId
|
|
92
155
|
}, resumingBatch ? {
|
|
93
156
|
continuation: true
|
|
94
157
|
} : {}, {
|
|
@@ -183,10 +246,17 @@ import { CampaignSendDeferredError, CampaignSendError, performCampaignSend } fro
|
|
|
183
246
|
});
|
|
184
247
|
}
|
|
185
248
|
}
|
|
186
|
-
|
|
249
|
+
if (awaitingMigration) {
|
|
250
|
+
console.warn(`[campaigns] ${awaitingMigration} due send(s) are still at a site path and wait for the migration`);
|
|
251
|
+
}
|
|
252
|
+
return res.status(200).json(_extends({
|
|
187
253
|
processed: results.length,
|
|
188
254
|
results
|
|
189
|
-
}
|
|
255
|
+
}, awaitingMigration ? {
|
|
256
|
+
awaitingMigration
|
|
257
|
+
} : {}, unsited ? {
|
|
258
|
+
unsited
|
|
259
|
+
} : {}));
|
|
190
260
|
} catch (error) {
|
|
191
261
|
console.error(error);
|
|
192
262
|
return res.status(500).json({
|