@aglyn/tenant-data-admin 1.0.0-beta.269 → 1.0.0-beta.271
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/render-cache.d.ts +10 -3
- package/src/lib/render-cache.js +10 -3
- package/src/lib/render-cache.js.map +1 -1
- package/src/lib/server/append-only-history-write.d.ts +38 -0
- package/src/lib/server/append-only-history-write.js +60 -0
- package/src/lib/server/append-only-history-write.js.map +1 -0
- package/src/lib/server/billing-addons.d.ts +58 -30
- package/src/lib/server/billing-addons.js +102 -77
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +166 -0
- package/src/lib/server/bundle-links.js +286 -0
- package/src/lib/server/bundle-links.js.map +1 -0
- package/src/lib/server/client-build.d.ts +74 -0
- package/src/lib/server/client-build.js +264 -0
- package/src/lib/server/client-build.js.map +1 -0
- package/src/lib/server/configured-url-fetch.d.ts +26 -0
- package/src/lib/server/configured-url-fetch.js +68 -0
- package/src/lib/server/configured-url-fetch.js.map +1 -1
- package/src/lib/server/custom-domain-redirects.d.ts +50 -0
- package/src/lib/server/custom-domain-redirects.js +61 -0
- package/src/lib/server/custom-domain-redirects.js.map +1 -0
- package/src/lib/server/host-custom-domain.d.ts +125 -0
- package/src/lib/server/host-custom-domain.js +395 -0
- package/src/lib/server/host-custom-domain.js.map +1 -0
- package/src/lib/server/host-memberships.d.ts +35 -2
- package/src/lib/server/host-memberships.js +63 -2
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/host-released-names.d.ts +1 -2
- package/src/lib/server/host-released-names.js +4 -2
- package/src/lib/server/host-released-names.js.map +1 -1
- package/src/lib/server/media-photo-links.d.ts +196 -0
- package/src/lib/server/media-photo-links.js +290 -0
- package/src/lib/server/media-photo-links.js.map +1 -0
- package/src/lib/server/org-billing.d.ts +4 -2
- package/src/lib/server/org-billing.js +5 -0
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/organizations.d.ts +25 -1
- package/src/lib/server/organizations.js +62 -2
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/personal-data-export.js +21 -1
- package/src/lib/server/personal-data-export.js.map +1 -1
- package/src/lib/server/push-delivery.js +32 -14
- package/src/lib/server/push-delivery.js.map +1 -1
- package/src/lib/server/site-care-emails.d.ts +52 -0
- package/src/lib/server/site-care-emails.js +97 -0
- package/src/lib/server/site-care-emails.js.map +1 -0
- package/src/lib/server/site-care-inbound.d.ts +80 -0
- package/src/lib/server/site-care-inbound.js +171 -0
- package/src/lib/server/site-care-inbound.js.map +1 -0
- package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
- package/src/lib/server/site-care-project-reconcile.js +211 -0
- package/src/lib/server/site-care-project-reconcile.js.map +1 -0
- package/src/lib/server/site-care-project-stripe.d.ts +114 -0
- package/src/lib/server/site-care-project-stripe.js +305 -0
- package/src/lib/server/site-care-project-stripe.js.map +1 -0
- package/src/lib/server/site-care-projects.d.ts +169 -0
- package/src/lib/server/site-care-projects.js +882 -0
- package/src/lib/server/site-care-projects.js.map +1 -0
- package/src/lib/server/site-care-reconcile.d.ts +81 -0
- package/src/lib/server/site-care-reconcile.js +349 -0
- package/src/lib/server/site-care-reconcile.js.map +1 -0
- package/src/lib/server/site-care-requests.d.ts +243 -0
- package/src/lib/server/site-care-requests.js +1414 -0
- package/src/lib/server/site-care-requests.js.map +1 -0
- package/src/lib/server/site-care-stripe.d.ts +175 -0
- package/src/lib/server/site-care-stripe.js +375 -0
- package/src/lib/server/site-care-stripe.js.map +1 -0
- package/src/lib/server/tenant-dns-check.d.ts +58 -0
- package/src/lib/server/tenant-dns-check.js +197 -0
- package/src/lib/server/tenant-dns-check.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +40 -1
- package/src/lib/server/upgrade-proposal.js +92 -50
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/tenancy.d.ts +5 -0
- package/src/tenancy.js +10 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1,197 @@
|
|
|
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 { CNAME_TARGET, HOST_APEX_ADDRESSES } from "@aglyn/aglyn/app-utils/tenant-dns-targets";
|
|
18
|
+
import { promises as dns, Resolver as CallbackResolver } from "dns";
|
|
19
|
+
import { PUBLIC_DNS_RESOLVERS as PUBLIC_RESOLVERS } from "./dns-probe.js";
|
|
20
|
+
/**
|
|
21
|
+
* WHETHER A NAME POINTS AT THE TENANT EDGE: the check behind
|
|
22
|
+
* `/api/domains/verify`, here so a caller with no request of its own reads
|
|
23
|
+
* the same answer (AGL-3963). The domains plugin's one-click DNS asks it after
|
|
24
|
+
* a DNS provider wrote the records, and its sweep asks it again for a session
|
|
25
|
+
* whose owner closed the tab; neither can import the console app, and a
|
|
26
|
+
* second copy of this rule is how the displayed target and the accepted one
|
|
27
|
+
* came apart before (AGL-733).
|
|
28
|
+
*
|
|
29
|
+
* The targets are `@aglyn/aglyn/app-utils/tenant-dns-targets`, the values the
|
|
30
|
+
* connect card prints.
|
|
31
|
+
*/ /** A domain as the check accepts one: labels of letters, digits and hyphens. */ export const TENANT_DNS_DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\.[a-z0-9-]{1,63})+$/i;
|
|
32
|
+
/**
|
|
33
|
+
* Resolve against public resolvers rather than the runtime's default (AGL-734).
|
|
34
|
+
*
|
|
35
|
+
* A stale zone left over from a nameserver migration made Vercel's own resolver
|
|
36
|
+
* return NXDOMAIN for records that every public resolver could see — so a
|
|
37
|
+
* correctly-configured domain reported "no CNAME record found" indefinitely,
|
|
38
|
+
* while `dig` from anywhere else resolved it fine. Pinning the resolver makes
|
|
39
|
+
* the check depend on public DNS, which is what the customer's browser will use
|
|
40
|
+
* anyway, instead of on whatever cache a given lambda inherited.
|
|
41
|
+
*
|
|
42
|
+
* Falls back to the default resolver if the pinned ones are unreachable, so a
|
|
43
|
+
* blocked egress path degrades to today's behaviour rather than failing shut.
|
|
44
|
+
*/ async function resolveCnameRecords(domain) {
|
|
45
|
+
const normalise = (records)=>records.map((record)=>record.toLowerCase().replace(/\.$/, ''));
|
|
46
|
+
try {
|
|
47
|
+
const resolver = new CallbackResolver();
|
|
48
|
+
resolver.setServers(PUBLIC_RESOLVERS);
|
|
49
|
+
const records = await new Promise((resolve, reject)=>{
|
|
50
|
+
resolver.resolveCname(domain, (error, addresses)=>error ? reject(error) : resolve(addresses));
|
|
51
|
+
});
|
|
52
|
+
return normalise(records);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
// ENOTFOUND/ENODATA are real answers — the name has no CNAME. Only fall
|
|
55
|
+
// back when the pinned resolvers could not be reached at all.
|
|
56
|
+
const code = error == null ? void 0 : error.code;
|
|
57
|
+
if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
return normalise(await dns.resolveCname(domain));
|
|
62
|
+
} catch (unused) {
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function resolveARecords(domain) {
|
|
68
|
+
const lookup = async (resolver)=>resolver ? new Promise((resolve, reject)=>{
|
|
69
|
+
resolver.resolve4(domain, (error, addresses)=>error ? reject(error) : resolve(addresses));
|
|
70
|
+
}) : dns.resolve4(domain);
|
|
71
|
+
try {
|
|
72
|
+
const resolver = new CallbackResolver();
|
|
73
|
+
resolver.setServers(PUBLIC_RESOLVERS);
|
|
74
|
+
return await lookup(resolver);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
const code = error == null ? void 0 : error.code;
|
|
77
|
+
if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
return await lookup();
|
|
82
|
+
} catch (unused) {
|
|
83
|
+
return [];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* An apex (`aglyn.com`) cannot carry a CNAME — RFC 1034 forbids one alongside
|
|
89
|
+
* the SOA/NS records every zone apex must have. So the CNAME check below can
|
|
90
|
+
* never pass for a bare domain, and until this existed the wizard simply
|
|
91
|
+
* refused every apex: customers could connect `www.` and nothing else.
|
|
92
|
+
*
|
|
93
|
+
* Instead, compare where the domain actually lands against where the CNAME
|
|
94
|
+
* target lands. Both sides are resolved at check time rather than compared to
|
|
95
|
+
* a hardcoded address list, because the edge IPs behind `sites.aglyn.app` are
|
|
96
|
+
* the host's to change — pinning them here would turn a routine infrastructure
|
|
97
|
+
* change into every customer's domain reporting itself broken.
|
|
98
|
+
*
|
|
99
|
+
* An intersection, not equality: the two names legitimately return different
|
|
100
|
+
* subsets of the same anycast pool from one lookup to the next.
|
|
101
|
+
*
|
|
102
|
+
* `HOST_APEX_ADDRESSES` covers the case the intersection cannot: our platform
|
|
103
|
+
* host publishes a small anycast pool for every apex it serves, routing by
|
|
104
|
+
* `Host` rather than by IP. An apex pointed there therefore never shares an
|
|
105
|
+
* address with `sites.aglyn.app`, yet is configured correctly.
|
|
106
|
+
*
|
|
107
|
+
* The list has to span the host's WHOLE pool, not just the address we happen
|
|
108
|
+
* to have used. It shipped with only `76.76.21.21` — the host's legacy
|
|
109
|
+
* address, which still resolves but is no longer what a newly-pointed apex
|
|
110
|
+
* lands on, so every new customer would have failed the very check this
|
|
111
|
+
* fallback exists to let them pass. Our own zones are the proof: after taking
|
|
112
|
+
* the host's recommended records, `aglyn.com` and `aglyn.io` resolve into the
|
|
113
|
+
* `216.198.79.x` / `64.29.17.x` range and not one of them is the legacy
|
|
114
|
+
* address. Keep the legacy entry — zones still pointed at it work fine.
|
|
115
|
+
*
|
|
116
|
+
* Accepting an address match is deliberately a weaker claim — "this domain
|
|
117
|
+
* resolves to our platform" rather than "to this account". That is sound
|
|
118
|
+
* because it is not the ownership check: attaching a domain to the project is,
|
|
119
|
+
* and the platform performs that itself. This only answers "has DNS been
|
|
120
|
+
* pointed yet", which is what the customer is actually stuck on. Configurable
|
|
121
|
+
* so the next range expansion is an env edit rather than a patch.
|
|
122
|
+
*
|
|
123
|
+
* The list itself lives in `tenant-dns-targets.ts` beside `CNAME_TARGET`, so the
|
|
124
|
+
* wizard prints an address this check will actually accept rather than keeping
|
|
125
|
+
* its own copy under a different env var (AGL-1275) — that env edit is exactly
|
|
126
|
+
* the move which used to leave the two disagreeing.
|
|
127
|
+
*/ /**
|
|
128
|
+
* The `stray` half exists because the intersection above is deliberately an
|
|
129
|
+
* `some`, and a name can answer with our addresses AND somebody else's at the
|
|
130
|
+
* same time (AGL-1913).
|
|
131
|
+
*
|
|
132
|
+
* That is the shape a stale A record makes: a previous host's address left in
|
|
133
|
+
* the zone answers alongside a correct ALIAS, the resolver hands out whichever
|
|
134
|
+
* it likes, and the site loads for one visitor and not the next. Every check we
|
|
135
|
+
* had reported that domain as verified, because it is — some of the time — and
|
|
136
|
+
* "it works when I try it" is exactly why nobody finds it.
|
|
137
|
+
*
|
|
138
|
+
* Reported, not refused. Refusing would mean treating "an address we do not
|
|
139
|
+
* recognise" as proof of misconfiguration, and the recognised set is an env var
|
|
140
|
+
* plus a live lookup of one hostname: the day the platform widens its pool
|
|
141
|
+
* ahead of our config, refusing would fail every correctly-pointed apex at
|
|
142
|
+
* once. A warning costs a confused customer nothing and cannot take the flow
|
|
143
|
+
* down.
|
|
144
|
+
*/ async function apexPointsAtTenantEdge(domain) {
|
|
145
|
+
const [domainAddresses, targetAddresses] = await Promise.all([
|
|
146
|
+
resolveARecords(domain),
|
|
147
|
+
resolveARecords(CNAME_TARGET)
|
|
148
|
+
]);
|
|
149
|
+
if (!domainAddresses.length) return {
|
|
150
|
+
matched: false,
|
|
151
|
+
stray: []
|
|
152
|
+
};
|
|
153
|
+
const acceptable = new Set([
|
|
154
|
+
...targetAddresses,
|
|
155
|
+
...HOST_APEX_ADDRESSES
|
|
156
|
+
]);
|
|
157
|
+
return {
|
|
158
|
+
matched: domainAddresses.some((address)=>acceptable.has(address)),
|
|
159
|
+
stray: domainAddresses.filter((address)=>!acceptable.has(address))
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Resolves `domain` and answers whether it points at the tenant edge: its
|
|
164
|
+
* CNAME names `CNAME_TARGET`, or, carrying no CNAME, its addresses are ours.
|
|
165
|
+
*
|
|
166
|
+
* `softPass` accepts ANY CNAME and belongs to local development alone, where
|
|
167
|
+
* nothing points at the edge. A caller passes `isDevelopmentRuntime()` and
|
|
168
|
+
* never a guess: a soft pass that keys on a missing hosting variable is the
|
|
169
|
+
* AGL-2180 hole, where any domain with any CNAME verified on a container.
|
|
170
|
+
*
|
|
171
|
+
* Expects a lowercased name that matched {@link TENANT_DNS_DOMAIN_PATTERN}.
|
|
172
|
+
* Never throws: an unreachable resolver reads as no records.
|
|
173
|
+
*/ export async function checkTenantDnsPointing(domain, options = {}) {
|
|
174
|
+
// NXDOMAIN / no CNAME comes back as an empty list — reported as unverified.
|
|
175
|
+
const records = await resolveCnameRecords(domain);
|
|
176
|
+
const cnameVerified = records.includes(CNAME_TARGET) || options.softPass === true && records.length > 0;
|
|
177
|
+
// Only fall back to the address comparison when there is no CNAME at all.
|
|
178
|
+
// A domain that DOES carry a CNAME but points somewhere else must keep
|
|
179
|
+
// failing — otherwise "pointed at the wrong place" and "pointed at an apex"
|
|
180
|
+
// would verify identically.
|
|
181
|
+
const apex = records.length ? {
|
|
182
|
+
matched: false,
|
|
183
|
+
stray: []
|
|
184
|
+
} : await apexPointsAtTenantEdge(domain);
|
|
185
|
+
return _extends({
|
|
186
|
+
domain,
|
|
187
|
+
records,
|
|
188
|
+
expected: CNAME_TARGET,
|
|
189
|
+
verified: cnameVerified || apex.matched
|
|
190
|
+
}, apex.matched && {
|
|
191
|
+
matchedBy: 'apex-address'
|
|
192
|
+
}, apex.stray.length ? {
|
|
193
|
+
strayAddresses: apex.stray
|
|
194
|
+
} : {});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
//# sourceMappingURL=tenant-dns-check.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/tenant-dns-check.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 { CNAME_TARGET, HOST_APEX_ADDRESSES } from '@aglyn/aglyn/app-utils/tenant-dns-targets'\nimport { promises as dns, Resolver as CallbackResolver } from 'dns'\nimport { PUBLIC_DNS_RESOLVERS as PUBLIC_RESOLVERS } from './dns-probe'\n\n/**\n * WHETHER A NAME POINTS AT THE TENANT EDGE: the check behind\n * `/api/domains/verify`, here so a caller with no request of its own reads\n * the same answer (AGL-3963). The domains plugin's one-click DNS asks it after\n * a DNS provider wrote the records, and its sweep asks it again for a session\n * whose owner closed the tab; neither can import the console app, and a\n * second copy of this rule is how the displayed target and the accepted one\n * came apart before (AGL-733).\n *\n * The targets are `@aglyn/aglyn/app-utils/tenant-dns-targets`, the values the\n * connect card prints.\n */\n\n/** A domain as the check accepts one: labels of letters, digits and hyphens. */\nexport const TENANT_DNS_DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/i\n\n/**\n * Resolve against public resolvers rather than the runtime's default (AGL-734).\n *\n * A stale zone left over from a nameserver migration made Vercel's own resolver\n * return NXDOMAIN for records that every public resolver could see — so a\n * correctly-configured domain reported \"no CNAME record found\" indefinitely,\n * while `dig` from anywhere else resolved it fine. Pinning the resolver makes\n * the check depend on public DNS, which is what the customer's browser will use\n * anyway, instead of on whatever cache a given lambda inherited.\n *\n * Falls back to the default resolver if the pinned ones are unreachable, so a\n * blocked egress path degrades to today's behaviour rather than failing shut.\n */\n\nasync function resolveCnameRecords(domain: string): Promise<string[]> {\n const normalise = (records: string[]) =>\n records.map((record) => record.toLowerCase().replace(/\\.$/, ''))\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[]>((resolve, reject) => {\n resolver.resolveCname(domain, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return normalise(records)\n } catch (error) {\n // ENOTFOUND/ENODATA are real answers — the name has no CNAME. Only fall\n // back when the pinned resolvers could not be reached at all.\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return normalise(await dns.resolveCname(domain))\n } catch {\n return []\n }\n }\n}\n\nasync function resolveARecords(domain: string): Promise<string[]> {\n const lookup = async (resolver?: CallbackResolver) =>\n resolver\n ? new Promise<string[]>((resolve, reject) => {\n resolver.resolve4(domain, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n : dns.resolve4(domain)\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n return await lookup(resolver)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return await lookup()\n } catch {\n return []\n }\n }\n}\n\n/**\n * An apex (`aglyn.com`) cannot carry a CNAME — RFC 1034 forbids one alongside\n * the SOA/NS records every zone apex must have. So the CNAME check below can\n * never pass for a bare domain, and until this existed the wizard simply\n * refused every apex: customers could connect `www.` and nothing else.\n *\n * Instead, compare where the domain actually lands against where the CNAME\n * target lands. Both sides are resolved at check time rather than compared to\n * a hardcoded address list, because the edge IPs behind `sites.aglyn.app` are\n * the host's to change — pinning them here would turn a routine infrastructure\n * change into every customer's domain reporting itself broken.\n *\n * An intersection, not equality: the two names legitimately return different\n * subsets of the same anycast pool from one lookup to the next.\n *\n * `HOST_APEX_ADDRESSES` covers the case the intersection cannot: our platform\n * host publishes a small anycast pool for every apex it serves, routing by\n * `Host` rather than by IP. An apex pointed there therefore never shares an\n * address with `sites.aglyn.app`, yet is configured correctly.\n *\n * The list has to span the host's WHOLE pool, not just the address we happen\n * to have used. It shipped with only `76.76.21.21` — the host's legacy\n * address, which still resolves but is no longer what a newly-pointed apex\n * lands on, so every new customer would have failed the very check this\n * fallback exists to let them pass. Our own zones are the proof: after taking\n * the host's recommended records, `aglyn.com` and `aglyn.io` resolve into the\n * `216.198.79.x` / `64.29.17.x` range and not one of them is the legacy\n * address. Keep the legacy entry — zones still pointed at it work fine.\n *\n * Accepting an address match is deliberately a weaker claim — \"this domain\n * resolves to our platform\" rather than \"to this account\". That is sound\n * because it is not the ownership check: attaching a domain to the project is,\n * and the platform performs that itself. This only answers \"has DNS been\n * pointed yet\", which is what the customer is actually stuck on. Configurable\n * so the next range expansion is an env edit rather than a patch.\n *\n * The list itself lives in `tenant-dns-targets.ts` beside `CNAME_TARGET`, so the\n * wizard prints an address this check will actually accept rather than keeping\n * its own copy under a different env var (AGL-1275) — that env edit is exactly\n * the move which used to leave the two disagreeing.\n */\n/**\n * The `stray` half exists because the intersection above is deliberately an\n * `some`, and a name can answer with our addresses AND somebody else's at the\n * same time (AGL-1913).\n *\n * That is the shape a stale A record makes: a previous host's address left in\n * the zone answers alongside a correct ALIAS, the resolver hands out whichever\n * it likes, and the site loads for one visitor and not the next. Every check we\n * had reported that domain as verified, because it is — some of the time — and\n * \"it works when I try it\" is exactly why nobody finds it.\n *\n * Reported, not refused. Refusing would mean treating \"an address we do not\n * recognise\" as proof of misconfiguration, and the recognised set is an env var\n * plus a live lookup of one hostname: the day the platform widens its pool\n * ahead of our config, refusing would fail every correctly-pointed apex at\n * once. A warning costs a confused customer nothing and cannot take the flow\n * down.\n */\nasync function apexPointsAtTenantEdge(\n domain: string,\n): Promise<{ matched: boolean; stray: string[] }> {\n const [domainAddresses, targetAddresses] = await Promise.all([\n resolveARecords(domain),\n resolveARecords(CNAME_TARGET),\n ])\n if (!domainAddresses.length) return { matched: false, stray: [] }\n const acceptable = new Set([...targetAddresses, ...HOST_APEX_ADDRESSES])\n return {\n matched: domainAddresses.some((address) => acceptable.has(address)),\n stray: domainAddresses.filter((address) => !acceptable.has(address)),\n }\n}\n\n/** What the check found for one name, as `/api/domains/verify` answers it. */\nexport interface TenantDnsCheck {\n domain: string\n /** The name's CNAME targets, lowercased; empty when it carries none. */\n records: string[]\n /** The CNAME target a subdomain must name. */\n expected: string\n verified: boolean\n /** Set when an apex passed by the addresses it lands on. */\n matchedBy?: 'apex-address'\n /** Addresses answering for the name that are not ours (AGL-1913). */\n strayAddresses?: string[]\n}\n\n/**\n * Resolves `domain` and answers whether it points at the tenant edge: its\n * CNAME names `CNAME_TARGET`, or, carrying no CNAME, its addresses are ours.\n *\n * `softPass` accepts ANY CNAME and belongs to local development alone, where\n * nothing points at the edge. A caller passes `isDevelopmentRuntime()` and\n * never a guess: a soft pass that keys on a missing hosting variable is the\n * AGL-2180 hole, where any domain with any CNAME verified on a container.\n *\n * Expects a lowercased name that matched {@link TENANT_DNS_DOMAIN_PATTERN}.\n * Never throws: an unreachable resolver reads as no records.\n */\nexport async function checkTenantDnsPointing(\n domain: string,\n options: { softPass?: boolean } = {},\n): Promise<TenantDnsCheck> {\n // NXDOMAIN / no CNAME comes back as an empty list — reported as unverified.\n const records = await resolveCnameRecords(domain)\n const cnameVerified =\n records.includes(CNAME_TARGET) || (options.softPass === true && records.length > 0)\n // Only fall back to the address comparison when there is no CNAME at all.\n // A domain that DOES carry a CNAME but points somewhere else must keep\n // failing — otherwise \"pointed at the wrong place\" and \"pointed at an apex\"\n // would verify identically.\n const apex = records.length\n ? { matched: false, stray: [] as string[] }\n : await apexPointsAtTenantEdge(domain)\n return {\n domain,\n records,\n expected: CNAME_TARGET,\n verified: cnameVerified || apex.matched,\n // Which rule passed, so the wizard can explain itself rather than just\n // showing a tick.\n ...(apex.matched && { matchedBy: 'apex-address' as const }),\n // Addresses answering for the name that are not ours. A verified domain\n // with a non-empty list here is the one that loads intermittently.\n ...(apex.stray.length ? { strayAddresses: apex.stray } : {}),\n }\n}\n"],"names":["CNAME_TARGET","HOST_APEX_ADDRESSES","promises","dns","Resolver","CallbackResolver","PUBLIC_DNS_RESOLVERS","PUBLIC_RESOLVERS","TENANT_DNS_DOMAIN_PATTERN","resolveCnameRecords","domain","normalise","records","map","record","toLowerCase","replace","resolver","setServers","Promise","resolve","reject","resolveCname","error","addresses","code","resolveARecords","lookup","resolve4","apexPointsAtTenantEdge","domainAddresses","targetAddresses","all","length","matched","stray","acceptable","Set","some","address","has","filter","checkTenantDnsPointing","options","cnameVerified","includes","softPass","apex","expected","verified","matchedBy","strayAddresses"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,mBAAmB,QAAQ,4CAA2C;AAC7F,SAASC,YAAYC,GAAG,EAAEC,YAAYC,gBAAgB,QAAQ,MAAK;AACnE,SAASC,wBAAwBC,gBAAgB,QAAQ,iBAAa;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|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
* so a comp granted to evaluate cannot revive free access if the customer
|
|
29
29
|
* later cancels.
|
|
30
30
|
*/
|
|
31
|
-
import type { OrgUpgradeProposal } from '@aglyn/aglyn/server';
|
|
31
|
+
import type { AglynOrgBilling, OrgUpgradeProposal } from '@aglyn/aglyn/server';
|
|
32
32
|
/** The override reason a sales-evaluation comp is granted under. */
|
|
33
33
|
export declare const TRIAL_PLAN_COMP_REASON = "trial";
|
|
34
34
|
/** A proposal refused before anything was written. */
|
|
@@ -40,6 +40,13 @@ export interface ProposeOrgUpgradeOptions {
|
|
|
40
40
|
orgId: string;
|
|
41
41
|
plan: unknown;
|
|
42
42
|
note?: unknown;
|
|
43
|
+
/**
|
|
44
|
+
* The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any
|
|
45
|
+
* shape `parseBundleAddons` reads; fitted to the plan before storing.
|
|
46
|
+
*/
|
|
47
|
+
addons?: unknown;
|
|
48
|
+
interval?: unknown;
|
|
49
|
+
coupon?: unknown;
|
|
43
50
|
/** The staff member proposing. */
|
|
44
51
|
actor: {
|
|
45
52
|
uid: string;
|
|
@@ -66,6 +73,38 @@ export interface ProposeOrgUpgradeResult {
|
|
|
66
73
|
* buy themselves.
|
|
67
74
|
*/
|
|
68
75
|
export declare function proposeOrgUpgrade(options: ProposeOrgUpgradeOptions): Promise<ProposeOrgUpgradeResult>;
|
|
76
|
+
/**
|
|
77
|
+
* The proposal as it will be stored, or the refusal: a plan the workspace
|
|
78
|
+
* can buy itself, a bounded note, and the bundle fitted to the plan
|
|
79
|
+
* (AGL-3956). Nothing is read or written.
|
|
80
|
+
*/
|
|
81
|
+
export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {
|
|
82
|
+
now?: number;
|
|
83
|
+
}): OrgUpgradeProposal;
|
|
84
|
+
/**
|
|
85
|
+
* Read the org a proposal is for, inside the caller's transaction, refusing
|
|
86
|
+
* an unknown workspace and one whose subscription is already live — the
|
|
87
|
+
* question a proposal asks is then already answered.
|
|
88
|
+
*/
|
|
89
|
+
export declare function readUpgradeProposalTarget(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference): Promise<Partial<AglynOrgBilling>>;
|
|
90
|
+
/**
|
|
91
|
+
* Write the proposal and its audit row into the caller's transaction, so
|
|
92
|
+
* they commit with whatever else the caller writes (AGL-1784) — the owner
|
|
93
|
+
* invitation, for a hand-off that proposes in the same act (AGL-3956).
|
|
94
|
+
*/
|
|
95
|
+
export declare function stageUpgradeProposal(tx: FirebaseFirestore.Transaction, db: FirebaseFirestore.Firestore, options: {
|
|
96
|
+
orgId: string;
|
|
97
|
+
proposal: OrgUpgradeProposal;
|
|
98
|
+
before: Partial<AglynOrgBilling>;
|
|
99
|
+
actorUid: string;
|
|
100
|
+
}): void;
|
|
101
|
+
/** "Proposed the Starter plan", naming the bundle when there is one. */
|
|
102
|
+
export declare function proposalActivityLine(proposal: OrgUpgradeProposal): string;
|
|
103
|
+
/** The workspace's feed line for a proposal, after it commits. */
|
|
104
|
+
export declare function recordUpgradeProposalActivity(orgId: string, actor: {
|
|
105
|
+
uid: string;
|
|
106
|
+
email?: string | null;
|
|
107
|
+
}, proposal: OrgUpgradeProposal): Promise<void>;
|
|
69
108
|
/** Remove a standing proposal, audited. Answers whether one stood. */
|
|
70
109
|
export declare function withdrawOrgUpgrade(options: {
|
|
71
110
|
orgId: string;
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
30
30
|
import { PLAN_LABELS } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
31
31
|
import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
|
|
32
|
-
import { isUpgradeProposalPlan, normalizeUpgradeProposalNote, upgradeProposalDestination } from "@aglyn/aglyn/app-utils/upgrade-proposal";
|
|
32
|
+
import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, normalizeUpgradeProposalNote, upgradeProposalDestination, upgradeProposalSummary } from "@aglyn/aglyn/app-utils/upgrade-proposal";
|
|
33
33
|
// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).
|
|
34
34
|
import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
|
|
35
35
|
import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
|
|
@@ -60,72 +60,110 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
60
60
|
* a proposal asks is already answered — and for any plan a customer cannot
|
|
61
61
|
* buy themselves.
|
|
62
62
|
*/ export async function proposeOrgUpgrade(options) {
|
|
63
|
-
var _actor_email;
|
|
64
63
|
const { orgId, actor, origin } = options;
|
|
64
|
+
const proposal = buildUpgradeProposal(options);
|
|
65
|
+
const db = firestore();
|
|
66
|
+
const orgRef = db.collection('orgs').doc(orgId);
|
|
67
|
+
const org = await db.runTransaction(async (tx)=>{
|
|
68
|
+
const data = await readUpgradeProposalTarget(tx, orgRef);
|
|
69
|
+
stageUpgradeProposal(tx, db, {
|
|
70
|
+
orgId,
|
|
71
|
+
proposal,
|
|
72
|
+
before: data,
|
|
73
|
+
actorUid: actor.uid
|
|
74
|
+
});
|
|
75
|
+
return data;
|
|
76
|
+
});
|
|
77
|
+
await recordUpgradeProposalActivity(orgId, actor, proposal);
|
|
78
|
+
const emailed = await emailUpgradeProposal({
|
|
79
|
+
orgId,
|
|
80
|
+
org,
|
|
81
|
+
proposal,
|
|
82
|
+
origin
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
proposal,
|
|
86
|
+
emailed
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The proposal as it will be stored, or the refusal: a plan the workspace
|
|
91
|
+
* can buy itself, a bounded note, and the bundle fitted to the plan
|
|
92
|
+
* (AGL-3956). Nothing is read or written.
|
|
93
|
+
*/ export function buildUpgradeProposal(options) {
|
|
94
|
+
var _options_now;
|
|
65
95
|
if (!isUpgradeProposalPlan(options.plan)) {
|
|
66
96
|
throw new UpgradeProposalError('Choose a paid plan the workspace can buy itself');
|
|
67
97
|
}
|
|
68
98
|
const plan = options.plan;
|
|
69
99
|
const note = normalizeUpgradeProposalNote(options.note);
|
|
70
|
-
|
|
71
|
-
const orgRef = db.collection('orgs').doc(orgId);
|
|
72
|
-
const proposal = _extends({
|
|
100
|
+
return _extends({
|
|
73
101
|
plan,
|
|
74
|
-
proposedBy: actor.uid,
|
|
75
|
-
proposedAt: Date.now()
|
|
102
|
+
proposedBy: options.actor.uid,
|
|
103
|
+
proposedAt: (_options_now = options.now) != null ? _options_now : Date.now()
|
|
76
104
|
}, note ? {
|
|
77
105
|
note
|
|
78
|
-
} : {});
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
106
|
+
} : {}, normalizeUpgradeProposalBundle(plan, options));
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Read the org a proposal is for, inside the caller's transaction, refusing
|
|
110
|
+
* an unknown workspace and one whose subscription is already live — the
|
|
111
|
+
* question a proposal asks is then already answered.
|
|
112
|
+
*/ export async function readUpgradeProposalTarget(tx, orgRef) {
|
|
113
|
+
var _ref;
|
|
114
|
+
var _billing_get;
|
|
115
|
+
const snapshot = await tx.get(orgRef);
|
|
116
|
+
if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404);
|
|
117
|
+
const data = snapshot.data();
|
|
118
|
+
const billing = await tx.get(orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID));
|
|
119
|
+
const status = (_ref = (_billing_get = billing.get('subscription')) == null ? void 0 : _billing_get.status) != null ? _ref : data.billingStatus;
|
|
120
|
+
if (isLiveSubscriptionStatus(status)) {
|
|
121
|
+
throw new UpgradeProposalError('This workspace already has a live subscription, so there is nothing to propose', 409);
|
|
122
|
+
}
|
|
123
|
+
return data;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Write the proposal and its audit row into the caller's transaction, so
|
|
127
|
+
* they commit with whatever else the caller writes (AGL-1784) — the owner
|
|
128
|
+
* invitation, for a hand-off that proposes in the same act (AGL-3956).
|
|
129
|
+
*/ export function stageUpgradeProposal(tx, db, options) {
|
|
130
|
+
var _before_upgradeProposal;
|
|
131
|
+
const { orgId, proposal, before, actorUid } = options;
|
|
132
|
+
tx.set(db.collection('orgs').doc(orgId), {
|
|
133
|
+
upgradeProposal: proposal,
|
|
134
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
135
|
+
}, {
|
|
136
|
+
merge: true
|
|
109
137
|
});
|
|
138
|
+
setAdminAudit(tx, db, {
|
|
139
|
+
actorUid,
|
|
140
|
+
action: 'org.upgradeProposal.propose',
|
|
141
|
+
target: `orgs/${orgId}`,
|
|
142
|
+
before: {
|
|
143
|
+
upgradeProposal: (_before_upgradeProposal = before.upgradeProposal) != null ? _before_upgradeProposal : null
|
|
144
|
+
},
|
|
145
|
+
after: {
|
|
146
|
+
upgradeProposal: proposal
|
|
147
|
+
},
|
|
148
|
+
at: FieldValue.serverTimestamp()
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** "Proposed the Starter plan", naming the bundle when there is one. */ export function proposalActivityLine(proposal) {
|
|
152
|
+
const label = planName(proposal.plan);
|
|
153
|
+
const summary = upgradeProposalSummary(proposal);
|
|
154
|
+
return summary === label ? `Proposed the ${label} plan` : `Proposed the ${label} plan (${summary})`;
|
|
155
|
+
}
|
|
156
|
+
/** The workspace's feed line for a proposal, after it commits. */ export async function recordUpgradeProposalActivity(orgId, actor, proposal) {
|
|
157
|
+
var _actor_email;
|
|
110
158
|
await logOrgActivity(orgId, {
|
|
111
159
|
uid: actor.uid,
|
|
112
160
|
email: (_actor_email = actor.email) != null ? _actor_email : null
|
|
113
|
-
},
|
|
161
|
+
}, proposalActivityLine(proposal), {
|
|
114
162
|
type: 'subscription',
|
|
115
163
|
id: orgId
|
|
116
164
|
}, {
|
|
117
165
|
staffActorId: actor.uid
|
|
118
166
|
});
|
|
119
|
-
const emailed = await emailUpgradeProposal({
|
|
120
|
-
orgId,
|
|
121
|
-
org,
|
|
122
|
-
proposal,
|
|
123
|
-
origin
|
|
124
|
-
});
|
|
125
|
-
return {
|
|
126
|
-
proposal,
|
|
127
|
-
emailed
|
|
128
|
-
};
|
|
129
167
|
}
|
|
130
168
|
/** Remove a standing proposal, audited. Answers whether one stood. */ export async function withdrawOrgUpgrade(options) {
|
|
131
169
|
var _actor_email;
|
|
@@ -278,14 +316,18 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
278
316
|
const billingUrl = slug ? `${origin}${upgradeProposalDestination(slug, proposal)}` : origin;
|
|
279
317
|
const label = planName(proposal.plan);
|
|
280
318
|
const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME;
|
|
319
|
+
const summary = upgradeProposalSummary(proposal, {
|
|
320
|
+
brand: productName
|
|
321
|
+
});
|
|
281
322
|
const content = await renderSystemEmailContent('org-upgrade-proposal', {
|
|
282
323
|
'org.name': orgName,
|
|
283
324
|
'plan.name': label,
|
|
284
325
|
'proposal.note': (_proposal_note = proposal.note) != null ? _proposal_note : '',
|
|
326
|
+
'proposal.summary': summary === label ? '' : summary,
|
|
285
327
|
billingUrl
|
|
286
328
|
}, brand, {
|
|
287
329
|
subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,
|
|
288
|
-
text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + 'plan. When you are ready, start the subscription from Billing, ' + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
|
|
330
|
+
text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + (summary === label ? 'plan. ' : `plan (${summary}). `) + 'When you are ready, start the subscription from Billing, ' + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
|
|
289
331
|
});
|
|
290
332
|
const result = await sendEmail(_extends({
|
|
291
333
|
to,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.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 platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n const note = normalizeUpgradeProposalNote(options.note)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const proposal: OrgUpgradeProposal = {\n plan,\n proposedBy: actor.uid,\n proposedAt: Date.now(),\n ...(note ? { note } : {}),\n }\n const org = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n tx.set(\n orgRef,\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: data.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n return data\n })\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Proposed the ${PLAN_LABELS[plan]} plan`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n 'plan. When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalNote","upgradeProposalDestination","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","actor","orgId","origin","plan","note","db","orgRef","collection","doc","proposal","proposedBy","uid","proposedAt","Date","now","org","runTransaction","tx","data","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","actorUid","action","target","before","after","at","email","type","id","staffActorId","emailed","emailUpgradeProposal","withdrawOrgUpgrade","withdrawn","stored","delete","planName","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","label","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,4BAA4B,EAC5BC,0BAA0B,QACrB,0CAAyC;AAChD,wEAAwE;AACxE,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAC/C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B,MAAMC,YAAY,IAAMJ,cAAcK,GAAG,GAAGD,SAAS;AAErD,kEAAkE,GAClE,OAAO,MAAME,yBAAyB,QAAO;AAE7C,oDAAoD,GACpD,OAAO,MAAMC,6BAA6BC;IAExC,YAAYC,OAAe,EAAEC,SAAS,GAAG,CAAE;QACzC,KAAK,CAACD;QACN,IAAI,CAACE,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IA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H,SAAS;YAC7EO,MACE,CAAC,KAAK,EAAEH,YAAY,sBAAsB,EAAEJ,QAAQ,QAAQ,EAAEG,MAAM,CAAC,CAAC,GACtE,oEACA,CAAC,uCAAuC,EAAED,YAAY,GACrD5D,CAAAA,SAASL,IAAI,GAAG,CAAC,IAAI,EAAEK,SAASL,IAAI,EAAE,GAAG,EAAC;QAC/C;QAEF,MAAMuE,SAAS,MAAM7F,UAAU;YAC7BmF;YACAQ,SAASD,QAAQC,OAAO;YACxBC,MAAMF,QAAQE,IAAI;WACdF,QAAQI,IAAI,GAAG;YAAEA,MAAMJ,QAAQI,IAAI;QAAC,IAAI,CAAC,GACzCV,MAAMW,QAAQ,GAAG;YAAEA,UAAUX,MAAMW,QAAQ;QAAC,IAAI,CAAC;YACrD9B,SAAS;;QAEX,IAAI4B,OAAOG,IAAI,EAAE,MAAM7F,cAAcgB;QACrC,OAAO0E,OAAOG,IAAI;IACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAASlC,SAAS1C,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQ9B,cACvCA,WAAW,CAAC8B,KAAgB,GAC5B8E,OAAO9E,eAAAA,OAAQ;AACrB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.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 platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AA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ACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAAS1C,SAAStB,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQlD,cACvCA,WAAW,CAACkD,KAAgB,GAC5BkE,OAAOlE,eAAAA,OAAQ;AACrB"}
|
package/src/tenancy.d.ts
CHANGED
|
@@ -25,6 +25,7 @@ export type { MerchantAccountReadiness, MerchantAccountReadinessInput, PaymentMo
|
|
|
25
25
|
export * from './lib/server/auth-handoff';
|
|
26
26
|
export * from './lib/server/console-domains';
|
|
27
27
|
export * from './lib/server/dns-probe';
|
|
28
|
+
export * from './lib/server/tenant-dns-check';
|
|
28
29
|
export * from './lib/server/sending-domains';
|
|
29
30
|
export * from './lib/server/sender-readiness';
|
|
30
31
|
export * from './lib/server/host-sending-domain';
|
|
@@ -62,6 +63,8 @@ export * from './lib/server/firebase-admin';
|
|
|
62
63
|
export * from './lib/server/free-workspace-cap';
|
|
63
64
|
export * from './lib/server/ga4-measurement-protocol';
|
|
64
65
|
export * from './lib/server/host-memberships';
|
|
66
|
+
export * from './lib/server/host-custom-domain';
|
|
67
|
+
export * from './lib/server/custom-domain-redirects';
|
|
65
68
|
export * from './lib/server/host-visitor-records';
|
|
66
69
|
export * from './lib/server/list-members';
|
|
67
70
|
export * from './lib/server/lockdown';
|
|
@@ -105,6 +108,8 @@ export * from './lib/server/media-strong-digest';
|
|
|
105
108
|
export * from './lib/server/media-tombstone';
|
|
106
109
|
export * from './lib/server/media-delivery-regeneration';
|
|
107
110
|
export * from './lib/server/media-variants';
|
|
111
|
+
export * from './lib/server/media-photo-links';
|
|
112
|
+
export * from './lib/server/client-build';
|
|
108
113
|
export * from './lib/server/serve-media-cdn';
|
|
109
114
|
export * from './lib/server/serve-plugin-fetch';
|
|
110
115
|
export * from './lib/server/configured-url-fetch';
|