@aglyn/tenant-data-admin 1.0.0-beta.221 → 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.
- package/package.json +7 -7
- package/src/lib/server/api-keys.js +3 -3
- package/src/lib/server/api-keys.js.map +1 -1
- package/src/lib/server/api-v1-resources.d.ts +44 -3
- package/src/lib/server/api-v1-resources.js +82 -5
- package/src/lib/server/api-v1-resources.js.map +1 -1
- package/src/lib/server/collection-live-pages.d.ts +2 -2
- package/src/lib/server/collection-live-pages.js +1 -1
- package/src/lib/server/collection-live-pages.js.map +1 -1
- package/src/lib/server/email-delivery-log.d.ts +17 -73
- package/src/lib/server/email-delivery-log.js +44 -222
- package/src/lib/server/email-delivery-log.js.map +1 -1
- package/src/lib/server/email-flow-gate.js +27 -38
- package/src/lib/server/email-flow-gate.js.map +1 -1
- package/src/lib/server/erase-person.d.ts +34 -54
- package/src/lib/server/erase-person.js +44 -239
- package/src/lib/server/erase-person.js.map +1 -1
- package/src/lib/server/host-visitor-records.d.ts +12 -4
- package/src/lib/server/host-visitor-records.js +20 -10
- package/src/lib/server/host-visitor-records.js.map +1 -1
- package/src/lib/server/hosted-page-review.js +46 -33
- package/src/lib/server/hosted-page-review.js.map +1 -1
- package/src/lib/server/link-reputation-review.d.ts +6 -2
- package/src/lib/server/link-reputation-review.js +61 -20
- package/src/lib/server/link-reputation-review.js.map +1 -1
- package/src/lib/server/live-page-drops.d.ts +67 -0
- package/src/lib/server/live-page-drops.js +57 -0
- package/src/lib/server/live-page-drops.js.map +1 -0
- package/src/lib/server/media-bandwidth-cap.d.ts +78 -0
- package/src/lib/server/media-bandwidth-cap.js +180 -0
- package/src/lib/server/media-bandwidth-cap.js.map +1 -0
- package/src/lib/server/media-cdn-icon.d.ts +77 -0
- package/src/lib/server/media-cdn-icon.js +140 -0
- package/src/lib/server/media-cdn-icon.js.map +1 -0
- package/src/lib/server/media-delivery-regeneration.d.ts +132 -0
- package/src/lib/server/media-delivery-regeneration.js +216 -0
- package/src/lib/server/media-delivery-regeneration.js.map +1 -0
- package/src/lib/server/media-delivery.d.ts +2 -0
- package/src/lib/server/media-delivery.js +2 -1
- package/src/lib/server/media-delivery.js.map +1 -1
- package/src/lib/server/media-serve-count.d.ts +50 -0
- package/src/lib/server/media-serve-count.js +62 -0
- package/src/lib/server/media-serve-count.js.map +1 -0
- package/src/lib/server/media-signing.d.ts +13 -2
- package/src/lib/server/media-signing.js +12 -8
- package/src/lib/server/media-signing.js.map +1 -1
- package/src/lib/server/media-tombstone.js +7 -5
- package/src/lib/server/media-tombstone.js.map +1 -1
- package/src/lib/server/media-variants.d.ts +151 -20
- package/src/lib/server/media-variants.js +204 -27
- package/src/lib/server/media-variants.js.map +1 -1
- package/src/lib/server/organizations.d.ts +102 -2
- package/src/lib/server/organizations.js +388 -58
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/outbound-send-review.js +5 -4
- package/src/lib/server/outbound-send-review.js.map +1 -1
- package/src/lib/server/paged-sweeps.d.ts +51 -0
- package/src/lib/server/paged-sweeps.js +79 -0
- package/src/lib/server/paged-sweeps.js.map +1 -0
- package/src/lib/server/platform-marketing-consent.d.ts +0 -49
- package/src/lib/server/platform-marketing-consent.js +27 -11
- package/src/lib/server/platform-marketing-consent.js.map +1 -1
- package/src/lib/server/serve-media-cdn.d.ts +69 -1
- package/src/lib/server/serve-media-cdn.js +424 -70
- package/src/lib/server/serve-media-cdn.js.map +1 -1
- package/src/lib/server/site-icon-render.d.ts +68 -0
- package/src/lib/server/site-icon-render.js +157 -0
- package/src/lib/server/site-icon-render.js.map +1 -0
- package/src/lib/server/staff-seat.d.ts +50 -0
- package/src/lib/server/staff-seat.js +118 -0
- package/src/lib/server/staff-seat.js.map +1 -0
- package/src/lib/server/transfer-export.d.ts +46 -0
- package/src/lib/server/transfer-export.js +221 -0
- package/src/lib/server/transfer-export.js.map +1 -0
- package/src/lib/server/transfer-jobs.d.ts +385 -0
- package/src/lib/server/transfer-jobs.js +2368 -0
- package/src/lib/server/transfer-jobs.js.map +1 -0
- package/src/lib/server/transfer-packages.d.ts +127 -0
- package/src/lib/server/transfer-packages.js +1036 -0
- package/src/lib/server/transfer-packages.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +97 -0
- package/src/lib/server/upgrade-proposal.js +312 -0
- package/src/lib/server/upgrade-proposal.js.map +1 -0
- package/src/lib/server/upsert-contact.d.ts +17 -8
- package/src/lib/server/upsert-contact.js +82 -16
- package/src/lib/server/upsert-contact.js.map +1 -1
- package/src/lib/server/web-risk.d.ts +48 -9
- package/src/lib/server/web-risk.js +281 -143
- package/src/lib/server/web-risk.js.map +1 -1
- package/src/tenancy.d.ts +3 -1
- package/src/tenancy.js +5 -1
- package/src/tenancy.js.map +1 -1
- package/src/lib/server/campaign-attribution-store.d.ts +0 -55
- package/src/lib/server/campaign-attribution-store.js +0 -95
- package/src/lib/server/campaign-attribution-store.js.map +0 -1
- package/src/lib/server/campaign-conversion-attribution.d.ts +0 -283
- package/src/lib/server/campaign-conversion-attribution.js +0 -450
- package/src/lib/server/campaign-conversion-attribution.js.map +0 -1
- package/src/lib/server/dataset-live-pages.d.ts +0 -179
- package/src/lib/server/dataset-live-pages.js +0 -421
- package/src/lib/server/dataset-live-pages.js.map +0 -1
- package/src/lib/server/email-revenue-attribution.d.ts +0 -185
- package/src/lib/server/email-revenue-attribution.js +0 -321
- package/src/lib/server/email-revenue-attribution.js.map +0 -1
|
@@ -1,185 +0,0 @@
|
|
|
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
|
-
import { EMAIL_ATTRIBUTION_WINDOW_MS } from '@aglyn/shared-util-email';
|
|
18
|
-
/**
|
|
19
|
-
* THE COMMERCE↔EMAIL JOIN — an order, credited to the campaign that led to it.
|
|
20
|
-
*
|
|
21
|
-
* ## Why this is a join
|
|
22
|
-
*
|
|
23
|
-
* Every compared ESP attributes revenue through an integration into a store
|
|
24
|
-
* it does not own: a catalog sync, an on-site tracking snippet, an identity
|
|
25
|
-
* graph, and a window wide enough to absorb what the reconciliation misses.
|
|
26
|
-
* Commerce here is first-party and runs on the merchant's own Stripe Connect
|
|
27
|
-
* account, so the click and the order are two rows in one database keyed the
|
|
28
|
-
* same way. The window is not a fudge factor here — it is the model, and
|
|
29
|
-
* nothing else about the number is estimated.
|
|
30
|
-
*
|
|
31
|
-
* ## Three writes, and what each one is for
|
|
32
|
-
*
|
|
33
|
-
* - **The touch**, `emailDeliveries/{personKey}.campaignTouches[hostId]`,
|
|
34
|
-
* written by the delivery webhook on a click. Owned by
|
|
35
|
-
* `email-delivery-log.ts`, because it lives on the person's document and
|
|
36
|
-
* the erasure path has to be able to remove it.
|
|
37
|
-
* - **The attribution record**, `hosts/{hostId}/emailAttributions/{orderId}`,
|
|
38
|
-
* written here when an order is credited. It is the audit trail — which
|
|
39
|
-
* campaign, which click, which model, which window — and it is what the
|
|
40
|
-
* refund path reads to find out which campaign to take the money back off.
|
|
41
|
-
* - **The rollup**, `campaigns/{campaignId}/reports/revenue`, incremented
|
|
42
|
-
* here. One document per campaign, so the report reads it whole.
|
|
43
|
-
*
|
|
44
|
-
* ## Why the record is a document and not a field on the order
|
|
45
|
-
*
|
|
46
|
-
* Three reasons, and the first is decisive. `create()` fails when the
|
|
47
|
-
* document already exists, which is exact idempotency for free: webhook
|
|
48
|
-
* delivery is at-least-once, and a redelivered purchase must not be able to
|
|
49
|
-
* credit a campaign twice. Second, not every purchase door writes an order —
|
|
50
|
-
* a booking is a sale with no order document — and a field would have had to
|
|
51
|
-
* either skip those or conjure the document, and conjuring is the
|
|
52
|
-
* phantom-document shape this codebase spent a sweep removing. Third, the
|
|
53
|
-
* order document is read by the console list, the fulfilment path, the
|
|
54
|
-
* supplier outbox and the CSV export, and none of them wants a field about
|
|
55
|
-
* email.
|
|
56
|
-
*
|
|
57
|
-
* ## Never throws
|
|
58
|
-
*
|
|
59
|
-
* Same contract as `upsertHostContact`, which calls it, and for the same
|
|
60
|
-
* reason: the money has already moved and the order already records it, so
|
|
61
|
-
* nothing here may fail a sale. A lost attribution understates a campaign; a
|
|
62
|
-
* thrown one loses a checkout.
|
|
63
|
-
*/
|
|
64
|
-
/** The per-host collection of attribution records. */
|
|
65
|
-
export declare const EMAIL_ATTRIBUTIONS_COLLECTION = "emailAttributions";
|
|
66
|
-
/** The single rollup document under a campaign. */
|
|
67
|
-
export declare const CAMPAIGN_REVENUE_REPORT_DOC = "revenue";
|
|
68
|
-
/**
|
|
69
|
-
* The currency an amount is recorded under when the caller does not say.
|
|
70
|
-
*
|
|
71
|
-
* Every checkout door in this repo — cart, buy-now, POS, draft orders,
|
|
72
|
-
* reservations, subscriptions — writes `currency: 'usd'` onto the Stripe line
|
|
73
|
-
* items, and no order document carries a currency field to read back. So this
|
|
74
|
-
* is a statement about what the code charges rather than a guess about the
|
|
75
|
-
* money. The parameter exists so a door that ever charges in something else
|
|
76
|
-
* says so and lands in its own bucket, because the one thing the report may
|
|
77
|
-
* never do is add two currencies together.
|
|
78
|
-
*/
|
|
79
|
-
export declare const DEFAULT_ATTRIBUTION_CURRENCY = "usd";
|
|
80
|
-
/** What one attribution record holds. */
|
|
81
|
-
export interface EmailAttributionRecord {
|
|
82
|
-
campaignId: string;
|
|
83
|
-
/** When the credited click happened. */
|
|
84
|
-
clickedAtMs: number;
|
|
85
|
-
/** When the order was placed. */
|
|
86
|
-
orderedAtMs: number;
|
|
87
|
-
/** Minor units credited, gross — the amount the buyer was charged. */
|
|
88
|
-
amountCents: number;
|
|
89
|
-
/** Lowercase currency code the amount is in. */
|
|
90
|
-
currency: string;
|
|
91
|
-
/** The model this credit was decided under. */
|
|
92
|
-
model: string;
|
|
93
|
-
/** The window, in days, it was decided inside. */
|
|
94
|
-
windowDays: number;
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Credits one order to the campaign whose link the buyer last clicked.
|
|
98
|
-
*
|
|
99
|
-
* ## What happens when there is nobody to credit
|
|
100
|
-
*
|
|
101
|
-
* Each case answers `null` and writes NOTHING, which is the whole design:
|
|
102
|
-
*
|
|
103
|
-
* - **No email on the order.** A guest checkout that never identified its
|
|
104
|
-
* buyer cannot be joined to anybody's clicks. There is no fallback and
|
|
105
|
-
* there deliberately is not one — the alternatives are an IP or a device
|
|
106
|
-
* guess, which is the probabilistic attribution owning the checkout exists
|
|
107
|
-
* to avoid.
|
|
108
|
-
* - **A guest with an email but no contact record.** This is ATTRIBUTED
|
|
109
|
-
* normally. The join keys on the address hash, exactly as the touch and
|
|
110
|
-
* the suppression list do, so it never asks whether a contact document
|
|
111
|
-
* exists — which matters, because contact creation is audience-band gated
|
|
112
|
-
* and a Free org's dropped contact would otherwise silently drop the
|
|
113
|
-
* revenue with it.
|
|
114
|
-
* - **No touch, or a touch on another site.** Nobody clicked, so nobody is
|
|
115
|
-
* credited. The touch map is keyed by host and the send path refuses
|
|
116
|
-
* cross-site reach; the revenue join agrees with it.
|
|
117
|
-
* - **A touch outside the window**, in either direction. See
|
|
118
|
-
* {@link emailTouchIsInWindow} — a click AFTER the order is the receipt,
|
|
119
|
-
* not the cause.
|
|
120
|
-
*
|
|
121
|
-
* None of these is counted anywhere. A miss costs no write, which is what
|
|
122
|
-
* keeps the ordinary order — placed by somebody who is not on the mailing
|
|
123
|
-
* list at all — at exactly one document read. What it means for the report is
|
|
124
|
-
* stated on the report: the figure counts orders it could join, and is a
|
|
125
|
-
* floor.
|
|
126
|
-
*
|
|
127
|
-
* @returns the record written, or `null` when nothing was credited.
|
|
128
|
-
*/
|
|
129
|
-
export declare function attributeOrderToEmail(options: {
|
|
130
|
-
hostId: string;
|
|
131
|
-
/** The order, booking or invoice the money came in on. */
|
|
132
|
-
orderId: string;
|
|
133
|
-
/** The buyer as the sale recorded them, raw — normalized downstream. */
|
|
134
|
-
email: unknown;
|
|
135
|
-
/** Gross minor units the buyer was charged. */
|
|
136
|
-
amountCents: number;
|
|
137
|
-
/** Lowercase currency code, when the door knows one. */
|
|
138
|
-
currency?: string;
|
|
139
|
-
/** When the order was placed. Defaults to now. */
|
|
140
|
-
orderedAtMs?: number;
|
|
141
|
-
}, firestore?: any): Promise<EmailAttributionRecord | null>;
|
|
142
|
-
/**
|
|
143
|
-
* Takes back revenue a campaign was credited with, when it is refunded.
|
|
144
|
-
*
|
|
145
|
-
* ## Recorded beside the gross, never subtracted from it
|
|
146
|
-
*
|
|
147
|
-
* `grossCents` is left exactly as it is and the reversal lands in
|
|
148
|
-
* `refundedCents` next to it. This is the shape `contact-refund.ts` chose for
|
|
149
|
-
* `ltvCents`/`refundedCents` and the orders CSV chose for
|
|
150
|
-
* `amountUsd`/`refundedUsd`, and it is chosen a third time here so all three
|
|
151
|
-
* answer "what did this earn, net" identically. Decrementing would make a
|
|
152
|
-
* stored number mean one thing for rollups written before a refund and
|
|
153
|
-
* another after, with nothing on the document to tell them apart — and would
|
|
154
|
-
* put the question "can it go negative" onto storage, where the answer cannot
|
|
155
|
-
* be clamped without destroying evidence. Both stored figures are monotonic
|
|
156
|
-
* counters of money that really moved in one direction; the derived net is
|
|
157
|
-
* clamped at the point of display and nowhere else.
|
|
158
|
-
*
|
|
159
|
-
* ## The currency comes from the RECORD, not from the caller
|
|
160
|
-
*
|
|
161
|
-
* A refund reverses a specific sale, and the bucket it comes out of has to be
|
|
162
|
-
* the bucket it went into. Reading the currency back off the attribution
|
|
163
|
-
* record is what guarantees that, and it is the second thing the record is
|
|
164
|
-
* for.
|
|
165
|
-
*
|
|
166
|
-
* ## Chargebacks come through here too
|
|
167
|
-
*
|
|
168
|
-
* Money reversed is money reversed, whichever door it left by, so a lost
|
|
169
|
-
* dispute reverses the credit the same way a refund does. `kind` exists for
|
|
170
|
-
* the caller's clarity and changes nothing about the arithmetic — the same
|
|
171
|
-
* choice `recordContactRefund` made one field along.
|
|
172
|
-
*
|
|
173
|
-
* @returns whether a reversal was recorded.
|
|
174
|
-
*/
|
|
175
|
-
export declare function reverseEmailAttributedRevenue(options: {
|
|
176
|
-
hostId: string;
|
|
177
|
-
orderId: string;
|
|
178
|
-
/** Minor units reversed by THIS attempt, never the order total. */
|
|
179
|
-
amountCents: number;
|
|
180
|
-
/** True only for the write that moved the order into `refunded`. */
|
|
181
|
-
closedTheOrder: boolean;
|
|
182
|
-
kind?: 'refund' | 'chargeback';
|
|
183
|
-
}, firestore?: any): Promise<boolean>;
|
|
184
|
-
/** The window, re-exported so a caller needs one import for the whole join. */
|
|
185
|
-
export { EMAIL_ATTRIBUTION_WINDOW_MS };
|
|
@@ -1,321 +0,0 @@
|
|
|
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 { FieldValue } from "firebase-admin/firestore";
|
|
18
|
-
import { EMAIL_ATTRIBUTION_MODEL, EMAIL_ATTRIBUTION_WINDOW_DAYS, EMAIL_ATTRIBUTION_WINDOW_MS, emailTouchIsInWindow } from "@aglyn/shared-util-email";
|
|
19
|
-
import { resolveCampaignSendRef } from "./campaign-conversion-attribution.js";
|
|
20
|
-
import { readEmailCampaignTouch } from "./email-delivery-log.js";
|
|
21
|
-
import { isDocumentId } from "./document-id.js";
|
|
22
|
-
import firebaseAdmin from "./firebase-admin.js";
|
|
23
|
-
const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
24
|
-
/**
|
|
25
|
-
* THE COMMERCE↔EMAIL JOIN — an order, credited to the campaign that led to it.
|
|
26
|
-
*
|
|
27
|
-
* ## Why this is a join
|
|
28
|
-
*
|
|
29
|
-
* Every compared ESP attributes revenue through an integration into a store
|
|
30
|
-
* it does not own: a catalog sync, an on-site tracking snippet, an identity
|
|
31
|
-
* graph, and a window wide enough to absorb what the reconciliation misses.
|
|
32
|
-
* Commerce here is first-party and runs on the merchant's own Stripe Connect
|
|
33
|
-
* account, so the click and the order are two rows in one database keyed the
|
|
34
|
-
* same way. The window is not a fudge factor here — it is the model, and
|
|
35
|
-
* nothing else about the number is estimated.
|
|
36
|
-
*
|
|
37
|
-
* ## Three writes, and what each one is for
|
|
38
|
-
*
|
|
39
|
-
* - **The touch**, `emailDeliveries/{personKey}.campaignTouches[hostId]`,
|
|
40
|
-
* written by the delivery webhook on a click. Owned by
|
|
41
|
-
* `email-delivery-log.ts`, because it lives on the person's document and
|
|
42
|
-
* the erasure path has to be able to remove it.
|
|
43
|
-
* - **The attribution record**, `hosts/{hostId}/emailAttributions/{orderId}`,
|
|
44
|
-
* written here when an order is credited. It is the audit trail — which
|
|
45
|
-
* campaign, which click, which model, which window — and it is what the
|
|
46
|
-
* refund path reads to find out which campaign to take the money back off.
|
|
47
|
-
* - **The rollup**, `campaigns/{campaignId}/reports/revenue`, incremented
|
|
48
|
-
* here. One document per campaign, so the report reads it whole.
|
|
49
|
-
*
|
|
50
|
-
* ## Why the record is a document and not a field on the order
|
|
51
|
-
*
|
|
52
|
-
* Three reasons, and the first is decisive. `create()` fails when the
|
|
53
|
-
* document already exists, which is exact idempotency for free: webhook
|
|
54
|
-
* delivery is at-least-once, and a redelivered purchase must not be able to
|
|
55
|
-
* credit a campaign twice. Second, not every purchase door writes an order —
|
|
56
|
-
* a booking is a sale with no order document — and a field would have had to
|
|
57
|
-
* either skip those or conjure the document, and conjuring is the
|
|
58
|
-
* phantom-document shape this codebase spent a sweep removing. Third, the
|
|
59
|
-
* order document is read by the console list, the fulfilment path, the
|
|
60
|
-
* supplier outbox and the CSV export, and none of them wants a field about
|
|
61
|
-
* email.
|
|
62
|
-
*
|
|
63
|
-
* ## Never throws
|
|
64
|
-
*
|
|
65
|
-
* Same contract as `upsertHostContact`, which calls it, and for the same
|
|
66
|
-
* reason: the money has already moved and the order already records it, so
|
|
67
|
-
* nothing here may fail a sale. A lost attribution understates a campaign; a
|
|
68
|
-
* thrown one loses a checkout.
|
|
69
|
-
*/ /** The per-host collection of attribution records. */ export const EMAIL_ATTRIBUTIONS_COLLECTION = 'emailAttributions';
|
|
70
|
-
/** The single rollup document under a campaign. */ export const CAMPAIGN_REVENUE_REPORT_DOC = 'revenue';
|
|
71
|
-
/**
|
|
72
|
-
* The currency an amount is recorded under when the caller does not say.
|
|
73
|
-
*
|
|
74
|
-
* Every checkout door in this repo — cart, buy-now, POS, draft orders,
|
|
75
|
-
* reservations, subscriptions — writes `currency: 'usd'` onto the Stripe line
|
|
76
|
-
* items, and no order document carries a currency field to read back. So this
|
|
77
|
-
* is a statement about what the code charges rather than a guess about the
|
|
78
|
-
* money. The parameter exists so a door that ever charges in something else
|
|
79
|
-
* says so and lands in its own bucket, because the one thing the report may
|
|
80
|
-
* never do is add two currencies together.
|
|
81
|
-
*/ export const DEFAULT_ATTRIBUTION_CURRENCY = 'usd';
|
|
82
|
-
/** Normalizes a currency code to the key its bucket is stored under. */ function currencyKey(raw) {
|
|
83
|
-
const code = String(raw != null ? raw : '').trim().toLowerCase();
|
|
84
|
-
// Letters only: the code becomes a MAP KEY, and a key carrying a dot would
|
|
85
|
-
// be unreachable by any dotted field path a later reader wants to use.
|
|
86
|
-
return /^[a-z]{3}$/.test(code) ? code : DEFAULT_ATTRIBUTION_CURRENCY;
|
|
87
|
-
}
|
|
88
|
-
/** A positive integer number of minor units, or 0. */ function minorUnits(raw) {
|
|
89
|
-
const value = Math.round(Number(raw));
|
|
90
|
-
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Credits one order to the campaign whose link the buyer last clicked.
|
|
94
|
-
*
|
|
95
|
-
* ## What happens when there is nobody to credit
|
|
96
|
-
*
|
|
97
|
-
* Each case answers `null` and writes NOTHING, which is the whole design:
|
|
98
|
-
*
|
|
99
|
-
* - **No email on the order.** A guest checkout that never identified its
|
|
100
|
-
* buyer cannot be joined to anybody's clicks. There is no fallback and
|
|
101
|
-
* there deliberately is not one — the alternatives are an IP or a device
|
|
102
|
-
* guess, which is the probabilistic attribution owning the checkout exists
|
|
103
|
-
* to avoid.
|
|
104
|
-
* - **A guest with an email but no contact record.** This is ATTRIBUTED
|
|
105
|
-
* normally. The join keys on the address hash, exactly as the touch and
|
|
106
|
-
* the suppression list do, so it never asks whether a contact document
|
|
107
|
-
* exists — which matters, because contact creation is audience-band gated
|
|
108
|
-
* and a Free org's dropped contact would otherwise silently drop the
|
|
109
|
-
* revenue with it.
|
|
110
|
-
* - **No touch, or a touch on another site.** Nobody clicked, so nobody is
|
|
111
|
-
* credited. The touch map is keyed by host and the send path refuses
|
|
112
|
-
* cross-site reach; the revenue join agrees with it.
|
|
113
|
-
* - **A touch outside the window**, in either direction. See
|
|
114
|
-
* {@link emailTouchIsInWindow} — a click AFTER the order is the receipt,
|
|
115
|
-
* not the cause.
|
|
116
|
-
*
|
|
117
|
-
* None of these is counted anywhere. A miss costs no write, which is what
|
|
118
|
-
* keeps the ordinary order — placed by somebody who is not on the mailing
|
|
119
|
-
* list at all — at exactly one document read. What it means for the report is
|
|
120
|
-
* stated on the report: the figure counts orders it could join, and is a
|
|
121
|
-
* floor.
|
|
122
|
-
*
|
|
123
|
-
* @returns the record written, or `null` when nothing was credited.
|
|
124
|
-
*/ export async function attributeOrderToEmail(options, firestore) {
|
|
125
|
-
try {
|
|
126
|
-
var _options_hostId, _options_orderId, _options_orderedAtMs, _options_email;
|
|
127
|
-
const hostId = String((_options_hostId = options.hostId) != null ? _options_hostId : '');
|
|
128
|
-
const orderId = String((_options_orderId = options.orderId) != null ? _options_orderId : '');
|
|
129
|
-
const amountCents = minorUnits(options.amountCents);
|
|
130
|
-
if (!isDocumentId(hostId) || !isDocumentId(orderId)) return null;
|
|
131
|
-
if (!amountCents) return null;
|
|
132
|
-
const orderedAtMs = Number((_options_orderedAtMs = options.orderedAtMs) != null ? _options_orderedAtMs : Date.now());
|
|
133
|
-
const db = firestore != null ? firestore : defaultFirestore();
|
|
134
|
-
/*
|
|
135
|
-
* `String()` on an `unknown`, then let `emailSuppressionKey` decide.
|
|
136
|
-
*
|
|
137
|
-
* The buyer's address arrives as the ORDER recorded it, which is not
|
|
138
|
-
* consistently a string — the same rawness `recordContactRefund` takes
|
|
139
|
-
* `email: unknown` for. The key derivation is the one place that knows
|
|
140
|
-
* how an address becomes a document id, so nothing here tries to
|
|
141
|
-
* pre-clean it; a value that is not an address answers `null` there and
|
|
142
|
-
* the order is credited to nobody.
|
|
143
|
-
*/ const rawEmail = typeof options.email === 'string' ? options.email : String((_options_email = options.email) != null ? _options_email : '');
|
|
144
|
-
const touch = await readEmailCampaignTouch(rawEmail, hostId, db);
|
|
145
|
-
if (!touch) return null;
|
|
146
|
-
if (!isDocumentId(touch.campaignId)) return null;
|
|
147
|
-
if (!emailTouchIsInWindow(touch.clickedAtMs, orderedAtMs)) return null;
|
|
148
|
-
const record = {
|
|
149
|
-
campaignId: touch.campaignId,
|
|
150
|
-
clickedAtMs: touch.clickedAtMs,
|
|
151
|
-
orderedAtMs,
|
|
152
|
-
amountCents,
|
|
153
|
-
currency: currencyKey(options.currency),
|
|
154
|
-
model: EMAIL_ATTRIBUTION_MODEL,
|
|
155
|
-
windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS
|
|
156
|
-
};
|
|
157
|
-
const hostRef = db.collection('hosts').doc(hostId);
|
|
158
|
-
/*
|
|
159
|
-
* `create()`, never `set()`. It fails with ALREADY_EXISTS when this order
|
|
160
|
-
* has been credited before, and that failure is the idempotency: a
|
|
161
|
-
* webhook redelivery, a retried checkout completion and a replayed event
|
|
162
|
-
* all land here a second time, and all three must leave the rollup where
|
|
163
|
-
* they found it. The increment below is reached only when the create
|
|
164
|
-
* succeeded, so the two can never disagree about whether this order was
|
|
165
|
-
* counted.
|
|
166
|
-
*/ try {
|
|
167
|
-
await hostRef.collection(EMAIL_ATTRIBUTIONS_COLLECTION).doc(orderId).create(_extends({}, record, {
|
|
168
|
-
createdAt: FieldValue.serverTimestamp()
|
|
169
|
-
}));
|
|
170
|
-
} catch (unused) {
|
|
171
|
-
return null;
|
|
172
|
-
}
|
|
173
|
-
/*
|
|
174
|
-
* A merge-set that CREATES, unlike the campaign counters the delivery
|
|
175
|
-
* webhook writes through `updateExisting`.
|
|
176
|
-
*
|
|
177
|
-
* The distinction is which document is being conjured. Those counters
|
|
178
|
-
* refuse to create because a merge-set against a DELETED CAMPAIGN
|
|
179
|
-
* resurrects the campaign itself, as a husk holding a stats map and no
|
|
180
|
-
* subject. This writes a subcollection document UNDER a campaign, so a
|
|
181
|
-
* campaign that no longer exists gains an orphaned report rather than
|
|
182
|
-
* coming back to life in the merchant's history — and the campaign was
|
|
183
|
-
* proven to exist a moment ago, when its click wrote the touch.
|
|
184
|
-
*
|
|
185
|
-
* Every amount is an increment, so two orders settling at once both land.
|
|
186
|
-
*
|
|
187
|
-
* The send is found where it is — the org's `campaigns`, or the site's
|
|
188
|
-
* for a send the migration has not reached — and a send in neither
|
|
189
|
-
* place was discarded: the record above stands, and no report is
|
|
190
|
-
* conjured under nothing.
|
|
191
|
-
*/ const currency = record.currency;
|
|
192
|
-
const sendRef = await resolveCampaignSendRef({
|
|
193
|
-
hostId,
|
|
194
|
-
sendId: touch.campaignId,
|
|
195
|
-
firestore: db
|
|
196
|
-
});
|
|
197
|
-
if (!sendRef) return record;
|
|
198
|
-
await sendRef.collection('reports').doc(CAMPAIGN_REVENUE_REPORT_DOC).set({
|
|
199
|
-
model: EMAIL_ATTRIBUTION_MODEL,
|
|
200
|
-
windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,
|
|
201
|
-
byCurrency: {
|
|
202
|
-
[currency]: {
|
|
203
|
-
grossCents: FieldValue.increment(amountCents),
|
|
204
|
-
orders: FieldValue.increment(1)
|
|
205
|
-
}
|
|
206
|
-
},
|
|
207
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
208
|
-
}, {
|
|
209
|
-
merge: true
|
|
210
|
-
});
|
|
211
|
-
return record;
|
|
212
|
-
} catch (error) {
|
|
213
|
-
console.error('attributeOrderToEmail failed', error);
|
|
214
|
-
return null;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Takes back revenue a campaign was credited with, when it is refunded.
|
|
219
|
-
*
|
|
220
|
-
* ## Recorded beside the gross, never subtracted from it
|
|
221
|
-
*
|
|
222
|
-
* `grossCents` is left exactly as it is and the reversal lands in
|
|
223
|
-
* `refundedCents` next to it. This is the shape `contact-refund.ts` chose for
|
|
224
|
-
* `ltvCents`/`refundedCents` and the orders CSV chose for
|
|
225
|
-
* `amountUsd`/`refundedUsd`, and it is chosen a third time here so all three
|
|
226
|
-
* answer "what did this earn, net" identically. Decrementing would make a
|
|
227
|
-
* stored number mean one thing for rollups written before a refund and
|
|
228
|
-
* another after, with nothing on the document to tell them apart — and would
|
|
229
|
-
* put the question "can it go negative" onto storage, where the answer cannot
|
|
230
|
-
* be clamped without destroying evidence. Both stored figures are monotonic
|
|
231
|
-
* counters of money that really moved in one direction; the derived net is
|
|
232
|
-
* clamped at the point of display and nowhere else.
|
|
233
|
-
*
|
|
234
|
-
* ## The currency comes from the RECORD, not from the caller
|
|
235
|
-
*
|
|
236
|
-
* A refund reverses a specific sale, and the bucket it comes out of has to be
|
|
237
|
-
* the bucket it went into. Reading the currency back off the attribution
|
|
238
|
-
* record is what guarantees that, and it is the second thing the record is
|
|
239
|
-
* for.
|
|
240
|
-
*
|
|
241
|
-
* ## Chargebacks come through here too
|
|
242
|
-
*
|
|
243
|
-
* Money reversed is money reversed, whichever door it left by, so a lost
|
|
244
|
-
* dispute reverses the credit the same way a refund does. `kind` exists for
|
|
245
|
-
* the caller's clarity and changes nothing about the arithmetic — the same
|
|
246
|
-
* choice `recordContactRefund` made one field along.
|
|
247
|
-
*
|
|
248
|
-
* @returns whether a reversal was recorded.
|
|
249
|
-
*/ export async function reverseEmailAttributedRevenue(options, firestore) {
|
|
250
|
-
try {
|
|
251
|
-
var _options_hostId, _options_orderId, _snapshot_data, _record_campaignId;
|
|
252
|
-
const hostId = String((_options_hostId = options.hostId) != null ? _options_hostId : '');
|
|
253
|
-
const orderId = String((_options_orderId = options.orderId) != null ? _options_orderId : '');
|
|
254
|
-
const amountCents = minorUnits(options.amountCents);
|
|
255
|
-
if (!isDocumentId(hostId) || !isDocumentId(orderId)) return false;
|
|
256
|
-
if (!amountCents) return false;
|
|
257
|
-
const db = firestore != null ? firestore : defaultFirestore();
|
|
258
|
-
const hostRef = db.collection('hosts').doc(hostId);
|
|
259
|
-
const snapshot = await hostRef.collection(EMAIL_ATTRIBUTIONS_COLLECTION).doc(orderId).get();
|
|
260
|
-
// The ordinary case, and not an error: most orders were never credited to
|
|
261
|
-
// a campaign, so most refunds have nothing to reverse.
|
|
262
|
-
if (!snapshot.exists) return false;
|
|
263
|
-
const record = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
|
|
264
|
-
const campaignId = String((_record_campaignId = record.campaignId) != null ? _record_campaignId : '');
|
|
265
|
-
if (!isDocumentId(campaignId)) return false;
|
|
266
|
-
const currency = currencyKey(record.currency);
|
|
267
|
-
/*
|
|
268
|
-
* NOT capped against what was credited, and that is deliberate. The
|
|
269
|
-
* caller already caps each attempt against what is left on the ORDER, so
|
|
270
|
-
* several partials sum to at most the order total; capping again here
|
|
271
|
-
* against the attributed amount would silently discard the reversal of an
|
|
272
|
-
* order refunded for more than the amount the campaign was credited with
|
|
273
|
-
* — which happens when the credit was the charge and the refund includes
|
|
274
|
-
* something the credit did not. The stored pair keeps both true figures
|
|
275
|
-
* and the reader clamps the net it prints.
|
|
276
|
-
*
|
|
277
|
-
* The send is found where it is, as the credit found it; a send that
|
|
278
|
-
* has since been discarded has no rollup left to reverse, and the
|
|
279
|
-
* record below still takes the refund.
|
|
280
|
-
*/ const sendRef = await resolveCampaignSendRef({
|
|
281
|
-
hostId,
|
|
282
|
-
sendId: campaignId,
|
|
283
|
-
firestore: db
|
|
284
|
-
});
|
|
285
|
-
await (sendRef == null ? void 0 : sendRef.collection('reports').doc(CAMPAIGN_REVENUE_REPORT_DOC).set({
|
|
286
|
-
byCurrency: {
|
|
287
|
-
[currency]: _extends({
|
|
288
|
-
refundedCents: FieldValue.increment(amountCents)
|
|
289
|
-
}, options.closedTheOrder ? {
|
|
290
|
-
refundedOrders: FieldValue.increment(1)
|
|
291
|
-
} : {})
|
|
292
|
-
},
|
|
293
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
294
|
-
}, {
|
|
295
|
-
merge: true
|
|
296
|
-
}));
|
|
297
|
-
/*
|
|
298
|
-
* Stamped on the record as well as counted in the rollup. The rollup is a
|
|
299
|
-
* sum and cannot say WHICH orders came back; this is the per-order half
|
|
300
|
-
* of the same fact, and it is what a merchant asking "why did this
|
|
301
|
-
* campaign's revenue drop" is eventually going to need. Increments, so
|
|
302
|
-
* two partials on one order both land.
|
|
303
|
-
*/ await snapshot.ref.set(_extends({
|
|
304
|
-
refundedCents: FieldValue.increment(amountCents),
|
|
305
|
-
lastRefundAtMs: Date.now()
|
|
306
|
-
}, options.kind === 'chargeback' ? {
|
|
307
|
-
chargedBack: true
|
|
308
|
-
} : {}, options.closedTheOrder ? {
|
|
309
|
-
fullyRefunded: true
|
|
310
|
-
} : {}), {
|
|
311
|
-
merge: true
|
|
312
|
-
}).catch(()=>undefined);
|
|
313
|
-
return true;
|
|
314
|
-
} catch (error) {
|
|
315
|
-
console.error('reverseEmailAttributedRevenue failed', error);
|
|
316
|
-
return false;
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
/** The window, re-exported so a caller needs one import for the whole join. */ export { EMAIL_ATTRIBUTION_WINDOW_MS };
|
|
320
|
-
|
|
321
|
-
//# sourceMappingURL=email-revenue-attribution.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-revenue-attribution.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 { FieldValue } from 'firebase-admin/firestore'\nimport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n EMAIL_ATTRIBUTION_WINDOW_MS,\n emailTouchIsInWindow,\n} from '@aglyn/shared-util-email'\nimport { resolveCampaignSendRef } from './campaign-conversion-attribution'\nimport { readEmailCampaignTouch } from './email-delivery-log'\nimport { isDocumentId } from './document-id'\nimport firebaseAdmin from './firebase-admin'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/**\n * THE COMMERCE↔EMAIL JOIN — an order, credited to the campaign that led to it.\n *\n * ## Why this is a join\n *\n * Every compared ESP attributes revenue through an integration into a store\n * it does not own: a catalog sync, an on-site tracking snippet, an identity\n * graph, and a window wide enough to absorb what the reconciliation misses.\n * Commerce here is first-party and runs on the merchant's own Stripe Connect\n * account, so the click and the order are two rows in one database keyed the\n * same way. The window is not a fudge factor here — it is the model, and\n * nothing else about the number is estimated.\n *\n * ## Three writes, and what each one is for\n *\n * - **The touch**, `emailDeliveries/{personKey}.campaignTouches[hostId]`,\n * written by the delivery webhook on a click. Owned by\n * `email-delivery-log.ts`, because it lives on the person's document and\n * the erasure path has to be able to remove it.\n * - **The attribution record**, `hosts/{hostId}/emailAttributions/{orderId}`,\n * written here when an order is credited. It is the audit trail — which\n * campaign, which click, which model, which window — and it is what the\n * refund path reads to find out which campaign to take the money back off.\n * - **The rollup**, `campaigns/{campaignId}/reports/revenue`, incremented\n * here. One document per campaign, so the report reads it whole.\n *\n * ## Why the record is a document and not a field on the order\n *\n * Three reasons, and the first is decisive. `create()` fails when the\n * document already exists, which is exact idempotency for free: webhook\n * delivery is at-least-once, and a redelivered purchase must not be able to\n * credit a campaign twice. Second, not every purchase door writes an order —\n * a booking is a sale with no order document — and a field would have had to\n * either skip those or conjure the document, and conjuring is the\n * phantom-document shape this codebase spent a sweep removing. Third, the\n * order document is read by the console list, the fulfilment path, the\n * supplier outbox and the CSV export, and none of them wants a field about\n * email.\n *\n * ## Never throws\n *\n * Same contract as `upsertHostContact`, which calls it, and for the same\n * reason: the money has already moved and the order already records it, so\n * nothing here may fail a sale. A lost attribution understates a campaign; a\n * thrown one loses a checkout.\n */\n\n/** The per-host collection of attribution records. */\nexport const EMAIL_ATTRIBUTIONS_COLLECTION = 'emailAttributions'\n\n/** The single rollup document under a campaign. */\nexport const CAMPAIGN_REVENUE_REPORT_DOC = 'revenue'\n\n/**\n * The currency an amount is recorded under when the caller does not say.\n *\n * Every checkout door in this repo — cart, buy-now, POS, draft orders,\n * reservations, subscriptions — writes `currency: 'usd'` onto the Stripe line\n * items, and no order document carries a currency field to read back. So this\n * is a statement about what the code charges rather than a guess about the\n * money. The parameter exists so a door that ever charges in something else\n * says so and lands in its own bucket, because the one thing the report may\n * never do is add two currencies together.\n */\nexport const DEFAULT_ATTRIBUTION_CURRENCY = 'usd'\n\n/** What one attribution record holds. */\nexport interface EmailAttributionRecord {\n campaignId: string\n /** When the credited click happened. */\n clickedAtMs: number\n /** When the order was placed. */\n orderedAtMs: number\n /** Minor units credited, gross — the amount the buyer was charged. */\n amountCents: number\n /** Lowercase currency code the amount is in. */\n currency: string\n /** The model this credit was decided under. */\n model: string\n /** The window, in days, it was decided inside. */\n windowDays: number\n}\n\n/** Normalizes a currency code to the key its bucket is stored under. */\nfunction currencyKey(raw: unknown): string {\n const code = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Letters only: the code becomes a MAP KEY, and a key carrying a dot would\n // be unreachable by any dotted field path a later reader wants to use.\n return /^[a-z]{3}$/.test(code) ? code : DEFAULT_ATTRIBUTION_CURRENCY\n}\n\n/** A positive integer number of minor units, or 0. */\nfunction minorUnits(raw: unknown): number {\n const value = Math.round(Number(raw))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/**\n * Credits one order to the campaign whose link the buyer last clicked.\n *\n * ## What happens when there is nobody to credit\n *\n * Each case answers `null` and writes NOTHING, which is the whole design:\n *\n * - **No email on the order.** A guest checkout that never identified its\n * buyer cannot be joined to anybody's clicks. There is no fallback and\n * there deliberately is not one — the alternatives are an IP or a device\n * guess, which is the probabilistic attribution owning the checkout exists\n * to avoid.\n * - **A guest with an email but no contact record.** This is ATTRIBUTED\n * normally. The join keys on the address hash, exactly as the touch and\n * the suppression list do, so it never asks whether a contact document\n * exists — which matters, because contact creation is audience-band gated\n * and a Free org's dropped contact would otherwise silently drop the\n * revenue with it.\n * - **No touch, or a touch on another site.** Nobody clicked, so nobody is\n * credited. The touch map is keyed by host and the send path refuses\n * cross-site reach; the revenue join agrees with it.\n * - **A touch outside the window**, in either direction. See\n * {@link emailTouchIsInWindow} — a click AFTER the order is the receipt,\n * not the cause.\n *\n * None of these is counted anywhere. A miss costs no write, which is what\n * keeps the ordinary order — placed by somebody who is not on the mailing\n * list at all — at exactly one document read. What it means for the report is\n * stated on the report: the figure counts orders it could join, and is a\n * floor.\n *\n * @returns the record written, or `null` when nothing was credited.\n */\nexport async function attributeOrderToEmail(\n options: {\n hostId: string\n /** The order, booking or invoice the money came in on. */\n orderId: string\n /** The buyer as the sale recorded them, raw — normalized downstream. */\n email: unknown\n /** Gross minor units the buyer was charged. */\n amountCents: number\n /** Lowercase currency code, when the door knows one. */\n currency?: string\n /** When the order was placed. Defaults to now. */\n orderedAtMs?: number\n },\n firestore?: any,\n): Promise<EmailAttributionRecord | null> {\n try {\n const hostId = String(options.hostId ?? '')\n const orderId = String(options.orderId ?? '')\n const amountCents = minorUnits(options.amountCents)\n if (!isDocumentId(hostId) || !isDocumentId(orderId)) return null\n if (!amountCents) return null\n\n const orderedAtMs = Number(options.orderedAtMs ?? Date.now())\n const db = firestore ?? defaultFirestore()\n\n /*\n * `String()` on an `unknown`, then let `emailSuppressionKey` decide.\n *\n * The buyer's address arrives as the ORDER recorded it, which is not\n * consistently a string — the same rawness `recordContactRefund` takes\n * `email: unknown` for. The key derivation is the one place that knows\n * how an address becomes a document id, so nothing here tries to\n * pre-clean it; a value that is not an address answers `null` there and\n * the order is credited to nobody.\n */\n const rawEmail =\n typeof options.email === 'string' ? options.email : String(options.email ?? '')\n const touch = await readEmailCampaignTouch(rawEmail, hostId, db)\n if (!touch) return null\n if (!isDocumentId(touch.campaignId)) return null\n if (!emailTouchIsInWindow(touch.clickedAtMs, orderedAtMs)) return null\n\n const record: EmailAttributionRecord = {\n campaignId: touch.campaignId,\n clickedAtMs: touch.clickedAtMs,\n orderedAtMs,\n amountCents,\n currency: currencyKey(options.currency),\n model: EMAIL_ATTRIBUTION_MODEL,\n windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,\n }\n\n const hostRef = db.collection('hosts').doc(hostId)\n /*\n * `create()`, never `set()`. It fails with ALREADY_EXISTS when this order\n * has been credited before, and that failure is the idempotency: a\n * webhook redelivery, a retried checkout completion and a replayed event\n * all land here a second time, and all three must leave the rollup where\n * they found it. The increment below is reached only when the create\n * succeeded, so the two can never disagree about whether this order was\n * counted.\n */\n try {\n await hostRef\n .collection(EMAIL_ATTRIBUTIONS_COLLECTION)\n .doc(orderId)\n .create({ ...record, createdAt: FieldValue.serverTimestamp() })\n } catch {\n return null\n }\n\n /*\n * A merge-set that CREATES, unlike the campaign counters the delivery\n * webhook writes through `updateExisting`.\n *\n * The distinction is which document is being conjured. Those counters\n * refuse to create because a merge-set against a DELETED CAMPAIGN\n * resurrects the campaign itself, as a husk holding a stats map and no\n * subject. This writes a subcollection document UNDER a campaign, so a\n * campaign that no longer exists gains an orphaned report rather than\n * coming back to life in the merchant's history — and the campaign was\n * proven to exist a moment ago, when its click wrote the touch.\n *\n * Every amount is an increment, so two orders settling at once both land.\n *\n * The send is found where it is — the org's `campaigns`, or the site's\n * for a send the migration has not reached — and a send in neither\n * place was discarded: the record above stands, and no report is\n * conjured under nothing.\n */\n const currency = record.currency\n const sendRef = await resolveCampaignSendRef({ hostId, sendId: touch.campaignId, firestore: db })\n if (!sendRef) return record\n await sendRef\n .collection('reports')\n .doc(CAMPAIGN_REVENUE_REPORT_DOC)\n .set(\n {\n model: EMAIL_ATTRIBUTION_MODEL,\n windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,\n byCurrency: {\n [currency]: {\n grossCents: FieldValue.increment(amountCents),\n orders: FieldValue.increment(1),\n },\n },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n return record\n } catch (error) {\n console.error('attributeOrderToEmail failed', error)\n return null\n }\n}\n\n/**\n * Takes back revenue a campaign was credited with, when it is refunded.\n *\n * ## Recorded beside the gross, never subtracted from it\n *\n * `grossCents` is left exactly as it is and the reversal lands in\n * `refundedCents` next to it. This is the shape `contact-refund.ts` chose for\n * `ltvCents`/`refundedCents` and the orders CSV chose for\n * `amountUsd`/`refundedUsd`, and it is chosen a third time here so all three\n * answer \"what did this earn, net\" identically. Decrementing would make a\n * stored number mean one thing for rollups written before a refund and\n * another after, with nothing on the document to tell them apart — and would\n * put the question \"can it go negative\" onto storage, where the answer cannot\n * be clamped without destroying evidence. Both stored figures are monotonic\n * counters of money that really moved in one direction; the derived net is\n * clamped at the point of display and nowhere else.\n *\n * ## The currency comes from the RECORD, not from the caller\n *\n * A refund reverses a specific sale, and the bucket it comes out of has to be\n * the bucket it went into. Reading the currency back off the attribution\n * record is what guarantees that, and it is the second thing the record is\n * for.\n *\n * ## Chargebacks come through here too\n *\n * Money reversed is money reversed, whichever door it left by, so a lost\n * dispute reverses the credit the same way a refund does. `kind` exists for\n * the caller's clarity and changes nothing about the arithmetic — the same\n * choice `recordContactRefund` made one field along.\n *\n * @returns whether a reversal was recorded.\n */\nexport async function reverseEmailAttributedRevenue(\n options: {\n hostId: string\n orderId: string\n /** Minor units reversed by THIS attempt, never the order total. */\n amountCents: number\n /** True only for the write that moved the order into `refunded`. */\n closedTheOrder: boolean\n kind?: 'refund' | 'chargeback'\n },\n firestore?: any,\n): Promise<boolean> {\n try {\n const hostId = String(options.hostId ?? '')\n const orderId = String(options.orderId ?? '')\n const amountCents = minorUnits(options.amountCents)\n if (!isDocumentId(hostId) || !isDocumentId(orderId)) return false\n if (!amountCents) return false\n\n const db = firestore ?? defaultFirestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const snapshot = await hostRef\n .collection(EMAIL_ATTRIBUTIONS_COLLECTION)\n .doc(orderId)\n .get()\n // The ordinary case, and not an error: most orders were never credited to\n // a campaign, so most refunds have nothing to reverse.\n if (!snapshot.exists) return false\n\n const record = snapshot.data() ?? {}\n const campaignId = String(record.campaignId ?? '')\n if (!isDocumentId(campaignId)) return false\n const currency = currencyKey(record.currency)\n\n /*\n * NOT capped against what was credited, and that is deliberate. The\n * caller already caps each attempt against what is left on the ORDER, so\n * several partials sum to at most the order total; capping again here\n * against the attributed amount would silently discard the reversal of an\n * order refunded for more than the amount the campaign was credited with\n * — which happens when the credit was the charge and the refund includes\n * something the credit did not. The stored pair keeps both true figures\n * and the reader clamps the net it prints.\n *\n * The send is found where it is, as the credit found it; a send that\n * has since been discarded has no rollup left to reverse, and the\n * record below still takes the refund.\n */\n const sendRef = await resolveCampaignSendRef({ hostId, sendId: campaignId, firestore: db })\n await sendRef\n ?.collection('reports')\n .doc(CAMPAIGN_REVENUE_REPORT_DOC)\n .set(\n {\n byCurrency: {\n [currency]: {\n refundedCents: FieldValue.increment(amountCents),\n ...(options.closedTheOrder\n ? { refundedOrders: FieldValue.increment(1) }\n : {}),\n },\n },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n /*\n * Stamped on the record as well as counted in the rollup. The rollup is a\n * sum and cannot say WHICH orders came back; this is the per-order half\n * of the same fact, and it is what a merchant asking \"why did this\n * campaign's revenue drop\" is eventually going to need. Increments, so\n * two partials on one order both land.\n */\n await snapshot.ref\n .set(\n {\n refundedCents: FieldValue.increment(amountCents),\n lastRefundAtMs: Date.now(),\n ...(options.kind === 'chargeback' ? { chargedBack: true } : {}),\n ...(options.closedTheOrder ? { fullyRefunded: true } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n\n return true\n } catch (error) {\n console.error('reverseEmailAttributedRevenue failed', error)\n return false\n }\n}\n\n/** The window, re-exported so a caller needs one import for the whole join. */\nexport { EMAIL_ATTRIBUTION_WINDOW_MS }\n"],"names":["FieldValue","EMAIL_ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","EMAIL_ATTRIBUTION_WINDOW_MS","emailTouchIsInWindow","resolveCampaignSendRef","readEmailCampaignTouch","isDocumentId","firebaseAdmin","defaultFirestore","app","firestore","EMAIL_ATTRIBUTIONS_COLLECTION","CAMPAIGN_REVENUE_REPORT_DOC","DEFAULT_ATTRIBUTION_CURRENCY","currencyKey","raw","code","String","trim","toLowerCase","test","minorUnits","value","Math","round","Number","isFinite","attributeOrderToEmail","options","hostId","orderId","amountCents","orderedAtMs","Date","now","db","rawEmail","email","touch","campaignId","clickedAtMs","record","currency","model","windowDays","hostRef","collection","doc","create","createdAt","serverTimestamp","sendRef","sendId","set","byCurrency","grossCents","increment","orders","updatedAt","merge","error","console","reverseEmailAttributedRevenue","snapshot","get","exists","data","refundedCents","closedTheOrder","refundedOrders","ref","lastRefundAtMs","kind","chargedBack","fullyRefunded","catch","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AACrD,SACEC,uBAAuB,EACvBC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,uCAAmC;AAC1E,SAASC,sBAAsB,QAAQ,0BAAsB;AAC7D,SAASC,YAAY,QAAQ,mBAAe;AAC5C,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,mBAAmB,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GAED,oDAAoD,GACpD,OAAO,MAAMC,gCAAgC,oBAAmB;AAEhE,iDAAiD,GACjD,OAAO,MAAMC,8BAA8B,UAAS;AAEpD;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,+BAA+B,MAAK;AAmBjD,sEAAsE,GACtE,SAASC,YAAYC,GAAY;IAC/B,MAAMC,OAAOC,OAAOF,cAAAA,MAAO,IACxBG,IAAI,GACJC,WAAW;IACd,2EAA2E;IAC3E,uEAAuE;IACvE,OAAO,aAAaC,IAAI,CAACJ,QAAQA,OAAOH;AAC1C;AAEA,oDAAoD,GACpD,SAASQ,WAAWN,GAAY;IAC9B,MAAMO,QAAQC,KAAKC,KAAK,CAACC,OAAOV;IAChC,OAAO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