@aglyn/plugins-marketing 1.0.0-beta.220 → 1.0.0-beta.222

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +4 -1
  2. package/package.json +15 -15
  3. package/src/lib/components/campaign-conversions-card.js +53 -64
  4. package/src/lib/components/campaign-conversions-card.js.map +1 -1
  5. package/src/lib/components/campaign-detail-card.js +2 -1
  6. package/src/lib/components/campaign-detail-card.js.map +1 -1
  7. package/src/lib/components/campaign-edit-drawer.js +1 -1
  8. package/src/lib/components/campaign-edit-drawer.js.map +1 -1
  9. package/src/lib/components/campaign-queries.js +1 -1
  10. package/src/lib/components/campaign-queries.js.map +1 -1
  11. package/src/lib/components/campaign-reach-sections.js +1 -1
  12. package/src/lib/components/campaign-reach-sections.js.map +1 -1
  13. package/src/lib/components/campaign-report-card.js +5 -4
  14. package/src/lib/components/campaign-report-card.js.map +1 -1
  15. package/src/lib/components/campaigns-card.js +1 -1
  16. package/src/lib/components/campaigns-card.js.map +1 -1
  17. package/src/lib/components/email-compose-card.js +1 -1
  18. package/src/lib/components/email-compose-card.js.map +1 -1
  19. package/src/lib/components/email-detail.js +5 -4
  20. package/src/lib/components/email-detail.js.map +1 -1
  21. package/src/lib/components/email-template-report-card.d.ts +53 -0
  22. package/src/lib/components/email-template-report-card.js +469 -0
  23. package/src/lib/components/email-template-report-card.js.map +1 -0
  24. package/src/lib/components/emails-list-card.js +2 -2
  25. package/src/lib/components/emails-list-card.js.map +1 -1
  26. package/src/lib/components/host-experiments-card.component.js +3 -2
  27. package/src/lib/components/host-experiments-card.component.js.map +1 -1
  28. package/src/lib/components/site-runtime.js +3 -1
  29. package/src/lib/components/site-runtime.js.map +1 -1
  30. package/src/lib/declarations.server.d.ts +9 -0
  31. package/src/lib/declarations.server.js +62 -0
  32. package/src/lib/declarations.server.js.map +1 -1
  33. package/src/lib/model/campaign-container.d.ts +503 -0
  34. package/src/lib/model/campaign-container.js +498 -0
  35. package/src/lib/model/campaign-container.js.map +1 -0
  36. package/src/lib/model/campaign-conversions.d.ts +8 -1
  37. package/src/lib/model/campaign-conversions.js +11 -0
  38. package/src/lib/model/campaign-conversions.js.map +1 -1
  39. package/src/lib/model/campaign-report.d.ts +158 -0
  40. package/src/lib/model/campaign-report.js +268 -0
  41. package/src/lib/model/campaign-report.js.map +1 -0
  42. package/src/lib/model/campaign-revenue.d.ts +3 -3
  43. package/src/lib/model/campaign-revenue.js +3 -3
  44. package/src/lib/model/campaign-revenue.js.map +1 -1
  45. package/src/lib/model/campaign-send-time.js +2 -2
  46. package/src/lib/model/campaign-send-time.js.map +1 -1
  47. package/src/lib/model/compile-client-automations.d.ts +2 -2
  48. package/src/lib/model/compile-client-automations.js +3 -3
  49. package/src/lib/model/compile-client-automations.js.map +1 -1
  50. package/src/lib/model/email-record.d.ts +175 -0
  51. package/src/lib/model/email-record.js +206 -0
  52. package/src/lib/model/email-record.js.map +1 -0
  53. package/src/lib/model/site-contract.d.ts +2 -2
  54. package/src/lib/model/site-contract.js.map +1 -1
  55. package/src/lib/model/template-report.d.ts +158 -0
  56. package/src/lib/model/template-report.js +249 -0
  57. package/src/lib/model/template-report.js.map +1 -0
  58. package/src/lib/plugin.js +16 -0
  59. package/src/lib/plugin.js.map +1 -1
  60. package/src/lib/preview-props.js.map +1 -1
  61. package/src/lib/server/campaign-attribution-store.d.ts +55 -0
  62. package/src/lib/server/campaign-attribution-store.js +98 -0
  63. package/src/lib/server/campaign-attribution-store.js.map +1 -0
  64. package/src/lib/server/campaign-conversion-attribution.d.ts +283 -0
  65. package/src/lib/server/campaign-conversion-attribution.js +447 -0
  66. package/src/lib/server/campaign-conversion-attribution.js.map +1 -0
  67. package/src/lib/server/campaign-manage.js +1 -1
  68. package/src/lib/server/campaign-manage.js.map +1 -1
  69. package/src/lib/server/campaign-org-refs.js +1 -1
  70. package/src/lib/server/campaign-org-refs.js.map +1 -1
  71. package/src/lib/server/campaign-recipients.js +7 -7
  72. package/src/lib/server/campaign-recipients.js.map +1 -1
  73. package/src/lib/server/campaign-send.js +25 -19
  74. package/src/lib/server/campaign-send.js.map +1 -1
  75. package/src/lib/server/conversion-creditor.d.ts +18 -0
  76. package/src/lib/server/conversion-creditor.js +131 -0
  77. package/src/lib/server/conversion-creditor.js.map +1 -0
  78. package/src/lib/server/email-campaign-touch.d.ts +81 -0
  79. package/src/lib/server/email-campaign-touch.js +227 -0
  80. package/src/lib/server/email-campaign-touch.js.map +1 -0
  81. package/src/lib/server/email-events.js +8 -6
  82. package/src/lib/server/email-events.js.map +1 -1
  83. package/src/lib/server/email-revenue-attribution.d.ts +186 -0
  84. package/src/lib/server/email-revenue-attribution.js +322 -0
  85. package/src/lib/server/email-revenue-attribution.js.map +1 -0
  86. package/src/lib/server/email-send-record-index.d.ts +34 -0
  87. package/src/lib/server/email-send-record-index.js +90 -0
  88. package/src/lib/server/email-send-record-index.js.map +1 -0
  89. package/src/lib/server/get-client-automations.js.map +1 -1
  90. package/src/lib/server/marketing-figures.js +3 -3
  91. package/src/lib/server/marketing-figures.js.map +1 -1
  92. package/src/lib/server/send-tally.d.ts +32 -0
  93. package/src/lib/server/send-tally.js +54 -0
  94. package/src/lib/server/send-tally.js.map +1 -0
  95. package/src/lib/testing/stand-in-person-records.d.ts +35 -0
  96. package/src/lib/testing/stand-in-person-records.js +67 -0
  97. package/src/lib/testing/stand-in-person-records.js.map +1 -0
  98. package/src/lib/testing/stand-in-record-counts.d.ts +26 -0
  99. package/src/lib/testing/stand-in-record-counts.js +70 -0
  100. package/src/lib/testing/stand-in-record-counts.js.map +1 -0
  101. package/src/lib/transfer/campaigns-package.d.ts +72 -0
  102. package/src/lib/transfer/campaigns-package.js +145 -0
  103. package/src/lib/transfer/campaigns-package.js.map +1 -0
  104. package/src/lib/transfer/campaigns-package.server.d.ts +33 -0
  105. package/src/lib/transfer/campaigns-package.server.js +305 -0
  106. package/src/lib/transfer/campaigns-package.server.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/model/campaign-conversions.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 * The window and the model name come from `@aglyn/shared-util-email`, for the\n * reason `campaign-revenue.ts` gives: the writer is in `tenant-data-admin`,\n * which may not import a feature plugin, and a rule defined on both sides of\n * the join drifts into a figure credited under one and printed under another.\n */\nimport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n} from '@aglyn/shared-util-email'\nimport type { CampaignCaveat } from '@aglyn/shared-ui-email-campaigns/model/campaign-report'\n\n/**\n * WHAT A CAMPAIGN CAUSED — the read half of the identify-moment join.\n *\n * `campaign-revenue.ts` answers what a campaign EARNED, from orders that name\n * their buyer. This answers what it CAUSED among people who were anonymous\n * until the moment they became somebody: they arrive from a campaign link,\n * browse, and only become identifiable when they submit a form, sign up, book\n * or check out. Same window, same last-click rule, same `model`/`windowDays`\n * stamped on every record, so the two figures on one screen are two readings\n * of one rule rather than two rules that happen to agree.\n *\n * ## THE KINDS ARE NEVER SUMMED, and this module makes that structural\n *\n * One form submission by a new person writes a submission record, a contact\n * and a lead — three true statements about one visitor action. Adding them\n * would treble every campaign's conversions, and the reader would have no way\n * to see it had happened, because the sum looks like a bigger version of a\n * real number.\n *\n * So {@link CampaignConversionsReport} carries no total, no `all`, no\n * `conversions` scalar, and there is no function here that reduces the kinds.\n * A screen that wanted one would have to write the addition itself. The\n * report also raises {@link CampaignCaveat} `conversions-kinds-overlap` so\n * the reader is told WHY the four figures stand apart, rather than being left\n * to assume the product forgot to add them up.\n *\n * ## THE WEB CHANNEL HAS NO ROLLUP, and cannot be given one\n *\n * A conversion is credited to one of two touches. An EMAIL touch names a\n * campaign document — a real entity with a real id — so its conversions roll\n * up under it beside the revenue the same join credits it with. A WEB touch\n * is a `utm_` label a marketer typed into a URL: no document, no id, and no\n * bound on how many distinct values exist, because anybody who can vary a\n * query string can mint another one.\n *\n * A rollup keyed on that label is a map a stranger can grow, which is the\n * same unbounded key space the analytics collector caps its per-day label map\n * against. So the writer increments the rollup for the email channel ONLY,\n * this reader states that where the figure is drawn, and web-channel records\n * are read as records — see {@link campaignConversionsCoverage}.\n *\n * ## A CONVERSION WITH NO TOUCH IS NOT IN HERE AT ALL\n *\n * Direct traffic writes no record. There is deliberately no\n * `utm_source=direct` placeholder, no referrer inference and no \"most recent\n * campaign on this site\" fallback: a conversion nobody can be credited with\n * is a conversion nobody is credited with.\n *\n * That makes the absence of a record load-bearing, and it makes a screen\n * showing only attributed conversions a lie by omission — it renders \"we\n * credited three of these\" as \"three of these happened\".\n * {@link campaignConversionsCoverage} exists so the unattributed count is a\n * figure on the page rather than an inference nobody makes.\n */\n\n/*\n * The constants are NOT re-exported here, though `campaign-revenue.ts`\n * re-exports the same two. Both modules sit behind one barrel, and a name\n * exported twice through it is a name a bundler has to disambiguate. Every\n * screen reads the rule off `model`/`windowDays` on the report anyway, which\n * is the stored value rather than today's constant — a campaign credited\n * under an older window has to print the window it was credited under.\n */\n\n/**\n * Which identify moment a record credits.\n *\n * An array first, because the ORDER is the reading order on every screen and\n * a second list of these is a second chance to leave one out. The union is\n * derived from it rather than written twice.\n */\nexport const CAMPAIGN_CONVERSION_KINDS = [\n 'form',\n 'lead',\n 'contact',\n 'booking',\n] as const\n\n/** One identify moment. Mirrors the writer's `CampaignConversionKind`. */\nexport type CampaignConversionKind = (typeof CAMPAIGN_CONVERSION_KINDS)[number]\n\n/**\n * Which channel the credited touch arrived through.\n *\n * `sequence` (AGL-3254) is a one-to-one email a rep's sequence sent: the\n * touch names the CAMPAIGN the sequence is in, like an email touch names\n * the campaign whose mail was clicked, plus the sequence and the enrollment\n * it came through, so a record can say which rep's outreach it credits.\n */\nexport type CampaignTouchChannel = 'email' | 'web' | 'sequence'\n\n/**\n * What a reader calls one kind, and what the count means.\n *\n * The note is the half that stops the addition. Each one names a DIFFERENT\n * population of the same visitors, and saying so under every figure is what\n * makes four numbers standing apart read as deliberate rather than as a\n * missing total.\n */\nexport interface CampaignConversionKindCopy {\n label: string\n note: string\n}\n\nexport const CAMPAIGN_CONVERSION_KIND_COPY: Readonly<\n Record<CampaignConversionKind, CampaignConversionKindCopy>\n> = {\n form: {\n label: 'Form submissions',\n note: 'submissions credited to this campaign',\n },\n lead: { label: 'Leads', note: 'new leads credited to this campaign' },\n contact: {\n label: 'Contacts',\n note: 'new contacts credited to this campaign',\n },\n booking: { label: 'Bookings', note: 'bookings credited to this campaign' },\n}\n\n/**\n * The stored shape of `campaigns/{campaignId}/reports/conversions`.\n *\n * Its own document beside `reports/revenue`, for the reason that one is: the\n * campaign document is read by the history list, the glance widget and the\n * send path, and a map that grows with what the campaign caused would enlarge\n * every one of those reads.\n */\nexport interface CampaignConversionsRollup {\n byKind?: Partial<Record<CampaignConversionKind, number>>\n /** The model these conversions were credited under. */\n model?: string\n /** The window, in days, they were credited inside. */\n windowDays?: number\n}\n\n/**\n * The stored shape of `hosts/{hostId}/campaignAttributions/{kind}:{refId}`.\n *\n * Read-side only, and every field optional: this is a document somebody\n * else's writer produced, and a reader that assumed a field was present would\n * throw on the first record written by an older version of it.\n */\nexport interface CampaignConversionRecord {\n kind?: CampaignConversionKind\n /** The submission, lead, contact or booking this credits. */\n refId?: string\n channel?: CampaignTouchChannel\n /**\n * The campaign document, when the touch was a click on our own mail — or,\n * for a `sequence` touch, the campaign container the sequence is in.\n */\n campaignId?: string\n /** The sequence, when the touch was a sequence email (AGL-3254). */\n sequenceId?: string\n /** The enrollment the sequence email went out under (AGL-3254). */\n enrollmentId?: string\n /** `utm_source`, when the touch was a link on the web. */\n source?: string\n /** `utm_medium`, when the touch was a link on the web. */\n medium?: string\n /** `utm_campaign`, when the touch was a link on the web. */\n campaign?: string\n /** When the visitor followed the campaign link, epoch ms. */\n touchedAtMs?: number\n /** When the visitor became identifiable, epoch ms. */\n convertedAtMs?: number\n model?: string\n windowDays?: number\n}\n\n/**\n * The document id for one conversion — `{kind}:{refId}`.\n *\n * The reader's half of the writer's `campaignConversionId`. It is restated\n * here rather than imported because the writer lives in `tenant-data-admin`,\n * which a UI library may not import, and it is one line whose shape is\n * asserted in this module's spec.\n *\n * Answers `null` for an unusable pair rather than building `form:undefined`,\n * which would be a valid document path pointing at a record that can never\n * exist — a keyed read that silently reports \"not attributed\" for every\n * record on the screen.\n */\nexport function campaignConversionId(\n kind: string | null | undefined,\n refId: string | null | undefined,\n): string | null {\n const k = String(kind ?? '')\n const ref = String(refId ?? '')\n if (!k || !ref) return null\n if (!(CAMPAIGN_CONVERSION_KINDS as readonly string[]).includes(k)) return null\n // A slash would leave the collection; the id scheme already spends the\n // colon, and a ref carrying one would make the pair ambiguous.\n if (ref.includes('/') || ref.includes(':')) return null\n return `${k}:${ref}`\n}\n\n/** A stored count as a non-negative integer. */\nfunction count(raw: unknown): number {\n const value = Math.floor(Number(raw ?? 0))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/** One kind's figure on screen. Independent of every other kind's. */\nexport interface CampaignConversionKindReport {\n kind: CampaignConversionKind\n label: string\n /**\n * Conversions of this kind, or `null` when the rollup holds no entry.\n *\n * `null` rather than 0 for {@link CampaignConversionsReport.recorded}'s\n * reason, applied per kind: a site with no booking form has never written a\n * booking conversion, and rendering that as a measured zero invites the\n * reader to conclude the campaign failed at something it never attempted.\n */\n value: number | null\n note: string\n}\n\n/** Everything the conversions section renders. */\nexport interface CampaignConversionsReport {\n /**\n * One entry per kind, always all four and always in\n * {@link CAMPAIGN_CONVERSION_KINDS} order.\n *\n * There is deliberately NO total beside this array, and no field anywhere\n * on this report that holds one. See the module docblock.\n */\n kinds: CampaignConversionKindReport[]\n /**\n * Whether the rollup document exists at all.\n *\n * `false` is NOT \"this campaign caused nothing\" — it is also every campaign\n * sent before the join existed, and every campaign whose conversions all\n * arrived through the web channel, which writes no rollup. The screen\n * renders the difference rather than printing a zero for all three.\n */\n recorded: boolean\n /** At least one kind holds a figure. */\n any: boolean\n /** The model these figures were credited under, as stored. */\n model: string\n /** The window they were credited inside, as stored. */\n windowDays: number\n caveats: CampaignCaveat[]\n}\n\n/**\n * Turns the stored rollup into the conversions section.\n *\n * Takes the rollup and nothing else. Unlike the revenue report there is no\n * denominator to hand in: a conversion RATE over delivered messages would be\n * the same defect the revenue section refuses for orders — one visitor can\n * submit two forms, so the quotient passes 100% without anything being wrong\n * — and counting distinct people would need a document per person per\n * campaign, the per-recipient read this whole surface exists to refuse.\n */\nexport function campaignConversionsReport(options: {\n rollup: CampaignConversionsRollup | undefined\n}): CampaignConversionsReport {\n const { rollup } = options\n const stored = rollup?.byKind ?? {}\n const caveats: CampaignCaveat[] = []\n\n const kinds: CampaignConversionKindReport[] = CAMPAIGN_CONVERSION_KINDS.map(\n (kind) => {\n const raw = stored[kind]\n const copy = CAMPAIGN_CONVERSION_KIND_COPY[kind]\n return {\n kind,\n label: copy.label,\n // `undefined` means the rollup has no entry for this kind, which is\n // not a measured zero. A stored 0 is impossible — the writer only\n // ever increments — but it is read as unrecorded for the same reason.\n value: raw === undefined || count(raw) === 0 ? null : count(raw),\n note: copy.note,\n }\n },\n )\n\n const any = kinds.some((entry) => entry.value !== null)\n\n if (any) {\n caveats.push({\n id: 'conversions-kinds-overlap',\n message:\n 'These figures count different things about the same visits and are ' +\n 'deliberately not added together. One person filling in one form can ' +\n 'appear as a submission, a contact and a lead, so a total would ' +\n 'count that visit three times.',\n })\n caveats.push({\n id: 'conversions-web-not-rolled-up',\n message:\n 'Campaign emails only. A conversion credited to a link tagged with ' +\n 'utm_ parameters is recorded against that label rather than against ' +\n 'a campaign, so it is not in the figures above — those conversions ' +\n 'are listed under Conversions in the marketing console.',\n })\n }\n\n return {\n kinds,\n recorded: rollup !== undefined,\n any,\n model: String(rollup?.model ?? EMAIL_ATTRIBUTION_MODEL),\n windowDays: count(rollup?.windowDays) || EMAIL_ATTRIBUTION_WINDOW_DAYS,\n caveats,\n }\n}\n\n/**\n * How much of one kind was credited to anything at all.\n *\n * ## Why this figure has to exist\n *\n * The join writes nothing for a conversion it cannot credit, so a list of\n * attribution records is a list of the SUCCESSES. Rendering only that turns\n * \"we credited four of these\" into \"four of these happened\", and the reader\n * draws a conclusion about their campaigns from a number that is mostly a\n * fact about how many visitors arrived without a campaign link.\n *\n * So the screen shows both halves and this computes the second. `attributed`\n * is counted over the attribution records; `total` over the records the\n * conversions themselves live in.\n *\n * ## Why the difference is a CEILING and says so\n *\n * The two counts come from different collections with different histories,\n * and the gap between them holds three things that are not the same:\n *\n * - conversions by visitors who arrived directly, which is what the figure\n * is meant to describe;\n * - conversions from before the join existed, which were never eligible; and\n * - for contacts, conversions on the org's OTHER sites, because contacts are\n * shared across an org while attributions are per host.\n *\n * None of those can be separated from the others without a field nobody\n * writes, so `unattributed` is reported as an upper bound and\n * {@link CampaignConversionsCoverage.exact} is `false` whenever the reasons\n * apply. A figure presented as exact when it is not is the failure this\n * whole surface is built to avoid.\n */\nexport interface CampaignConversionsCoverage {\n kind: CampaignConversionKind\n /** Conversions of this kind credited to some campaign or label. */\n attributed: number\n /** Conversions of this kind that exist, credited or not. */\n total: number\n /** `total - attributed`, clamped at zero. An upper bound, not a count. */\n unattributed: number\n /**\n * Whether `unattributed` may be read as \"arrived directly\".\n *\n * Always `false` today — the three reasons in the docblock all apply to\n * every host — and kept as a field rather than hardcoded in the copy so a\n * screen asks the model rather than restating its conclusion.\n */\n exact: boolean\n caveats: CampaignCaveat[]\n}\n\n/**\n * The attributed/unattributed split for one kind.\n *\n * `total` is `null` when it could not be counted — the aggregation failed, or\n * the collection is not readable from this surface — and the split is then\n * withheld entirely rather than defaulting `total` to `attributed`, which\n * would render every conversion as attributed and is the single most\n * flattering wrong answer available here.\n */\nexport function campaignConversionsCoverage(options: {\n kind: CampaignConversionKind\n attributed: number | null | undefined\n total: number | null | undefined\n /** The kind's records live outside this host, so `total` over-counts. */\n crossHostTotal?: boolean\n}): CampaignConversionsCoverage | null {\n const { kind, crossHostTotal } = options\n if (options.total == null || options.attributed == null) return null\n const attributed = count(options.attributed)\n const total = count(options.total)\n const caveats: CampaignCaveat[] = []\n\n /*\n * CLAMPED, and only here at the point of display. The two counts are taken\n * from two collections a moment apart, so a conversion recorded between\n * them makes `attributed` briefly exceed `total`; a negative count of\n * things that did not happen is not a sentence anybody can act on.\n */\n const unattributed = Math.max(0, total - attributed)\n\n caveats.push({\n id: 'conversions-unattributed-is-a-ceiling',\n message:\n `${unattributed.toLocaleString()} of these are not credited to any ` +\n 'campaign. Most arrived without following a campaign link and are ' +\n 'recorded as direct — nothing is guessed from a referrer, and no ' +\n 'campaign is credited for being the most recent one to run. The rest ' +\n 'are records from before campaign attribution was recorded at all, so ' +\n 'read this as an upper bound rather than a count of direct arrivals.',\n })\n if (crossHostTotal) {\n caveats.push({\n id: 'conversions-total-crosses-hosts',\n message:\n 'Contacts are shared across every site in this organization, while ' +\n 'attributions belong to one site. The uncredited figure therefore ' +\n 'includes contacts that were created on another site and could ' +\n 'never have been credited here.',\n })\n }\n\n return {\n kind,\n attributed,\n total,\n unattributed,\n // Never true while the reasons above stand. The field exists so a screen\n // reads the model rather than restating its conclusion in JSX.\n exact: false,\n caveats,\n }\n}\n\n/**\n * How a record names the thing it was credited to.\n *\n * The email channel names a campaign document, so the screen can link to it,\n * and so does a sequence touch: the campaign the sequence is in is a\n * container with a page. The web channel names a label the marketer typed,\n * which is text and never a link — there is nothing at the other end of it.\n *\n * The `utm_` triple is joined in the order a marketer set it, with the parts\n * that are absent left out rather than filled with a placeholder.\n * `google / cpc` and `google / cpc / (none)` describe the same link, and only\n * one of them invites the reader to look for a campaign called \"(none)\".\n */\nexport function campaignTouchLabel(\n record: CampaignConversionRecord | null | undefined,\n): string {\n if (!record) return ''\n if (record.channel === 'email' || record.channel === 'sequence') {\n return String(record.campaignId ?? '')\n }\n const parts = [record.source, record.medium, record.campaign]\n .map((part) => String(part ?? '').trim())\n .filter(Boolean)\n return parts.join(' / ')\n}\n"],"names":["EMAIL_ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","CAMPAIGN_CONVERSION_KINDS","CAMPAIGN_CONVERSION_KIND_COPY","form","label","note","lead","contact","booking","campaignConversionId","kind","refId","k","String","ref","includes","count","raw","value","Math","floor","Number","isFinite","campaignConversionsReport","options","rollup","stored","byKind","caveats","kinds","map","copy","undefined","any","some","entry","push","id","message","recorded","model","windowDays","campaignConversionsCoverage","crossHostTotal","total","attributed","unattributed","max","toLocaleString","exact","campaignTouchLabel","record","channel","campaignId","parts","source","medium","campaign","part","trim","filter","Boolean","join"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GACD,SACEA,uBAAuB,EACvBC,6BAA6B,QACxB,2BAA0B;AAGjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GAED;;;;;;;CAOC,GAED;;;;;;CAMC,GACD,OAAO,MAAMC,4BAA4B;IACvC;IACA;IACA;IACA;CACD,CAAS;AA4BV,OAAO,MAAMC,gCAET;IACFC,MAAM;QACJC,OAAO;QACPC,MAAM;IACR;IACAC,MAAM;QAAEF,OAAO;QAASC,MAAM;IAAsC;IACpEE,SAAS;QACPH,OAAO;QACPC,MAAM;IACR;IACAG,SAAS;QAAEJ,OAAO;QAAYC,MAAM;IAAqC;AAC3E,EAAC;AAqDD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASI,qBACdC,IAA+B,EAC/BC,KAAgC;IAEhC,MAAMC,IAAIC,OAAOH,eAAAA,OAAQ;IACzB,MAAMI,MAAMD,OAAOF,gBAA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I,IACrCC,MAAM,CAACC;IACV,OAAOP,MAAMQ,IAAI,CAAC;AACpB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/model/campaign-conversions.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 * The window and the model name come from `@aglyn/shared-util-email`, for the\n * reason `campaign-revenue.ts` gives: the writer is in `tenant-data-admin`,\n * which may not import a feature plugin, and a rule defined on both sides of\n * the join drifts into a figure credited under one and printed under another.\n */\nimport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n} from '@aglyn/shared-util-email'\nimport type { CampaignCaveat } from './campaign-report'\n\n/**\n * WHAT A CAMPAIGN CAUSED — the read half of the identify-moment join.\n *\n * `campaign-revenue.ts` answers what a campaign EARNED, from orders that name\n * their buyer. This answers what it CAUSED among people who were anonymous\n * until the moment they became somebody: they arrive from a campaign link,\n * browse, and only become identifiable when they submit a form, sign up, book\n * or check out. Same window, same last-click rule, same `model`/`windowDays`\n * stamped on every record, so the two figures on one screen are two readings\n * of one rule rather than two rules that happen to agree.\n *\n * ## THE KINDS ARE NEVER SUMMED, and this module makes that structural\n *\n * One form submission by a new person writes a submission record, a contact\n * and a lead — three true statements about one visitor action. Adding them\n * would treble every campaign's conversions, and the reader would have no way\n * to see it had happened, because the sum looks like a bigger version of a\n * real number.\n *\n * So {@link CampaignConversionsReport} carries no total, no `all`, no\n * `conversions` scalar, and there is no function here that reduces the kinds.\n * A screen that wanted one would have to write the addition itself. The\n * report also raises {@link CampaignCaveat} `conversions-kinds-overlap` so\n * the reader is told WHY the four figures stand apart, rather than being left\n * to assume the product forgot to add them up.\n *\n * ## THE WEB CHANNEL HAS NO ROLLUP, and cannot be given one\n *\n * A conversion is credited to one of two touches. An EMAIL touch names a\n * campaign document — a real entity with a real id — so its conversions roll\n * up under it beside the revenue the same join credits it with. A WEB touch\n * is a `utm_` label a marketer typed into a URL: no document, no id, and no\n * bound on how many distinct values exist, because anybody who can vary a\n * query string can mint another one.\n *\n * A rollup keyed on that label is a map a stranger can grow, which is the\n * same unbounded key space the analytics collector caps its per-day label map\n * against. So the writer increments the rollup for the email channel ONLY,\n * this reader states that where the figure is drawn, and web-channel records\n * are read as records — see {@link campaignConversionsCoverage}.\n *\n * ## A CONVERSION WITH NO TOUCH IS NOT IN HERE AT ALL\n *\n * Direct traffic writes no record. There is deliberately no\n * `utm_source=direct` placeholder, no referrer inference and no \"most recent\n * campaign on this site\" fallback: a conversion nobody can be credited with\n * is a conversion nobody is credited with.\n *\n * That makes the absence of a record load-bearing, and it makes a screen\n * showing only attributed conversions a lie by omission — it renders \"we\n * credited three of these\" as \"three of these happened\".\n * {@link campaignConversionsCoverage} exists so the unattributed count is a\n * figure on the page rather than an inference nobody makes.\n */\n\n/*\n * The constants are NOT re-exported here, though `campaign-revenue.ts`\n * re-exports the same two. Both modules sit behind one barrel, and a name\n * exported twice through it is a name a bundler has to disambiguate. Every\n * screen reads the rule off `model`/`windowDays` on the report anyway, which\n * is the stored value rather than today's constant — a campaign credited\n * under an older window has to print the window it was credited under.\n */\n\n/**\n * Which identify moment a record credits.\n *\n * An array first, because the ORDER is the reading order on every screen and\n * a second list of these is a second chance to leave one out. The union is\n * derived from it rather than written twice.\n */\nexport const CAMPAIGN_CONVERSION_KINDS = [\n 'form',\n 'lead',\n 'contact',\n 'booking',\n] as const\n\n/** One identify moment. Mirrors the writer's `CampaignConversionKind`. */\nexport type CampaignConversionKind = (typeof CAMPAIGN_CONVERSION_KINDS)[number]\n\n/**\n * Which channel the credited touch arrived through.\n *\n * `sequence` (AGL-3254) is a one-to-one email a rep's sequence sent: the\n * touch names the CAMPAIGN the sequence is in, like an email touch names\n * the campaign whose mail was clicked, plus the sequence and the enrollment\n * it came through, so a record can say which rep's outreach it credits.\n */\nexport type CampaignTouchChannel = 'email' | 'web' | 'sequence'\n\n/**\n * The record each conversion kind credits, as its owner publishes the kind\n * (`plugin-record-counts`, `plugin-record-lists`): a credited form names the\n * SUBMISSION it credits, the rest the record of their own name. The owners\n * count and read those records; this plugin only names the kind.\n */\nexport const CAMPAIGN_CONVERSION_RECORD_KINDS: Readonly<\n Record<CampaignConversionKind, string>\n> = {\n form: 'formSubmission',\n lead: 'lead',\n contact: 'contact',\n booking: 'booking',\n}\n\n/**\n * What a reader calls one kind, and what the count means.\n *\n * The note is the half that stops the addition. Each one names a DIFFERENT\n * population of the same visitors, and saying so under every figure is what\n * makes four numbers standing apart read as deliberate rather than as a\n * missing total.\n */\nexport interface CampaignConversionKindCopy {\n label: string\n note: string\n}\n\nexport const CAMPAIGN_CONVERSION_KIND_COPY: Readonly<\n Record<CampaignConversionKind, CampaignConversionKindCopy>\n> = {\n form: {\n label: 'Form submissions',\n note: 'submissions credited to this campaign',\n },\n lead: { label: 'Leads', note: 'new leads credited to this campaign' },\n contact: {\n label: 'Contacts',\n note: 'new contacts credited to this campaign',\n },\n booking: { label: 'Bookings', note: 'bookings credited to this campaign' },\n}\n\n/**\n * The stored shape of `campaigns/{campaignId}/reports/conversions`.\n *\n * Its own document beside `reports/revenue`, for the reason that one is: the\n * campaign document is read by the history list, the glance widget and the\n * send path, and a map that grows with what the campaign caused would enlarge\n * every one of those reads.\n */\nexport interface CampaignConversionsRollup {\n byKind?: Partial<Record<CampaignConversionKind, number>>\n /** The model these conversions were credited under. */\n model?: string\n /** The window, in days, they were credited inside. */\n windowDays?: number\n}\n\n/**\n * The stored shape of `hosts/{hostId}/campaignAttributions/{kind}:{refId}`.\n *\n * Read-side only, and every field optional: this is a document somebody\n * else's writer produced, and a reader that assumed a field was present would\n * throw on the first record written by an older version of it.\n */\nexport interface CampaignConversionRecord {\n kind?: CampaignConversionKind\n /** The submission, lead, contact or booking this credits. */\n refId?: string\n channel?: CampaignTouchChannel\n /**\n * The campaign document, when the touch was a click on our own mail — or,\n * for a `sequence` touch, the campaign container the sequence is in.\n */\n campaignId?: string\n /** The sequence, when the touch was a sequence email (AGL-3254). */\n sequenceId?: string\n /** The enrollment the sequence email went out under (AGL-3254). */\n enrollmentId?: string\n /** `utm_source`, when the touch was a link on the web. */\n source?: string\n /** `utm_medium`, when the touch was a link on the web. */\n medium?: string\n /** `utm_campaign`, when the touch was a link on the web. */\n campaign?: string\n /** When the visitor followed the campaign link, epoch ms. */\n touchedAtMs?: number\n /** When the visitor became identifiable, epoch ms. */\n convertedAtMs?: number\n model?: string\n windowDays?: number\n}\n\n/**\n * The document id for one conversion — `{kind}:{refId}`.\n *\n * The reader's half of the writer's `campaignConversionId`. It is restated\n * here rather than imported because the writer lives in `tenant-data-admin`,\n * which a UI library may not import, and it is one line whose shape is\n * asserted in this module's spec.\n *\n * Answers `null` for an unusable pair rather than building `form:undefined`,\n * which would be a valid document path pointing at a record that can never\n * exist — a keyed read that silently reports \"not attributed\" for every\n * record on the screen.\n */\nexport function campaignConversionId(\n kind: string | null | undefined,\n refId: string | null | undefined,\n): string | null {\n const k = String(kind ?? '')\n const ref = String(refId ?? '')\n if (!k || !ref) return null\n if (!(CAMPAIGN_CONVERSION_KINDS as readonly string[]).includes(k)) return null\n // A slash would leave the collection; the id scheme already spends the\n // colon, and a ref carrying one would make the pair ambiguous.\n if (ref.includes('/') || ref.includes(':')) return null\n return `${k}:${ref}`\n}\n\n/** A stored count as a non-negative integer. */\nfunction count(raw: unknown): number {\n const value = Math.floor(Number(raw ?? 0))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/** One kind's figure on screen. Independent of every other kind's. */\nexport interface CampaignConversionKindReport {\n kind: CampaignConversionKind\n label: string\n /**\n * Conversions of this kind, or `null` when the rollup holds no entry.\n *\n * `null` rather than 0 for {@link CampaignConversionsReport.recorded}'s\n * reason, applied per kind: a site with no booking form has never written a\n * booking conversion, and rendering that as a measured zero invites the\n * reader to conclude the campaign failed at something it never attempted.\n */\n value: number | null\n note: string\n}\n\n/** Everything the conversions section renders. */\nexport interface CampaignConversionsReport {\n /**\n * One entry per kind, always all four and always in\n * {@link CAMPAIGN_CONVERSION_KINDS} order.\n *\n * There is deliberately NO total beside this array, and no field anywhere\n * on this report that holds one. See the module docblock.\n */\n kinds: CampaignConversionKindReport[]\n /**\n * Whether the rollup document exists at all.\n *\n * `false` is NOT \"this campaign caused nothing\" — it is also every campaign\n * sent before the join existed, and every campaign whose conversions all\n * arrived through the web channel, which writes no rollup. The screen\n * renders the difference rather than printing a zero for all three.\n */\n recorded: boolean\n /** At least one kind holds a figure. */\n any: boolean\n /** The model these figures were credited under, as stored. */\n model: string\n /** The window they were credited inside, as stored. */\n windowDays: number\n caveats: CampaignCaveat[]\n}\n\n/**\n * Turns the stored rollup into the conversions section.\n *\n * Takes the rollup and nothing else. Unlike the revenue report there is no\n * denominator to hand in: a conversion RATE over delivered messages would be\n * the same defect the revenue section refuses for orders — one visitor can\n * submit two forms, so the quotient passes 100% without anything being wrong\n * — and counting distinct people would need a document per person per\n * campaign, the per-recipient read this whole surface exists to refuse.\n */\nexport function campaignConversionsReport(options: {\n rollup: CampaignConversionsRollup | undefined\n}): CampaignConversionsReport {\n const { rollup } = options\n const stored = rollup?.byKind ?? {}\n const caveats: CampaignCaveat[] = []\n\n const kinds: CampaignConversionKindReport[] = CAMPAIGN_CONVERSION_KINDS.map(\n (kind) => {\n const raw = stored[kind]\n const copy = CAMPAIGN_CONVERSION_KIND_COPY[kind]\n return {\n kind,\n label: copy.label,\n // `undefined` means the rollup has no entry for this kind, which is\n // not a measured zero. A stored 0 is impossible — the writer only\n // ever increments — but it is read as unrecorded for the same reason.\n value: raw === undefined || count(raw) === 0 ? null : count(raw),\n note: copy.note,\n }\n },\n )\n\n const any = kinds.some((entry) => entry.value !== null)\n\n if (any) {\n caveats.push({\n id: 'conversions-kinds-overlap',\n message:\n 'These figures count different things about the same visits and are ' +\n 'deliberately not added together. One person filling in one form can ' +\n 'appear as a submission, a contact and a lead, so a total would ' +\n 'count that visit three times.',\n })\n caveats.push({\n id: 'conversions-web-not-rolled-up',\n message:\n 'Campaign emails only. A conversion credited to a link tagged with ' +\n 'utm_ parameters is recorded against that label rather than against ' +\n 'a campaign, so it is not in the figures above — those conversions ' +\n 'are listed under Conversions in the marketing console.',\n })\n }\n\n return {\n kinds,\n recorded: rollup !== undefined,\n any,\n model: String(rollup?.model ?? EMAIL_ATTRIBUTION_MODEL),\n windowDays: count(rollup?.windowDays) || EMAIL_ATTRIBUTION_WINDOW_DAYS,\n caveats,\n }\n}\n\n/**\n * How much of one kind was credited to anything at all.\n *\n * ## Why this figure has to exist\n *\n * The join writes nothing for a conversion it cannot credit, so a list of\n * attribution records is a list of the SUCCESSES. Rendering only that turns\n * \"we credited four of these\" into \"four of these happened\", and the reader\n * draws a conclusion about their campaigns from a number that is mostly a\n * fact about how many visitors arrived without a campaign link.\n *\n * So the screen shows both halves and this computes the second. `attributed`\n * is counted over the attribution records; `total` over the records the\n * conversions themselves live in.\n *\n * ## Why the difference is a CEILING and says so\n *\n * The two counts come from different collections with different histories,\n * and the gap between them holds three things that are not the same:\n *\n * - conversions by visitors who arrived directly, which is what the figure\n * is meant to describe;\n * - conversions from before the join existed, which were never eligible; and\n * - for contacts, conversions on the org's OTHER sites, because contacts are\n * shared across an org while attributions are per host.\n *\n * None of those can be separated from the others without a field nobody\n * writes, so `unattributed` is reported as an upper bound and\n * {@link CampaignConversionsCoverage.exact} is `false` whenever the reasons\n * apply. A figure presented as exact when it is not is the failure this\n * whole surface is built to avoid.\n */\nexport interface CampaignConversionsCoverage {\n kind: CampaignConversionKind\n /** Conversions of this kind credited to some campaign or label. */\n attributed: number\n /** Conversions of this kind that exist, credited or not. */\n total: number\n /** `total - attributed`, clamped at zero. An upper bound, not a count. */\n unattributed: number\n /**\n * Whether `unattributed` may be read as \"arrived directly\".\n *\n * Always `false` today — the three reasons in the docblock all apply to\n * every host — and kept as a field rather than hardcoded in the copy so a\n * screen asks the model rather than restating its conclusion.\n */\n exact: boolean\n caveats: CampaignCaveat[]\n}\n\n/**\n * The attributed/unattributed split for one kind.\n *\n * `total` is `null` when it could not be counted — the aggregation failed, or\n * the collection is not readable from this surface — and the split is then\n * withheld entirely rather than defaulting `total` to `attributed`, which\n * would render every conversion as attributed and is the single most\n * flattering wrong answer available here.\n */\nexport function campaignConversionsCoverage(options: {\n kind: CampaignConversionKind\n attributed: number | null | undefined\n total: number | null | undefined\n /** The kind's records live outside this host, so `total` over-counts. */\n crossHostTotal?: boolean\n}): CampaignConversionsCoverage | null {\n const { kind, crossHostTotal } = options\n if (options.total == null || options.attributed == null) return null\n const attributed = count(options.attributed)\n const total = count(options.total)\n const caveats: CampaignCaveat[] = []\n\n /*\n * CLAMPED, and only here at the point of display. The two counts are taken\n * from two collections a moment apart, so a conversion recorded between\n * them makes `attributed` briefly exceed `total`; a negative count of\n * things that did not happen is not a sentence anybody can act on.\n */\n const unattributed = Math.max(0, total - attributed)\n\n caveats.push({\n id: 'conversions-unattributed-is-a-ceiling',\n message:\n `${unattributed.toLocaleString()} of these are not credited to any ` +\n 'campaign. Most arrived without following a campaign link and are ' +\n 'recorded as direct — nothing is guessed from a referrer, and no ' +\n 'campaign is credited for being the most recent one to run. The rest ' +\n 'are records from before campaign attribution was recorded at all, so ' +\n 'read this as an upper bound rather than a count of direct arrivals.',\n })\n if (crossHostTotal) {\n caveats.push({\n id: 'conversions-total-crosses-hosts',\n message:\n 'Contacts are shared across every site in this organization, while ' +\n 'attributions belong to one site. The uncredited figure therefore ' +\n 'includes contacts that were created on another site and could ' +\n 'never have been credited here.',\n })\n }\n\n return {\n kind,\n attributed,\n total,\n unattributed,\n // Never true while the reasons above stand. The field exists so a screen\n // reads the model rather than restating its conclusion in JSX.\n exact: false,\n caveats,\n }\n}\n\n/**\n * How a record names the thing it was credited to.\n *\n * The email channel names a campaign document, so the screen can link to it,\n * and so does a sequence touch: the campaign the sequence is in is a\n * container with a page. The web channel names a label the marketer typed,\n * which is text and never a link — there is nothing at the other end of it.\n *\n * The `utm_` triple is joined in the order a marketer set it, with the parts\n * that are absent left out rather than filled with a placeholder.\n * `google / cpc` and `google / cpc / (none)` describe the same link, and only\n * one of them invites the reader to look for a campaign called \"(none)\".\n */\nexport function campaignTouchLabel(\n record: CampaignConversionRecord | null | undefined,\n): string {\n if (!record) return ''\n if (record.channel === 'email' || record.channel === 'sequence') {\n return String(record.campaignId ?? '')\n }\n const parts = [record.source, record.medium, record.campaign]\n .map((part) => String(part ?? '').trim())\n .filter(Boolean)\n return parts.join(' / ')\n}\n"],"names":["EMAIL_ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","CAMPAIGN_CONVERSION_KINDS","CAMPAIGN_CONVERSION_RECORD_KINDS","form","lead","contact","booking","CAMPAIGN_CONVERSION_KIND_COPY","label","note","campaignConversionId","kind","refId","k","String","ref","includes","count","raw","value","Math","floor","Number","isFinite","campaignConversionsReport","options","rollup","stored","byKind","caveats","kinds","map","copy","undefined","any","some","entry","push","id","message","recorded","model","windowDays","campaignConversionsCoverage","crossHostTotal","total","attributed","unattributed","max","toLocaleString","exact","campaignTouchLabel","record","channel","campaignId","parts","source","medium","campaign","part","trim","filter","Boolean","join"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GACD,SACEA,uBAAuB,EACvBC,6BAA6B,QACxB,2BAA0B;AAGjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GAED;;;;;;;CAOC,GAED;;;;;;CAMC,GACD,OAAO,MAAMC,4BAA4B;IACvC;IACA;IACA;IACA;CACD,CAAS;AAeV;;;;;CAKC,GACD,OAAO,MAAMC,mCAET;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AC/DG,OAAO;QACPrB;IACF;AACF;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASsB,mBACdC,MAAmD;IAEnD,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAIA,OAAOC,OAAO,KAAK,WAAWD,OAAOC,OAAO,KAAK,YAAY;YACjDD;QAAd,OAAOtC,QAAOsC,qBAAAA,OAAOE,UAAU,YAAjBF,qBAAqB;IACrC;IACA,MAAMG,QAAQ;QAACH,OAAOI,MAAM;QAAEJ,OAAOK,MAAM;QAAEL,OAAOM,QAAQ;KAAC,CAC1D3B,GAAG,CAAC,CAAC4B,OAAS7C,OAAO6C,eAAAA,OAAQ,IAAIC,IAAI,IACrCC,MAAM,CAACC;IACV,OAAOP,MAAMQ,IAAI,CAAC;AACpB"}
@@ -0,0 +1,158 @@
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
+ /**
18
+ * WHAT ONE CAMPAIGN SEND DID, AND WHAT ITS SEQUENCES PRODUCED.
19
+ *
20
+ * The rate math and the link rollup every bulk sender divides by are the mail
21
+ * model's (`@aglyn/shared-ui-email-campaigns/model/send-report`); this is the
22
+ * campaign's reading of them — which population each rate is over, the
23
+ * caveats that qualify a figure, and the funnel a campaign's sequences report
24
+ * into. It keeps the rule that module states: a rate names its denominator,
25
+ * or it is not reported.
26
+ */
27
+ import { type SendRate, type SendStats } from '@aglyn/shared-ui-email-campaigns/model/send-report';
28
+ /** Why a number the report would otherwise show is being withheld. */
29
+ export interface CampaignCaveat {
30
+ /** Stable id, so a spec can assert on the caveat rather than its prose. */
31
+ id: 'delivery-unrecorded' | 'click-tracking-unrecorded' | 'audience-truncated' | 'send-deferred' | 'revenue-denominator-unrecorded' | 'revenue-multi-currency' | 'revenue-mid-flight' | 'revenue-mixed-model' | 'conversions-kinds-overlap' | 'conversions-web-not-rolled-up' | 'conversions-unattributed-is-a-ceiling' | 'conversions-total-crosses-hosts' | 'sequences-funnel-not-summed';
32
+ message: string;
33
+ }
34
+ /** One population the send measured, for the audience breakdown. */
35
+ export interface CampaignPopulation {
36
+ id: string;
37
+ label: string;
38
+ count: number;
39
+ /** What this count is a part OF, named. */
40
+ ofLabel: string;
41
+ of: number;
42
+ }
43
+ /** Everything the report screen renders, decided here rather than in JSX. */
44
+ export interface CampaignReport {
45
+ sent: number;
46
+ recipients: number;
47
+ delivered: number | null;
48
+ opens: number;
49
+ clicks: number;
50
+ uniqueOpens: number | null;
51
+ uniqueClicks: number | null;
52
+ bounced: number;
53
+ complained: number;
54
+ unsubscribes: number;
55
+ /** Rates, each `null` when its denominator is zero or unrecorded. */
56
+ rates: {
57
+ /** Accepted by the receiving server, over what the provider accepted. */
58
+ delivery: SendRate | null;
59
+ /** Distinct readers who opened, over delivered. */
60
+ open: SendRate | null;
61
+ /** Distinct readers who clicked, over delivered. */
62
+ click: SendRate | null;
63
+ /**
64
+ * Distinct clickers over distinct OPENERS — a different question from
65
+ * `click`, and the one the two get confused for. It answers "of the
66
+ * people who read it, how many acted", not "of the people who received
67
+ * it". Reported separately and labelled separately, never as "click
68
+ * rate".
69
+ */
70
+ clickToOpen: SendRate | null;
71
+ /** Bounced over what the provider accepted. */
72
+ bounce: SendRate | null;
73
+ /** Complaints over delivered — the number mailbox providers judge on. */
74
+ complaint: SendRate | null;
75
+ /** Unsubscribes through this campaign's link, over delivered. */
76
+ unsubscribe: SendRate | null;
77
+ };
78
+ populations: CampaignPopulation[];
79
+ caveats: CampaignCaveat[];
80
+ }
81
+ /**
82
+ * Turns a stored `stats` map into the report.
83
+ *
84
+ * ## The denominator decisions, in one place
85
+ *
86
+ * - **`delivered`** carries the engagement rates — open, click, complaint,
87
+ * unsubscribe. Mail that bounced was never in front of a human, so
88
+ * including it in the denominator of an open rate depresses a number that
89
+ * describes the audience with a fact about the address list. This is also
90
+ * the convention every other tool reports, which matters: a merchant
91
+ * comparing our figure with their previous ESP's must be comparing the same
92
+ * quantity.
93
+ * - **`sent`** carries the delivery and bounce rates, because those describe
94
+ * what happened to what we handed the provider, and `delivered` is the
95
+ * numerator of one of them — a rate cannot be over itself.
96
+ * - **`uniqueOpens`** is the open-rate numerator, not `opens`. Open EVENTS
97
+ * over recipients can exceed 100% the moment one person opens twice, and a
98
+ * percentage above 100 is how a reader learns the number means something
99
+ * other than what it says. Both are shown; only the distinct count is
100
+ * divided.
101
+ *
102
+ * ## `delivered` unknown vs. zero
103
+ *
104
+ * A campaign predating the delivery webhook records no `delivered` at all.
105
+ * That is reported as `null` and every rate over it is withheld, with a
106
+ * caveat naming the reason — rather than substituting `sent`, which would
107
+ * silently publish the flattered number this module exists to refuse.
108
+ */
109
+ export declare function campaignReport(stats: SendStats | undefined): CampaignReport;
110
+ /**
111
+ * The outcomes the runtime credits, in funnel order. An array first, because
112
+ * the ORDER is the reading order and a second list is a second chance to
113
+ * leave one out; the union is derived from it.
114
+ */
115
+ export declare const CAMPAIGN_SEQUENCE_OUTCOMES: readonly ["enrolled", "sent", "replied", "meetings", "converted"];
116
+ export type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number];
117
+ /**
118
+ * The org collection holding one document per campaign container,
119
+ * `orgs/{orgId}/campaignSequenceReports/{campaignId}`.
120
+ */
121
+ export declare const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = "campaignSequenceReports";
122
+ /** What a reader calls each outcome, and what the count means. */
123
+ export declare const CAMPAIGN_SEQUENCE_OUTCOME_COPY: Readonly<Record<CampaignSequenceOutcome, {
124
+ label: string;
125
+ note: string;
126
+ }>>;
127
+ /**
128
+ * The stored shape of `campaignSequenceReports/{campaignId}`.
129
+ *
130
+ * Read-side only, every field optional: another plugin's runtime wrote it,
131
+ * and a reader that assumed a field was present would throw on the first
132
+ * document written before the field existed.
133
+ */
134
+ export interface CampaignSequencesRollup {
135
+ byOutcome?: Partial<Record<CampaignSequenceOutcome, number>>;
136
+ /** When the runtime last credited anything, epoch ms. */
137
+ updatedAtMs?: number;
138
+ }
139
+ /** One outcome's figure on screen. */
140
+ export interface CampaignSequenceFigure {
141
+ outcome: CampaignSequenceOutcome;
142
+ label: string;
143
+ /** The count, or `null` when the rollup holds no entry for the outcome. */
144
+ value: number | null;
145
+ note: string;
146
+ }
147
+ /** Everything the Sequences section renders. */
148
+ export interface CampaignSequencesReport {
149
+ /** Always all five, always in {@link CAMPAIGN_SEQUENCE_OUTCOMES} order. */
150
+ figures: CampaignSequenceFigure[];
151
+ /** Whether the rollup document exists at all — see the block header. */
152
+ recorded: boolean;
153
+ /** At least one outcome holds a figure. */
154
+ any: boolean;
155
+ caveats: CampaignCaveat[];
156
+ }
157
+ /** Turns the stored rollup into the Sequences section. */
158
+ export declare function campaignSequencesReport(rollup: CampaignSequencesRollup | undefined): CampaignSequencesReport;
@@ -0,0 +1,268 @@
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
+ * WHAT ONE CAMPAIGN SEND DID, AND WHAT ITS SEQUENCES PRODUCED.
18
+ *
19
+ * The rate math and the link rollup every bulk sender divides by are the mail
20
+ * model's (`@aglyn/shared-ui-email-campaigns/model/send-report`); this is the
21
+ * campaign's reading of them — which population each rate is over, the
22
+ * caveats that qualify a figure, and the funnel a campaign's sequences report
23
+ * into. It keeps the rule that module states: a rate names its denominator,
24
+ * or it is not reported.
25
+ */ import { sendRate } from "@aglyn/shared-ui-email-campaigns/model/send-report";
26
+ /**
27
+ * Turns a stored `stats` map into the report.
28
+ *
29
+ * ## The denominator decisions, in one place
30
+ *
31
+ * - **`delivered`** carries the engagement rates — open, click, complaint,
32
+ * unsubscribe. Mail that bounced was never in front of a human, so
33
+ * including it in the denominator of an open rate depresses a number that
34
+ * describes the audience with a fact about the address list. This is also
35
+ * the convention every other tool reports, which matters: a merchant
36
+ * comparing our figure with their previous ESP's must be comparing the same
37
+ * quantity.
38
+ * - **`sent`** carries the delivery and bounce rates, because those describe
39
+ * what happened to what we handed the provider, and `delivered` is the
40
+ * numerator of one of them — a rate cannot be over itself.
41
+ * - **`uniqueOpens`** is the open-rate numerator, not `opens`. Open EVENTS
42
+ * over recipients can exceed 100% the moment one person opens twice, and a
43
+ * percentage above 100 is how a reader learns the number means something
44
+ * other than what it says. Both are shown; only the distinct count is
45
+ * divided.
46
+ *
47
+ * ## `delivered` unknown vs. zero
48
+ *
49
+ * A campaign predating the delivery webhook records no `delivered` at all.
50
+ * That is reported as `null` and every rate over it is withheld, with a
51
+ * caveat naming the reason — rather than substituting `sent`, which would
52
+ * silently publish the flattered number this module exists to refuse.
53
+ */ export function campaignReport(stats) {
54
+ var _source_sent, _source_recipients, _source_opens, _source_clicks, _source_bounced, _source_complained, _source_unsubscribes, _source_audienceSize, _source_deferred;
55
+ const source = stats != null ? stats : {};
56
+ const sent = Number((_source_sent = source.sent) != null ? _source_sent : 0);
57
+ const recipients = Number((_source_recipients = source.recipients) != null ? _source_recipients : 0);
58
+ const opens = Number((_source_opens = source.opens) != null ? _source_opens : 0);
59
+ const clicks = Number((_source_clicks = source.clicks) != null ? _source_clicks : 0);
60
+ const bounced = Number((_source_bounced = source.bounced) != null ? _source_bounced : 0);
61
+ const complained = Number((_source_complained = source.complained) != null ? _source_complained : 0);
62
+ const unsubscribes = Number((_source_unsubscribes = source.unsubscribes) != null ? _source_unsubscribes : 0);
63
+ /*
64
+ * ABSENT, not zero. `stats.delivered` is written only by the delivery
65
+ * webhook, so `undefined` means "no delivery event has ever been recorded
66
+ * for this campaign" — which for an old campaign means the webhook was not
67
+ * connected, and for a campaign sent thirty seconds ago means the events
68
+ * are still in flight. Neither is "nothing was delivered", and both are
69
+ * ruined by `?? 0`, which would turn the unknown into a hard zero and make
70
+ * every rate over it `null` for the RIGHT answer by the WRONG reasoning —
71
+ * and would render "0 delivered" on screen beside "500 sent".
72
+ */ const delivered = source.delivered === undefined ? null : Number(source.delivered);
73
+ const uniqueOpens = source.uniqueOpens === undefined ? null : Number(source.uniqueOpens);
74
+ const uniqueClicks = source.uniqueClicks === undefined ? null : Number(source.uniqueClicks);
75
+ /*
76
+ * The click rate is withheld for a campaign that never recorded carrying an
77
+ * HTML part, even when clicks are non-zero and `delivered` is known. See
78
+ * the structural-zero note in the module header: for those sends 0 is the
79
+ * only value the number could ever have taken, so a rate computed from it
80
+ * measures our sending code rather than the recipients.
81
+ */ const clickTrackable = source.clickTracked === true;
82
+ const rates = {
83
+ /*
84
+ * `null` when `delivered` is UNRECORDED, and this is the one rate where
85
+ * the numerator can be unknown rather than zero.
86
+ *
87
+ * Everywhere else an absent numerator is a genuine nought — a campaign
88
+ * with delivery events and no opens really does have a 0% open rate, and
89
+ * that is worth showing. Here the numerator IS the unrecorded quantity,
90
+ * so `sendRate(undefined, 1000, 'sent')` would divide a missing
91
+ * measurement by a real one and publish "0.0% delivery rate — 0 of 1,000
92
+ * sent" for a campaign whose delivery events were merely never recorded.
93
+ * That is the flattering-substitution failure this module exists to
94
+ * refuse, running in the other direction: not a rate that reads too high,
95
+ * but a campaign that reads as a total delivery failure.
96
+ */ delivery: delivered === null ? null : sendRate(delivered, sent, 'sent'),
97
+ open: sendRate(uniqueOpens != null ? uniqueOpens : undefined, delivered != null ? delivered : undefined, 'delivered'),
98
+ click: clickTrackable ? sendRate(uniqueClicks != null ? uniqueClicks : undefined, delivered != null ? delivered : undefined, 'delivered') : null,
99
+ clickToOpen: clickTrackable ? sendRate(uniqueClicks != null ? uniqueClicks : undefined, uniqueOpens != null ? uniqueOpens : undefined, 'unique openers') : null,
100
+ bounce: sendRate(bounced, sent, 'sent'),
101
+ complaint: sendRate(complained, delivered != null ? delivered : undefined, 'delivered'),
102
+ unsubscribe: sendRate(unsubscribes, delivered != null ? delivered : undefined, 'delivered')
103
+ };
104
+ /*
105
+ * The populations the SEND measured, reported as parts of a named whole
106
+ * rather than as bare counts. "412 withheld" invites the question "out of
107
+ * what"; the answer is the audience, and it is a different whole from the
108
+ * one `suppressed` is measured against — consent is decided over the whole
109
+ * audience and suppression over the capped recipient list, because that is
110
+ * where each check runs. Netting them into one column would present two
111
+ * different denominators as one.
112
+ */ const audienceSize = Number((_source_audienceSize = source.audienceSize) != null ? _source_audienceSize : 0);
113
+ const populations = [];
114
+ const addPopulation = (id, label, count, ofLabel, of)=>{
115
+ if (count === undefined) return;
116
+ populations.push({
117
+ id,
118
+ label,
119
+ count: Number(count),
120
+ ofLabel,
121
+ of
122
+ });
123
+ };
124
+ addPopulation('consented', 'Had a consent basis', source.consented, 'audience', audienceSize);
125
+ addPopulation('consentedByOperator', 'Consent asserted by an operator', source.consentedByOperator, 'audience', audienceSize);
126
+ addPopulation('grandfathered', 'Reachable only because consent is not enforced retroactively', source.grandfathered, 'audience', audienceSize);
127
+ addPopulation('consentWithheld', 'Withheld by the consent rule', source.consentWithheld, 'audience', audienceSize);
128
+ addPopulation('suppressed', 'Already suppressed', source.suppressed, 'addressed', recipients);
129
+ addPopulation('cadenceHeld', 'Asked for mail less often than this', source.cadenceHeld, 'addressed', recipients);
130
+ addPopulation('noMailServer', 'Excluded: no mail server', source.noMailServer, 'addressed', recipients);
131
+ addPopulation('gatewayHeld', 'Excluded: behind a gateway that refused this sender', source.gatewayHeld, 'addressed', recipients);
132
+ const caveats = [];
133
+ if (delivered === null) {
134
+ caveats.push({
135
+ id: 'delivery-unrecorded',
136
+ message: 'No delivery events have been recorded for this campaign, so open, ' + 'click, complaint and unsubscribe rates cannot be computed — every ' + 'one of them is taken over delivered. Counts below are still real.'
137
+ });
138
+ }
139
+ if (!clickTrackable) {
140
+ caveats.push({
141
+ id: 'click-tracking-unrecorded',
142
+ message: 'This send did not record carrying an HTML part. Click tracking ' + 'rewrites links in the HTML, so a send without one reports zero ' + 'clicks whatever recipients did. The click count is shown; no click ' + 'rate is computed from it.'
143
+ });
144
+ }
145
+ if (source.audienceSizeTruncated) {
146
+ caveats.push({
147
+ id: 'audience-truncated',
148
+ message: 'Audience resolution stopped at its read ceiling, so the audience ' + 'size is a floor — the real audience is at least this large, and ' + 'every share taken over it is at most the figure shown.'
149
+ });
150
+ }
151
+ if (Number((_source_deferred = source.deferred) != null ? _source_deferred : 0) > 0) {
152
+ caveats.push({
153
+ id: 'send-deferred',
154
+ message: `${Number(source.deferred)} recipients were held back by the hourly ` + 'send governor and never received this campaign. They are counted in ' + 'addressed, not in sent.'
155
+ });
156
+ }
157
+ return {
158
+ sent,
159
+ recipients,
160
+ delivered,
161
+ opens,
162
+ clicks,
163
+ uniqueOpens,
164
+ uniqueClicks,
165
+ bounced,
166
+ complained,
167
+ unsubscribes,
168
+ rates,
169
+ populations,
170
+ caveats
171
+ };
172
+ }
173
+ /*==========================================
174
+ * WHAT THE CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).
175
+ *
176
+ * A sequence joins a campaign the way a form does — `campaignIds` on its own
177
+ * document — and its outcomes are then the campaign's to report: every
178
+ * person enrolled, the first email each one was sent, the replies, the
179
+ * meetings booked from a sequence link, and the enrolled leads that
180
+ * converted. The Outreach runtime credits each outcome once per enrollment
181
+ * to every campaign the sequence was in when the person was enrolled, into
182
+ * `hosts/{hostId}/campaignSequenceReports/{campaignId}` — one document per
183
+ * campaign, beside the conversions rollup and never inside the campaign
184
+ * document, which the history list and the glance widget read.
185
+ *
186
+ * ## The five figures are a funnel, not a sum
187
+ *
188
+ * Each figure counts ENROLLMENTS at a stage: 40 enrolled, 38 sent, 6
189
+ * replied, 2 meetings, 1 converted. They are read across, never added — a
190
+ * person is in every stage they reached — and the model keeps them as an
191
+ * ordered list rather than a total for the reason the conversion kinds are
192
+ * kept apart.
193
+ *
194
+ * ## Absent is not zero
195
+ *
196
+ * A campaign no sequence was ever in has no document, and a stage nobody
197
+ * reached has no field. Both are `null` here, so the screen can say
198
+ * "nothing recorded" for the first and draw a dash for the second, rather
199
+ * than printing a measured 0 replies for a campaign whose sequence went
200
+ * out yesterday.
201
+ *=========================================*/ /**
202
+ * The outcomes the runtime credits, in funnel order. An array first, because
203
+ * the ORDER is the reading order and a second list is a second chance to
204
+ * leave one out; the union is derived from it.
205
+ */ export const CAMPAIGN_SEQUENCE_OUTCOMES = [
206
+ 'enrolled',
207
+ 'sent',
208
+ 'replied',
209
+ 'meetings',
210
+ 'converted'
211
+ ];
212
+ /**
213
+ * The org collection holding one document per campaign container,
214
+ * `orgs/{orgId}/campaignSequenceReports/{campaignId}`.
215
+ */ export const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports';
216
+ /** What a reader calls each outcome, and what the count means. */ export const CAMPAIGN_SEQUENCE_OUTCOME_COPY = {
217
+ enrolled: {
218
+ label: 'Enrolled',
219
+ note: 'people enrolled in a sequence in this campaign'
220
+ },
221
+ sent: {
222
+ label: 'Sent',
223
+ note: 'of them, sent their first sequence email'
224
+ },
225
+ replied: {
226
+ label: 'Replied',
227
+ note: 'of them, who wrote back'
228
+ },
229
+ meetings: {
230
+ label: 'Meetings',
231
+ note: 'bookings made from a sequence link'
232
+ },
233
+ converted: {
234
+ label: 'Converted',
235
+ note: 'enrolled leads that became contacts'
236
+ }
237
+ };
238
+ /** Turns the stored rollup into the Sequences section. */ export function campaignSequencesReport(rollup) {
239
+ var _ref;
240
+ const stored = (_ref = rollup == null ? void 0 : rollup.byOutcome) != null ? _ref : {};
241
+ const figures = CAMPAIGN_SEQUENCE_OUTCOMES.map((outcome)=>{
242
+ const raw = stored[outcome];
243
+ const value = Math.floor(Number(raw != null ? raw : 0));
244
+ return {
245
+ outcome,
246
+ label: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].label,
247
+ // Unrecorded, negative and non-numeric all read as "no figure": the
248
+ // runtime only ever increments, so a stored 0 is not a count either.
249
+ value: raw === undefined || !Number.isFinite(value) || value <= 0 ? null : value,
250
+ note: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].note
251
+ };
252
+ });
253
+ const any = figures.some((figure)=>figure.value !== null);
254
+ const caveats = any ? [
255
+ {
256
+ id: 'sequences-funnel-not-summed',
257
+ message: 'Each figure counts the people who reached that stage, so a person ' + 'who replied is counted under Enrolled and Sent as well. Read them ' + 'across; they are deliberately not added together.'
258
+ }
259
+ ] : [];
260
+ return {
261
+ figures,
262
+ recorded: rollup !== undefined,
263
+ any,
264
+ caveats
265
+ };
266
+ }
267
+
268
+ //# sourceMappingURL=campaign-report.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/model/campaign-report.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 * WHAT ONE CAMPAIGN SEND DID, AND WHAT ITS SEQUENCES PRODUCED.\n *\n * The rate math and the link rollup every bulk sender divides by are the mail\n * model's (`@aglyn/shared-ui-email-campaigns/model/send-report`); this is the\n * campaign's reading of them — which population each rate is over, the\n * caveats that qualify a figure, and the funnel a campaign's sequences report\n * into. It keeps the rule that module states: a rate names its denominator,\n * or it is not reported.\n */\n\nimport {\n sendRate,\n type SendRate,\n type SendStats,\n} from '@aglyn/shared-ui-email-campaigns/model/send-report'\n\n/** Why a number the report would otherwise show is being withheld. */\nexport interface CampaignCaveat {\n /** Stable id, so a spec can assert on the caveat rather than its prose. */\n id:\n | 'delivery-unrecorded'\n | 'click-tracking-unrecorded'\n | 'audience-truncated'\n | 'send-deferred'\n /* Raised by `campaign-revenue.ts`, which reports through this shape so\n * the screen has one way of saying \"a number is being withheld and here\n * is why\" rather than one per section. */\n | 'revenue-denominator-unrecorded'\n | 'revenue-multi-currency'\n | 'revenue-mid-flight'\n | 'revenue-mixed-model'\n /* Raised by `campaign-conversions.ts`, through this shape for the same\n * reason: one way of saying \"a number is being withheld, or must not be\n * read the obvious way, and here is why\". The first two are the reasons\n * the four conversion kinds stand apart instead of totalling; the last\n * two qualify the uncredited figure rather than withholding it. */\n | 'conversions-kinds-overlap'\n | 'conversions-web-not-rolled-up'\n | 'conversions-unattributed-is-a-ceiling'\n | 'conversions-total-crosses-hosts'\n /* Raised by the Sequences block below (AGL-3254): the five figures are\n * a funnel read across, never a sum. */\n | 'sequences-funnel-not-summed'\n message: string\n}\n\n/** One population the send measured, for the audience breakdown. */\nexport interface CampaignPopulation {\n id: string\n label: string\n count: number\n /** What this count is a part OF, named. */\n ofLabel: string\n of: number\n}\n\n/** Everything the report screen renders, decided here rather than in JSX. */\nexport interface CampaignReport {\n sent: number\n recipients: number\n delivered: number | null\n opens: number\n clicks: number\n uniqueOpens: number | null\n uniqueClicks: number | null\n bounced: number\n complained: number\n unsubscribes: number\n /** Rates, each `null` when its denominator is zero or unrecorded. */\n rates: {\n /** Accepted by the receiving server, over what the provider accepted. */\n delivery: SendRate | null\n /** Distinct readers who opened, over delivered. */\n open: SendRate | null\n /** Distinct readers who clicked, over delivered. */\n click: SendRate | null\n /**\n * Distinct clickers over distinct OPENERS — a different question from\n * `click`, and the one the two get confused for. It answers \"of the\n * people who read it, how many acted\", not \"of the people who received\n * it\". Reported separately and labelled separately, never as \"click\n * rate\".\n */\n clickToOpen: SendRate | null\n /** Bounced over what the provider accepted. */\n bounce: SendRate | null\n /** Complaints over delivered — the number mailbox providers judge on. */\n complaint: SendRate | null\n /** Unsubscribes through this campaign's link, over delivered. */\n unsubscribe: SendRate | null\n }\n populations: CampaignPopulation[]\n caveats: CampaignCaveat[]\n}\n\n/**\n * Turns a stored `stats` map into the report.\n *\n * ## The denominator decisions, in one place\n *\n * - **`delivered`** carries the engagement rates — open, click, complaint,\n * unsubscribe. Mail that bounced was never in front of a human, so\n * including it in the denominator of an open rate depresses a number that\n * describes the audience with a fact about the address list. This is also\n * the convention every other tool reports, which matters: a merchant\n * comparing our figure with their previous ESP's must be comparing the same\n * quantity.\n * - **`sent`** carries the delivery and bounce rates, because those describe\n * what happened to what we handed the provider, and `delivered` is the\n * numerator of one of them — a rate cannot be over itself.\n * - **`uniqueOpens`** is the open-rate numerator, not `opens`. Open EVENTS\n * over recipients can exceed 100% the moment one person opens twice, and a\n * percentage above 100 is how a reader learns the number means something\n * other than what it says. Both are shown; only the distinct count is\n * divided.\n *\n * ## `delivered` unknown vs. zero\n *\n * A campaign predating the delivery webhook records no `delivered` at all.\n * That is reported as `null` and every rate over it is withheld, with a\n * caveat naming the reason — rather than substituting `sent`, which would\n * silently publish the flattered number this module exists to refuse.\n */\nexport function campaignReport(stats: SendStats | undefined): CampaignReport {\n const source = stats ?? {}\n const sent = Number(source.sent ?? 0)\n const recipients = Number(source.recipients ?? 0)\n const opens = Number(source.opens ?? 0)\n const clicks = Number(source.clicks ?? 0)\n const bounced = Number(source.bounced ?? 0)\n const complained = Number(source.complained ?? 0)\n const unsubscribes = Number(source.unsubscribes ?? 0)\n\n /*\n * ABSENT, not zero. `stats.delivered` is written only by the delivery\n * webhook, so `undefined` means \"no delivery event has ever been recorded\n * for this campaign\" — which for an old campaign means the webhook was not\n * connected, and for a campaign sent thirty seconds ago means the events\n * are still in flight. Neither is \"nothing was delivered\", and both are\n * ruined by `?? 0`, which would turn the unknown into a hard zero and make\n * every rate over it `null` for the RIGHT answer by the WRONG reasoning —\n * and would render \"0 delivered\" on screen beside \"500 sent\".\n */\n const delivered =\n source.delivered === undefined ? null : Number(source.delivered)\n const uniqueOpens =\n source.uniqueOpens === undefined ? null : Number(source.uniqueOpens)\n const uniqueClicks =\n source.uniqueClicks === undefined ? null : Number(source.uniqueClicks)\n\n /*\n * The click rate is withheld for a campaign that never recorded carrying an\n * HTML part, even when clicks are non-zero and `delivered` is known. See\n * the structural-zero note in the module header: for those sends 0 is the\n * only value the number could ever have taken, so a rate computed from it\n * measures our sending code rather than the recipients.\n */\n const clickTrackable = source.clickTracked === true\n\n const rates: CampaignReport['rates'] = {\n /*\n * `null` when `delivered` is UNRECORDED, and this is the one rate where\n * the numerator can be unknown rather than zero.\n *\n * Everywhere else an absent numerator is a genuine nought — a campaign\n * with delivery events and no opens really does have a 0% open rate, and\n * that is worth showing. Here the numerator IS the unrecorded quantity,\n * so `sendRate(undefined, 1000, 'sent')` would divide a missing\n * measurement by a real one and publish \"0.0% delivery rate — 0 of 1,000\n * sent\" for a campaign whose delivery events were merely never recorded.\n * That is the flattering-substitution failure this module exists to\n * refuse, running in the other direction: not a rate that reads too high,\n * but a campaign that reads as a total delivery failure.\n */\n delivery:\n delivered === null ? null : sendRate(delivered, sent, 'sent'),\n open: sendRate(uniqueOpens ?? undefined, delivered ?? undefined, 'delivered'),\n click: clickTrackable\n ? sendRate(uniqueClicks ?? undefined, delivered ?? undefined, 'delivered')\n : null,\n clickToOpen: clickTrackable\n ? sendRate(uniqueClicks ?? undefined, uniqueOpens ?? undefined, 'unique openers')\n : null,\n bounce: sendRate(bounced, sent, 'sent'),\n complaint: sendRate(complained, delivered ?? undefined, 'delivered'),\n unsubscribe: sendRate(unsubscribes, delivered ?? undefined, 'delivered'),\n }\n\n /*\n * The populations the SEND measured, reported as parts of a named whole\n * rather than as bare counts. \"412 withheld\" invites the question \"out of\n * what\"; the answer is the audience, and it is a different whole from the\n * one `suppressed` is measured against — consent is decided over the whole\n * audience and suppression over the capped recipient list, because that is\n * where each check runs. Netting them into one column would present two\n * different denominators as one.\n */\n const audienceSize = Number(source.audienceSize ?? 0)\n const populations: CampaignPopulation[] = []\n const addPopulation = (\n id: string,\n label: string,\n count: number | undefined,\n ofLabel: string,\n of: number,\n ) => {\n if (count === undefined) return\n populations.push({ id, label, count: Number(count), ofLabel, of })\n }\n addPopulation(\n 'consented',\n 'Had a consent basis',\n source.consented,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'consentedByOperator',\n 'Consent asserted by an operator',\n source.consentedByOperator,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'grandfathered',\n 'Reachable only because consent is not enforced retroactively',\n source.grandfathered,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'consentWithheld',\n 'Withheld by the consent rule',\n source.consentWithheld,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'suppressed',\n 'Already suppressed',\n source.suppressed,\n 'addressed',\n recipients,\n )\n addPopulation(\n 'cadenceHeld',\n 'Asked for mail less often than this',\n source.cadenceHeld,\n 'addressed',\n recipients,\n )\n addPopulation(\n 'noMailServer',\n 'Excluded: no mail server',\n source.noMailServer,\n 'addressed',\n recipients,\n )\n addPopulation(\n 'gatewayHeld',\n 'Excluded: behind a gateway that refused this sender',\n source.gatewayHeld,\n 'addressed',\n recipients,\n )\n\n const caveats: CampaignCaveat[] = []\n if (delivered === null) {\n caveats.push({\n id: 'delivery-unrecorded',\n message:\n 'No delivery events have been recorded for this campaign, so open, ' +\n 'click, complaint and unsubscribe rates cannot be computed — every ' +\n 'one of them is taken over delivered. Counts below are still real.',\n })\n }\n if (!clickTrackable) {\n caveats.push({\n id: 'click-tracking-unrecorded',\n message:\n 'This send did not record carrying an HTML part. Click tracking ' +\n 'rewrites links in the HTML, so a send without one reports zero ' +\n 'clicks whatever recipients did. The click count is shown; no click ' +\n 'rate is computed from it.',\n })\n }\n if (source.audienceSizeTruncated) {\n caveats.push({\n id: 'audience-truncated',\n message:\n 'Audience resolution stopped at its read ceiling, so the audience ' +\n 'size is a floor — the real audience is at least this large, and ' +\n 'every share taken over it is at most the figure shown.',\n })\n }\n if (Number(source.deferred ?? 0) > 0) {\n caveats.push({\n id: 'send-deferred',\n message:\n `${Number(source.deferred)} recipients were held back by the hourly ` +\n 'send governor and never received this campaign. They are counted in ' +\n 'addressed, not in sent.',\n })\n }\n\n return {\n sent,\n recipients,\n delivered,\n opens,\n clicks,\n uniqueOpens,\n uniqueClicks,\n bounced,\n complained,\n unsubscribes,\n rates,\n populations,\n caveats,\n }\n}\n\n/*==========================================\n * WHAT THE CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).\n *\n * A sequence joins a campaign the way a form does — `campaignIds` on its own\n * document — and its outcomes are then the campaign's to report: every\n * person enrolled, the first email each one was sent, the replies, the\n * meetings booked from a sequence link, and the enrolled leads that\n * converted. The Outreach runtime credits each outcome once per enrollment\n * to every campaign the sequence was in when the person was enrolled, into\n * `hosts/{hostId}/campaignSequenceReports/{campaignId}` — one document per\n * campaign, beside the conversions rollup and never inside the campaign\n * document, which the history list and the glance widget read.\n *\n * ## The five figures are a funnel, not a sum\n *\n * Each figure counts ENROLLMENTS at a stage: 40 enrolled, 38 sent, 6\n * replied, 2 meetings, 1 converted. They are read across, never added — a\n * person is in every stage they reached — and the model keeps them as an\n * ordered list rather than a total for the reason the conversion kinds are\n * kept apart.\n *\n * ## Absent is not zero\n *\n * A campaign no sequence was ever in has no document, and a stage nobody\n * reached has no field. Both are `null` here, so the screen can say\n * \"nothing recorded\" for the first and draw a dash for the second, rather\n * than printing a measured 0 replies for a campaign whose sequence went\n * out yesterday.\n *=========================================*/\n\n/**\n * The outcomes the runtime credits, in funnel order. An array first, because\n * the ORDER is the reading order and a second list is a second chance to\n * leave one out; the union is derived from it.\n */\nexport const CAMPAIGN_SEQUENCE_OUTCOMES = [\n 'enrolled',\n 'sent',\n 'replied',\n 'meetings',\n 'converted',\n] as const\n\nexport type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number]\n\n/**\n * The org collection holding one document per campaign container,\n * `orgs/{orgId}/campaignSequenceReports/{campaignId}`.\n */\nexport const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports'\n\n/** What a reader calls each outcome, and what the count means. */\nexport const CAMPAIGN_SEQUENCE_OUTCOME_COPY: Readonly<\n Record<CampaignSequenceOutcome, { label: string; note: string }>\n> = {\n enrolled: { label: 'Enrolled', note: 'people enrolled in a sequence in this campaign' },\n sent: { label: 'Sent', note: 'of them, sent their first sequence email' },\n replied: { label: 'Replied', note: 'of them, who wrote back' },\n meetings: { label: 'Meetings', note: 'bookings made from a sequence link' },\n converted: { label: 'Converted', note: 'enrolled leads that became contacts' },\n}\n\n/**\n * The stored shape of `campaignSequenceReports/{campaignId}`.\n *\n * Read-side only, every field optional: another plugin's runtime wrote it,\n * and a reader that assumed a field was present would throw on the first\n * document written before the field existed.\n */\nexport interface CampaignSequencesRollup {\n byOutcome?: Partial<Record<CampaignSequenceOutcome, number>>\n /** When the runtime last credited anything, epoch ms. */\n updatedAtMs?: number\n}\n\n/** One outcome's figure on screen. */\nexport interface CampaignSequenceFigure {\n outcome: CampaignSequenceOutcome\n label: string\n /** The count, or `null` when the rollup holds no entry for the outcome. */\n value: number | null\n note: string\n}\n\n/** Everything the Sequences section renders. */\nexport interface CampaignSequencesReport {\n /** Always all five, always in {@link CAMPAIGN_SEQUENCE_OUTCOMES} order. */\n figures: CampaignSequenceFigure[]\n /** Whether the rollup document exists at all — see the block header. */\n recorded: boolean\n /** At least one outcome holds a figure. */\n any: boolean\n caveats: CampaignCaveat[]\n}\n\n/** Turns the stored rollup into the Sequences section. */\nexport function campaignSequencesReport(\n rollup: CampaignSequencesRollup | undefined,\n): CampaignSequencesReport {\n const stored = rollup?.byOutcome ?? {}\n const figures: CampaignSequenceFigure[] = CAMPAIGN_SEQUENCE_OUTCOMES.map((outcome) => {\n const raw = stored[outcome]\n const value = Math.floor(Number(raw ?? 0))\n return {\n outcome,\n label: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].label,\n // Unrecorded, negative and non-numeric all read as \"no figure\": the\n // runtime only ever increments, so a stored 0 is not a count either.\n value: raw === undefined || !Number.isFinite(value) || value <= 0 ? null : value,\n note: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].note,\n }\n })\n const any = figures.some((figure) => figure.value !== null)\n const caveats: CampaignCaveat[] = any\n ? [\n {\n id: 'sequences-funnel-not-summed',\n message:\n 'Each figure counts the people who reached that stage, so a person ' +\n 'who replied is counted under Enrolled and Sent as well. Read them ' +\n 'across; they are deliberately not added together.',\n },\n ]\n : []\n return { figures, recorded: rollup !== undefined, any, caveats }\n}\n"],"names":["sendRate","campaignReport","stats","source","sent","Number","recipients","opens","clicks","bounced","complained","unsubscribes","delivered","undefined","uniqueOpens","uniqueClicks","clickTrackable","clickTracked","rates","delivery","open","click","clickToOpen","bounce","complaint","unsubscribe","audienceSize","populations","addPopulation","id","label","count","ofLabel","of","push","consented","consentedByOperator","grandfathered","consentWithheld","suppressed","cadenceHeld","noMailServer","gatewayHeld","caveats","message","audienceSizeTruncated","deferred","CAMPAIGN_SEQUENCE_OUTCOMES","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","CAMPAIGN_SEQUENCE_OUTCOME_COPY","enrolled","note","replied","meetings","converted","campaignSequencesReport","rollup","stored","byOutcome","figures","map","outcome","raw","value","Math","floor","isFinite","any","some","figure","recorded"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,GAED,SACEA,QAAQ,QAGH,qDAAoD;AAiF3D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,eAAeC,KAA4B;QAErCC,cACMA,oBACLA,eACCA,gBACCA,iBACG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WA,OAAON,KAAK,KAAK;IACtD,MAAMpB,UAA4BwB,MAC9B;QACE;YACEtC,IAAI;YACJe,SACE,uEACA,uEACA;QACJ;KACD,GACD,EAAE;IACN,OAAO;QAAEe;QAASW,UAAUd,WAAW3C;QAAWsD;QAAKxB;IAAQ;AACjE"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type CampaignCaveat } from '@aglyn/shared-ui-email-campaigns/model/campaign-report';
17
+ import { type CampaignCaveat } from './campaign-report';
18
18
  /**
19
19
  * WHAT A CAMPAIGN EARNED — the read half of the commerce↔email join.
20
20
  *
@@ -138,7 +138,7 @@ export interface CampaignRevenueRollup {
138
138
  windowDays?: number;
139
139
  }
140
140
  /**
141
- * Money over a population, with the population named — {@link CampaignRate}'s
141
+ * Money over a population, with the population named — {@link SendRate}'s
142
142
  * rule applied to an average instead of a share.
143
143
  *
144
144
  * A percentage and an average go wrong the same way, so they carry the same
@@ -214,7 +214,7 @@ export declare const REVENUE_MULTI_CURRENCY_MESSAGE: string;
214
214
  /**
215
215
  * Money per message, or `null` when the division cannot honestly be taken.
216
216
  *
217
- * The three refusals are {@link campaignRate}'s, and this defers to it rather
217
+ * The three refusals are {@link sendRate}'s, and this defers to it rather
218
218
  * than restating them: a zero denominator, an unrecorded denominator, and a
219
219
  * non-finite input all answer `null` there, so a second implementation of
220
220
  * "when may we divide" cannot drift from the first.