@aglyn/shared-ui-email-campaigns 1.0.0-beta.143
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/LICENSE +201 -0
- package/README.md +73 -0
- package/package.json +39 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +23 -0
- package/src/index.js.map +1 -0
- package/src/lib/components/campaign-picker.component.d.ts +54 -0
- package/src/lib/components/campaign-picker.component.js +121 -0
- package/src/lib/components/campaign-picker.component.js.map +1 -0
- package/src/lib/components/report-figures.d.ts +51 -0
- package/src/lib/components/report-figures.js +120 -0
- package/src/lib/components/report-figures.js.map +1 -0
- package/src/lib/model/campaign-container.d.ts +359 -0
- package/src/lib/model/campaign-container.js +355 -0
- package/src/lib/model/campaign-container.js.map +1 -0
- package/src/lib/model/campaign-conversions.d.ts +286 -0
- package/src/lib/model/campaign-conversions.js +249 -0
- package/src/lib/model/campaign-conversions.js.map +1 -0
- package/src/lib/model/campaign-report.d.ts +304 -0
- package/src/lib/model/campaign-report.js +326 -0
- package/src/lib/model/campaign-report.js.map +1 -0
- package/src/lib/model/campaign-revenue.d.ts +327 -0
- package/src/lib/model/campaign-revenue.js +332 -0
- package/src/lib/model/campaign-revenue.js.map +1 -0
- package/src/lib/model/campaign-send-time.d.ts +74 -0
- package/src/lib/model/campaign-send-time.js +120 -0
- package/src/lib/model/campaign-send-time.js.map +1 -0
- package/src/lib/model/email-record.d.ts +175 -0
- package/src/lib/model/email-record.js +198 -0
- package/src/lib/model/email-record.js.map +1 -0
- package/src/lib/model/index.d.ts +53 -0
- package/src/lib/model/index.js +48 -0
- package/src/lib/model/index.js.map +1 -0
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ /*
|
|
18
|
+
* The window and the model name come from `@aglyn/shared-util-email`, not
|
|
19
|
+
* from here. The writer is in `tenant-data-admin`, which may not import a
|
|
20
|
+
* feature plugin, and a window defined on both sides of the join would drift
|
|
21
|
+
* into a number credited under one rule and printed under another.
|
|
22
|
+
*/ import { EMAIL_ATTRIBUTION_MODEL, EMAIL_ATTRIBUTION_WINDOW_DAYS } from "@aglyn/shared-util-email";
|
|
23
|
+
import { campaignRate } from "./campaign-report.js";
|
|
24
|
+
/**
|
|
25
|
+
* WHAT A CAMPAIGN EARNED — the read half of the commerce↔email join.
|
|
26
|
+
*
|
|
27
|
+
* ## Why this is a join and not an attribution model
|
|
28
|
+
*
|
|
29
|
+
* Every compared ESP reconstructs campaign revenue probabilistically, because
|
|
30
|
+
* none of them owns the order. Klaviyo and Mailchimp watch someone else's
|
|
31
|
+
* store through an integration and a browser snippet, so their figure is a
|
|
32
|
+
* reconciliation against a foreign system and their window is the fudge
|
|
33
|
+
* factor that makes the reconciliation close. Commerce here is first-party:
|
|
34
|
+
* the click and the order are rows in one database, keyed the same way, so
|
|
35
|
+
* the "attribution" is a lookup.
|
|
36
|
+
*
|
|
37
|
+
* That does not make the MODEL choice go away — two campaigns can both have
|
|
38
|
+
* touched a buyer and only one can be credited — but it does mean the model
|
|
39
|
+
* is the only judgement in the number. There is no sampling, no identity
|
|
40
|
+
* resolution and no cookie.
|
|
41
|
+
*
|
|
42
|
+
* ## The model: LAST CLICK, inside a fixed 7-day window
|
|
43
|
+
*
|
|
44
|
+
* Stated in one sentence, which is the whole requirement: **an order is
|
|
45
|
+
* credited to the last campaign whose link the buyer clicked, if they clicked
|
|
46
|
+
* it within the {@link EMAIL_ATTRIBUTION_WINDOW_DAYS} days before they
|
|
47
|
+
* ordered.**
|
|
48
|
+
*
|
|
49
|
+
* Three decisions are inside that sentence.
|
|
50
|
+
*
|
|
51
|
+
* **Last touch, not multi-touch.** Multi-touch is the more honest description
|
|
52
|
+
* of how buying works and it is unpresentable: it splits one order across
|
|
53
|
+
* several campaigns by a rule the merchant did not choose, so no campaign's
|
|
54
|
+
* revenue is a number they can check against their own bank, and two
|
|
55
|
+
* campaigns' figures cannot be added or compared without knowing the split
|
|
56
|
+
* rule. HubSpot ships multi-touch and puts it behind an Enterprise plan and a
|
|
57
|
+
* consultant. A figure a merchant cannot explain to themselves is worse than
|
|
58
|
+
* no figure, and it is worse in the specific way that matters here: they will
|
|
59
|
+
* still make decisions with it.
|
|
60
|
+
*
|
|
61
|
+
* **A CLICK is the touch. An open is not.** An open is evidence about the
|
|
62
|
+
* recipient's mail client, not about the recipient — Apple's Mail Privacy
|
|
63
|
+
* Protection prefetches images, which inflated network-wide open rates by
|
|
64
|
+
* roughly 15% and means a large share of recorded opens had no human behind
|
|
65
|
+
* them. Crediting revenue to an open would therefore credit campaigns for
|
|
66
|
+
* orders from people who never saw them, and the error is not random: it
|
|
67
|
+
* concentrates on whichever campaign most recently reached an Apple Mail
|
|
68
|
+
* user. `email-delivery-log.ts` records the same preference for the same
|
|
69
|
+
* reason, and the audience rules already segment on clicks over opens.
|
|
70
|
+
*
|
|
71
|
+
* **Seven days, and not configurable.** Klaviyo's window is 1–30 days per
|
|
72
|
+
* channel; ActiveCampaign's is a fixed, unadjustable 7. Fixed is the better
|
|
73
|
+
* default here because a configurable window is a setting whose change
|
|
74
|
+
* silently rewrites history: yesterday's report and today's would disagree
|
|
75
|
+
* about a campaign that has not been touched since, with nothing on screen to
|
|
76
|
+
* say why. The stored record carries `windowDays` per order for exactly that
|
|
77
|
+
* reason — a future setting can be added without making the orders already
|
|
78
|
+
* attributed unreadable, because each one says which window it was judged
|
|
79
|
+
* under.
|
|
80
|
+
*
|
|
81
|
+
* ## GROSS and REFUNDED, never a decrement
|
|
82
|
+
*
|
|
83
|
+
* A refunded order must stop counting as revenue a campaign earned, and there
|
|
84
|
+
* are two ways to make it stop. Decrementing the gross figure makes a stored
|
|
85
|
+
* number mean one thing before a refund and another after, with nothing to
|
|
86
|
+
* distinguish them; recording the reversal beside it keeps both facts. This
|
|
87
|
+
* is the shape `contact-refund.ts` chose for `ltvCents`/`refundedCents` on the
|
|
88
|
+
* contact and the orders CSV chose for `amountUsd`/`refundedUsd`, and it is
|
|
89
|
+
* chosen again here so all three answer "what did this earn, net" the same
|
|
90
|
+
* way.
|
|
91
|
+
*
|
|
92
|
+
* So {@link campaignRevenueReport} reports gross, refunded and net, and NET
|
|
93
|
+
* is the figure the screen leads with. Net is clamped at zero for display
|
|
94
|
+
* only: a refund larger than the sale it reverses is arithmetically possible
|
|
95
|
+
* on an order attributed before a partial refund settled, and a negative
|
|
96
|
+
* campaign revenue is a sentence nobody can act on.
|
|
97
|
+
*
|
|
98
|
+
* ## Currencies are never summed
|
|
99
|
+
*
|
|
100
|
+
* Money is stored in minor units and no currency travels with it — every
|
|
101
|
+
* checkout door in this repo sets `currency: 'usd'` on the Stripe line items,
|
|
102
|
+
* so the amounts really are all USD, but that is a fact about the code rather
|
|
103
|
+
* than a field on the order. The rollup therefore buckets BY currency and
|
|
104
|
+
* this module never adds two buckets together. A campaign with two currencies
|
|
105
|
+
* renders two blocks and no total, and says so.
|
|
106
|
+
*
|
|
107
|
+
* The rule survives the merge across a container's emails.
|
|
108
|
+
* {@link campaignRevenueAcrossSends} keys its accumulator on the currency, so
|
|
109
|
+
* two rollups can only ever meet inside a bucket they already share — there
|
|
110
|
+
* is no code path in which a USD amount and a EUR amount reach the same
|
|
111
|
+
* addition, and no combined figure exists for a screen to print by accident.
|
|
112
|
+
*/ /**
|
|
113
|
+
* Re-exported so a reader of the report has the window and the model name
|
|
114
|
+
* without reaching past this module for them — the screen prints both, and a
|
|
115
|
+
* window nobody can see is a window nobody can check.
|
|
116
|
+
*/ export { EMAIL_ATTRIBUTION_MODEL, EMAIL_ATTRIBUTION_WINDOW_DAYS, EMAIL_ATTRIBUTION_WINDOW_MS } from "@aglyn/shared-util-email";
|
|
117
|
+
/**
|
|
118
|
+
* Why there is no total, in the words both reports use.
|
|
119
|
+
*
|
|
120
|
+
* One sentence, one definition. A send's report and its campaign's report
|
|
121
|
+
* make the same refusal for the same reason, and two copies of the sentence
|
|
122
|
+
* is how one of them comes to be softened into a promise of a total.
|
|
123
|
+
*/ export const REVENUE_MULTI_CURRENCY_MESSAGE = 'This campaign earned in more than one currency. Each is reported on its ' + 'own — nothing here converts between them, so there is deliberately no ' + 'combined total.';
|
|
124
|
+
/** A stored count as a non-negative integer. */ function count(raw) {
|
|
125
|
+
const value = Math.floor(Number(raw != null ? raw : 0));
|
|
126
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Money per message, or `null` when the division cannot honestly be taken.
|
|
130
|
+
*
|
|
131
|
+
* The three refusals are {@link campaignRate}'s, and this defers to it rather
|
|
132
|
+
* than restating them: a zero denominator, an unrecorded denominator, and a
|
|
133
|
+
* non-finite input all answer `null` there, so a second implementation of
|
|
134
|
+
* "when may we divide" cannot drift from the first.
|
|
135
|
+
*/ export function campaignMoneyPerMessage(numeratorCents, denominator, denominatorLabel, currency) {
|
|
136
|
+
const divisible = campaignRate(numeratorCents, denominator, denominatorLabel);
|
|
137
|
+
if (!divisible) return null;
|
|
138
|
+
return {
|
|
139
|
+
cents: divisible.value,
|
|
140
|
+
numeratorCents: divisible.numerator,
|
|
141
|
+
denominator: divisible.denominator,
|
|
142
|
+
denominatorLabel,
|
|
143
|
+
currency
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Turns the stored rollup into the revenue section.
|
|
148
|
+
*
|
|
149
|
+
* `delivered` comes from the campaign's own `stats` and is passed in rather
|
|
150
|
+
* than re-read, so the numerator and the denominator on screen are taken from
|
|
151
|
+
* the same instant. It is `null` when no delivery event has ever been
|
|
152
|
+
* recorded — the campaign predates the delivery webhook, or the events are
|
|
153
|
+
* still in flight — and every figure over it is then withheld with a caveat,
|
|
154
|
+
* never substituted for `sent`.
|
|
155
|
+
*/ export function campaignRevenueReport(options) {
|
|
156
|
+
var _ref, _ref1;
|
|
157
|
+
const { rollup, delivered, midFlight } = options;
|
|
158
|
+
const stored = (_ref = rollup == null ? void 0 : rollup.byCurrency) != null ? _ref : {};
|
|
159
|
+
const caveats = [];
|
|
160
|
+
const currencies = Object.entries(stored).map(([currency, totals])=>{
|
|
161
|
+
const grossCents = count(totals == null ? void 0 : totals.grossCents);
|
|
162
|
+
const refundedCents = count(totals == null ? void 0 : totals.refundedCents);
|
|
163
|
+
/*
|
|
164
|
+
* CLAMPED, and only here at the point of display.
|
|
165
|
+
*
|
|
166
|
+
* Both stored figures are monotonic counters of money that really
|
|
167
|
+
* moved in one direction, so neither can be negative; their DIFFERENCE
|
|
168
|
+
* can be, for one reason — an order credited to a campaign and then
|
|
169
|
+
* refunded by more than the amount that was credited, which happens
|
|
170
|
+
* when a partial refund settles against an order whose attributed
|
|
171
|
+
* amount was the charge at the time. Clamping at write time would
|
|
172
|
+
* erase the evidence; clamping at read time keeps the stored pair
|
|
173
|
+
* intact and stops the screen printing a campaign with negative
|
|
174
|
+
* earnings, which is not a sentence anybody can act on.
|
|
175
|
+
*/ const netCents = Math.max(0, grossCents - refundedCents);
|
|
176
|
+
return {
|
|
177
|
+
currency,
|
|
178
|
+
grossCents,
|
|
179
|
+
refundedCents,
|
|
180
|
+
netCents,
|
|
181
|
+
orders: count(totals == null ? void 0 : totals.orders),
|
|
182
|
+
refundedOrders: count(totals == null ? void 0 : totals.refundedOrders),
|
|
183
|
+
netPerDelivered: campaignMoneyPerMessage(netCents, delivered != null ? delivered : undefined, 'delivered', currency)
|
|
184
|
+
};
|
|
185
|
+
}).filter((entry)=>entry.orders > 0 || entry.grossCents > 0).sort((a, b)=>b.netCents - a.netCents || a.currency.localeCompare(b.currency));
|
|
186
|
+
const attributedOrders = currencies.reduce((total, entry)=>total + entry.orders, 0);
|
|
187
|
+
const multiCurrency = currencies.length > 1;
|
|
188
|
+
if (delivered === null && currencies.length) {
|
|
189
|
+
caveats.push({
|
|
190
|
+
id: 'revenue-denominator-unrecorded',
|
|
191
|
+
message: 'No delivery events have been recorded for this campaign, so revenue ' + 'per delivered message cannot be computed. The amounts below are ' + 'still real.'
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
if (multiCurrency) {
|
|
195
|
+
caveats.push({
|
|
196
|
+
id: 'revenue-multi-currency',
|
|
197
|
+
message: REVENUE_MULTI_CURRENCY_MESSAGE
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
if (midFlight && currencies.length) {
|
|
201
|
+
caveats.push({
|
|
202
|
+
id: 'revenue-mid-flight',
|
|
203
|
+
message: 'This campaign is still going out. Revenue and delivered messages ' + 'are both still rising, so every figure below is a running total ' + 'rather than a final one.'
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
currencies,
|
|
208
|
+
attributedOrders,
|
|
209
|
+
recorded: rollup !== undefined,
|
|
210
|
+
multiCurrency,
|
|
211
|
+
model: String((_ref1 = rollup == null ? void 0 : rollup.model) != null ? _ref1 : EMAIL_ATTRIBUTION_MODEL),
|
|
212
|
+
windowDays: count(rollup == null ? void 0 : rollup.windowDays) || EMAIL_ATTRIBUTION_WINDOW_DAYS,
|
|
213
|
+
caveats
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* MERGES A CAMPAIGN'S EMAILS INTO ONE REVENUE SECTION, per currency.
|
|
218
|
+
*
|
|
219
|
+
* `reports/revenue` is written per SEND, so a container's figure is one
|
|
220
|
+
* document per email and a merge. The merge is the whole risk: two emails of
|
|
221
|
+
* one campaign can have earned in different currencies, and adding their
|
|
222
|
+
* amounts produces a number that is wrong with nothing on screen to show it.
|
|
223
|
+
*
|
|
224
|
+
* ## The currency is the accumulator's KEY, not a field beside the amount
|
|
225
|
+
*
|
|
226
|
+
* That is the structural half of the guarantee. Amounts are added into a map
|
|
227
|
+
* keyed by currency, so two amounts can only reach the same addition when
|
|
228
|
+
* they already carry the same code — a USD figure and a EUR figure have no
|
|
229
|
+
* path to each other, whatever a later caller asks for. There is no combined
|
|
230
|
+
* field on the result, so a screen cannot print a cross-currency total by
|
|
231
|
+
* reading the wrong property, and
|
|
232
|
+
* {@link CampaignRevenueAcrossSends.multiCurrency} is what tells the screen
|
|
233
|
+
* to label the blocks.
|
|
234
|
+
*
|
|
235
|
+
* ## Clamped ONCE, over the campaign
|
|
236
|
+
*
|
|
237
|
+
* The single-send report clamps its net at zero because a partial refund can
|
|
238
|
+
* settle against an order credited at the full charge. Doing that per email
|
|
239
|
+
* and then summing would let one over-refunded email keep money a sibling
|
|
240
|
+
* email handed back — an email at -$50 clamped to $0 beside one at $200 would
|
|
241
|
+
* report $200 for a campaign holding $150. So gross and refunded are summed
|
|
242
|
+
* as they stand and the difference is clamped once, at the end.
|
|
243
|
+
*
|
|
244
|
+
* ## No per-message average, deliberately
|
|
245
|
+
*
|
|
246
|
+
* The send report divides net revenue by that send's own `delivered`, taken
|
|
247
|
+
* from the same document at the same instant. A container has no such pair.
|
|
248
|
+
* Its delivery total is summed over the emails that RECORDED a delivery count
|
|
249
|
+
* and its revenue over the emails that have a revenue record, and those are
|
|
250
|
+
* different subsets of the campaign — so the quotient would be an average
|
|
251
|
+
* over a population nobody named, which is the defect the whole reporting
|
|
252
|
+
* surface is built to refuse. The amounts are reported without one.
|
|
253
|
+
*
|
|
254
|
+
* @param rollups - one entry per email read, `undefined` where no record
|
|
255
|
+
* exists.
|
|
256
|
+
*/ export function campaignRevenueAcrossSends(rollups) {
|
|
257
|
+
const byCurrency = new Map();
|
|
258
|
+
const models = new Set();
|
|
259
|
+
const windows = new Set();
|
|
260
|
+
let recorded = 0;
|
|
261
|
+
for (const rollup of rollups){
|
|
262
|
+
var _rollup_model, _rollup_byCurrency;
|
|
263
|
+
if (!rollup) continue;
|
|
264
|
+
recorded += 1;
|
|
265
|
+
models.add(String((_rollup_model = rollup.model) != null ? _rollup_model : EMAIL_ATTRIBUTION_MODEL));
|
|
266
|
+
windows.add(count(rollup.windowDays) || EMAIL_ATTRIBUTION_WINDOW_DAYS);
|
|
267
|
+
for (const [code, stored] of Object.entries((_rollup_byCurrency = rollup.byCurrency) != null ? _rollup_byCurrency : {})){
|
|
268
|
+
var _byCurrency_get;
|
|
269
|
+
const currency = String(code).trim().toLowerCase();
|
|
270
|
+
if (!currency) continue;
|
|
271
|
+
const entry = (_byCurrency_get = byCurrency.get(currency)) != null ? _byCurrency_get : {
|
|
272
|
+
currency,
|
|
273
|
+
grossCents: 0,
|
|
274
|
+
refundedCents: 0,
|
|
275
|
+
netCents: 0,
|
|
276
|
+
orders: 0,
|
|
277
|
+
refundedOrders: 0,
|
|
278
|
+
emails: 0
|
|
279
|
+
};
|
|
280
|
+
entry.grossCents += count(stored == null ? void 0 : stored.grossCents);
|
|
281
|
+
entry.refundedCents += count(stored == null ? void 0 : stored.refundedCents);
|
|
282
|
+
entry.orders += count(stored == null ? void 0 : stored.orders);
|
|
283
|
+
entry.refundedOrders += count(stored == null ? void 0 : stored.refundedOrders);
|
|
284
|
+
// One rollup holds at most one bucket per currency, so this counts
|
|
285
|
+
// EMAILS that earned in it rather than orders.
|
|
286
|
+
entry.emails += 1;
|
|
287
|
+
byCurrency.set(currency, entry);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const currencies = [
|
|
291
|
+
...byCurrency.values()
|
|
292
|
+
].map((entry)=>_extends({}, entry, {
|
|
293
|
+
netCents: Math.max(0, entry.grossCents - entry.refundedCents)
|
|
294
|
+
})).filter((entry)=>entry.orders > 0 || entry.grossCents > 0).sort((a, b)=>b.netCents - a.netCents || a.currency.localeCompare(b.currency));
|
|
295
|
+
const multiCurrency = currencies.length > 1;
|
|
296
|
+
const caveats = [];
|
|
297
|
+
if (multiCurrency) {
|
|
298
|
+
caveats.push({
|
|
299
|
+
id: 'revenue-multi-currency',
|
|
300
|
+
message: REVENUE_MULTI_CURRENCY_MESSAGE
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
/*
|
|
304
|
+
* Two rules met in one figure, which is the currency problem in another
|
|
305
|
+
* dimension: a campaign whose older emails were credited under a different
|
|
306
|
+
* model or a different window holds amounts that were judged by different
|
|
307
|
+
* tests. They are still money in one unit, so unlike two currencies they
|
|
308
|
+
* add — the total stands, and the reader is told the rule behind it is not
|
|
309
|
+
* single.
|
|
310
|
+
*/ if (models.size > 1 || windows.size > 1) {
|
|
311
|
+
caveats.push({
|
|
312
|
+
id: 'revenue-mixed-model',
|
|
313
|
+
message: 'This campaign’s emails were not all credited under the same rule. ' + 'The amounts are real, but they were judged by different attribution ' + 'models or windows, so they are not strictly comparable with each ' + 'other.'
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
currencies,
|
|
318
|
+
attributedOrders: currencies.reduce((total, entry)=>total + entry.orders, 0),
|
|
319
|
+
read: rollups.length,
|
|
320
|
+
recorded,
|
|
321
|
+
multiCurrency,
|
|
322
|
+
models: [
|
|
323
|
+
...models
|
|
324
|
+
].sort(),
|
|
325
|
+
windowDays: [
|
|
326
|
+
...windows
|
|
327
|
+
].sort((a, b)=>a - b),
|
|
328
|
+
caveats
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
//# sourceMappingURL=campaign-revenue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/shared/ui/email-campaigns/src/lib/model/campaign-revenue.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`, not\n * from here. The writer is in `tenant-data-admin`, which may not import a\n * feature plugin, and a window defined on both sides of the join would drift\n * into a number credited under one rule and printed under another.\n */\nimport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n} from '@aglyn/shared-util-email'\nimport { campaignRate, type CampaignCaveat } from './campaign-report'\n\n/**\n * WHAT A CAMPAIGN EARNED — the read half of the commerce↔email join.\n *\n * ## Why this is a join and not an attribution model\n *\n * Every compared ESP reconstructs campaign revenue probabilistically, because\n * none of them owns the order. Klaviyo and Mailchimp watch someone else's\n * store through an integration and a browser snippet, so their figure is a\n * reconciliation against a foreign system and their window is the fudge\n * factor that makes the reconciliation close. Commerce here is first-party:\n * the click and the order are rows in one database, keyed the same way, so\n * the \"attribution\" is a lookup.\n *\n * That does not make the MODEL choice go away — two campaigns can both have\n * touched a buyer and only one can be credited — but it does mean the model\n * is the only judgement in the number. There is no sampling, no identity\n * resolution and no cookie.\n *\n * ## The model: LAST CLICK, inside a fixed 7-day window\n *\n * Stated in one sentence, which is the whole requirement: **an order is\n * credited to the last campaign whose link the buyer clicked, if they clicked\n * it within the {@link EMAIL_ATTRIBUTION_WINDOW_DAYS} days before they\n * ordered.**\n *\n * Three decisions are inside that sentence.\n *\n * **Last touch, not multi-touch.** Multi-touch is the more honest description\n * of how buying works and it is unpresentable: it splits one order across\n * several campaigns by a rule the merchant did not choose, so no campaign's\n * revenue is a number they can check against their own bank, and two\n * campaigns' figures cannot be added or compared without knowing the split\n * rule. HubSpot ships multi-touch and puts it behind an Enterprise plan and a\n * consultant. A figure a merchant cannot explain to themselves is worse than\n * no figure, and it is worse in the specific way that matters here: they will\n * still make decisions with it.\n *\n * **A CLICK is the touch. An open is not.** An open is evidence about the\n * recipient's mail client, not about the recipient — Apple's Mail Privacy\n * Protection prefetches images, which inflated network-wide open rates by\n * roughly 15% and means a large share of recorded opens had no human behind\n * them. Crediting revenue to an open would therefore credit campaigns for\n * orders from people who never saw them, and the error is not random: it\n * concentrates on whichever campaign most recently reached an Apple Mail\n * user. `email-delivery-log.ts` records the same preference for the same\n * reason, and the audience rules already segment on clicks over opens.\n *\n * **Seven days, and not configurable.** Klaviyo's window is 1–30 days per\n * channel; ActiveCampaign's is a fixed, unadjustable 7. Fixed is the better\n * default here because a configurable window is a setting whose change\n * silently rewrites history: yesterday's report and today's would disagree\n * about a campaign that has not been touched since, with nothing on screen to\n * say why. The stored record carries `windowDays` per order for exactly that\n * reason — a future setting can be added without making the orders already\n * attributed unreadable, because each one says which window it was judged\n * under.\n *\n * ## GROSS and REFUNDED, never a decrement\n *\n * A refunded order must stop counting as revenue a campaign earned, and there\n * are two ways to make it stop. Decrementing the gross figure makes a stored\n * number mean one thing before a refund and another after, with nothing to\n * distinguish them; recording the reversal beside it keeps both facts. This\n * is the shape `contact-refund.ts` chose for `ltvCents`/`refundedCents` on the\n * contact and the orders CSV chose for `amountUsd`/`refundedUsd`, and it is\n * chosen again here so all three answer \"what did this earn, net\" the same\n * way.\n *\n * So {@link campaignRevenueReport} reports gross, refunded and net, and NET\n * is the figure the screen leads with. Net is clamped at zero for display\n * only: a refund larger than the sale it reverses is arithmetically possible\n * on an order attributed before a partial refund settled, and a negative\n * campaign revenue is a sentence nobody can act on.\n *\n * ## Currencies are never summed\n *\n * Money is stored in minor units and no currency travels with it — every\n * checkout door in this repo sets `currency: 'usd'` on the Stripe line items,\n * so the amounts really are all USD, but that is a fact about the code rather\n * than a field on the order. The rollup therefore buckets BY currency and\n * this module never adds two buckets together. A campaign with two currencies\n * renders two blocks and no total, and says so.\n *\n * The rule survives the merge across a container's emails.\n * {@link campaignRevenueAcrossSends} keys its accumulator on the currency, so\n * two rollups can only ever meet inside a bucket they already share — there\n * is no code path in which a USD amount and a EUR amount reach the same\n * addition, and no combined figure exists for a screen to print by accident.\n */\n\n/**\n * Re-exported so a reader of the report has the window and the model name\n * without reaching past this module for them — the screen prints both, and a\n * window nobody can see is a window nobody can check.\n */\nexport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n EMAIL_ATTRIBUTION_WINDOW_MS,\n} from '@aglyn/shared-util-email'\n\n/** One currency's totals as the rollup stores them. */\nexport interface CampaignRevenueCurrencyStored {\n /** Minor units credited to this campaign, gross of refunds. */\n grossCents?: number\n /** Minor units handed back on orders that had been credited. */\n refundedCents?: number\n /** Orders credited to this campaign. */\n orders?: number\n /** Of those, how many ended fully reversed. */\n refundedOrders?: number\n}\n\n/**\n * The stored shape of `campaigns/{campaignId}/reports/revenue`.\n *\n * Its own document, for the reason the link rollup is its own document: the\n * campaign document is read by the history list, the glance widget and the\n * send path, and a map that grows with the campaign's sales would make every\n * one of those reads larger. Split, it is read by the one screen that draws\n * it.\n */\nexport interface CampaignRevenueRollup {\n byCurrency?: Record<string, CampaignRevenueCurrencyStored>\n /** The model the orders in this rollup were credited under. */\n model?: string\n /** The window, in days, they were credited inside. */\n windowDays?: number\n}\n\n/**\n * Money over a population, with the population named — {@link CampaignRate}'s\n * rule applied to an average instead of a share.\n *\n * A percentage and an average go wrong the same way, so they carry the same\n * guarantee: the denominator travels as data and the screen has to print it.\n * \"$0.42 per recipient\" over an audience nobody named is the figure this\n * whole reporting surface exists to refuse.\n */\nexport interface CampaignMoneyPerMessage {\n /** Minor units per message of the denominator. Fractional by nature. */\n cents: number\n numeratorCents: number\n denominator: number\n denominatorLabel: string\n currency: string\n}\n\n/** One currency's block on screen. */\nexport interface CampaignRevenueCurrencyReport {\n /** Lowercase ISO code as the sale recorded it, e.g. `'usd'`. */\n currency: string\n grossCents: number\n refundedCents: number\n /** `gross - refunded`, clamped at zero. */\n netCents: number\n orders: number\n refundedOrders: number\n /**\n * Net revenue per DELIVERED message, or `null` when it cannot be taken.\n *\n * Delivered is the denominator for the same reason every engagement rate on\n * this report is taken over it: mail that bounced was never in front of a\n * human, so counting it depresses a figure describing the audience with a\n * fact about the address list.\n *\n * It is deliberately NOT taken over `audienceSize`. That figure is written\n * by the FIRST batch only and is a floor when audience resolution hit its\n * read ceiling, so a campaign delivered over six runs would divide six\n * runs' revenue by one run's measure of the audience — the stale-population\n * division this surface is built to make impossible.\n */\n netPerDelivered: CampaignMoneyPerMessage | null\n}\n\n/** Everything the revenue section renders. */\nexport interface CampaignRevenueReport {\n /** One block per currency, largest net first. Never summed together. */\n currencies: CampaignRevenueCurrencyReport[]\n /** Orders credited to this campaign, across every currency. */\n attributedOrders: number\n /**\n * Whether any attribution has ever been recorded for this campaign.\n *\n * `false` means the rollup document does not exist, which is NOT the same\n * as \"this campaign earned nothing\" — it is also every campaign sent before\n * the join existed, and every campaign on a site with no store. The screen\n * renders the difference rather than printing a zero for both.\n */\n recorded: boolean\n /** More than one currency is present, so no total may be shown. */\n multiCurrency: 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 * Why there is no total, in the words both reports use.\n *\n * One sentence, one definition. A send's report and its campaign's report\n * make the same refusal for the same reason, and two copies of the sentence\n * is how one of them comes to be softened into a promise of a total.\n */\nexport const REVENUE_MULTI_CURRENCY_MESSAGE =\n 'This campaign earned in more than one currency. Each is reported on its ' +\n 'own — nothing here converts between them, so there is deliberately no ' +\n 'combined total.'\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/**\n * Money per message, or `null` when the division cannot honestly be taken.\n *\n * The three refusals are {@link campaignRate}'s, and this defers to it rather\n * than restating them: a zero denominator, an unrecorded denominator, and a\n * non-finite input all answer `null` there, so a second implementation of\n * \"when may we divide\" cannot drift from the first.\n */\nexport function campaignMoneyPerMessage(\n numeratorCents: number,\n denominator: number | undefined,\n denominatorLabel: string,\n currency: string,\n): CampaignMoneyPerMessage | null {\n const divisible = campaignRate(numeratorCents, denominator, denominatorLabel)\n if (!divisible) return null\n return {\n cents: divisible.value,\n numeratorCents: divisible.numerator,\n denominator: divisible.denominator,\n denominatorLabel,\n currency,\n }\n}\n\n/**\n * Turns the stored rollup into the revenue section.\n *\n * `delivered` comes from the campaign's own `stats` and is passed in rather\n * than re-read, so the numerator and the denominator on screen are taken from\n * the same instant. It is `null` when no delivery event has ever been\n * recorded — the campaign predates the delivery webhook, or the events are\n * still in flight — and every figure over it is then withheld with a caveat,\n * never substituted for `sent`.\n */\nexport function campaignRevenueReport(options: {\n rollup: CampaignRevenueRollup | undefined\n /** `stats.delivered`, or `null` when it was never recorded. */\n delivered: number | null\n /** True while the send is still working through its audience. */\n midFlight?: boolean\n}): CampaignRevenueReport {\n const { rollup, delivered, midFlight } = options\n const stored = rollup?.byCurrency ?? {}\n const caveats: CampaignCaveat[] = []\n\n const currencies: CampaignRevenueCurrencyReport[] = Object.entries(stored)\n .map(([currency, totals]) => {\n const grossCents = count(totals?.grossCents)\n const refundedCents = count(totals?.refundedCents)\n /*\n * CLAMPED, and only here at the point of display.\n *\n * Both stored figures are monotonic counters of money that really\n * moved in one direction, so neither can be negative; their DIFFERENCE\n * can be, for one reason — an order credited to a campaign and then\n * refunded by more than the amount that was credited, which happens\n * when a partial refund settles against an order whose attributed\n * amount was the charge at the time. Clamping at write time would\n * erase the evidence; clamping at read time keeps the stored pair\n * intact and stops the screen printing a campaign with negative\n * earnings, which is not a sentence anybody can act on.\n */\n const netCents = Math.max(0, grossCents - refundedCents)\n return {\n currency,\n grossCents,\n refundedCents,\n netCents,\n orders: count(totals?.orders),\n refundedOrders: count(totals?.refundedOrders),\n netPerDelivered: campaignMoneyPerMessage(\n netCents,\n delivered ?? undefined,\n 'delivered',\n currency,\n ),\n }\n })\n .filter((entry) => entry.orders > 0 || entry.grossCents > 0)\n .sort(\n (a, b) => b.netCents - a.netCents || a.currency.localeCompare(b.currency),\n )\n\n const attributedOrders = currencies.reduce(\n (total, entry) => total + entry.orders,\n 0,\n )\n const multiCurrency = currencies.length > 1\n\n if (delivered === null && currencies.length) {\n caveats.push({\n id: 'revenue-denominator-unrecorded',\n message:\n 'No delivery events have been recorded for this campaign, so revenue ' +\n 'per delivered message cannot be computed. The amounts below are ' +\n 'still real.',\n })\n }\n if (multiCurrency) {\n caveats.push({\n id: 'revenue-multi-currency',\n message: REVENUE_MULTI_CURRENCY_MESSAGE,\n })\n }\n if (midFlight && currencies.length) {\n caveats.push({\n id: 'revenue-mid-flight',\n message:\n 'This campaign is still going out. Revenue and delivered messages ' +\n 'are both still rising, so every figure below is a running total ' +\n 'rather than a final one.',\n })\n }\n\n return {\n currencies,\n attributedOrders,\n recorded: rollup !== undefined,\n multiCurrency,\n model: String(rollup?.model ?? EMAIL_ATTRIBUTION_MODEL),\n windowDays: count(rollup?.windowDays) || EMAIL_ATTRIBUTION_WINDOW_DAYS,\n caveats,\n }\n}\n\n/** One currency's totals, merged across a campaign's emails. */\nexport interface CampaignRevenueCurrencyAcrossSends {\n /** Lowercase ISO code as the sales recorded it, e.g. `'usd'`. */\n currency: string\n grossCents: number\n refundedCents: number\n /** `gross - refunded` over the whole campaign, clamped once at zero. */\n netCents: number\n orders: number\n refundedOrders: number\n /** Emails of the campaign whose revenue record holds this currency. */\n emails: number\n}\n\n/** Everything a campaign container's revenue section renders. */\nexport interface CampaignRevenueAcrossSends {\n /** One block per currency, largest net first. Never summed together. */\n currencies: CampaignRevenueCurrencyAcrossSends[]\n /**\n * Orders credited across every currency.\n *\n * A COUNT, which is why it may cross currencies when the money may not: an\n * order is one order whatever it was paid in, and counting two of them\n * loses nothing. Adding their amounts loses the unit.\n */\n attributedOrders: number\n /** Emails whose revenue record was looked for. */\n read: number\n /**\n * Of those, how many have a revenue record at all.\n *\n * The rollup is created by the attribution writer on the first order it\n * credits, so an email with no record has never been credited with one.\n * Zero across the whole campaign is therefore the container's version of\n * {@link CampaignRevenueReport.recorded} being `false`: it is not \"this\n * campaign earned nothing\", it is also every campaign sent before the join\n * existed and every campaign on a site with no store.\n */\n recorded: number\n /** More than one currency is present, so no total may be shown. */\n multiCurrency: boolean\n /** The models these emails were credited under, distinct and sorted. */\n models: string[]\n /** The windows, in days, they were credited inside, distinct and sorted. */\n windowDays: number[]\n caveats: CampaignCaveat[]\n}\n\n/**\n * MERGES A CAMPAIGN'S EMAILS INTO ONE REVENUE SECTION, per currency.\n *\n * `reports/revenue` is written per SEND, so a container's figure is one\n * document per email and a merge. The merge is the whole risk: two emails of\n * one campaign can have earned in different currencies, and adding their\n * amounts produces a number that is wrong with nothing on screen to show it.\n *\n * ## The currency is the accumulator's KEY, not a field beside the amount\n *\n * That is the structural half of the guarantee. Amounts are added into a map\n * keyed by currency, so two amounts can only reach the same addition when\n * they already carry the same code — a USD figure and a EUR figure have no\n * path to each other, whatever a later caller asks for. There is no combined\n * field on the result, so a screen cannot print a cross-currency total by\n * reading the wrong property, and\n * {@link CampaignRevenueAcrossSends.multiCurrency} is what tells the screen\n * to label the blocks.\n *\n * ## Clamped ONCE, over the campaign\n *\n * The single-send report clamps its net at zero because a partial refund can\n * settle against an order credited at the full charge. Doing that per email\n * and then summing would let one over-refunded email keep money a sibling\n * email handed back — an email at -$50 clamped to $0 beside one at $200 would\n * report $200 for a campaign holding $150. So gross and refunded are summed\n * as they stand and the difference is clamped once, at the end.\n *\n * ## No per-message average, deliberately\n *\n * The send report divides net revenue by that send's own `delivered`, taken\n * from the same document at the same instant. A container has no such pair.\n * Its delivery total is summed over the emails that RECORDED a delivery count\n * and its revenue over the emails that have a revenue record, and those are\n * different subsets of the campaign — so the quotient would be an average\n * over a population nobody named, which is the defect the whole reporting\n * surface is built to refuse. The amounts are reported without one.\n *\n * @param rollups - one entry per email read, `undefined` where no record\n * exists.\n */\nexport function campaignRevenueAcrossSends(\n rollups: readonly (CampaignRevenueRollup | undefined)[],\n): CampaignRevenueAcrossSends {\n const byCurrency = new Map<string, CampaignRevenueCurrencyAcrossSends>()\n const models = new Set<string>()\n const windows = new Set<number>()\n let recorded = 0\n\n for (const rollup of rollups) {\n if (!rollup) continue\n recorded += 1\n models.add(String(rollup.model ?? EMAIL_ATTRIBUTION_MODEL))\n windows.add(count(rollup.windowDays) || EMAIL_ATTRIBUTION_WINDOW_DAYS)\n for (const [code, stored] of Object.entries(rollup.byCurrency ?? {})) {\n const currency = String(code).trim().toLowerCase()\n if (!currency) continue\n const entry = byCurrency.get(currency) ?? {\n currency,\n grossCents: 0,\n refundedCents: 0,\n netCents: 0,\n orders: 0,\n refundedOrders: 0,\n emails: 0,\n }\n entry.grossCents += count(stored?.grossCents)\n entry.refundedCents += count(stored?.refundedCents)\n entry.orders += count(stored?.orders)\n entry.refundedOrders += count(stored?.refundedOrders)\n // One rollup holds at most one bucket per currency, so this counts\n // EMAILS that earned in it rather than orders.\n entry.emails += 1\n byCurrency.set(currency, entry)\n }\n }\n\n const currencies = [...byCurrency.values()]\n .map((entry) => ({\n ...entry,\n netCents: Math.max(0, entry.grossCents - entry.refundedCents),\n }))\n .filter((entry) => entry.orders > 0 || entry.grossCents > 0)\n .sort(\n (a, b) => b.netCents - a.netCents || a.currency.localeCompare(b.currency),\n )\n\n const multiCurrency = currencies.length > 1\n const caveats: CampaignCaveat[] = []\n if (multiCurrency) {\n caveats.push({\n id: 'revenue-multi-currency',\n message: REVENUE_MULTI_CURRENCY_MESSAGE,\n })\n }\n /*\n * Two rules met in one figure, which is the currency problem in another\n * dimension: a campaign whose older emails were credited under a different\n * model or a different window holds amounts that were judged by different\n * tests. They are still money in one unit, so unlike two currencies they\n * add — the total stands, and the reader is told the rule behind it is not\n * single.\n */\n if (models.size > 1 || windows.size > 1) {\n caveats.push({\n id: 'revenue-mixed-model',\n message:\n 'This campaign’s emails were not all credited under the same rule. ' +\n 'The amounts are real, but they were judged by different attribution ' +\n 'models or windows, so they are not strictly comparable with each ' +\n 'other.',\n })\n }\n\n return {\n currencies,\n attributedOrders: currencies.reduce(\n (total, entry) => total + entry.orders,\n 0,\n ),\n read: rollups.length,\n recorded,\n multiCurrency,\n models: [...models].sort(),\n windowDays: [...windows].sort((a, b) => a - b),\n caveats,\n }\n}\n"],"names":["EMAIL_ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","campaignRate","EMAIL_ATTRIBUTION_WINDOW_MS","REVENUE_MULTI_CURRENCY_MESSAGE","count","raw","value","Math","floor","Number","isFinite","campaignMoneyPerMessage","numeratorCents","denominator","denominatorLabel","currency","divisible","cents","numerator","campaignRevenueReport","options","rollup","delivered","midFlight","stored","byCurrency","caveats","currencies","Object","entries","map","totals","grossCents","refundedCents","netCents","max","orders","refundedOrders","netPerDelivered","undefined","filter","entry","sort","a","b","localeCompare","attributedOrders","reduce","total","multiCurrency","length","push","id","message","recorded","model","String","windowDays","campaignRevenueAcrossSends","rollups","Map","models","Set","windows","add","code","trim","toLowerCase","get","emails","set","values","size","read"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GACD,SACEA,uBAAuB,EACvBC,6BAA6B,QACxB,2BAA0B;AACjC,SAASC,YAAY,QAA6B,uBAAmB;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwFC,GAED;;;;CAIC,GACD,SACEF,uBAAuB,EACvBC,6BAA6B,EAC7BE,2BAA2B,QACtB,2BAA0B;AAoGjC;;;;;;CAMC,GACD,OAAO,MAAMC,iCACX,6EACA,2EACA,kBAAiB;AAEnB,8CAA8C,GAC9C,SAASC,MAAMC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AI,GAAG,KAAKT,QAAQS,IAAI,GAAG,GAAG;QACvC9C,QAAQyB,IAAI,CAAC;YACXC,IAAI;YACJC,SACE,uEACA,yEACA,sEACA;QACJ;IACF;IAEA,OAAO;QACL1B;QACAmB,kBAAkBnB,WAAWoB,MAAM,CACjC,CAACC,OAAOP,QAAUO,QAAQP,MAAML,MAAM,EACtC;QAEFqC,MAAMd,QAAQT,MAAM;QACpBI;QACAL;QACAY,QAAQ;eAAIA;SAAO,CAACnB,IAAI;QACxBe,YAAY;eAAIM;SAAQ,CAACrB,IAAI,CAAC,CAACC,GAAGC,IAAMD,IAAIC;QAC5ClB;IACF;AACF"}
|
|
@@ -0,0 +1,74 @@
|
|
|
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
|
+
* WHEN A LIST READS ITS MAIL: a suggested send time, taken from the sends that
|
|
19
|
+
* already went to it.
|
|
20
|
+
*
|
|
21
|
+
* A rule and not a guess. Each past send is put in the slot it went out in —
|
|
22
|
+
* its weekday and hour, in one named time zone — and the slot whose sends were
|
|
23
|
+
* opened by the largest share of the people they reached is the suggestion.
|
|
24
|
+
* The share is POOLED across a slot's sends (every unique open over every
|
|
25
|
+
* delivered message) rather than averaged, so one small send that happened to
|
|
26
|
+
* be opened by all nine of its recipients does not outrank a slot that reached
|
|
27
|
+
* thousands.
|
|
28
|
+
*
|
|
29
|
+
* Only sends that can be measured are counted: a send with no delivered count
|
|
30
|
+
* large enough to say anything is left out, and so is one whose opens exceed
|
|
31
|
+
* its deliveries, which is a record that disagrees with itself. With fewer
|
|
32
|
+
* measured sends than the minimum there is no suggestion at all — "not enough
|
|
33
|
+
* history" is an answer a composer can say, and a slot picked from one send is
|
|
34
|
+
* not.
|
|
35
|
+
*
|
|
36
|
+
* Pure, with the reads left to the caller that holds the credentials.
|
|
37
|
+
*/
|
|
38
|
+
/** One past send to the list, as the suggestion needs it. */
|
|
39
|
+
export interface CampaignSendTimeSample {
|
|
40
|
+
/** When the send went out. */
|
|
41
|
+
sentAtMs: number;
|
|
42
|
+
/** Messages the provider delivered. */
|
|
43
|
+
delivered: number;
|
|
44
|
+
/** Distinct recipients who opened it. */
|
|
45
|
+
uniqueOpens: number;
|
|
46
|
+
}
|
|
47
|
+
export interface CampaignSendTimeSuggestion {
|
|
48
|
+
/** 0 for Sunday through 6 for Saturday, in `timeZone`. */
|
|
49
|
+
weekday: number;
|
|
50
|
+
/** 0 to 23, in `timeZone`. */
|
|
51
|
+
hour: number;
|
|
52
|
+
/** The IANA zone the slot is stated in. */
|
|
53
|
+
timeZone: string;
|
|
54
|
+
/** The pooled unique-open rate of the sends in the slot, 0 to 1. */
|
|
55
|
+
openRate: number;
|
|
56
|
+
/** Measured sends that went out in the slot. */
|
|
57
|
+
sends: number;
|
|
58
|
+
/** Measured sends the slot was chosen among. */
|
|
59
|
+
measured: number;
|
|
60
|
+
}
|
|
61
|
+
/** The fewest measured sends a suggestion is taken from. */
|
|
62
|
+
export declare const CAMPAIGN_SEND_TIME_MIN_SENDS = 3;
|
|
63
|
+
/** The fewest delivered messages that make a send measurable. */
|
|
64
|
+
export declare const CAMPAIGN_SEND_TIME_MIN_DELIVERED = 20;
|
|
65
|
+
/**
|
|
66
|
+
* The slot the list's past sends were opened most in, or `null` when too few
|
|
67
|
+
* sends can be measured. An unknown time zone is read as UTC, and the answer
|
|
68
|
+
* says so.
|
|
69
|
+
*/
|
|
70
|
+
export declare function suggestCampaignSendTime(samples: ReadonlyArray<CampaignSendTimeSample>, options?: {
|
|
71
|
+
timeZone?: string;
|
|
72
|
+
}): CampaignSendTimeSuggestion | null;
|
|
73
|
+
/** The slot as a person reads it: "Tuesdays around 9 AM (UTC)". */
|
|
74
|
+
export declare function campaignSendTimeLabel(suggestion: Pick<CampaignSendTimeSuggestion, 'weekday' | 'hour' | 'timeZone'>): string;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { campaignRate } from "./campaign-report.js";
|
|
18
|
+
/** The fewest measured sends a suggestion is taken from. */ export const CAMPAIGN_SEND_TIME_MIN_SENDS = 3;
|
|
19
|
+
/** The fewest delivered messages that make a send measurable. */ export const CAMPAIGN_SEND_TIME_MIN_DELIVERED = 20;
|
|
20
|
+
const WEEKDAYS = {
|
|
21
|
+
Sun: 0,
|
|
22
|
+
Mon: 1,
|
|
23
|
+
Tue: 2,
|
|
24
|
+
Wed: 3,
|
|
25
|
+
Thu: 4,
|
|
26
|
+
Fri: 5,
|
|
27
|
+
Sat: 6
|
|
28
|
+
};
|
|
29
|
+
const WEEKDAY_NAMES = [
|
|
30
|
+
'Sunday',
|
|
31
|
+
'Monday',
|
|
32
|
+
'Tuesday',
|
|
33
|
+
'Wednesday',
|
|
34
|
+
'Thursday',
|
|
35
|
+
'Friday',
|
|
36
|
+
'Saturday'
|
|
37
|
+
];
|
|
38
|
+
function slotFormatter(timeZone) {
|
|
39
|
+
try {
|
|
40
|
+
return new Intl.DateTimeFormat('en-US', {
|
|
41
|
+
timeZone,
|
|
42
|
+
weekday: 'short',
|
|
43
|
+
hour: 'numeric',
|
|
44
|
+
hourCycle: 'h23'
|
|
45
|
+
});
|
|
46
|
+
} catch (unused) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** The weekday and hour an instant falls in, in a zone. */ function slotOf(formatter, atMs) {
|
|
51
|
+
let weekday;
|
|
52
|
+
let hour;
|
|
53
|
+
for (const part of formatter.formatToParts(new Date(atMs))){
|
|
54
|
+
if (part.type === 'weekday') weekday = WEEKDAYS[part.value];
|
|
55
|
+
if (part.type === 'hour') hour = Number(part.value) % 24;
|
|
56
|
+
}
|
|
57
|
+
return weekday === undefined || hour === undefined || !Number.isFinite(hour) ? null : {
|
|
58
|
+
weekday,
|
|
59
|
+
hour
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The slot the list's past sends were opened most in, or `null` when too few
|
|
64
|
+
* sends can be measured. An unknown time zone is read as UTC, and the answer
|
|
65
|
+
* says so.
|
|
66
|
+
*/ export function suggestCampaignSendTime(samples, options = {}) {
|
|
67
|
+
var _slotFormatter;
|
|
68
|
+
var _options_timeZone;
|
|
69
|
+
const requested = ((_options_timeZone = options.timeZone) == null ? void 0 : _options_timeZone.trim()) || 'UTC';
|
|
70
|
+
const formatter = (_slotFormatter = slotFormatter(requested)) != null ? _slotFormatter : slotFormatter('UTC');
|
|
71
|
+
const timeZone = slotFormatter(requested) ? requested : 'UTC';
|
|
72
|
+
if (!formatter) return null;
|
|
73
|
+
const slots = new Map();
|
|
74
|
+
let measured = 0;
|
|
75
|
+
for (const sample of samples){
|
|
76
|
+
var _slots_get;
|
|
77
|
+
const delivered = Number(sample.delivered);
|
|
78
|
+
const opens = Number(sample.uniqueOpens);
|
|
79
|
+
if (!Number.isFinite(sample.sentAtMs) || sample.sentAtMs <= 0) continue;
|
|
80
|
+
if (!Number.isFinite(delivered) || delivered < CAMPAIGN_SEND_TIME_MIN_DELIVERED) continue;
|
|
81
|
+
if (!Number.isFinite(opens) || opens < 0 || opens > delivered) continue;
|
|
82
|
+
const slot = slotOf(formatter, sample.sentAtMs);
|
|
83
|
+
if (!slot) continue;
|
|
84
|
+
measured += 1;
|
|
85
|
+
const key = `${slot.weekday}:${slot.hour}`;
|
|
86
|
+
const held = (_slots_get = slots.get(key)) != null ? _slots_get : _extends({}, slot, {
|
|
87
|
+
delivered: 0,
|
|
88
|
+
opens: 0,
|
|
89
|
+
sends: 0
|
|
90
|
+
});
|
|
91
|
+
held.delivered += delivered;
|
|
92
|
+
held.opens += opens;
|
|
93
|
+
held.sends += 1;
|
|
94
|
+
slots.set(key, held);
|
|
95
|
+
}
|
|
96
|
+
if (measured < CAMPAIGN_SEND_TIME_MIN_SENDS) return null;
|
|
97
|
+
let best = null;
|
|
98
|
+
for (const slot of slots.values()){
|
|
99
|
+
const rate = campaignRate(slot.opens, slot.delivered, 'delivered');
|
|
100
|
+
if (!rate) continue;
|
|
101
|
+
const candidate = {
|
|
102
|
+
weekday: slot.weekday,
|
|
103
|
+
hour: slot.hour,
|
|
104
|
+
timeZone,
|
|
105
|
+
openRate: rate.value,
|
|
106
|
+
sends: slot.sends,
|
|
107
|
+
measured
|
|
108
|
+
};
|
|
109
|
+
const better = !best || candidate.openRate > best.openRate || candidate.openRate === best.openRate && (candidate.sends > best.sends || candidate.sends === best.sends && candidate.weekday * 24 + candidate.hour < best.weekday * 24 + best.hour);
|
|
110
|
+
if (better) best = candidate;
|
|
111
|
+
}
|
|
112
|
+
return best;
|
|
113
|
+
}
|
|
114
|
+
/** The slot as a person reads it: "Tuesdays around 9 AM (UTC)". */ export function campaignSendTimeLabel(suggestion) {
|
|
115
|
+
const hour12 = suggestion.hour % 12 === 0 ? 12 : suggestion.hour % 12;
|
|
116
|
+
const meridiem = suggestion.hour < 12 ? 'AM' : 'PM';
|
|
117
|
+
return `${WEEKDAY_NAMES[suggestion.weekday]}s around ${hour12} ${meridiem} (${suggestion.timeZone})`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=campaign-send-time.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/shared/ui/email-campaigns/src/lib/model/campaign-send-time.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { campaignRate } from './campaign-report'\n\n/**\n * WHEN A LIST READS ITS MAIL: a suggested send time, taken from the sends that\n * already went to it.\n *\n * A rule and not a guess. Each past send is put in the slot it went out in —\n * its weekday and hour, in one named time zone — and the slot whose sends were\n * opened by the largest share of the people they reached is the suggestion.\n * The share is POOLED across a slot's sends (every unique open over every\n * delivered message) rather than averaged, so one small send that happened to\n * be opened by all nine of its recipients does not outrank a slot that reached\n * thousands.\n *\n * Only sends that can be measured are counted: a send with no delivered count\n * large enough to say anything is left out, and so is one whose opens exceed\n * its deliveries, which is a record that disagrees with itself. With fewer\n * measured sends than the minimum there is no suggestion at all — \"not enough\n * history\" is an answer a composer can say, and a slot picked from one send is\n * not.\n *\n * Pure, with the reads left to the caller that holds the credentials.\n */\n\n/** One past send to the list, as the suggestion needs it. */\nexport interface CampaignSendTimeSample {\n /** When the send went out. */\n sentAtMs: number\n /** Messages the provider delivered. */\n delivered: number\n /** Distinct recipients who opened it. */\n uniqueOpens: number\n}\n\nexport interface CampaignSendTimeSuggestion {\n /** 0 for Sunday through 6 for Saturday, in `timeZone`. */\n weekday: number\n /** 0 to 23, in `timeZone`. */\n hour: number\n /** The IANA zone the slot is stated in. */\n timeZone: string\n /** The pooled unique-open rate of the sends in the slot, 0 to 1. */\n openRate: number\n /** Measured sends that went out in the slot. */\n sends: number\n /** Measured sends the slot was chosen among. */\n measured: number\n}\n\n/** The fewest measured sends a suggestion is taken from. */\nexport const CAMPAIGN_SEND_TIME_MIN_SENDS = 3\n\n/** The fewest delivered messages that make a send measurable. */\nexport const CAMPAIGN_SEND_TIME_MIN_DELIVERED = 20\n\nconst WEEKDAYS: Record<string, number> = {\n Sun: 0,\n Mon: 1,\n Tue: 2,\n Wed: 3,\n Thu: 4,\n Fri: 5,\n Sat: 6,\n}\n\nconst WEEKDAY_NAMES = [\n 'Sunday',\n 'Monday',\n 'Tuesday',\n 'Wednesday',\n 'Thursday',\n 'Friday',\n 'Saturday',\n]\n\nfunction slotFormatter(timeZone: string): Intl.DateTimeFormat | null {\n try {\n return new Intl.DateTimeFormat('en-US', {\n timeZone,\n weekday: 'short',\n hour: 'numeric',\n hourCycle: 'h23',\n })\n } catch {\n return null\n }\n}\n\n/** The weekday and hour an instant falls in, in a zone. */\nfunction slotOf(\n formatter: Intl.DateTimeFormat,\n atMs: number,\n): { weekday: number; hour: number } | null {\n let weekday: number | undefined\n let hour: number | undefined\n for (const part of formatter.formatToParts(new Date(atMs))) {\n if (part.type === 'weekday') weekday = WEEKDAYS[part.value]\n if (part.type === 'hour') hour = Number(part.value) % 24\n }\n return weekday === undefined || hour === undefined || !Number.isFinite(hour)\n ? null\n : { weekday, hour }\n}\n\n/**\n * The slot the list's past sends were opened most in, or `null` when too few\n * sends can be measured. An unknown time zone is read as UTC, and the answer\n * says so.\n */\nexport function suggestCampaignSendTime(\n samples: ReadonlyArray<CampaignSendTimeSample>,\n options: { timeZone?: string } = {},\n): CampaignSendTimeSuggestion | null {\n const requested = options.timeZone?.trim() || 'UTC'\n const formatter = slotFormatter(requested) ?? slotFormatter('UTC')\n const timeZone = slotFormatter(requested) ? requested : 'UTC'\n if (!formatter) return null\n const slots = new Map<string, { weekday: number; hour: number; delivered: number; opens: number; sends: number }>()\n let measured = 0\n for (const sample of samples) {\n const delivered = Number(sample.delivered)\n const opens = Number(sample.uniqueOpens)\n if (!Number.isFinite(sample.sentAtMs) || sample.sentAtMs <= 0) continue\n if (!Number.isFinite(delivered) || delivered < CAMPAIGN_SEND_TIME_MIN_DELIVERED) continue\n if (!Number.isFinite(opens) || opens < 0 || opens > delivered) continue\n const slot = slotOf(formatter, sample.sentAtMs)\n if (!slot) continue\n measured += 1\n const key = `${slot.weekday}:${slot.hour}`\n const held = slots.get(key) ?? { ...slot, delivered: 0, opens: 0, sends: 0 }\n held.delivered += delivered\n held.opens += opens\n held.sends += 1\n slots.set(key, held)\n }\n if (measured < CAMPAIGN_SEND_TIME_MIN_SENDS) return null\n let best: CampaignSendTimeSuggestion | null = null\n for (const slot of slots.values()) {\n const rate = campaignRate(slot.opens, slot.delivered, 'delivered')\n if (!rate) continue\n const candidate: CampaignSendTimeSuggestion = {\n weekday: slot.weekday,\n hour: slot.hour,\n timeZone,\n openRate: rate.value,\n sends: slot.sends,\n measured,\n }\n const better =\n !best ||\n candidate.openRate > best.openRate ||\n (candidate.openRate === best.openRate &&\n (candidate.sends > best.sends ||\n (candidate.sends === best.sends &&\n candidate.weekday * 24 + candidate.hour < best.weekday * 24 + best.hour)))\n if (better) best = candidate\n }\n return best\n}\n\n/** The slot as a person reads it: \"Tuesdays around 9 AM (UTC)\". */\nexport function campaignSendTimeLabel(\n suggestion: Pick<CampaignSendTimeSuggestion, 'weekday' | 'hour' | 'timeZone'>,\n): string {\n const hour12 = suggestion.hour % 12 === 0 ? 12 : suggestion.hour % 12\n const meridiem = suggestion.hour < 12 ? 'AM' : 'PM'\n return `${WEEKDAY_NAMES[suggestion.weekday]}s around ${hour12} ${meridiem} (${suggestion.timeZone})`\n}\n"],"names":["campaignRate","CAMPAIGN_SEND_TIME_MIN_SENDS","CAMPAIGN_SEND_TIME_MIN_DELIVERED","WEEKDAYS","Sun","Mon","Tue","Wed","Thu","Fri","Sat","WEEKDAY_NAMES","slotFormatter","timeZone","Intl","DateTimeFormat","weekday","hour","hourCycle","slotOf","formatter","atMs","part","formatToParts","Date","type","value","Number","undefined","isFinite","suggestCampaignSendTime","samples","options","requested","trim","slots","Map","measured","sample","delivered","opens","uniqueOpens","sentAtMs","slot","key","held","get","sends","set","best","values","rate","candidate","openRate","better","campaignSendTimeLabel","suggestion","hour12","meridiem"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAQ,uBAAmB;AAiDhD,0DAA0D,GAC1D,OAAO,MAAMC,+BAA+B,EAAC;AAE7C,+DAA+D,GAC/D,OAAO,MAAMC,mCAAmC,GAAE;AAElD,MAAMC,WAAmC;IACvCC,KAAK;IACLC,KAAK;IACLC,KAAK;IACLC,KAAK;IACLC,KAAK;IACLC,KAAK;IACLC,KAAK;AACP;AAEA,MAAMC,gBAAgB;IACpB;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,SAASC,cAAcC,QAAgB;IACrC,IAAI;QACF,OAAO,IAAIC,KAAKC,cAAc,CAAC,SAAS;YACtCF;YACAG,SAAS;YACTC,MAAM;YACNC,WAAW;QACb;IACF,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,yDAAyD,GACzD,SAASC,OACPC,SAA8B,EAC9BC,IAAY;IAEZ,IAAIL;IACJ,IAAIC;IACJ,KAAK,MAAMK,QAAQF,UAAUG,aAAa,CAAC,IAAIC,KAAKH,OAAQ;QAC1D,IAAIC,KAAKG,IAAI,KAAK,WAAWT,UAAUb,QAAQ,CAACmB,KAA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