@simplelayer/graniteer-core 0.2.0 → 0.2.2
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/index.js +2 -2
- package/package.json +1 -1
- package/src/agreementCheckout.ts +250 -250
- package/src/agreementPortalEmail.ts +128 -128
- package/src/billingPortalLinkEmail.ts +117 -117
- package/src/bookingAgreementEmail.ts +149 -149
- package/src/bookingEffects.ts +388 -388
- package/src/busClient.ts +268 -268
- package/src/busSignature.ts +71 -71
- package/src/checkoutCoupon.test.ts +675 -675
- package/src/checkoutCoupon.ts +455 -455
- package/src/commonsDeposit.ts +298 -298
- package/src/commonsDepositWebhook.ts +237 -237
- package/src/dayPassConfirmation.ts +230 -230
- package/src/dunningEmails.test.ts +263 -263
- package/src/dunningEmails.ts +203 -203
- package/src/email-templates/brand.ts +93 -93
- package/src/email-templates/magic-link.tsx +59 -59
- package/src/email-templates/recovery.tsx +59 -59
- package/src/email-templates/signup.tsx +67 -67
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -312
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -460
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -231
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -168
- package/src/functions/admin-mint-portal-link.ts +62 -62
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -366
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.ts +333 -333
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -467
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -259
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -149
- package/src/functions/create-booking.ts +648 -648
- package/src/functions/create-day-pass-checkout.ts +218 -218
- package/src/functions/create-portal-session.ts +142 -142
- package/src/functions/create-subscription-checkout.test.ts +222 -222
- package/src/functions/create-subscription-checkout.ts +440 -440
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -277
- package/src/functions/event-access-store.ts +334 -309
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -457
- package/src/functions/get-provider-sign-link.ts +155 -155
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/mcp.ts +67 -67
- package/src/functions/member-door-action.test.ts +1248 -1248
- package/src/functions/member-door-action.ts +863 -863
- package/src/functions/member-unifi-mapping.test.ts +516 -516
- package/src/functions/member-unifi-mapping.ts +206 -206
- package/src/functions/membership-door-sync.ts +956 -956
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +219 -192
- package/src/functions/portal-resend-invite.ts +248 -248
- package/src/functions/portal-submit-event.ts +168 -168
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -348
- package/src/functions/push-test.ts +234 -234
- package/src/functions/request-portal-link.ts +211 -211
- package/src/functions/review-ratings.ts +113 -113
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -319
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
- package/src/functions/stripe-webhook.ts +2595 -2595
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -478
- package/src/functions/upload-booking-display-image.ts +179 -179
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -453
- package/src/functions/voice-day-pass.ts +346 -346
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -355
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -429
- package/src/ghlEventInquiry.ts +143 -143
- package/src/mailArrivalEmail.ts +121 -121
- package/src/manageToken.ts +363 -363
- package/src/membershipBusClient.ts +537 -537
- package/src/membershipWelcome.ts +683 -683
- package/src/migrationCheckout.ts +366 -366
- package/src/paymentLinkEmail.ts +123 -123
- package/src/signedUnpaidReminderEmail.test.ts +246 -246
- package/src/signedUnpaidReminderEmail.ts +132 -132
- package/src/stripeCoworkingPortal.ts +91 -91
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -119
- package/src/unifiAccessPolicies.ts +228 -228
- package/src/unifiGroups.ts +129 -129
package/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// Spike/smoke-test placeholder for graniteer-core. Real code lands in Phase 2+.
|
|
2
|
-
module.exports = { ping: () => "pong" };
|
|
1
|
+
// Spike/smoke-test placeholder for graniteer-core. Real code lands in Phase 2+.
|
|
2
|
+
module.exports = { ping: () => "pong" };
|
package/package.json
CHANGED
package/src/agreementCheckout.ts
CHANGED
|
@@ -1,250 +1,250 @@
|
|
|
1
|
-
// Shared Stripe checkout construction for private-office agreements.
|
|
2
|
-
//
|
|
3
|
-
// Extracted VERBATIM from boldsign-webhook/index.ts so the first-issuance path
|
|
4
|
-
// and the admin resend path can never drift apart.
|
|
5
|
-
|
|
6
|
-
import Stripe from 'npm:stripe@17.5.0';
|
|
7
|
-
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
8
|
-
import { centsFrom, parseRetainerConfig } from './money.ts';
|
|
9
|
-
|
|
10
|
-
export interface AddonRow { label?: string; amount?: string; notes?: string }
|
|
11
|
-
|
|
12
|
-
// Re-exported so the existing `import { centsFrom } from './agreementCheckout.ts'`
|
|
13
|
-
// call sites (create-agreement, agreement-portal-get) keep working unchanged.
|
|
14
|
-
export { centsFrom };
|
|
15
|
-
|
|
16
|
-
export function buildAgreementLineItems(
|
|
17
|
-
fieldValues: Record<string, unknown>,
|
|
18
|
-
): Stripe.Checkout.SessionCreateParams.LineItem[] {
|
|
19
|
-
const v = fieldValues ?? {};
|
|
20
|
-
const lineItems: Stripe.Checkout.SessionCreateParams.LineItem[] = [];
|
|
21
|
-
|
|
22
|
-
// A source value counts as "configured" unless it is null/undefined/blank.
|
|
23
|
-
const isPresent = (x: unknown) =>
|
|
24
|
-
x !== null && x !== undefined && String(x).trim() !== '';
|
|
25
|
-
const bad = (field: string, value: unknown) => {
|
|
26
|
-
throw new Error(`unparseable_amount: ${field}=${JSON.stringify(value)}`);
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
const monthlyCents = centsFrom(v.monthly_fee);
|
|
30
|
-
if (isPresent(v.monthly_fee) && monthlyCents <= 0) bad('monthly_fee', v.monthly_fee);
|
|
31
|
-
if (monthlyCents > 0) {
|
|
32
|
-
lineItems.push({
|
|
33
|
-
price_data: {
|
|
34
|
-
currency: 'usd',
|
|
35
|
-
product_data: { name: `Private Office ${String(v.office_number ?? '')}`.trim() },
|
|
36
|
-
unit_amount: monthlyCents,
|
|
37
|
-
recurring: { interval: 'month' },
|
|
38
|
-
},
|
|
39
|
-
quantity: 1,
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const addons = Array.isArray(v.addons) ? (v.addons as AddonRow[]) : [];
|
|
44
|
-
for (const addon of addons) {
|
|
45
|
-
const cents = centsFrom(addon?.amount);
|
|
46
|
-
if (isPresent(addon?.amount) && cents <= 0) bad('addon.amount', addon?.amount);
|
|
47
|
-
if (cents <= 0) continue;
|
|
48
|
-
lineItems.push({
|
|
49
|
-
price_data: {
|
|
50
|
-
currency: 'usd',
|
|
51
|
-
product_data: { name: String(addon.label || 'Add-on') },
|
|
52
|
-
unit_amount: cents,
|
|
53
|
-
recurring: { interval: 'month' },
|
|
54
|
-
},
|
|
55
|
-
quantity: 1,
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const retainer = parseRetainerConfig(v);
|
|
60
|
-
if (!retainer.ok && retainer.code !== 'service_retainer_absent') bad('service_retainer', v.service_retainer);
|
|
61
|
-
else if (retainer.ok && retainer.cents > 0) {
|
|
62
|
-
lineItems.push({
|
|
63
|
-
price_data: {
|
|
64
|
-
currency: 'usd',
|
|
65
|
-
product_data: { name: 'Service retainer' },
|
|
66
|
-
unit_amount: retainer.cents,
|
|
67
|
-
},
|
|
68
|
-
quantity: 1,
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
// absent, or ok-and-zero (an explicit waiver): no line item, no throw.
|
|
72
|
-
|
|
73
|
-
if (lineItems.length === 0) throw new Error('no_line_items_from_field_values');
|
|
74
|
-
|
|
75
|
-
return lineItems;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Reuse-or-create the Stripe customer by email (search is eventually consistent).
|
|
80
|
-
* If `existingCustomerId` is supplied and non-empty, it is returned as-is.
|
|
81
|
-
*/
|
|
82
|
-
export async function resolveStripeCustomer(
|
|
83
|
-
stripe: Stripe,
|
|
84
|
-
email: string,
|
|
85
|
-
name: string | null | undefined,
|
|
86
|
-
existingCustomerId?: string | null,
|
|
87
|
-
): Promise<string> {
|
|
88
|
-
if (existingCustomerId && existingCustomerId.trim() !== '') return existingCustomerId;
|
|
89
|
-
|
|
90
|
-
const emailKey = String(email ?? '').toLowerCase();
|
|
91
|
-
let customerId: string | null = null;
|
|
92
|
-
let matchCount = 0;
|
|
93
|
-
try {
|
|
94
|
-
const found = await stripe.customers.search({
|
|
95
|
-
query: `email:'${emailKey.replace(/'/g, "\\'")}'`,
|
|
96
|
-
limit: 2,
|
|
97
|
-
});
|
|
98
|
-
matchCount = found.data.length;
|
|
99
|
-
if (found.data.length > 0) customerId = found.data[0].id;
|
|
100
|
-
} catch (e) {
|
|
101
|
-
console.warn('[agreementCheckout] customers.search failed', e);
|
|
102
|
-
}
|
|
103
|
-
if (!customerId) {
|
|
104
|
-
try {
|
|
105
|
-
const listed = await stripe.customers.list({ email: emailKey, limit: 2 });
|
|
106
|
-
matchCount = listed.data.length;
|
|
107
|
-
if (listed.data.length > 0) customerId = listed.data[0].id;
|
|
108
|
-
} catch (e2) {
|
|
109
|
-
console.warn('[agreementCheckout] customers.list failed', e2);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
// Stripe does NOT enforce Customer email uniqueness. With >1 Customer per
|
|
113
|
-
// email the reused id is arbitrary, which makes any stripe_customer_id
|
|
114
|
-
// predicate downstream nondeterministic. Assert exactly one; flag otherwise.
|
|
115
|
-
if (matchCount > 1) {
|
|
116
|
-
console.error('[agreementCheckout] multiple Stripe Customers for one email',
|
|
117
|
-
{ email: emailKey, match_count: matchCount, chosen: customerId });
|
|
118
|
-
}
|
|
119
|
-
if (!customerId) {
|
|
120
|
-
const created = await stripe.customers.create({
|
|
121
|
-
email: emailKey,
|
|
122
|
-
name: name ?? undefined,
|
|
123
|
-
});
|
|
124
|
-
customerId = created.id;
|
|
125
|
-
}
|
|
126
|
-
return customerId;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
export async function createAgreementCheckoutSession(
|
|
130
|
-
stripe: Stripe,
|
|
131
|
-
args: {
|
|
132
|
-
customerId: string;
|
|
133
|
-
lineItems: Stripe.Checkout.SessionCreateParams.LineItem[];
|
|
134
|
-
metadata: Record<string, string>;
|
|
135
|
-
idempotencyKey?: string;
|
|
136
|
-
baseUrl: string;
|
|
137
|
-
},
|
|
138
|
-
): Promise<Stripe.Checkout.Session> {
|
|
139
|
-
return await stripe.checkout.sessions.create({
|
|
140
|
-
mode: 'subscription',
|
|
141
|
-
customer: args.customerId,
|
|
142
|
-
line_items: args.lineItems,
|
|
143
|
-
metadata: args.metadata,
|
|
144
|
-
subscription_data: { metadata: args.metadata },
|
|
145
|
-
success_url: `${args.baseUrl}/membership/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
146
|
-
cancel_url: `${args.baseUrl}/private-offices/`,
|
|
147
|
-
}, args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : undefined);
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// ---------------------------------------------------------------------------
|
|
151
|
-
// Unified sign+pay flow additions. The legacy checkout helpers above are
|
|
152
|
-
// unchanged and remain the only thing boldsign-webhook / admin-resend use.
|
|
153
|
-
// ---------------------------------------------------------------------------
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Recurring subscription items for the unified flow. Uses a real Stripe
|
|
157
|
-
* Product ID because the Subscriptions API's price_data accepts `product`
|
|
158
|
-
* only (no inline product_data, unlike Checkout line items).
|
|
159
|
-
*/
|
|
160
|
-
export function buildAgreementSubscriptionItems(
|
|
161
|
-
fieldValues: Record<string, unknown>,
|
|
162
|
-
stripeProductId: string,
|
|
163
|
-
): Stripe.SubscriptionCreateParams.Item[] {
|
|
164
|
-
const v = fieldValues ?? {};
|
|
165
|
-
const items: Stripe.SubscriptionCreateParams.Item[] = [];
|
|
166
|
-
const isPresent = (x: unknown) => x !== null && x !== undefined && String(x).trim() !== '';
|
|
167
|
-
const bad = (field: string, value: unknown) => {
|
|
168
|
-
throw new Error(`unparseable_amount: ${field}=${JSON.stringify(value)}`);
|
|
169
|
-
};
|
|
170
|
-
|
|
171
|
-
const monthlyCents = centsFrom(v.monthly_fee);
|
|
172
|
-
if (isPresent(v.monthly_fee) && monthlyCents <= 0) bad('monthly_fee', v.monthly_fee);
|
|
173
|
-
if (monthlyCents <= 0) throw new Error('no_monthly_fee_for_subscription');
|
|
174
|
-
items.push({
|
|
175
|
-
price_data: {
|
|
176
|
-
currency: 'usd',
|
|
177
|
-
product: stripeProductId,
|
|
178
|
-
unit_amount: monthlyCents,
|
|
179
|
-
recurring: { interval: 'month' },
|
|
180
|
-
},
|
|
181
|
-
quantity: 1,
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
const addons = Array.isArray(v.addons) ? (v.addons as AddonRow[]) : [];
|
|
185
|
-
for (const addon of addons) {
|
|
186
|
-
const cents = centsFrom(addon?.amount);
|
|
187
|
-
if (isPresent(addon?.amount) && cents <= 0) bad('addon.amount', addon?.amount);
|
|
188
|
-
if (cents <= 0) continue;
|
|
189
|
-
items.push({
|
|
190
|
-
price_data: {
|
|
191
|
-
currency: 'usd',
|
|
192
|
-
// Same product as monthly rent -- addons are additional recurring line
|
|
193
|
-
// items on the same office subscription, not separate products.
|
|
194
|
-
product: stripeProductId,
|
|
195
|
-
unit_amount: cents,
|
|
196
|
-
recurring: { interval: 'month' },
|
|
197
|
-
},
|
|
198
|
-
quantity: 1,
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Deliberately no reference to v.service_retainer anywhere in this function --
|
|
203
|
-
// the retainer is a one-time PaymentIntent charged separately (see
|
|
204
|
-
// agreementActivation.ts), never a subscription line item.
|
|
205
|
-
return items;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* Idempotent Stripe customer resolution + persistence for the unified flow.
|
|
212
|
-
* Not used by the legacy callers of resolveStripeCustomer.
|
|
213
|
-
*/
|
|
214
|
-
export async function resolveAndPersistStripeCustomer(
|
|
215
|
-
supabase: SupabaseLike,
|
|
216
|
-
stripe: Stripe,
|
|
217
|
-
signatureDocumentId: string,
|
|
218
|
-
email: string,
|
|
219
|
-
name: string | null | undefined,
|
|
220
|
-
): Promise<string> {
|
|
221
|
-
// Re-read fresh -- a concurrent call may already have persisted a customer id.
|
|
222
|
-
const { data: row } = await supabase
|
|
223
|
-
.from('signature_documents')
|
|
224
|
-
.select('stripe_customer_id')
|
|
225
|
-
.eq('id', signatureDocumentId)
|
|
226
|
-
.maybeSingle();
|
|
227
|
-
const existing = (row as { stripe_customer_id?: string | null } | null)?.stripe_customer_id;
|
|
228
|
-
if (existing && existing.trim() !== '') return existing;
|
|
229
|
-
|
|
230
|
-
const customerId = await resolveStripeCustomer(stripe, email, name, undefined);
|
|
231
|
-
|
|
232
|
-
// Conditional write: only the first caller for this row wins.
|
|
233
|
-
const { data: claimed } = await supabase
|
|
234
|
-
.from('signature_documents')
|
|
235
|
-
.update({ stripe_customer_id: customerId } as never)
|
|
236
|
-
.eq('id', signatureDocumentId)
|
|
237
|
-
.is('stripe_customer_id', null)
|
|
238
|
-
.select('id')
|
|
239
|
-
.maybeSingle();
|
|
240
|
-
|
|
241
|
-
if (claimed) return customerId;
|
|
242
|
-
|
|
243
|
-
// Someone else's write won the race -- use theirs.
|
|
244
|
-
const { data: fresh } = await supabase
|
|
245
|
-
.from('signature_documents')
|
|
246
|
-
.select('stripe_customer_id')
|
|
247
|
-
.eq('id', signatureDocumentId)
|
|
248
|
-
.maybeSingle();
|
|
249
|
-
return (fresh as { stripe_customer_id?: string | null } | null)?.stripe_customer_id ?? customerId;
|
|
250
|
-
}
|
|
1
|
+
// Shared Stripe checkout construction for private-office agreements.
|
|
2
|
+
//
|
|
3
|
+
// Extracted VERBATIM from boldsign-webhook/index.ts so the first-issuance path
|
|
4
|
+
// and the admin resend path can never drift apart.
|
|
5
|
+
|
|
6
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
7
|
+
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
8
|
+
import { centsFrom, parseRetainerConfig } from './money.ts';
|
|
9
|
+
|
|
10
|
+
export interface AddonRow { label?: string; amount?: string; notes?: string }
|
|
11
|
+
|
|
12
|
+
// Re-exported so the existing `import { centsFrom } from './agreementCheckout.ts'`
|
|
13
|
+
// call sites (create-agreement, agreement-portal-get) keep working unchanged.
|
|
14
|
+
export { centsFrom };
|
|
15
|
+
|
|
16
|
+
export function buildAgreementLineItems(
|
|
17
|
+
fieldValues: Record<string, unknown>,
|
|
18
|
+
): Stripe.Checkout.SessionCreateParams.LineItem[] {
|
|
19
|
+
const v = fieldValues ?? {};
|
|
20
|
+
const lineItems: Stripe.Checkout.SessionCreateParams.LineItem[] = [];
|
|
21
|
+
|
|
22
|
+
// A source value counts as "configured" unless it is null/undefined/blank.
|
|
23
|
+
const isPresent = (x: unknown) =>
|
|
24
|
+
x !== null && x !== undefined && String(x).trim() !== '';
|
|
25
|
+
const bad = (field: string, value: unknown) => {
|
|
26
|
+
throw new Error(`unparseable_amount: ${field}=${JSON.stringify(value)}`);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const monthlyCents = centsFrom(v.monthly_fee);
|
|
30
|
+
if (isPresent(v.monthly_fee) && monthlyCents <= 0) bad('monthly_fee', v.monthly_fee);
|
|
31
|
+
if (monthlyCents > 0) {
|
|
32
|
+
lineItems.push({
|
|
33
|
+
price_data: {
|
|
34
|
+
currency: 'usd',
|
|
35
|
+
product_data: { name: `Private Office ${String(v.office_number ?? '')}`.trim() },
|
|
36
|
+
unit_amount: monthlyCents,
|
|
37
|
+
recurring: { interval: 'month' },
|
|
38
|
+
},
|
|
39
|
+
quantity: 1,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const addons = Array.isArray(v.addons) ? (v.addons as AddonRow[]) : [];
|
|
44
|
+
for (const addon of addons) {
|
|
45
|
+
const cents = centsFrom(addon?.amount);
|
|
46
|
+
if (isPresent(addon?.amount) && cents <= 0) bad('addon.amount', addon?.amount);
|
|
47
|
+
if (cents <= 0) continue;
|
|
48
|
+
lineItems.push({
|
|
49
|
+
price_data: {
|
|
50
|
+
currency: 'usd',
|
|
51
|
+
product_data: { name: String(addon.label || 'Add-on') },
|
|
52
|
+
unit_amount: cents,
|
|
53
|
+
recurring: { interval: 'month' },
|
|
54
|
+
},
|
|
55
|
+
quantity: 1,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const retainer = parseRetainerConfig(v);
|
|
60
|
+
if (!retainer.ok && retainer.code !== 'service_retainer_absent') bad('service_retainer', v.service_retainer);
|
|
61
|
+
else if (retainer.ok && retainer.cents > 0) {
|
|
62
|
+
lineItems.push({
|
|
63
|
+
price_data: {
|
|
64
|
+
currency: 'usd',
|
|
65
|
+
product_data: { name: 'Service retainer' },
|
|
66
|
+
unit_amount: retainer.cents,
|
|
67
|
+
},
|
|
68
|
+
quantity: 1,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
// absent, or ok-and-zero (an explicit waiver): no line item, no throw.
|
|
72
|
+
|
|
73
|
+
if (lineItems.length === 0) throw new Error('no_line_items_from_field_values');
|
|
74
|
+
|
|
75
|
+
return lineItems;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Reuse-or-create the Stripe customer by email (search is eventually consistent).
|
|
80
|
+
* If `existingCustomerId` is supplied and non-empty, it is returned as-is.
|
|
81
|
+
*/
|
|
82
|
+
export async function resolveStripeCustomer(
|
|
83
|
+
stripe: Stripe,
|
|
84
|
+
email: string,
|
|
85
|
+
name: string | null | undefined,
|
|
86
|
+
existingCustomerId?: string | null,
|
|
87
|
+
): Promise<string> {
|
|
88
|
+
if (existingCustomerId && existingCustomerId.trim() !== '') return existingCustomerId;
|
|
89
|
+
|
|
90
|
+
const emailKey = String(email ?? '').toLowerCase();
|
|
91
|
+
let customerId: string | null = null;
|
|
92
|
+
let matchCount = 0;
|
|
93
|
+
try {
|
|
94
|
+
const found = await stripe.customers.search({
|
|
95
|
+
query: `email:'${emailKey.replace(/'/g, "\\'")}'`,
|
|
96
|
+
limit: 2,
|
|
97
|
+
});
|
|
98
|
+
matchCount = found.data.length;
|
|
99
|
+
if (found.data.length > 0) customerId = found.data[0].id;
|
|
100
|
+
} catch (e) {
|
|
101
|
+
console.warn('[agreementCheckout] customers.search failed', e);
|
|
102
|
+
}
|
|
103
|
+
if (!customerId) {
|
|
104
|
+
try {
|
|
105
|
+
const listed = await stripe.customers.list({ email: emailKey, limit: 2 });
|
|
106
|
+
matchCount = listed.data.length;
|
|
107
|
+
if (listed.data.length > 0) customerId = listed.data[0].id;
|
|
108
|
+
} catch (e2) {
|
|
109
|
+
console.warn('[agreementCheckout] customers.list failed', e2);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// Stripe does NOT enforce Customer email uniqueness. With >1 Customer per
|
|
113
|
+
// email the reused id is arbitrary, which makes any stripe_customer_id
|
|
114
|
+
// predicate downstream nondeterministic. Assert exactly one; flag otherwise.
|
|
115
|
+
if (matchCount > 1) {
|
|
116
|
+
console.error('[agreementCheckout] multiple Stripe Customers for one email',
|
|
117
|
+
{ email: emailKey, match_count: matchCount, chosen: customerId });
|
|
118
|
+
}
|
|
119
|
+
if (!customerId) {
|
|
120
|
+
const created = await stripe.customers.create({
|
|
121
|
+
email: emailKey,
|
|
122
|
+
name: name ?? undefined,
|
|
123
|
+
});
|
|
124
|
+
customerId = created.id;
|
|
125
|
+
}
|
|
126
|
+
return customerId;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function createAgreementCheckoutSession(
|
|
130
|
+
stripe: Stripe,
|
|
131
|
+
args: {
|
|
132
|
+
customerId: string;
|
|
133
|
+
lineItems: Stripe.Checkout.SessionCreateParams.LineItem[];
|
|
134
|
+
metadata: Record<string, string>;
|
|
135
|
+
idempotencyKey?: string;
|
|
136
|
+
baseUrl: string;
|
|
137
|
+
},
|
|
138
|
+
): Promise<Stripe.Checkout.Session> {
|
|
139
|
+
return await stripe.checkout.sessions.create({
|
|
140
|
+
mode: 'subscription',
|
|
141
|
+
customer: args.customerId,
|
|
142
|
+
line_items: args.lineItems,
|
|
143
|
+
metadata: args.metadata,
|
|
144
|
+
subscription_data: { metadata: args.metadata },
|
|
145
|
+
success_url: `${args.baseUrl}/membership/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
146
|
+
cancel_url: `${args.baseUrl}/private-offices/`,
|
|
147
|
+
}, args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : undefined);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// Unified sign+pay flow additions. The legacy checkout helpers above are
|
|
152
|
+
// unchanged and remain the only thing boldsign-webhook / admin-resend use.
|
|
153
|
+
// ---------------------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Recurring subscription items for the unified flow. Uses a real Stripe
|
|
157
|
+
* Product ID because the Subscriptions API's price_data accepts `product`
|
|
158
|
+
* only (no inline product_data, unlike Checkout line items).
|
|
159
|
+
*/
|
|
160
|
+
export function buildAgreementSubscriptionItems(
|
|
161
|
+
fieldValues: Record<string, unknown>,
|
|
162
|
+
stripeProductId: string,
|
|
163
|
+
): Stripe.SubscriptionCreateParams.Item[] {
|
|
164
|
+
const v = fieldValues ?? {};
|
|
165
|
+
const items: Stripe.SubscriptionCreateParams.Item[] = [];
|
|
166
|
+
const isPresent = (x: unknown) => x !== null && x !== undefined && String(x).trim() !== '';
|
|
167
|
+
const bad = (field: string, value: unknown) => {
|
|
168
|
+
throw new Error(`unparseable_amount: ${field}=${JSON.stringify(value)}`);
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const monthlyCents = centsFrom(v.monthly_fee);
|
|
172
|
+
if (isPresent(v.monthly_fee) && monthlyCents <= 0) bad('monthly_fee', v.monthly_fee);
|
|
173
|
+
if (monthlyCents <= 0) throw new Error('no_monthly_fee_for_subscription');
|
|
174
|
+
items.push({
|
|
175
|
+
price_data: {
|
|
176
|
+
currency: 'usd',
|
|
177
|
+
product: stripeProductId,
|
|
178
|
+
unit_amount: monthlyCents,
|
|
179
|
+
recurring: { interval: 'month' },
|
|
180
|
+
},
|
|
181
|
+
quantity: 1,
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const addons = Array.isArray(v.addons) ? (v.addons as AddonRow[]) : [];
|
|
185
|
+
for (const addon of addons) {
|
|
186
|
+
const cents = centsFrom(addon?.amount);
|
|
187
|
+
if (isPresent(addon?.amount) && cents <= 0) bad('addon.amount', addon?.amount);
|
|
188
|
+
if (cents <= 0) continue;
|
|
189
|
+
items.push({
|
|
190
|
+
price_data: {
|
|
191
|
+
currency: 'usd',
|
|
192
|
+
// Same product as monthly rent -- addons are additional recurring line
|
|
193
|
+
// items on the same office subscription, not separate products.
|
|
194
|
+
product: stripeProductId,
|
|
195
|
+
unit_amount: cents,
|
|
196
|
+
recurring: { interval: 'month' },
|
|
197
|
+
},
|
|
198
|
+
quantity: 1,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Deliberately no reference to v.service_retainer anywhere in this function --
|
|
203
|
+
// the retainer is a one-time PaymentIntent charged separately (see
|
|
204
|
+
// agreementActivation.ts), never a subscription line item.
|
|
205
|
+
return items;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Idempotent Stripe customer resolution + persistence for the unified flow.
|
|
212
|
+
* Not used by the legacy callers of resolveStripeCustomer.
|
|
213
|
+
*/
|
|
214
|
+
export async function resolveAndPersistStripeCustomer(
|
|
215
|
+
supabase: SupabaseLike,
|
|
216
|
+
stripe: Stripe,
|
|
217
|
+
signatureDocumentId: string,
|
|
218
|
+
email: string,
|
|
219
|
+
name: string | null | undefined,
|
|
220
|
+
): Promise<string> {
|
|
221
|
+
// Re-read fresh -- a concurrent call may already have persisted a customer id.
|
|
222
|
+
const { data: row } = await supabase
|
|
223
|
+
.from('signature_documents')
|
|
224
|
+
.select('stripe_customer_id')
|
|
225
|
+
.eq('id', signatureDocumentId)
|
|
226
|
+
.maybeSingle();
|
|
227
|
+
const existing = (row as { stripe_customer_id?: string | null } | null)?.stripe_customer_id;
|
|
228
|
+
if (existing && existing.trim() !== '') return existing;
|
|
229
|
+
|
|
230
|
+
const customerId = await resolveStripeCustomer(stripe, email, name, undefined);
|
|
231
|
+
|
|
232
|
+
// Conditional write: only the first caller for this row wins.
|
|
233
|
+
const { data: claimed } = await supabase
|
|
234
|
+
.from('signature_documents')
|
|
235
|
+
.update({ stripe_customer_id: customerId } as never)
|
|
236
|
+
.eq('id', signatureDocumentId)
|
|
237
|
+
.is('stripe_customer_id', null)
|
|
238
|
+
.select('id')
|
|
239
|
+
.maybeSingle();
|
|
240
|
+
|
|
241
|
+
if (claimed) return customerId;
|
|
242
|
+
|
|
243
|
+
// Someone else's write won the race -- use theirs.
|
|
244
|
+
const { data: fresh } = await supabase
|
|
245
|
+
.from('signature_documents')
|
|
246
|
+
.select('stripe_customer_id')
|
|
247
|
+
.eq('id', signatureDocumentId)
|
|
248
|
+
.maybeSingle();
|
|
249
|
+
return (fresh as { stripe_customer_id?: string | null } | null)?.stripe_customer_id ?? customerId;
|
|
250
|
+
}
|