@aglyn/tenant-data-admin 1.0.0-beta.270 → 1.0.0-beta.272
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/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 -32
- package/src/lib/server/billing-addons.js +100 -86
- 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/domain-ownership.d.ts +205 -0
- package/src/lib/server/domain-ownership.js +575 -0
- package/src/lib/server/domain-ownership.js.map +1 -0
- package/src/lib/server/erase.d.ts +17 -0
- package/src/lib/server/erase.js +21 -0
- package/src/lib/server/erase.js.map +1 -1
- 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/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/site-care-emails.d.ts +53 -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 +123 -0
- package/src/lib/server/site-care-inbound.js +197 -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/sso-provisioning.d.ts +6 -0
- package/src/lib/server/sso-provisioning.js +7 -0
- package/src/lib/server/sso-provisioning.js.map +1 -1
- 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 +1 -0
- package/src/tenancy.js +2 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1,123 @@
|
|
|
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 { type ReceivedEmail } from '@aglyn/shared-util-email';
|
|
18
|
+
import { type SiteCareDeps } from './site-care-requests';
|
|
19
|
+
/**
|
|
20
|
+
* SITE CARE MAIL ARRIVES AT THE SUPPORT ADDRESS (AGL-3959, AGL-3997).
|
|
21
|
+
*
|
|
22
|
+
* Site Care has no address of its own. An owner emails the support address
|
|
23
|
+
* they already know, and the support mailbox delivers a copy of each message
|
|
24
|
+
* to `support@<inbound mail domain>`, where the mail provider announces it.
|
|
25
|
+
* A message to either address from a member of a workspace with Site Care
|
|
26
|
+
* becomes a Site Care request on that workspace, matched by the sender's
|
|
27
|
+
* address against the members of workspaces that have Site Care. A reply to
|
|
28
|
+
* any Site Care email goes to `support+<requestId>@…` and joins that
|
|
29
|
+
* request's thread, when the sender is a member of its workspace.
|
|
30
|
+
*
|
|
31
|
+
* Everything else is acknowledged and left alone: nothing is filed and
|
|
32
|
+
* nothing is sent back, and a message to the support address stays in the
|
|
33
|
+
* support inbox as ordinary support mail. That includes the platform's own
|
|
34
|
+
* mail and anything a machine sent: an out-of-office answering a Site Care
|
|
35
|
+
* email would otherwise join the request, and one answering anything that
|
|
36
|
+
* replies to support would open one.
|
|
37
|
+
*/
|
|
38
|
+
/** What a received message was addressed to: a new request, or a reply on one. */
|
|
39
|
+
export type SiteCareInboundTarget = {
|
|
40
|
+
kind: 'new';
|
|
41
|
+
} | {
|
|
42
|
+
kind: 'reply';
|
|
43
|
+
requestId: string;
|
|
44
|
+
};
|
|
45
|
+
/** The addresses the intake reads as the platform's own. */
|
|
46
|
+
export interface SiteCareInboundAddresses {
|
|
47
|
+
/** The inbound mail domain: `support@` and `support+<requestId>@` it. */
|
|
48
|
+
domain: string;
|
|
49
|
+
/** The operator's support address, or null when the deployment publishes none. */
|
|
50
|
+
supportEmail: string | null;
|
|
51
|
+
/** The address the platform sends from, `USAGE_EMAIL_FROM`'s, or null. */
|
|
52
|
+
platformSender: string | null;
|
|
53
|
+
}
|
|
54
|
+
/** This deployment's {@link SiteCareInboundAddresses}, read per call. */
|
|
55
|
+
export declare function siteCareInboundAddresses(): SiteCareInboundAddresses;
|
|
56
|
+
/** The Site Care target among a message's recipients, or null. */
|
|
57
|
+
export declare function siteCareInboundTarget(recipients: readonly string[], addresses: Pick<SiteCareInboundAddresses, 'domain' | 'supportEmail'>): SiteCareInboundTarget | null;
|
|
58
|
+
/** Why a message is ignored without a lookup: the platform wrote it, or a machine did. */
|
|
59
|
+
export type SiteCareMachineMail = 'ours' | 'automatic';
|
|
60
|
+
/**
|
|
61
|
+
* Whether a message is not a person writing in: from the support address,
|
|
62
|
+
* the platform's sender or any address on the inbound mail domain, or one
|
|
63
|
+
* its headers say a machine sent. Null when it may be a person.
|
|
64
|
+
*/
|
|
65
|
+
export declare function siteCareMachineMail(message: Pick<ReceivedEmail, 'from' | 'autoSubmitted'>, addresses: SiteCareInboundAddresses): SiteCareMachineMail | null;
|
|
66
|
+
export interface SiteCareSenderMatch {
|
|
67
|
+
orgId: string;
|
|
68
|
+
org: Record<string, unknown>;
|
|
69
|
+
uid: string;
|
|
70
|
+
email: string;
|
|
71
|
+
}
|
|
72
|
+
/** The account an address signs in with: its uid, or null when it has none. */
|
|
73
|
+
export type SiteCareAccountLookup = (email: string) => Promise<{
|
|
74
|
+
uid: string;
|
|
75
|
+
} | null>;
|
|
76
|
+
/**
|
|
77
|
+
* Every pool, not only the project's: an owner who signs in through SSO is a
|
|
78
|
+
* GCIP tenant user the project pool never returns (AGL-1122), and their mail
|
|
79
|
+
* would be read as a stranger's.
|
|
80
|
+
*/
|
|
81
|
+
export declare const findSiteCareAccount: SiteCareAccountLookup;
|
|
82
|
+
/**
|
|
83
|
+
* The Site Care workspace a sender belongs to: the account their address
|
|
84
|
+
* signs in with (in any pool), then the workspaces it is a member of, the
|
|
85
|
+
* first with Site Care in force (by id, so the choice is stable).
|
|
86
|
+
*/
|
|
87
|
+
export declare function findSiteCareWorkspaceForSender(firestore: FirebaseFirestore.Firestore, findAccount: SiteCareAccountLookup, sender: string): Promise<SiteCareSenderMatch | null>;
|
|
88
|
+
/** The words of a message, above any quoted history. */
|
|
89
|
+
export declare function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string;
|
|
90
|
+
/** Why a message was acknowledged and left alone. */
|
|
91
|
+
export type SiteCareIgnoredReason =
|
|
92
|
+
/** No workspace with Site Care has the sender as a member: ordinary support mail. */
|
|
93
|
+
'not-a-member'
|
|
94
|
+
/** The platform's own address wrote it. */
|
|
95
|
+
| 'ours'
|
|
96
|
+
/** Its headers say a machine sent it. */
|
|
97
|
+
| 'automatic'
|
|
98
|
+
/** A member wrote, but said nothing. */
|
|
99
|
+
| 'empty';
|
|
100
|
+
export type SiteCareInboundOutcome = {
|
|
101
|
+
outcome: 'opened';
|
|
102
|
+
requestId: string;
|
|
103
|
+
} | {
|
|
104
|
+
outcome: 'replied';
|
|
105
|
+
requestId: string;
|
|
106
|
+
} | {
|
|
107
|
+
outcome: 'ignored';
|
|
108
|
+
reason: SiteCareIgnoredReason;
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Files one received message addressed to the support address or to a
|
|
112
|
+
* request's reply address. Nothing is ever sent back to a sender it does
|
|
113
|
+
* not file for: a message to the support address is still in the support
|
|
114
|
+
* inbox, answered there like any other.
|
|
115
|
+
*/
|
|
116
|
+
export declare function fileSiteCareInboundEmail(firestore: FirebaseFirestore.Firestore, input: {
|
|
117
|
+
target: SiteCareInboundTarget;
|
|
118
|
+
message: ReceivedEmail;
|
|
119
|
+
/** The platform's own addresses; this deployment's by default. */
|
|
120
|
+
addresses?: SiteCareInboundAddresses;
|
|
121
|
+
/** The seam a spec replaces; every auth pool by default. */
|
|
122
|
+
findAccount?: SiteCareAccountLookup;
|
|
123
|
+
}, deps?: SiteCareDeps): Promise<SiteCareInboundOutcome>;
|
|
@@ -0,0 +1,197 @@
|
|
|
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
|
+
*/ import { inboundMailDomain } from "@aglyn/aglyn/app-utils/inbound-mail-domain";
|
|
17
|
+
import { emailAddressOf, htmlToPlainText, stripQuotedHistory, threadSubject } from "@aglyn/aglyn/app-utils/email-text";
|
|
18
|
+
import { SITE_CARE_INBOUND_LOCAL_PART, siteCareSupportAddress } from "@aglyn/aglyn/app-utils/site-care";
|
|
19
|
+
import { getEmailConfig } from "@aglyn/shared-util-email";
|
|
20
|
+
import { appendSiteCareReply, openSiteCareRequest, orgHasSiteCare, readSiteCareOrg } from "./site-care-requests.js";
|
|
21
|
+
import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
22
|
+
/** This deployment's {@link SiteCareInboundAddresses}, read per call. */ export function siteCareInboundAddresses() {
|
|
23
|
+
return {
|
|
24
|
+
domain: inboundMailDomain(),
|
|
25
|
+
supportEmail: emailAddressOf(siteCareSupportAddress()),
|
|
26
|
+
platformSender: emailAddressOf(getEmailConfig().from)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** The Site Care target among a message's recipients, or null. */ export function siteCareInboundTarget(recipients, addresses) {
|
|
30
|
+
const domain = addresses.domain.toLowerCase();
|
|
31
|
+
const support = emailAddressOf(addresses.supportEmail);
|
|
32
|
+
let found = null;
|
|
33
|
+
for (const value of recipients){
|
|
34
|
+
var _ref;
|
|
35
|
+
var _exec;
|
|
36
|
+
// Validated (and lowercased) for the comparison, but the local part is
|
|
37
|
+
// read as written: a request id is a case-sensitive Firestore id, and
|
|
38
|
+
// lowercasing `support+AbC…` would look up a ticket that does not exist.
|
|
39
|
+
const address = emailAddressOf(value);
|
|
40
|
+
if (!address) continue;
|
|
41
|
+
if (support && address === support) {
|
|
42
|
+
found = found != null ? found : {
|
|
43
|
+
kind: 'new'
|
|
44
|
+
};
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const raw = String(value != null ? value : '').trim();
|
|
48
|
+
const written = ((_ref = (_exec = /<([^<>]+)>\s*$/.exec(raw)) == null ? void 0 : _exec[1]) != null ? _ref : raw).trim();
|
|
49
|
+
const at = written.lastIndexOf('@');
|
|
50
|
+
if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain) continue;
|
|
51
|
+
const local = written.slice(0, at);
|
|
52
|
+
if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {
|
|
53
|
+
found = found != null ? found : {
|
|
54
|
+
kind: 'new'
|
|
55
|
+
};
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`;
|
|
59
|
+
if (local.toLowerCase().startsWith(prefix)) {
|
|
60
|
+
const requestId = local.slice(prefix.length);
|
|
61
|
+
// Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape
|
|
62
|
+
// is refused rather than looked up.
|
|
63
|
+
if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return {
|
|
64
|
+
kind: 'reply',
|
|
65
|
+
requestId
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return found;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Whether a message is not a person writing in: from the support address,
|
|
73
|
+
* the platform's sender or any address on the inbound mail domain, or one
|
|
74
|
+
* its headers say a machine sent. Null when it may be a person.
|
|
75
|
+
*/ export function siteCareMachineMail(message, addresses) {
|
|
76
|
+
const sender = emailAddressOf(message.from);
|
|
77
|
+
if (sender) {
|
|
78
|
+
const own = [
|
|
79
|
+
addresses.supportEmail,
|
|
80
|
+
addresses.platformSender
|
|
81
|
+
].map((value)=>emailAddressOf(value));
|
|
82
|
+
if (own.includes(sender)) return 'ours';
|
|
83
|
+
if (sender.slice(sender.lastIndexOf('@') + 1) === addresses.domain.toLowerCase()) return 'ours';
|
|
84
|
+
}
|
|
85
|
+
return message.autoSubmitted ? 'automatic' : null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Every pool, not only the project's: an owner who signs in through SSO is a
|
|
89
|
+
* GCIP tenant user the project pool never returns (AGL-1122), and their mail
|
|
90
|
+
* would be read as a stranger's.
|
|
91
|
+
*/ export const findSiteCareAccount = async (email)=>{
|
|
92
|
+
const found = await findUserByEmailAcrossPools(email).catch(()=>null);
|
|
93
|
+
return found ? {
|
|
94
|
+
uid: found.record.uid
|
|
95
|
+
} : null;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* The Site Care workspace a sender belongs to: the account their address
|
|
99
|
+
* signs in with (in any pool), then the workspaces it is a member of, the
|
|
100
|
+
* first with Site Care in force (by id, so the choice is stable).
|
|
101
|
+
*/ export async function findSiteCareWorkspaceForSender(firestore, findAccount, sender) {
|
|
102
|
+
const email = emailAddressOf(sender);
|
|
103
|
+
if (!email) return null;
|
|
104
|
+
const user = await findAccount(email).catch(()=>null);
|
|
105
|
+
if (!user) return null;
|
|
106
|
+
const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get();
|
|
107
|
+
const orgIds = memberships.docs.map((doc)=>doc.id).sort();
|
|
108
|
+
for (const orgId of orgIds){
|
|
109
|
+
const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get();
|
|
110
|
+
if (!member.exists) continue;
|
|
111
|
+
const org = await readSiteCareOrg(firestore, orgId);
|
|
112
|
+
if (org && orgHasSiteCare(org)) return {
|
|
113
|
+
orgId,
|
|
114
|
+
org,
|
|
115
|
+
uid: user.uid,
|
|
116
|
+
email
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
/** The words of a message, above any quoted history. */ export function siteCareMessageBody(message) {
|
|
122
|
+
var _message_text;
|
|
123
|
+
const plain = (((_message_text = message.text) == null ? void 0 : _message_text.trim()) ? message.text : htmlToPlainText(message.html)).replace(/\r\n?/g, '\n');
|
|
124
|
+
return stripQuotedHistory(plain).trim();
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Files one received message addressed to the support address or to a
|
|
128
|
+
* request's reply address. Nothing is ever sent back to a sender it does
|
|
129
|
+
* not file for: a message to the support address is still in the support
|
|
130
|
+
* inbox, answered there like any other.
|
|
131
|
+
*/ export async function fileSiteCareInboundEmail(firestore, input, deps = {}) {
|
|
132
|
+
var _input_addresses, _input_findAccount;
|
|
133
|
+
const { message } = input;
|
|
134
|
+
const machine = siteCareMachineMail(message, (_input_addresses = input.addresses) != null ? _input_addresses : siteCareInboundAddresses());
|
|
135
|
+
if (machine) return {
|
|
136
|
+
outcome: 'ignored',
|
|
137
|
+
reason: machine
|
|
138
|
+
};
|
|
139
|
+
const body = siteCareMessageBody(message);
|
|
140
|
+
const sender = emailAddressOf(message.from);
|
|
141
|
+
const findAccount = (_input_findAccount = input.findAccount) != null ? _input_findAccount : findSiteCareAccount;
|
|
142
|
+
const match = sender ? await findSiteCareWorkspaceForSender(firestore, findAccount, sender) : null;
|
|
143
|
+
if (input.target.kind === 'reply' && match) {
|
|
144
|
+
var _ticket_get;
|
|
145
|
+
const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get();
|
|
146
|
+
const orgId = String((_ticket_get = ticket.get('orgId')) != null ? _ticket_get : '');
|
|
147
|
+
// Only a member of the request's own workspace may add to it.
|
|
148
|
+
const member = orgId ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists : false;
|
|
149
|
+
if (ticket.exists && member) {
|
|
150
|
+
if (!body) return {
|
|
151
|
+
outcome: 'ignored',
|
|
152
|
+
reason: 'empty'
|
|
153
|
+
};
|
|
154
|
+
await appendSiteCareReply(firestore, {
|
|
155
|
+
ticketId: ticket.id,
|
|
156
|
+
from: {
|
|
157
|
+
uid: match.uid,
|
|
158
|
+
email: match.email
|
|
159
|
+
},
|
|
160
|
+
body,
|
|
161
|
+
dedupeKey: message.messageId || message.id
|
|
162
|
+
}, deps);
|
|
163
|
+
return {
|
|
164
|
+
outcome: 'replied',
|
|
165
|
+
requestId: ticket.id
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
// A reply that cannot join its request is read as a new one below.
|
|
169
|
+
}
|
|
170
|
+
if (!match) return {
|
|
171
|
+
outcome: 'ignored',
|
|
172
|
+
reason: 'not-a-member'
|
|
173
|
+
};
|
|
174
|
+
if (!body && !threadSubject(message.subject)) return {
|
|
175
|
+
outcome: 'ignored',
|
|
176
|
+
reason: 'empty'
|
|
177
|
+
};
|
|
178
|
+
const opened = await openSiteCareRequest(firestore, {
|
|
179
|
+
orgId: match.orgId,
|
|
180
|
+
org: match.org,
|
|
181
|
+
hostId: null,
|
|
182
|
+
subject: threadSubject(message.subject) || body.split('\n')[0].slice(0, 150) || 'A change by email',
|
|
183
|
+
body: body || threadSubject(message.subject),
|
|
184
|
+
requester: {
|
|
185
|
+
uid: match.uid,
|
|
186
|
+
email: match.email
|
|
187
|
+
},
|
|
188
|
+
source: 'email',
|
|
189
|
+
dedupeKey: message.messageId || message.id
|
|
190
|
+
}, deps);
|
|
191
|
+
return {
|
|
192
|
+
outcome: 'opened',
|
|
193
|
+
requestId: opened.ticketId
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
//# sourceMappingURL=site-care-inbound.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-inbound.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 { inboundMailDomain } from '@aglyn/aglyn/app-utils/inbound-mail-domain'\nimport {\n emailAddressOf,\n htmlToPlainText,\n stripQuotedHistory,\n threadSubject,\n} from '@aglyn/aglyn/app-utils/email-text'\nimport { SITE_CARE_INBOUND_LOCAL_PART, siteCareSupportAddress } from '@aglyn/aglyn/app-utils/site-care'\nimport { getEmailConfig, type ReceivedEmail } from '@aglyn/shared-util-email'\nimport {\n appendSiteCareReply,\n openSiteCareRequest,\n orgHasSiteCare,\n readSiteCareOrg,\n type SiteCareDeps,\n} from './site-care-requests'\nimport { findUserByEmailAcrossPools } from './auth-pools'\n\n/**\n * SITE CARE MAIL ARRIVES AT THE SUPPORT ADDRESS (AGL-3959, AGL-3997).\n *\n * Site Care has no address of its own. An owner emails the support address\n * they already know, and the support mailbox delivers a copy of each message\n * to `support@<inbound mail domain>`, where the mail provider announces it.\n * A message to either address from a member of a workspace with Site Care\n * becomes a Site Care request on that workspace, matched by the sender's\n * address against the members of workspaces that have Site Care. A reply to\n * any Site Care email goes to `support+<requestId>@…` and joins that\n * request's thread, when the sender is a member of its workspace.\n *\n * Everything else is acknowledged and left alone: nothing is filed and\n * nothing is sent back, and a message to the support address stays in the\n * support inbox as ordinary support mail. That includes the platform's own\n * mail and anything a machine sent: an out-of-office answering a Site Care\n * email would otherwise join the request, and one answering anything that\n * replies to support would open one.\n */\n\n/** What a received message was addressed to: a new request, or a reply on one. */\nexport type SiteCareInboundTarget = { kind: 'new' } | { kind: 'reply'; requestId: string }\n\n/** The addresses the intake reads as the platform's own. */\nexport interface SiteCareInboundAddresses {\n /** The inbound mail domain: `support@` and `support+<requestId>@` it. */\n domain: string\n /** The operator's support address, or null when the deployment publishes none. */\n supportEmail: string | null\n /** The address the platform sends from, `USAGE_EMAIL_FROM`'s, or null. */\n platformSender: string | null\n}\n\n/** This deployment's {@link SiteCareInboundAddresses}, read per call. */\nexport function siteCareInboundAddresses(): SiteCareInboundAddresses {\n return {\n domain: inboundMailDomain(),\n supportEmail: emailAddressOf(siteCareSupportAddress()),\n platformSender: emailAddressOf(getEmailConfig().from),\n }\n}\n\n/** The Site Care target among a message's recipients, or null. */\nexport function siteCareInboundTarget(\n recipients: readonly string[],\n addresses: Pick<SiteCareInboundAddresses, 'domain' | 'supportEmail'>,\n): SiteCareInboundTarget | null {\n const domain = addresses.domain.toLowerCase()\n const support = emailAddressOf(addresses.supportEmail)\n let found: SiteCareInboundTarget | null = null\n for (const value of recipients) {\n // Validated (and lowercased) for the comparison, but the local part is\n // read as written: a request id is a case-sensitive Firestore id, and\n // lowercasing `support+AbC…` would look up a ticket that does not exist.\n const address = emailAddressOf(value)\n if (!address) continue\n if (support && address === support) {\n found = found ?? { kind: 'new' }\n continue\n }\n const raw = String(value ?? '').trim()\n const written = (/<([^<>]+)>\\s*$/.exec(raw)?.[1] ?? raw).trim()\n const at = written.lastIndexOf('@')\n if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain) continue\n const local = written.slice(0, at)\n if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {\n found = found ?? { kind: 'new' }\n continue\n }\n const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`\n if (local.toLowerCase().startsWith(prefix)) {\n const requestId = local.slice(prefix.length)\n // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape\n // is refused rather than looked up.\n if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return { kind: 'reply', requestId }\n }\n }\n return found\n}\n\n/** Why a message is ignored without a lookup: the platform wrote it, or a machine did. */\nexport type SiteCareMachineMail = 'ours' | 'automatic'\n\n/**\n * Whether a message is not a person writing in: from the support address,\n * the platform's sender or any address on the inbound mail domain, or one\n * its headers say a machine sent. Null when it may be a person.\n */\nexport function siteCareMachineMail(\n message: Pick<ReceivedEmail, 'from' | 'autoSubmitted'>,\n addresses: SiteCareInboundAddresses,\n): SiteCareMachineMail | null {\n const sender = emailAddressOf(message.from)\n if (sender) {\n const own = [addresses.supportEmail, addresses.platformSender].map((value) => emailAddressOf(value))\n if (own.includes(sender)) return 'ours'\n if (sender.slice(sender.lastIndexOf('@') + 1) === addresses.domain.toLowerCase()) return 'ours'\n }\n return message.autoSubmitted ? 'automatic' : null\n}\n\nexport interface SiteCareSenderMatch {\n orgId: string\n org: Record<string, unknown>\n uid: string\n email: string\n}\n\n/** The account an address signs in with: its uid, or null when it has none. */\nexport type SiteCareAccountLookup = (email: string) => Promise<{ uid: string } | null>\n\n/**\n * Every pool, not only the project's: an owner who signs in through SSO is a\n * GCIP tenant user the project pool never returns (AGL-1122), and their mail\n * would be read as a stranger's.\n */\nexport const findSiteCareAccount: SiteCareAccountLookup = async (email) => {\n const found = await findUserByEmailAcrossPools(email).catch(() => null)\n return found ? { uid: found.record.uid } : null\n}\n\n/**\n * The Site Care workspace a sender belongs to: the account their address\n * signs in with (in any pool), then the workspaces it is a member of, the\n * first with Site Care in force (by id, so the choice is stable).\n */\nexport async function findSiteCareWorkspaceForSender(\n firestore: FirebaseFirestore.Firestore,\n findAccount: SiteCareAccountLookup,\n sender: string,\n): Promise<SiteCareSenderMatch | null> {\n const email = emailAddressOf(sender)\n if (!email) return null\n const user = await findAccount(email).catch(() => null)\n if (!user) return null\n const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get()\n const orgIds = memberships.docs.map((doc) => doc.id).sort()\n for (const orgId of orgIds) {\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get()\n if (!member.exists) continue\n const org = await readSiteCareOrg(firestore, orgId)\n if (org && orgHasSiteCare(org)) return { orgId, org, uid: user.uid, email }\n }\n return null\n}\n\n/** The words of a message, above any quoted history. */\nexport function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string {\n const plain = (message.text?.trim() ? message.text : htmlToPlainText(message.html)).replace(/\\r\\n?/g, '\\n')\n return stripQuotedHistory(plain).trim()\n}\n\n/** Why a message was acknowledged and left alone. */\nexport type SiteCareIgnoredReason =\n /** No workspace with Site Care has the sender as a member: ordinary support mail. */\n | 'not-a-member'\n /** The platform's own address wrote it. */\n | 'ours'\n /** Its headers say a machine sent it. */\n | 'automatic'\n /** A member wrote, but said nothing. */\n | 'empty'\n\nexport type SiteCareInboundOutcome =\n | { outcome: 'opened'; requestId: string }\n | { outcome: 'replied'; requestId: string }\n | { outcome: 'ignored'; reason: SiteCareIgnoredReason }\n\n/**\n * Files one received message addressed to the support address or to a\n * request's reply address. Nothing is ever sent back to a sender it does\n * not file for: a message to the support address is still in the support\n * inbox, answered there like any other.\n */\nexport async function fileSiteCareInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n target: SiteCareInboundTarget\n message: ReceivedEmail\n /** The platform's own addresses; this deployment's by default. */\n addresses?: SiteCareInboundAddresses\n /** The seam a spec replaces; every auth pool by default. */\n findAccount?: SiteCareAccountLookup\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareInboundOutcome> {\n const { message } = input\n const machine = siteCareMachineMail(message, input.addresses ?? siteCareInboundAddresses())\n if (machine) return { outcome: 'ignored', reason: machine }\n const body = siteCareMessageBody(message)\n const sender = emailAddressOf(message.from)\n const findAccount = input.findAccount ?? findSiteCareAccount\n const match = sender ? await findSiteCareWorkspaceForSender(firestore, findAccount, sender) : null\n if (input.target.kind === 'reply' && match) {\n const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get()\n const orgId = String(ticket.get('orgId') ?? '')\n // Only a member of the request's own workspace may add to it.\n const member = orgId\n ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists\n : false\n if (ticket.exists && member) {\n if (!body) return { outcome: 'ignored', reason: 'empty' }\n await appendSiteCareReply(\n firestore,\n {\n ticketId: ticket.id,\n from: { uid: match.uid, email: match.email },\n body,\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'replied', requestId: ticket.id }\n }\n // A reply that cannot join its request is read as a new one below.\n }\n if (!match) return { outcome: 'ignored', reason: 'not-a-member' }\n if (!body && !threadSubject(message.subject)) return { outcome: 'ignored', reason: 'empty' }\n const opened = await openSiteCareRequest(\n firestore,\n {\n orgId: match.orgId,\n org: match.org,\n hostId: null,\n subject: threadSubject(message.subject) || body.split('\\n')[0].slice(0, 150) || 'A change by email',\n body: body || threadSubject(message.subject),\n requester: { uid: match.uid, email: match.email },\n source: 'email',\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'opened', requestId: opened.ticketId }\n}\n"],"names":["inboundMailDomain","emailAddressOf","htmlToPlainText","stripQuotedHistory","threadSubject","SITE_CARE_INBOUND_LOCAL_PART","siteCareSupportAddress","getEmailConfig","appendSiteCareReply","openSiteCareRequest","orgHasSiteCare","readSiteCareOrg","findUserByEmailAcrossPools","siteCareInboundAddresses","domain","supportEmail","platformSender","from","siteCareInboundTarget","recipients","addresses","toLowerCase","support","found","value","address","kind","raw","String","trim","written","exec","at","lastIndexOf","slice","local","prefix","startsWith","requestId","length","test","siteCareMachineMail","message","sender","own","map","includes","autoSubmitted","findSiteCareAccount","email","catch","uid","record","findSiteCareWorkspaceForSender","firestore","findAccount","user","memberships","collection","doc","limit","get","orgIds","docs","id","sort","orgId","member","exists","org","siteCareMessageBody","plain","text","html","replace","fileSiteCareInboundEmail","input","deps","machine","outcome","reason","body","match","target","ticket","ticketId","dedupeKey","messageId","subject","opened","hostId","split","requester","source"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,aAAa,QACR,oCAAmC;AAC1C,SAASC,4BAA4B,EAAEC,sBAAsB,QAAQ,mCAAkC;AACvG,SAASC,cAAc,QAA4B,2BAA0B;AAC7E,SACEC,m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csC,QAAQ8C,OAAO;QAC3CI,WAAW;YAAEzC,KAAK+B,MAAM/B,GAAG;YAAEF,OAAOiC,MAAMjC,KAAK;QAAC;QAChD4C,QAAQ;QACRP,WAAW5C,QAAQ6C,SAAS,IAAI7C,QAAQsB,EAAE;IAC5C,GACAa;IAEF,OAAO;QAAEE,SAAS;QAAUzC,WAAWmD,OAAOJ,QAAQ;IAAC;AACzD"}
|
|
@@ -0,0 +1,64 @@
|
|
|
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 { type SiteCareProject } from '@aglyn/aglyn/app-utils/site-care-project';
|
|
18
|
+
import { type ProjectInvoiceState } from './site-care-project-stripe';
|
|
19
|
+
import type { SiteCareStripeOptions } from './site-care-stripe';
|
|
20
|
+
/**
|
|
21
|
+
* SITE CARE PROJECTS IN THE DAILY RECONCILIATION (AGL-3970).
|
|
22
|
+
*
|
|
23
|
+
* The same scheduled check as extra time (`reconcileSiteCare` calls this):
|
|
24
|
+
* each project invoice the record holds against the Stripe invoice it
|
|
25
|
+
* names — status, and the amount before tax — and each Stripe invoice that
|
|
26
|
+
* names a project against a record that holds it. Any difference is a
|
|
27
|
+
* finding on `billing.siteCareReconciliation`. It compares and reports and
|
|
28
|
+
* never changes either side: the fix is a person's, from the project.
|
|
29
|
+
*/
|
|
30
|
+
export type SiteCareProjectFindingCode = 'project-invoice-stuck' | 'project-invoice-failed' | 'project-invoice-missing' | 'project-invoice-status' | 'project-invoice-amount' | 'project-invoice-without-row' | 'project-status';
|
|
31
|
+
export interface SiteCareProjectFinding {
|
|
32
|
+
orgId: string;
|
|
33
|
+
projectId: string | null;
|
|
34
|
+
code: SiteCareProjectFindingCode;
|
|
35
|
+
detail: string;
|
|
36
|
+
}
|
|
37
|
+
export interface ProjectRow {
|
|
38
|
+
id: string;
|
|
39
|
+
project: SiteCareProject;
|
|
40
|
+
/** The status stored on the document, which every write recomputes. */
|
|
41
|
+
storedStatus: string;
|
|
42
|
+
}
|
|
43
|
+
/** Compares one workspace's projects with its Stripe invoices. Pure. */
|
|
44
|
+
export declare function compareSiteCareProjects(input: {
|
|
45
|
+
orgId: string;
|
|
46
|
+
projects: readonly ProjectRow[];
|
|
47
|
+
/** Every Stripe invoice the record names, plus any listed that name a project. */
|
|
48
|
+
invoices: ReadonlyMap<string, ProjectInvoiceState | null>;
|
|
49
|
+
/** Listed invoices that name one of this workspace's projects. */
|
|
50
|
+
listed: readonly ProjectInvoiceState[];
|
|
51
|
+
}): SiteCareProjectFinding[];
|
|
52
|
+
export interface SiteCareProjectReconcileResult {
|
|
53
|
+
projects: number;
|
|
54
|
+
findings: SiteCareProjectFinding[];
|
|
55
|
+
errors: string[];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Reads every project still open, or settled within the window, and
|
|
59
|
+
* compares each workspace's with Stripe.
|
|
60
|
+
*/
|
|
61
|
+
export declare function reconcileSiteCareProjects(firestore: FirebaseFirestore.Firestore, input: {
|
|
62
|
+
nowMs: number;
|
|
63
|
+
stripe?: SiteCareStripeOptions;
|
|
64
|
+
}): Promise<SiteCareProjectReconcileResult>;
|
|
@@ -0,0 +1,211 @@
|
|
|
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 { readSiteCareProject, siteCareProjectStatus } from "@aglyn/aglyn/app-utils/site-care-project";
|
|
18
|
+
import { readOrgBilling } from "./org-billing.js";
|
|
19
|
+
import { listProjectInvoices, readProjectInvoice, SITE_CARE_PROJECT_METADATA_KEY } from "./site-care-project-stripe.js";
|
|
20
|
+
import { SITE_CARE_PROJECTS_COLLECTION } from "./site-care-projects.js";
|
|
21
|
+
/** The Stripe statuses a recorded invoice status may be in. */ const EXPECTED = {
|
|
22
|
+
open: [
|
|
23
|
+
'open'
|
|
24
|
+
],
|
|
25
|
+
paid: [
|
|
26
|
+
'paid'
|
|
27
|
+
],
|
|
28
|
+
voided: [
|
|
29
|
+
'void'
|
|
30
|
+
],
|
|
31
|
+
// A fully credited open invoice is closed by Stripe as paid at nothing.
|
|
32
|
+
credited: [
|
|
33
|
+
'paid',
|
|
34
|
+
'void'
|
|
35
|
+
],
|
|
36
|
+
refunded: [
|
|
37
|
+
'paid'
|
|
38
|
+
]
|
|
39
|
+
};
|
|
40
|
+
/** Compares one workspace's projects with its Stripe invoices. Pure. */ export function compareSiteCareProjects(input) {
|
|
41
|
+
const findings = [];
|
|
42
|
+
const claimed = new Set();
|
|
43
|
+
for (const row of input.projects){
|
|
44
|
+
const { project } = row;
|
|
45
|
+
const at = {
|
|
46
|
+
orgId: input.orgId,
|
|
47
|
+
projectId: row.id
|
|
48
|
+
};
|
|
49
|
+
const derived = siteCareProjectStatus(project);
|
|
50
|
+
if (row.storedStatus && row.storedStatus !== derived) {
|
|
51
|
+
findings.push(_extends({}, at, {
|
|
52
|
+
code: 'project-status',
|
|
53
|
+
detail: `“${project.title}” is stored as ${row.storedStatus} but its record reads ${derived}.`
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
for (const invoice of project.invoices){
|
|
57
|
+
var _input_invoices_get, _EXPECTED_invoice_status;
|
|
58
|
+
if (invoice.invoiceId) claimed.add(invoice.invoiceId);
|
|
59
|
+
const name = `“${project.title}” invoice ${invoice.seq} (${invoice.kind})`;
|
|
60
|
+
if (invoice.status === 'creating') {
|
|
61
|
+
findings.push(_extends({}, at, {
|
|
62
|
+
code: 'project-invoice-stuck',
|
|
63
|
+
detail: `${name} was started and never recorded. Retry it from the project.`
|
|
64
|
+
}));
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (invoice.status === 'failed') {
|
|
68
|
+
var _invoice_error;
|
|
69
|
+
findings.push(_extends({}, at, {
|
|
70
|
+
code: 'project-invoice-failed',
|
|
71
|
+
detail: `${name} failed (${(_invoice_error = invoice.error) != null ? _invoice_error : 'unknown'}). Retry it from the project.`
|
|
72
|
+
}));
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (!invoice.invoiceId) {
|
|
76
|
+
findings.push(_extends({}, at, {
|
|
77
|
+
code: 'project-invoice-missing',
|
|
78
|
+
detail: `${name} is ${invoice.status} with no Stripe invoice.`
|
|
79
|
+
}));
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const stripe = (_input_invoices_get = input.invoices.get(invoice.invoiceId)) != null ? _input_invoices_get : null;
|
|
83
|
+
if (!stripe) {
|
|
84
|
+
findings.push(_extends({}, at, {
|
|
85
|
+
code: 'project-invoice-missing',
|
|
86
|
+
detail: `${name}: Stripe invoice ${invoice.invoiceId} is gone.`
|
|
87
|
+
}));
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const expected = (_EXPECTED_invoice_status = EXPECTED[invoice.status]) != null ? _EXPECTED_invoice_status : [];
|
|
91
|
+
if (!expected.includes(stripe.status)) {
|
|
92
|
+
findings.push(_extends({}, at, {
|
|
93
|
+
code: 'project-invoice-status',
|
|
94
|
+
detail: invoice.status === 'open' && stripe.status === 'paid' ? `${name} is paid in Stripe but not recorded. Use Check payments on the project.` : `${name} is ${invoice.status} here and ${stripe.status} in Stripe (${invoice.invoiceId}).`
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
if (stripe.subtotalCents !== invoice.amountCents) {
|
|
98
|
+
findings.push(_extends({}, at, {
|
|
99
|
+
code: 'project-invoice-amount',
|
|
100
|
+
detail: `${name}: Stripe bills ${stripe.subtotalCents} cents before tax, the record ${invoice.amountCents}.`
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const invoice of input.listed){
|
|
106
|
+
var _invoice_metadata_SITE_CARE_PROJECT_METADATA_KEY;
|
|
107
|
+
if (claimed.has(invoice.invoiceId)) continue;
|
|
108
|
+
if (invoice.status === 'void') continue;
|
|
109
|
+
findings.push({
|
|
110
|
+
orgId: input.orgId,
|
|
111
|
+
projectId: (_invoice_metadata_SITE_CARE_PROJECT_METADATA_KEY = invoice.metadata[SITE_CARE_PROJECT_METADATA_KEY]) != null ? _invoice_metadata_SITE_CARE_PROJECT_METADATA_KEY : null,
|
|
112
|
+
code: 'project-invoice-without-row',
|
|
113
|
+
detail: `Stripe invoice ${invoice.invoiceId} (${invoice.status}, ${invoice.subtotalCents} cents) names project ${invoice.metadata[SITE_CARE_PROJECT_METADATA_KEY]}, which does not record it.`
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return findings;
|
|
117
|
+
}
|
|
118
|
+
/** How far back a settled project is still compared. */ const SETTLED_WINDOW_MS = 70 * 24 * 60 * 60 * 1000;
|
|
119
|
+
/**
|
|
120
|
+
* Reads every project still open, or settled within the window, and
|
|
121
|
+
* compares each workspace's with Stripe.
|
|
122
|
+
*/ export async function reconcileSiteCareProjects(firestore, input) {
|
|
123
|
+
const snapshot = await firestore.collectionGroup(SITE_CARE_PROJECTS_COLLECTION).limit(2000).get();
|
|
124
|
+
const byOrg = new Map();
|
|
125
|
+
for (const doc of snapshot.docs){
|
|
126
|
+
var _byOrg_get, _doc_get;
|
|
127
|
+
const project = readSiteCareProject(doc.data());
|
|
128
|
+
if (!(project == null ? void 0 : project.orgId)) continue;
|
|
129
|
+
const settled = project.status === 'paid' || project.status === 'refunded' || project.status === 'quoted';
|
|
130
|
+
if (settled && input.nowMs - project.updatedAtMs > SETTLED_WINDOW_MS) continue;
|
|
131
|
+
const rows = (_byOrg_get = byOrg.get(project.orgId)) != null ? _byOrg_get : [];
|
|
132
|
+
rows.push({
|
|
133
|
+
id: doc.id,
|
|
134
|
+
project,
|
|
135
|
+
storedStatus: String((_doc_get = doc.get('status')) != null ? _doc_get : '')
|
|
136
|
+
});
|
|
137
|
+
byOrg.set(project.orgId, rows);
|
|
138
|
+
}
|
|
139
|
+
const result = {
|
|
140
|
+
projects: 0,
|
|
141
|
+
findings: [],
|
|
142
|
+
errors: []
|
|
143
|
+
};
|
|
144
|
+
for (const [orgId, rows] of byOrg){
|
|
145
|
+
result.projects += rows.length;
|
|
146
|
+
try {
|
|
147
|
+
var _billing_stripeCustomerId;
|
|
148
|
+
const invoiced = rows.filter((row)=>row.project.invoices.length);
|
|
149
|
+
if (!invoiced.length) {
|
|
150
|
+
result.findings.push(...compareSiteCareProjects({
|
|
151
|
+
orgId,
|
|
152
|
+
projects: rows,
|
|
153
|
+
invoices: new Map(),
|
|
154
|
+
listed: []
|
|
155
|
+
}));
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const billing = await readOrgBilling(orgId);
|
|
159
|
+
const customerId = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '');
|
|
160
|
+
if (!customerId) {
|
|
161
|
+
result.findings.push({
|
|
162
|
+
orgId,
|
|
163
|
+
projectId: null,
|
|
164
|
+
code: 'project-invoice-missing',
|
|
165
|
+
detail: 'Project invoices are recorded but the workspace has no Stripe customer.'
|
|
166
|
+
});
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const sinceMs = Math.min(...invoiced.map((row)=>row.project.createdAtMs));
|
|
170
|
+
const list = await listProjectInvoices({
|
|
171
|
+
customerId,
|
|
172
|
+
sinceMs
|
|
173
|
+
}, input.stripe);
|
|
174
|
+
if (list.ok === false) {
|
|
175
|
+
result.errors.push(`${orgId}: ${list.error}`);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const projectIds = new Set(rows.map((row)=>row.id));
|
|
179
|
+
const listed = list.invoices.filter((row)=>{
|
|
180
|
+
var _row_metadata_SITE_CARE_PROJECT_METADATA_KEY;
|
|
181
|
+
return projectIds.has((_row_metadata_SITE_CARE_PROJECT_METADATA_KEY = row.metadata[SITE_CARE_PROJECT_METADATA_KEY]) != null ? _row_metadata_SITE_CARE_PROJECT_METADATA_KEY : '');
|
|
182
|
+
});
|
|
183
|
+
const invoices = new Map(list.invoices.map((row)=>[
|
|
184
|
+
row.invoiceId,
|
|
185
|
+
row
|
|
186
|
+
]));
|
|
187
|
+
for (const row of invoiced){
|
|
188
|
+
for (const invoice of row.project.invoices){
|
|
189
|
+
if (!invoice.invoiceId || invoices.has(invoice.invoiceId)) continue;
|
|
190
|
+
const read = await readProjectInvoice(invoice.invoiceId, input.stripe);
|
|
191
|
+
if (read.ok === false) {
|
|
192
|
+
result.errors.push(`${orgId}/${row.id}: ${read.error}`);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
invoices.set(invoice.invoiceId, read.state);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
result.findings.push(...compareSiteCareProjects({
|
|
199
|
+
orgId,
|
|
200
|
+
projects: rows,
|
|
201
|
+
invoices,
|
|
202
|
+
listed
|
|
203
|
+
}));
|
|
204
|
+
} catch (error) {
|
|
205
|
+
result.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
//# sourceMappingURL=site-care-project-reconcile.js.map
|