@simplelayer/graniteer-core 0.4.3 → 0.5.0-rc.0

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.
Files changed (119) hide show
  1. package/LICENSE +4 -0
  2. package/dist/bookingAgreementEmail.d.ts +34 -3
  3. package/dist/bookingAgreementEmail.js +100 -1
  4. package/dist/bookingEffects.d.ts +3 -1
  5. package/dist/bookingEffects.js +4 -3
  6. package/dist/bookingSource.d.ts +2 -0
  7. package/dist/bookingSource.js +11 -0
  8. package/dist/businessHours.d.ts +11 -0
  9. package/dist/businessHours.js +55 -0
  10. package/dist/checkoutSessionParams.d.ts +33 -0
  11. package/dist/checkoutSessionParams.js +71 -0
  12. package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
  13. package/dist/commonsSignedUnpaidCancellation.js +650 -0
  14. package/dist/connectBookingCharge.d.ts +49 -0
  15. package/dist/connectBookingCharge.js +72 -0
  16. package/dist/entitlements.d.ts +1 -1
  17. package/dist/entitlements.js +6 -1
  18. package/dist/functions/admin-acknowledge-contract-violation.d.ts +1 -0
  19. package/dist/functions/admin-acknowledge-contract-violation.js +120 -0
  20. package/dist/functions/admin-cancel-membership.js +109 -13
  21. package/dist/functions/admin-change-membership-plan.js +74 -18
  22. package/dist/functions/admin-charge-guest-print.d.ts +3 -1
  23. package/dist/functions/admin-charge-guest-print.js +8 -1
  24. package/dist/functions/admin-create-booking.d.ts +8 -3
  25. package/dist/functions/admin-create-booking.js +15 -2
  26. package/dist/functions/admin-create-commons-event.d.ts +3 -1
  27. package/dist/functions/admin-create-commons-event.js +8 -1
  28. package/dist/functions/admin-door-write.d.ts +3 -1
  29. package/dist/functions/admin-door-write.js +8 -1
  30. package/dist/functions/admin-issue-day-pass.d.ts +1 -0
  31. package/dist/functions/admin-issue-day-pass.js +8 -1
  32. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  33. package/dist/functions/admin-mark-booking-paid.js +27 -3
  34. package/dist/functions/admin-request-trial.js +22 -1
  35. package/dist/functions/auth-email-hook.js +42 -2
  36. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  37. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  38. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  39. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  40. package/dist/functions/booking-access-revoke.d.ts +35 -0
  41. package/dist/functions/booking-access-revoke.js +279 -0
  42. package/dist/functions/booking-availability.d.ts +2 -1
  43. package/dist/functions/booking-availability.js +14 -5
  44. package/dist/functions/conductor.js +39 -16
  45. package/dist/functions/create-booking.d.ts +10 -3
  46. package/dist/functions/create-booking.js +22 -4
  47. package/dist/functions/create-day-pass-checkout.d.ts +1 -0
  48. package/dist/functions/create-day-pass-checkout.js +6 -0
  49. package/dist/functions/create-subscription-checkout.js +7 -2
  50. package/dist/functions/event-access-admin.d.ts +1 -0
  51. package/dist/functions/event-access-admin.js +23 -1
  52. package/dist/functions/event-access-store.js +18 -0
  53. package/dist/functions/guest-print-setup-confirm.d.ts +3 -1
  54. package/dist/functions/guest-print-setup-confirm.js +8 -1
  55. package/dist/functions/guest-print-submit.d.ts +3 -1
  56. package/dist/functions/guest-print-submit.js +8 -1
  57. package/dist/functions/manage-booking.d.ts +9 -1
  58. package/dist/functions/manage-booking.js +140 -6
  59. package/dist/functions/mcp.d.ts +2 -2
  60. package/dist/functions/mcp.js +2 -2
  61. package/dist/functions/member-door-action.d.ts +3 -1
  62. package/dist/functions/member-door-action.js +9 -2
  63. package/dist/functions/membership-door-sync.d.ts +18 -0
  64. package/dist/functions/membership-door-sync.js +76 -6
  65. package/dist/functions/office-assignment-end.d.ts +3 -1
  66. package/dist/functions/office-assignment-end.js +8 -1
  67. package/dist/functions/portal-submit-event.d.ts +1 -0
  68. package/dist/functions/portal-submit-event.js +4 -0
  69. package/dist/functions/reschedule-booking.d.ts +11 -4
  70. package/dist/functions/reschedule-booking.js +39 -2
  71. package/dist/functions/review-ratings.js +1 -1
  72. package/dist/functions/space-availability-range.d.ts +2 -1
  73. package/dist/functions/space-availability-range.js +8 -1
  74. package/dist/functions/stripe-db-reconcile.js +8 -1
  75. package/dist/functions/stripe-webhook.d.ts +4 -0
  76. package/dist/functions/stripe-webhook.js +328 -17
  77. package/dist/functions/sync-gcal-blackouts.js +1 -1
  78. package/dist/functions/timetable-event-register.d.ts +3 -1
  79. package/dist/functions/timetable-event-register.js +8 -1
  80. package/dist/functions/touch-pass-signup.d.ts +3 -1
  81. package/dist/functions/touch-pass-signup.js +9 -2
  82. package/dist/functions/voice-booking.d.ts +1 -1
  83. package/dist/functions/voice-day-pass.d.ts +2 -1
  84. package/dist/functions/voice-day-pass.js +4 -0
  85. package/dist/functions/voice-inquiry.d.ts +3 -1
  86. package/dist/functions/voice-inquiry.js +9 -2
  87. package/dist/functions/voice-membership-signup.d.ts +2 -2
  88. package/dist/functions/voice-tour-booking.d.ts +1 -1
  89. package/dist/gcalBookingEvents.d.ts +59 -0
  90. package/dist/gcalBookingEvents.js +182 -0
  91. package/dist/gcalSync.d.ts +1 -0
  92. package/dist/gcalSync.js +5 -0
  93. package/dist/membershipSubscriptionItems.d.ts +87 -0
  94. package/dist/membershipSubscriptionItems.js +71 -0
  95. package/dist/membershipWelcome.d.ts +1 -1
  96. package/dist/outbox.d.ts +64 -0
  97. package/dist/outbox.js +70 -0
  98. package/dist/pricing.d.ts +10 -2
  99. package/dist/pricing.js +14 -9
  100. package/dist/referralCodeLookup.d.ts +13 -0
  101. package/dist/referralCodeLookup.js +17 -0
  102. package/dist/referralCredits.d.ts +5 -0
  103. package/dist/referralCredits.js +5 -0
  104. package/dist/referralGrant.d.ts +4 -31
  105. package/dist/referralGrant.js +14 -234
  106. package/dist/runtime/env.d.ts +7 -0
  107. package/dist/runtime/env.js +32 -0
  108. package/dist/runtime/fs.d.ts +5 -0
  109. package/dist/runtime/fs.js +16 -0
  110. package/dist/runtime/serve.d.ts +8 -0
  111. package/dist/runtime/serve.js +12 -0
  112. package/dist/stripeConnectEvents.d.ts +11 -0
  113. package/dist/stripeConnectEvents.js +37 -0
  114. package/dist/supabaseTestFakes.js +7 -1
  115. package/dist/tenant-config.d.ts +8 -0
  116. package/dist/tenant-config.js +25 -0
  117. package/dist/tenantManifest.d.ts +85 -0
  118. package/dist/tenantManifest.js +43 -0
  119. package/package.json +59 -3
@@ -0,0 +1,59 @@
1
+ export interface BookingEventInput {
2
+ calendarId: string;
3
+ bookingId: string;
4
+ startIso: string;
5
+ endIso: string;
6
+ summary: string;
7
+ description?: string;
8
+ location?: string;
9
+ }
10
+ export interface GcalWritebackDeps {
11
+ fetch?: typeof fetch;
12
+ getAccessToken?: () => Promise<string | null>;
13
+ }
14
+ export type WritebackResult = {
15
+ ok: true;
16
+ eventId: string;
17
+ action: 'created' | 'updated' | 'deleted' | 'already_absent';
18
+ } | {
19
+ ok: false;
20
+ reason: 'no_credentials' | 'no_calendar' | 'http_error' | 'exception';
21
+ status?: number;
22
+ detail?: string;
23
+ };
24
+ export declare function eventIdForBooking(bookingId: string): string;
25
+ export declare function createBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
26
+ export declare function updateBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
27
+ export declare function deleteBookingEvent(calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps): Promise<WritebackResult>;
28
+ export interface WritebackOperator {
29
+ googleCalendarWriteback?: boolean | null;
30
+ }
31
+ export declare function isGcalWritebackEnabled(operator: WritebackOperator | null | undefined): boolean;
32
+ export interface WritebackBookingRow {
33
+ id: string;
34
+ contact_name?: string | null;
35
+ contact_email?: string | null;
36
+ contact_phone?: string | null;
37
+ during: string;
38
+ rooms?: {
39
+ name?: string | null;
40
+ address?: string | null;
41
+ google_calendar_id?: string | null;
42
+ } | null;
43
+ }
44
+ export declare function bookingRowToEventInput(row: WritebackBookingRow): BookingEventInput | null;
45
+ type LogFn = (msg: string, detail: unknown) => void;
46
+ /**
47
+ * Fail-soft create for a paid booking row. Never throws; returns null when the
48
+ * operator flag is off (the default), so callers can invoke it unconditionally.
49
+ */
50
+ export declare function writebackBookingCreated(operator: WritebackOperator | null | undefined, row: WritebackBookingRow, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
51
+ export declare function writebackBookingCancelled(operator: WritebackOperator | null | undefined, calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
52
+ /**
53
+ * Adapter matching the `createCalendarEvent` dep shape used by create-booking,
54
+ * admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
55
+ * without door hardware can pass this as that dep; it is the only way to cover
56
+ * stripe-webhook's paid path without editing the webhook.
57
+ */
58
+ export declare function makeWritebackCreateCalendarEvent(operator: WritebackOperator, deps?: GcalWritebackDeps): (admin: unknown, row: WritebackBookingRow) => Promise<void>;
59
+ export {};
@@ -0,0 +1,182 @@
1
+ import { JWT } from 'google-auth-library';
2
+ import { parsePgRange } from './availability.js';
3
+ import { CS_BOOKING_ID_KEY } from './gcalSync.js';
4
+ const EVENTS_SCOPE = 'https://www.googleapis.com/auth/calendar.events';
5
+ const CAL_BASE = 'https://www.googleapis.com/calendar/v3/calendars';
6
+ const TZ = 'America/Los_Angeles';
7
+ // Deterministic id (Google allows client ids of [a-v0-9], 5-1024 chars; a UUID's
8
+ // hex digits qualify) so create is idempotent and update/delete need no stored id.
9
+ export function eventIdForBooking(bookingId) {
10
+ return `csb${bookingId.replace(/-/g, '').toLowerCase()}`;
11
+ }
12
+ async function defaultGetAccessToken() {
13
+ const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
14
+ const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
15
+ if (!clientEmail || !rawKey)
16
+ return null;
17
+ const jwt = new JWT({ email: clientEmail, key: rawKey.replace(/\\n/g, '\n'), scopes: [EVENTS_SCOPE] });
18
+ const tok = await jwt.getAccessToken();
19
+ return tok?.token ?? null;
20
+ }
21
+ function eventBody(input, includeId) {
22
+ return {
23
+ ...(includeId ? { id: eventIdForBooking(input.bookingId) } : {}),
24
+ summary: input.summary,
25
+ description: input.description,
26
+ location: input.location,
27
+ start: { dateTime: input.startIso, timeZone: TZ },
28
+ end: { dateTime: input.endIso, timeZone: TZ },
29
+ transparency: 'opaque',
30
+ extendedProperties: { private: { [CS_BOOKING_ID_KEY]: input.bookingId } },
31
+ };
32
+ }
33
+ async function call(method, calendarId, eventId, body, deps) {
34
+ const token = await (deps.getAccessToken ?? defaultGetAccessToken)();
35
+ if (!token)
36
+ return { noToken: true, status: 0 };
37
+ const url = `${CAL_BASE}/${encodeURIComponent(calendarId)}/events${eventId ? `/${encodeURIComponent(eventId)}` : ''}`;
38
+ const res = await (deps.fetch ?? fetch)(url, {
39
+ method,
40
+ headers: {
41
+ Authorization: `Bearer ${token}`,
42
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
43
+ },
44
+ body: body ? JSON.stringify(body) : undefined,
45
+ signal: AbortSignal.timeout(15000),
46
+ });
47
+ return { noToken: false, status: res.status };
48
+ }
49
+ const isOk = (s) => s >= 200 && s < 300;
50
+ const noCreds = { ok: false, reason: 'no_credentials' };
51
+ const httpFail = (status) => ({ ok: false, reason: 'http_error', status });
52
+ export async function createBookingEvent(input, deps = {}) {
53
+ if (!input.calendarId)
54
+ return { ok: false, reason: 'no_calendar' };
55
+ try {
56
+ const eventId = eventIdForBooking(input.bookingId);
57
+ const r = await call('POST', input.calendarId, null, eventBody(input, true), deps);
58
+ if (r.noToken)
59
+ return noCreds;
60
+ if (isOk(r.status))
61
+ return { ok: true, eventId, action: 'created' };
62
+ // Deterministic id already exists (retry / duplicate delivery): converge via update.
63
+ if (r.status === 409)
64
+ return await updateBookingEvent(input, deps);
65
+ return httpFail(r.status);
66
+ }
67
+ catch (e) {
68
+ return { ok: false, reason: 'exception', detail: String(e) };
69
+ }
70
+ }
71
+ export async function updateBookingEvent(input, deps = {}) {
72
+ if (!input.calendarId)
73
+ return { ok: false, reason: 'no_calendar' };
74
+ try {
75
+ const eventId = eventIdForBooking(input.bookingId);
76
+ const r = await call('PATCH', input.calendarId, eventId, eventBody(input, false), deps);
77
+ if (r.noToken)
78
+ return noCreds;
79
+ if (isOk(r.status))
80
+ return { ok: true, eventId, action: 'updated' };
81
+ if (r.status === 404) {
82
+ const c = await call('POST', input.calendarId, null, eventBody(input, true), deps);
83
+ if (c.noToken)
84
+ return noCreds;
85
+ return isOk(c.status) ? { ok: true, eventId, action: 'created' } : httpFail(c.status);
86
+ }
87
+ return httpFail(r.status);
88
+ }
89
+ catch (e) {
90
+ return { ok: false, reason: 'exception', detail: String(e) };
91
+ }
92
+ }
93
+ export async function deleteBookingEvent(calendarId, bookingId, deps = {}) {
94
+ if (!calendarId)
95
+ return { ok: false, reason: 'no_calendar' };
96
+ try {
97
+ const eventId = eventIdForBooking(bookingId);
98
+ const r = await call('DELETE', calendarId, eventId, null, deps);
99
+ if (r.noToken)
100
+ return noCreds;
101
+ if (isOk(r.status))
102
+ return { ok: true, eventId, action: 'deleted' };
103
+ if (r.status === 404 || r.status === 410)
104
+ return { ok: true, eventId, action: 'already_absent' };
105
+ return httpFail(r.status);
106
+ }
107
+ catch (e) {
108
+ return { ok: false, reason: 'exception', detail: String(e) };
109
+ }
110
+ }
111
+ export function isGcalWritebackEnabled(operator) {
112
+ return operator?.googleCalendarWriteback === true;
113
+ }
114
+ export function bookingRowToEventInput(row) {
115
+ const calendarId = row.rooms?.google_calendar_id;
116
+ const range = parsePgRange(row.during);
117
+ if (!calendarId || !range)
118
+ return null;
119
+ const who = row.contact_name || row.contact_email || 'Guest';
120
+ const lines = [
121
+ row.contact_name ? `Name: ${row.contact_name}` : null,
122
+ row.contact_email ? `Email: ${row.contact_email}` : null,
123
+ row.contact_phone ? `Phone: ${row.contact_phone}` : null,
124
+ `Booking: ${row.id}`,
125
+ ].filter(Boolean);
126
+ return {
127
+ calendarId,
128
+ bookingId: row.id,
129
+ startIso: new Date(range[0]).toISOString(),
130
+ endIso: new Date(range[1]).toISOString(),
131
+ summary: `${row.rooms?.name ?? 'Booking'} — ${who}`,
132
+ description: lines.join('\n'),
133
+ location: row.rooms?.address ?? undefined,
134
+ };
135
+ }
136
+ const defaultLog = (m, d) => console.warn(m, d);
137
+ /**
138
+ * Fail-soft create for a paid booking row. Never throws; returns null when the
139
+ * operator flag is off (the default), so callers can invoke it unconditionally.
140
+ */
141
+ export async function writebackBookingCreated(operator, row, deps = {}, log = defaultLog) {
142
+ if (!isGcalWritebackEnabled(operator))
143
+ return null;
144
+ try {
145
+ const input = bookingRowToEventInput(row);
146
+ if (!input)
147
+ return { ok: false, reason: 'no_calendar' };
148
+ const res = await createBookingEvent(input, deps);
149
+ if (!res.ok)
150
+ log('[gcalBookingEvents] create failed', { bookingId: row.id, ...res });
151
+ return res;
152
+ }
153
+ catch (e) {
154
+ log('[gcalBookingEvents] create threw', { bookingId: row.id, error: String(e) });
155
+ return { ok: false, reason: 'exception', detail: String(e) };
156
+ }
157
+ }
158
+ export async function writebackBookingCancelled(operator, calendarId, bookingId, deps = {}, log = defaultLog) {
159
+ if (!isGcalWritebackEnabled(operator))
160
+ return null;
161
+ try {
162
+ const res = await deleteBookingEvent(calendarId, bookingId, deps);
163
+ if (!res.ok)
164
+ log('[gcalBookingEvents] delete failed', { bookingId, ...res });
165
+ return res;
166
+ }
167
+ catch (e) {
168
+ log('[gcalBookingEvents] delete threw', { bookingId, error: String(e) });
169
+ return { ok: false, reason: 'exception', detail: String(e) };
170
+ }
171
+ }
172
+ /**
173
+ * Adapter matching the `createCalendarEvent` dep shape used by create-booking,
174
+ * admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
175
+ * without door hardware can pass this as that dep; it is the only way to cover
176
+ * stripe-webhook's paid path without editing the webhook.
177
+ */
178
+ export function makeWritebackCreateCalendarEvent(operator, deps = {}) {
179
+ return async (_admin, row) => {
180
+ await writebackBookingCreated(operator, row, deps);
181
+ };
182
+ }
@@ -5,6 +5,7 @@ export declare function allDayToUtcRange(startDate: string, endDate: string): {
5
5
  endIso: string;
6
6
  };
7
7
  export declare function laMidnightUtc(dateStr: string): Date;
8
+ export declare const CS_BOOKING_ID_KEY = "cs_booking_id";
8
9
  export interface GcalEventStartEnd {
9
10
  dateTime?: string;
10
11
  date?: string;
package/dist/gcalSync.js CHANGED
@@ -62,6 +62,7 @@ export function laMidnightUtc(dateStr) {
62
62
  // Fallback (should not happen for real LA dates).
63
63
  return new Date(Date.UTC(y, mo - 1, d, 8, 0));
64
64
  }
65
+ export const CS_BOOKING_ID_KEY = 'cs_booking_id';
65
66
  // True when this event was created by our own booking system and must NOT be
66
67
  // re-imported as a blackout (belt & braces: gc_source marker OR known booking
67
68
  // google_event_id). Also drops cancelled and transparent (free) events.
@@ -75,6 +76,10 @@ export function shouldSkipEvent(ev, selfIds) {
75
76
  const source = ev.extendedProperties?.private?.gc_source;
76
77
  if (source === 'gc-connect')
77
78
  return true;
79
+ // Events written back by gcalBookingEvents.ts carry cs_booking_id; importing
80
+ // them as blackouts would make every booking block its own slot.
81
+ if (ev.extendedProperties?.private?.[CS_BOOKING_ID_KEY])
82
+ return true;
78
83
  if (selfIds.has(ev.id))
79
84
  return true;
80
85
  return false;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Deliberately not the full Stripe.SubscriptionItem type: every existing call
3
+ * site already narrows to this shape via `as unknown as {...}` because the
4
+ * installed Stripe SDK's types lag the API's per-item billing-period fields.
5
+ * Keeping the helper's own shape this small also means test fixtures don't
6
+ * need to satisfy Stripe's full item type.
7
+ */
8
+ export interface BaseSubscriptionItem {
9
+ id: string;
10
+ current_period_start: number;
11
+ current_period_end: number;
12
+ metadata?: Record<string, string> | null;
13
+ }
14
+ export interface SubscriptionWithItems<T extends BaseSubscriptionItem = BaseSubscriptionItem> {
15
+ items: {
16
+ data: T[];
17
+ };
18
+ }
19
+ /**
20
+ * Resolve the single non-addon item on a subscription. Returns null unless
21
+ * exactly one item remains after add-on-tagged items are filtered out --
22
+ * including when every item is an add-on, or when more than one untagged
23
+ * item is present (an unexpected configuration, same as the old
24
+ * items.data.length !== 1 guard it replaces). A subscription with no
25
+ * gc_addon-tagged items at all (every subscription before add-ons existed)
26
+ * still resolves to its single item, unchanged.
27
+ */
28
+ export declare function findBaseItem<T extends BaseSubscriptionItem>(sub: SubscriptionWithItems<T>): T | null;
29
+ /** Count of non-addon items, for error details when findBaseItem returns null. */
30
+ export declare function countBaseItems<T extends BaseSubscriptionItem>(sub: SubscriptionWithItems<T>): number;
31
+ /**
32
+ * True if the subscription carries at least one gc_addon-tagged item. Used to
33
+ * gate add-on-aware guards (refund-with-addons block, base-price mismatch
34
+ * check) so subscriptions with no add-ons keep their pre-add-on behavior
35
+ * exactly.
36
+ */
37
+ export declare function hasAddonItems<T extends BaseSubscriptionItem>(sub: SubscriptionWithItems<T>): boolean;
38
+ export interface PricedSubscriptionItem {
39
+ price?: {
40
+ id?: string | null;
41
+ product?: string | null;
42
+ } | null;
43
+ }
44
+ export interface PlanPriceIdentity {
45
+ stripe_price_id?: string | null;
46
+ stripe_product_id?: string | null;
47
+ }
48
+ /**
49
+ * True if baseItem's Stripe price identifies the same plan as currentPlan:
50
+ * first by price id, falling back to product id when the plan has no stored
51
+ * price id or the ids differ. Fails closed -- returns false, meaning
52
+ * "reject" to the caller -- when neither identifies a match, including when
53
+ * the plan has neither id stored.
54
+ */
55
+ export declare function matchesPlanPrice(baseItem: PricedSubscriptionItem, plan: PlanPriceIdentity): boolean;
56
+ export interface InvoiceBillingReason {
57
+ billing_reason?: string | null;
58
+ }
59
+ /**
60
+ * True only for the invoice Stripe creates for a normal subscription renewal
61
+ * or the original subscription creation -- the one invoice whose amount
62
+ * actually corresponds to a full billing period, which the cancel-refund
63
+ * proration math assumes. Any other billing_reason (e.g. an add-on's
64
+ * always_invoice charge, or a manual/one-off invoice) is not safe to prorate
65
+ * as if it were the base-period invoice.
66
+ */
67
+ export declare function isRenewalInvoice(invoice: InvoiceBillingReason | null | undefined): boolean;
68
+ export interface InvoiceWithLines {
69
+ lines?: {
70
+ data?: Array<{
71
+ period?: {
72
+ start?: number | null;
73
+ } | null;
74
+ }> | null;
75
+ } | null;
76
+ }
77
+ /**
78
+ * True only if at least one of the invoice's line items has period.start
79
+ * equal to periodStart -- i.e. the invoice actually covers the CURRENT
80
+ * billing period, not a past or future one. isRenewalInvoice() confirms the
81
+ * invoice is SHAPED like a full-period charge; it says nothing about WHICH
82
+ * period. A past_due subscription or the brief draft window right after a
83
+ * renewal can leave the latest PAID invoice as last period's while the
84
+ * current period is still unpaid, and prorating that stale invoice against
85
+ * the current period's bounds would over-refund the member.
86
+ */
87
+ export declare function invoiceCoversPeriod(invoice: InvoiceWithLines | null | undefined, periodStart: number): boolean;
@@ -0,0 +1,71 @@
1
+ // Membership add-ons (membership add-ons phase) give a subscription a second
2
+ // Stripe subscription item alongside the base membership item, tagged with
3
+ // item-level metadata.gc_addon === '1'. Every admin path that used to assume
4
+ // "a membership subscription has exactly one item" -- plan changes,
5
+ // cancellation, and the period-bounds reads in the webhook/reconciler --
6
+ // must instead resolve the ONE remaining non-addon ("base") item and ignore
7
+ // add-on items entirely.
8
+ /**
9
+ * Resolve the single non-addon item on a subscription. Returns null unless
10
+ * exactly one item remains after add-on-tagged items are filtered out --
11
+ * including when every item is an add-on, or when more than one untagged
12
+ * item is present (an unexpected configuration, same as the old
13
+ * items.data.length !== 1 guard it replaces). A subscription with no
14
+ * gc_addon-tagged items at all (every subscription before add-ons existed)
15
+ * still resolves to its single item, unchanged.
16
+ */
17
+ export function findBaseItem(sub) {
18
+ const baseItems = (sub.items?.data ?? []).filter((item) => item.metadata?.gc_addon !== '1');
19
+ return baseItems.length === 1 ? baseItems[0] : null;
20
+ }
21
+ /** Count of non-addon items, for error details when findBaseItem returns null. */
22
+ export function countBaseItems(sub) {
23
+ return (sub.items?.data ?? []).filter((item) => item.metadata?.gc_addon !== '1').length;
24
+ }
25
+ /**
26
+ * True if the subscription carries at least one gc_addon-tagged item. Used to
27
+ * gate add-on-aware guards (refund-with-addons block, base-price mismatch
28
+ * check) so subscriptions with no add-ons keep their pre-add-on behavior
29
+ * exactly.
30
+ */
31
+ export function hasAddonItems(sub) {
32
+ return (sub.items?.data ?? []).some((item) => item.metadata?.gc_addon === '1');
33
+ }
34
+ /**
35
+ * True if baseItem's Stripe price identifies the same plan as currentPlan:
36
+ * first by price id, falling back to product id when the plan has no stored
37
+ * price id or the ids differ. Fails closed -- returns false, meaning
38
+ * "reject" to the caller -- when neither identifies a match, including when
39
+ * the plan has neither id stored.
40
+ */
41
+ export function matchesPlanPrice(baseItem, plan) {
42
+ if (plan.stripe_price_id && baseItem.price?.id === plan.stripe_price_id)
43
+ return true;
44
+ if (plan.stripe_product_id && baseItem.price?.product === plan.stripe_product_id)
45
+ return true;
46
+ return false;
47
+ }
48
+ /**
49
+ * True only for the invoice Stripe creates for a normal subscription renewal
50
+ * or the original subscription creation -- the one invoice whose amount
51
+ * actually corresponds to a full billing period, which the cancel-refund
52
+ * proration math assumes. Any other billing_reason (e.g. an add-on's
53
+ * always_invoice charge, or a manual/one-off invoice) is not safe to prorate
54
+ * as if it were the base-period invoice.
55
+ */
56
+ export function isRenewalInvoice(invoice) {
57
+ return invoice?.billing_reason === 'subscription_cycle' || invoice?.billing_reason === 'subscription_create';
58
+ }
59
+ /**
60
+ * True only if at least one of the invoice's line items has period.start
61
+ * equal to periodStart -- i.e. the invoice actually covers the CURRENT
62
+ * billing period, not a past or future one. isRenewalInvoice() confirms the
63
+ * invoice is SHAPED like a full-period charge; it says nothing about WHICH
64
+ * period. A past_due subscription or the brief draft window right after a
65
+ * renewal can leave the latest PAID invoice as last period's while the
66
+ * current period is still unpaid, and prorating that stale invoice against
67
+ * the current period's bounds would over-refund the member.
68
+ */
69
+ export function invoiceCoversPeriod(invoice, periodStart) {
70
+ return (invoice?.lines?.data ?? []).some((line) => line?.period?.start === periodStart);
71
+ }
@@ -20,7 +20,7 @@ export type WelcomePlan = {
20
20
  };
21
21
  /** The operator (venue/business) identity interpolated into the emails. */
22
22
  export type WelcomeOperator = {
23
- /** Full legal/brand name, e.g. "Granite City Workspaces". */
23
+ /** Full legal/brand name, e.g. "Acme Coworking". */
24
24
  name: string;
25
25
  /** Short brand name used in subject lines and GHL `source`. */
26
26
  shortName: string;
@@ -0,0 +1,64 @@
1
+ /** Pure outbox/retry rules and a generic batch loop. No I/O, no DB, no Deno. */
2
+ /** Wait before retry N (1-based count of failed attempts so far). */
3
+ export declare const BACKOFF_MS: readonly [60000, number, number, number, number];
4
+ /** Total attempts before a row is dead-lettered. */
5
+ export declare const MAX_ATTEMPTS = 6;
6
+ /** Provider hints cannot extend a retry by more than an hour. */
7
+ export declare function cappedRetryAfterSeconds(value: unknown): number;
8
+ /** Scheduled retries age from their due time, not their original enqueue time. */
9
+ export declare function oldestPendingAgeSeconds(rows: {
10
+ created_at: string;
11
+ next_attempt_at: string | null;
12
+ }[], now?: number): number;
13
+ /** Next delay after `attempts` failures, or null when the row should be dead-lettered. */
14
+ export declare function nextRetryDelayMs(attempts: number): number | null;
15
+ export type OutboxRow = {
16
+ id: string;
17
+ booking_id: string | null;
18
+ event: string;
19
+ audience: string;
20
+ to_email: string;
21
+ reply_to: string | null;
22
+ subject: string;
23
+ body_text: string;
24
+ status: string;
25
+ attempts: number;
26
+ };
27
+ /** Only 'queued' rows may ever be delivered. 'held' waits for an admin confirm. */
28
+ export declare const isSendable: (row: Pick<OutboxRow, "status">) => boolean;
29
+ /** Staff alerts are events starting with "alert". */
30
+ export declare const isAlertRow: (row: Pick<OutboxRow, "audience" | "event">) => boolean;
31
+ /** A dead-lettered alert never raises another alert (prevents alert loops). */
32
+ export declare const shouldAlertOnDeadLetter: (row: Pick<OutboxRow, "audience" | "event">) => boolean;
33
+ /** Stable idempotency key so one dead letter produces at most one alert per recipient. */
34
+ export declare const deadLetterAlertKey: (rowId: string) => string;
35
+ /** Customer messages reply to the studio; staff messages reply to the customer (stored at enqueue), else the studio. */
36
+ export declare function replyToFor(row: Pick<OutboxRow, "audience" | "reply_to">, supportEmail: string): string | undefined;
37
+ export interface OutboxStore {
38
+ claimBatch: (limit: number) => Promise<OutboxRow[]>;
39
+ markSent: (id: string, note?: string) => Promise<void>;
40
+ markRetry: (id: string, nextAtISO: string, error: string) => Promise<void>;
41
+ markDead: (id: string, error: string) => Promise<void>;
42
+ }
43
+ export interface OutboxSender {
44
+ send: (row: OutboxRow) => Promise<{
45
+ sent: boolean;
46
+ }>;
47
+ }
48
+ export interface OutboxDeps {
49
+ store: OutboxStore;
50
+ sender: OutboxSender;
51
+ /** Called once per dead-lettered row after markDead (e.g. ops event). */
52
+ onDeadLetter?: (row: OutboxRow, error: string) => Promise<void>;
53
+ /** Called once per dead-lettered non-alert row; use deadLetterAlertKey(row.id) as idempotency key. */
54
+ queueDeadLetterAlert?: (row: OutboxRow, error: string, idempotencyKey: string) => Promise<void>;
55
+ now?: () => number;
56
+ }
57
+ export type OutboxBatchResult = {
58
+ claimed: number;
59
+ sent: number;
60
+ retried: number;
61
+ dead: number;
62
+ };
63
+ export declare const SUPPRESSED_NOTE = "recipient_suppressed";
64
+ export declare function processOutboxBatch(deps: OutboxDeps, limit?: number): Promise<OutboxBatchResult>;
package/dist/outbox.js ADDED
@@ -0,0 +1,70 @@
1
+ /** Pure outbox/retry rules and a generic batch loop. No I/O, no DB, no Deno. */
2
+ /** Wait before retry N (1-based count of failed attempts so far). */
3
+ export const BACKOFF_MS = [60_000, 5 * 60_000, 30 * 60_000, 2 * 3_600_000, 6 * 3_600_000];
4
+ /** Total attempts before a row is dead-lettered. */
5
+ export const MAX_ATTEMPTS = 6;
6
+ /** Provider hints cannot extend a retry by more than an hour. */
7
+ export function cappedRetryAfterSeconds(value) {
8
+ if (typeof value !== "number" || Number.isNaN(value))
9
+ return 0;
10
+ return Math.max(0, Math.min(3600, value));
11
+ }
12
+ /** Scheduled retries age from their due time, not their original enqueue time. */
13
+ export function oldestPendingAgeSeconds(rows, now = Date.now()) {
14
+ const times = rows.map((row) => Date.parse(row.next_attempt_at ?? row.created_at)).filter(Number.isFinite);
15
+ return times.length ? Math.max(0, Math.round((now - Math.min(...times)) / 1000)) : 0;
16
+ }
17
+ /** Next delay after `attempts` failures, or null when the row should be dead-lettered. */
18
+ export function nextRetryDelayMs(attempts) {
19
+ if (attempts >= MAX_ATTEMPTS)
20
+ return null;
21
+ return BACKOFF_MS[Math.max(0, Math.min(attempts, BACKOFF_MS.length) - 1)] ?? BACKOFF_MS[0];
22
+ }
23
+ /** Only 'queued' rows may ever be delivered. 'held' waits for an admin confirm. */
24
+ export const isSendable = (row) => row.status === "queued";
25
+ /** Staff alerts are events starting with "alert". */
26
+ export const isAlertRow = (row) => row.audience === "staff" && row.event.startsWith("alert");
27
+ /** A dead-lettered alert never raises another alert (prevents alert loops). */
28
+ export const shouldAlertOnDeadLetter = (row) => !isAlertRow(row);
29
+ /** Stable idempotency key so one dead letter produces at most one alert per recipient. */
30
+ export const deadLetterAlertKey = (rowId) => `deadletter:${rowId}`;
31
+ const singleLine = (v) => (v ?? "").replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
32
+ /** Customer messages reply to the studio; staff messages reply to the customer (stored at enqueue), else the studio. */
33
+ export function replyToFor(row, supportEmail) {
34
+ const support = singleLine(supportEmail);
35
+ if (row.audience === "customer")
36
+ return support || undefined;
37
+ return singleLine(row.reply_to) || support || undefined;
38
+ }
39
+ export const SUPPRESSED_NOTE = "recipient_suppressed";
40
+ export async function processOutboxBatch(deps, limit = 25) {
41
+ const { store, sender } = deps;
42
+ const now = deps.now ?? Date.now;
43
+ const rows = (await store.claimBatch(limit)).filter(isSendable);
44
+ let sent = 0, retried = 0, dead = 0;
45
+ for (const row of rows) {
46
+ try {
47
+ const res = await sender.send(row);
48
+ await store.markSent(row.id, res.sent ? undefined : SUPPRESSED_NOTE);
49
+ sent++;
50
+ }
51
+ catch (e) {
52
+ const msg = String(e).slice(0, 1000);
53
+ const delay = nextRetryDelayMs(row.attempts);
54
+ const retryAfter = cappedRetryAfterSeconds(e?.retryAfterSeconds);
55
+ if (delay === null) {
56
+ await store.markDead(row.id, msg);
57
+ await deps.onDeadLetter?.(row, msg);
58
+ if (shouldAlertOnDeadLetter(row))
59
+ await deps.queueDeadLetterAlert?.(row, msg, deadLetterAlertKey(row.id));
60
+ dead++;
61
+ }
62
+ else {
63
+ const wait = Math.max(delay, retryAfter * 1000);
64
+ await store.markRetry(row.id, new Date(now() + wait).toISOString(), msg);
65
+ retried++;
66
+ }
67
+ }
68
+ }
69
+ return { claimed: rows.length, sent, retried, dead };
70
+ }
package/dist/pricing.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { SupabaseClient } from '@supabase/supabase-js';
2
+ import type { NoticeConfig } from './businessHours.js';
2
3
  type SupabaseLike = SupabaseClient<any, any, any>;
3
4
  export interface RoomForPricing {
4
5
  id: string;
@@ -95,8 +96,8 @@ export declare function resolveHalfDayWindow(room: RoomForPricing, dayMode: 'hal
95
96
  ok: false;
96
97
  error: string;
97
98
  };
98
- export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number): Promise<PricingResult>;
99
- export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number): Promise<PricingResult>;
99
+ export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number, notice?: NoticeConfig | null): Promise<PricingResult>;
100
+ export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number, notice?: NoticeConfig | null): Promise<PricingResult>;
100
101
  /**
101
102
  * Entry point: dispatches to hourly or day_block based on room.booking_mode.
102
103
  * `quote` rooms cannot be booked via checkout.
@@ -302,5 +303,12 @@ export declare function validateAndPriceForRoom(supabase: SupabaseLike, room: Ro
302
303
  discount_cents: number;
303
304
  rule_type: string | null;
304
305
  };
306
+ /**
307
+ * Optional per-operator minimum-notice config (minNoticeBusinessHours /
308
+ * holidays). Public customer paths (create-booking, reschedule-booking)
309
+ * pass it; staff paths (admin-create-booking) omit it and keep the plain
310
+ * 15-minute floor. Unset => exactly the historical 15-minute floor.
311
+ */
312
+ notice?: NoticeConfig | null;
305
313
  }): Promise<PricingResult>;
306
314
  export {};