@composable-os/cli 0.1.0-beta.10 → 0.1.0-beta.11

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 (64) hide show
  1. package/dist/{accounts-X4CKM3HL.js → accounts-UHYLCLEY.js} +10 -11
  2. package/dist/{blocks-YWDHEBOK.js → blocks-5IFU25J6.js} +2 -2
  3. package/dist/chunk-2IVEVPMY.js +669 -0
  4. package/dist/{chunk-QGGJ2G6Z.js → chunk-2TWV3SVB.js} +3 -3
  5. package/dist/chunk-2XC5JLBO.js +1931 -0
  6. package/dist/chunk-324WJXNP.js +320 -0
  7. package/dist/chunk-6ELZRNUU.js +116 -0
  8. package/dist/{chunk-YJJHF65I.js → chunk-6WGFA2IV.js} +58 -174
  9. package/dist/{chunk-A4NTSYWV.js → chunk-6XTU2MTP.js} +196 -10
  10. package/dist/{chunk-Q4N55M2Z.js → chunk-7D4GKZOX.js} +66 -3
  11. package/dist/{chunk-GYSGVT6R.js → chunk-7OGCMQXG.js} +9 -9
  12. package/dist/chunk-DHS2CV2M.js +139 -0
  13. package/dist/{chunk-LJFLENFC.js → chunk-E64SG24J.js} +1 -1
  14. package/dist/{chunk-Z3RMMB6S.js → chunk-FJIZGS5Q.js} +45 -15
  15. package/dist/chunk-K34UKWEI.js +298 -0
  16. package/dist/{chunk-LLULPZAJ.js → chunk-LAAL4YGR.js} +4 -4
  17. package/dist/{chunk-CP6BXI6F.js → chunk-LO6WGU5Y.js} +1338 -974
  18. package/dist/{chunk-Y7JZFSTQ.js → chunk-MBIKVRAC.js} +6 -6
  19. package/dist/{chunk-WC5LHBBA.js → chunk-P6UWZ6QQ.js} +1 -1
  20. package/dist/{chunk-6VXHPKGG.js → chunk-PDD2ETVF.js} +8 -8
  21. package/dist/{chunk-6UPUF4ML.js → chunk-UB4I2QKR.js} +1957 -380
  22. package/dist/{chunk-M7A6FR2Z.js → chunk-WHKJGF36.js} +154 -322
  23. package/dist/{chunk-VY64DMQO.js → chunk-XIDLW3EP.js} +190 -21
  24. package/dist/{chunk-IFG4FRW5.js → chunk-YFTLIEWU.js} +1 -1
  25. package/dist/{chunk-JJHHNV46.js → chunk-YNUZRTPH.js} +5 -50
  26. package/dist/{chunk-WO6D3XP3.js → chunk-ZAWES2UD.js} +31 -18
  27. package/dist/{chunk-K6T42YCH.js → chunk-ZZFWMVJO.js} +5 -5
  28. package/dist/{cli-2DFENR62.js → cli-5UNY5G5L.js} +22 -20
  29. package/dist/{cli-YIOVSKOD.js → cli-UYZMVQMR.js} +16 -13
  30. package/dist/cli.js +1 -1
  31. package/dist/{client-repo-PRU3VCQQ.js → client-repo-SE4EKG6W.js} +2 -2
  32. package/dist/create.js +1 -1
  33. package/dist/{fields-2NC7LSYE.js → fields-FTWWMD7N.js} +3 -3
  34. package/dist/grants-LOW6TSWD.js +32 -0
  35. package/dist/invoke-6KVT6WJI.js +41 -0
  36. package/dist/moves-E2HKYCTK.js +41 -0
  37. package/dist/{order-PUWD65BC.js → order-U4KZLLSJ.js} +2 -2
  38. package/dist/{person-WIQQ7ITU.js → person-UHLVBVLR.js} +9 -10
  39. package/dist/plan-on-sale-TJPFCNL7.js +26 -0
  40. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  41. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  42. package/dist/platform/migrations/0650_person_links.sql +90 -0
  43. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  44. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  45. package/dist/platform/sdk/capacity.ts +102 -0
  46. package/dist/platform/sdk/contract.ts +25 -0
  47. package/dist/platform/sdk/manifest.ts +77 -1
  48. package/dist/platform/sdk/sellable.ts +251 -1
  49. package/dist/platform/sdk/states.ts +163 -49
  50. package/dist/{run-RT2HVWMK.js → run-7P4RQALH.js} +2 -2
  51. package/dist/{run-PZUCSDDL.js → run-PO3W5BFA.js} +1 -1
  52. package/dist/{run-Y7T4TVOL.js → run-ZCGFMEZF.js} +2 -2
  53. package/dist/src-CRO35DYY.js +46 -0
  54. package/dist/{src-XTOD7EXW.js → src-I3IJ4NKC.js} +8 -2
  55. package/dist/{visibility-DLGHU4YN.js → visibility-TVXZ67FD.js} +12 -4
  56. package/package.json +2 -2
  57. package/dist/chunk-6GDEDOV7.js +0 -157
  58. package/dist/chunk-O2UIZHND.js +0 -249
  59. package/dist/chunk-R4W5XAUD.js +0 -837
  60. package/dist/chunk-TQFGGSA4.js +0 -748
  61. package/dist/grants-QXMKYMGB.js +0 -32
  62. package/dist/invoke-I3NNNXVL.js +0 -39
  63. package/dist/plan-on-sale-NB774CQL.js +0 -26
  64. package/dist/src-GYS6NBQB.js +0 -44
@@ -1,32 +1,46 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ findPlanOnSale,
4
+ forgetPlanOnSale,
5
+ hasPlanOnSale,
6
+ subscriptionSetup
7
+ } from "./chunk-DHS2CV2M.js";
8
+ import {
9
+ grantFieldValue,
10
+ grantsFollowPerson,
11
+ readGrantItem
12
+ } from "./chunk-K34UKWEI.js";
13
+ import {
14
+ ORDER_TOKEN,
15
+ hashOrderToken,
16
+ movesFollowPerson,
17
+ newOrderToken,
18
+ orderForToken,
19
+ releaseUnsettledGuest,
20
+ resolveBuyer,
21
+ startHeld
22
+ } from "./chunk-2IVEVPMY.js";
2
23
  import {
3
24
  ORDER_MAX_LINES,
4
25
  ORDER_MAX_QUANTITY,
5
26
  changeOrder,
6
27
  chargeFor,
7
28
  createOrder,
8
- findPlanOnSale,
9
- forgetPlanOnSale,
10
29
  formatMoney,
11
- hasPlanOnSale,
12
30
  loadOrderRow,
13
31
  orderSnapshot,
14
32
  overdueOrders,
15
33
  priceLines,
16
- requireState,
17
- subscriptionSetup
18
- } from "./chunk-YJJHF65I.js";
34
+ requireState
35
+ } from "./chunk-6WGFA2IV.js";
19
36
  import {
20
37
  RECURRING_MAX_PER_RUN,
21
38
  checkRecordValues,
22
39
  createRecord,
23
40
  generateSeries,
24
- grantFieldValue,
25
- grantsFollowPerson,
26
41
  holderOf,
27
42
  keyingAt,
28
43
  loadRecord,
29
- readGrantItem,
30
44
  recordOperations,
31
45
  recordSchema,
32
46
  requireClosureObject,
@@ -35,20 +49,17 @@ import {
35
49
  slugsForCreate,
36
50
  storedTerms,
37
51
  updateRecord
38
- } from "./chunk-M7A6FR2Z.js";
52
+ } from "./chunk-WHKJGF36.js";
39
53
  import {
40
54
  applyTransition,
41
55
  callerMover,
42
- callerOf,
43
- onRecordMove,
44
- resolveStateRequest
45
- } from "./chunk-R4W5XAUD.js";
56
+ onRecordMove
57
+ } from "./chunk-324WJXNP.js";
46
58
  import {
47
59
  CUSTOMER_EMAIL_CONNECTION_SETTING,
48
60
  CUSTOMER_ERASE_DUE_SETTING,
49
61
  CUSTOMER_SIGNUP_SETTING,
50
62
  CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING,
51
- creatorFor,
52
63
  customerSignupModeSchema,
53
64
  eraseDueDaysSchema,
54
65
  inviteCustomerStatement,
@@ -56,10 +67,8 @@ import {
56
67
  loadCustomerSignIn,
57
68
  loadCustomerSignup,
58
69
  loadCustomerSignupSubscribers,
59
- loadEraseDueDays,
60
- normaliseCustomerEmail,
61
- sameEmailPeople
62
- } from "./chunk-GYSGVT6R.js";
70
+ loadEraseDueDays
71
+ } from "./chunk-7OGCMQXG.js";
63
72
  import {
64
73
  A2UI_CATALOGUE_VERSION,
65
74
  AGENT_SETTINGS,
@@ -134,11 +143,11 @@ import {
134
143
  emptyCacheLifetimeState,
135
144
  entitlementsSchema,
136
145
  erasedAddressHash,
137
- erasedAddresses,
138
146
  errorForLog,
139
147
  estimateCacheLifetime,
140
148
  failureOf,
141
149
  ftsQuery,
150
+ hasLiveLink,
142
151
  highlight,
143
152
  idOrEmailIn,
144
153
  idsMatchingConditions,
@@ -200,6 +209,7 @@ import {
200
209
  personSnapshot,
201
210
  personWritableFields,
202
211
  plainGateWords,
212
+ planMergeLinks,
203
213
  planReapply,
204
214
  prepareCard,
205
215
  producerRef,
@@ -209,6 +219,7 @@ import {
209
219
  queueDeleteMemory,
210
220
  queueDeleteMemoryFromMessages,
211
221
  queueEraseAllowances,
222
+ queueEraseLinks,
212
223
  queueMemoryRefs,
213
224
  queueScanAfterImport,
214
225
  readCachedSummary,
@@ -245,7 +256,7 @@ import {
245
256
  uniqueRefs,
246
257
  uniqueTagNames,
247
258
  vectorId
248
- } from "./chunk-VY64DMQO.js";
259
+ } from "./chunk-XIDLW3EP.js";
249
260
  import {
250
261
  ASSIGNMENT_METHODS,
251
262
  addDaysToDate,
@@ -267,20 +278,7 @@ import {
267
278
  validateConditions,
268
279
  valuesEqual,
269
280
  zonedTime
270
- } from "./chunk-Z3RMMB6S.js";
271
- import {
272
- OUTSIDE_RISK_CLASSES,
273
- afterCommit,
274
- allowsAudience,
275
- audiencesOf,
276
- defineOperation,
277
- isAfterCommit,
278
- isHostTool,
279
- markHostTool,
280
- operationProblems,
281
- recordHostChange,
282
- runAfterCommit
283
- } from "./chunk-6GDEDOV7.js";
281
+ } from "./chunk-FJIZGS5Q.js";
284
282
  import {
285
283
  HIDDEN_RETENTION_DAYS,
286
284
  NO_TRIAL_REASONS,
@@ -316,16 +314,16 @@ import {
316
314
  useTrial,
317
315
  widgetSpecSchema,
318
316
  withdrawOffer
319
- } from "./chunk-WO6D3XP3.js";
317
+ } from "./chunk-ZAWES2UD.js";
320
318
  import {
321
319
  callSubscriptionGatekeeper,
322
320
  openProviderCheckout,
323
321
  paymentsTarget,
324
322
  requestProviderRefund
325
- } from "./chunk-LJFLENFC.js";
323
+ } from "./chunk-E64SG24J.js";
326
324
  import {
327
325
  periodOf
328
- } from "./chunk-JJHHNV46.js";
326
+ } from "./chunk-YNUZRTPH.js";
329
327
  import {
330
328
  ORDER_CURRENCY_SETTING,
331
329
  ORDER_EXPIRY_SETTING,
@@ -342,12 +340,11 @@ import {
342
340
  loadOrderTaxCodes,
343
341
  loadReturnOrigins,
344
342
  loadSetting,
345
- localParts,
346
343
  minPartPaymentSchema,
347
344
  orderExpiryMinutesSchema,
348
345
  returnOriginsSchema,
349
346
  taxCodesSchema
350
- } from "./chunk-O2UIZHND.js";
347
+ } from "./chunk-6ELZRNUU.js";
351
348
  import {
352
349
  AUTOMATION_SETTINGS,
353
350
  CATALOGUE,
@@ -358,7 +355,7 @@ import {
358
355
  revokeBindingsPlan,
359
356
  syncKindOf,
360
357
  triggerObject
361
- } from "./chunk-QGGJ2G6Z.js";
358
+ } from "./chunk-2TWV3SVB.js";
362
359
  import {
363
360
  LIST_MAX_LIMIT,
364
361
  TRASH_RETENTION_DAYS,
@@ -379,34 +376,51 @@ import {
379
376
  runListQuery,
380
377
  selectFields,
381
378
  sortSchema
382
- } from "./chunk-K6T42YCH.js";
379
+ } from "./chunk-ZZFWMVJO.js";
383
380
  import {
384
381
  AI_SETTINGS,
385
382
  APPROVAL_POLICY_SETTING,
386
383
  ASSISTANT_NAME_SETTING,
387
384
  BASE_CURRENCY_SETTING,
388
- CompiledQuery,
389
385
  ID_PREFIXES,
390
386
  ORG_LOGO_SETTING,
391
387
  ORG_NAME_SETTING,
392
388
  ORG_TIMEZONE_SETTING,
389
+ OUTSIDE_RISK_CLASSES,
393
390
  POLICY_PRESETS,
394
391
  PRESET_MATRICES,
392
+ afterCommit,
393
+ allowsAudience,
395
394
  approvalPolicySchema,
395
+ audiencesOf,
396
+ beforeCutoff,
397
+ callerOf,
398
+ defineOperation,
396
399
  evaluateGate,
397
400
  evaluateOutsideGate,
398
401
  findIds,
399
402
  findProvisionalIds,
403
+ isAfterCommit,
404
+ isHostTool,
400
405
  isLoosening,
401
406
  isProvisionalId,
402
407
  isTimezone,
403
408
  loadAiSettings,
404
409
  loadApprovalPolicy,
405
410
  loadGeneralSettings,
411
+ localParts,
412
+ markHostTool,
406
413
  newId,
414
+ operationProblems,
415
+ recordHostChange,
416
+ releaseHoldsStatements,
407
417
  replaceIds,
408
- toProvisionalId
409
- } from "./chunk-TQFGGSA4.js";
418
+ requireWaitlist,
419
+ resolveStateRequest,
420
+ runAfterCommit,
421
+ toProvisionalId,
422
+ waitlistPosition
423
+ } from "./chunk-2XC5JLBO.js";
410
424
  import {
411
425
  CHANNELS,
412
426
  compareVersions,
@@ -437,11 +451,13 @@ import {
437
451
  import {
438
452
  ACTORS,
439
453
  ALL_ACTORS,
454
+ CompiledQuery,
440
455
  ConfigError,
441
456
  ConflictError,
442
457
  FIELD_TYPE_REGISTRY,
443
458
  ForbiddenError,
444
459
  GRANTABLE_PERMISSIONS,
460
+ GUARDIAN_LINK,
445
461
  GateDeniedError,
446
462
  MCP_SCOPES,
447
463
  NeedsOwnApprovalError,
@@ -464,8 +480,10 @@ import {
464
480
  orgReader,
465
481
  originSchema,
466
482
  ownedSource,
483
+ recordsMadeFor,
467
484
  refreshSchemaRegistry,
468
485
  roleHasPermission,
486
+ sharedEmailWarning,
469
487
  sql,
470
488
  staffPrincipal,
471
489
  toOperationError,
@@ -474,7 +492,7 @@ import {
474
492
  visibleObject,
475
493
  visibleSource,
476
494
  visibleTable
477
- } from "./chunk-A4NTSYWV.js";
495
+ } from "./chunk-6XTU2MTP.js";
478
496
  import {
479
497
  activityObject,
480
498
  getObject,
@@ -482,7 +500,7 @@ import {
482
500
  listObjects,
483
501
  personObject,
484
502
  taskObject
485
- } from "./chunk-IFG4FRW5.js";
503
+ } from "./chunk-YFTLIEWU.js";
486
504
  import {
487
505
  ORDER_STATES,
488
506
  SUBSCRIPTION_STATES,
@@ -492,7 +510,7 @@ import {
492
510
  orderLineObject,
493
511
  orderObject,
494
512
  subscriptionObject
495
- } from "./chunk-Q4N55M2Z.js";
513
+ } from "./chunk-7D4GKZOX.js";
496
514
  import {
497
515
  CAPTION_LANGUAGE_RE,
498
516
  EXTENSION_ID_RE,
@@ -516,7 +534,7 @@ import {
516
534
  renamedMessage,
517
535
  renamedView,
518
536
  sniffUpload
519
- } from "./chunk-CP6BXI6F.js";
537
+ } from "./chunk-LO6WGU5Y.js";
520
538
 
521
539
  // ../core/src/approvals/describe.ts
522
540
  var NOUNS = {
@@ -621,6 +639,9 @@ function toolOperation(manifest, name, tool, source = "runtime") {
621
639
  ...audiences ? { audiences } : {},
622
640
  // Only a person (ADR 0512): it narrows who may call, so it holds from any extension.
623
641
  ...tool.humanOnly ? { actors: ["human"] } : {},
642
+ // A person approves anyone else's call (ADR 0552): it only adds review, so it holds from any
643
+ // extension. The gate queues it whatever the policy, preset or floor says (a deny applies).
644
+ ...tool.personApproves ? { alwaysReview: ["assistant", "mcp", "automation", "extension"] } : {},
624
645
  ...packPermission ? { packPermission } : {},
625
646
  ...packPermission && (manifest.grantable ?? []).includes(packPermission) ? { packPermissionGrantable: true } : {},
626
647
  async handler(input, ctx) {
@@ -647,7 +668,15 @@ function toolOperation(manifest, name, tool, source = "runtime") {
647
668
  input,
648
669
  ...tool.risk === "read" ? { readOnly: true } : {},
649
670
  ...cascade ? { cascade } : {},
650
- caller: ctx.principal.kind === "staff" ? { actor: ctx.actor, userId: ctx.user.id, name: ctx.user.name } : {
671
+ caller: ctx.principal.kind === "staff" ? {
672
+ actor: ctx.actor,
673
+ userId: ctx.user.id,
674
+ name: ctx.user.name,
675
+ // A pack role limited to today holds inside the tool too (ADR 0553).
676
+ ...ctx.roleToday ? { roleToday: ctx.roleToday } : {},
677
+ // Who approved it, for a tool a person approves called by another actor.
678
+ ...ctx.approval?.approvedBy ? { approvedBy: ctx.approval.approvedBy } : {}
679
+ } : {
651
680
  actor: ctx.principal.kind,
652
681
  userId: ctx.principal.kind === "customer" ? ctx.principal.customerId : "",
653
682
  principal: ctx.principal
@@ -2515,14 +2544,14 @@ async function overlayRead(operation, input, overlay, real) {
2515
2544
  }
2516
2545
  if (operation === "activity.listForRecord") {
2517
2546
  const recordObject = String(input.object);
2518
- const recordId4 = String(input.recordId);
2519
- const page = isProvisionalId(recordId4) ? { items: [], nextCursor: null } : await real();
2547
+ const recordId5 = String(input.recordId);
2548
+ const page = isProvisionalId(recordId5) ? { items: [], nextCursor: null } : await real();
2520
2549
  const items = patchItems("activity", page.items, overlay);
2521
2550
  if (input.cursor) return { ...page, items };
2522
2551
  const present = new Set(items.map((i) => String(i.id)));
2523
2552
  const types = Array.isArray(input.types) ? input.types : null;
2524
2553
  const added = overlay.records().filter((r) => r.object === "activity" && r.state === "live" && r.record).filter((r) => !present.has(r.id)).filter((r) => !types || types.includes(String(r.record?.type))).filter(
2525
- (r) => arr(r.record?.links).some((l) => l.object === recordObject && l.id === recordId4)
2554
+ (r) => arr(r.record?.links).some((l) => l.object === recordObject && l.id === recordId5)
2526
2555
  ).map((r) => ({ ...r.record, pending: pendingMarker(r) }));
2527
2556
  const merged = [...added, ...items].sort(
2528
2557
  (a, b) => String(b.occurredAt ?? "").localeCompare(String(a.occurredAt ?? ""))
@@ -3037,6 +3066,136 @@ async function checkOutsideRateLimit(binding, principal, operation) {
3037
3066
  if (!result2.ok) refuse2("calls", result2.retryAfterSeconds);
3038
3067
  }
3039
3068
 
3069
+ // ../core/src/pack-role-today.ts
3070
+ var BEFORE_MS = 3 * 864e5;
3071
+ var AFTER_MS = 2 * 864e5;
3072
+ var ident = (name) => `"${name.replaceAll('"', '""')}"`;
3073
+ function planOf(objectName9, limit) {
3074
+ const object = getObject(objectName9);
3075
+ if (!object) return null;
3076
+ const spec = typeof limit === "string" ? { at: limit } : limit;
3077
+ const split = (path) => {
3078
+ const parts = path.split(".");
3079
+ return parts.length === 2 ? { rel: parts[0], field: parts[1] } : null;
3080
+ };
3081
+ const at = split(spec.at);
3082
+ const relation = at?.rel ?? null;
3083
+ let target = object;
3084
+ let relationColumn = null;
3085
+ if (relation) {
3086
+ const rel = object.fields.find((f) => f.name === relation);
3087
+ target = rel?.options?.to ? getObject(rel.options.to) : void 0;
3088
+ relationColumn = rel ? viewColumnOf(rel) : null;
3089
+ if (!target || !relationColumn) return null;
3090
+ } else if (spec.at.includes(".")) {
3091
+ return null;
3092
+ }
3093
+ const columnOf = (path) => {
3094
+ if (path === void 0) return void 0;
3095
+ const p = split(path);
3096
+ if ((p?.rel ?? null) !== relation) return null;
3097
+ const name = p ? p.field : path;
3098
+ const field = target.fields.find((f) => f.name === name);
3099
+ return field ? viewColumnOf(field) : null;
3100
+ };
3101
+ const atColumn = columnOf(spec.at);
3102
+ const untilColumn = columnOf(spec.until);
3103
+ const zoneColumn = columnOf(spec.zone);
3104
+ if (!atColumn || untilColumn === null || zoneColumn === null) return null;
3105
+ return {
3106
+ relation,
3107
+ relationColumn,
3108
+ target,
3109
+ atColumn,
3110
+ untilColumn: untilColumn ?? null,
3111
+ zoneColumn: zoneColumn ?? null
3112
+ };
3113
+ }
3114
+ var dayOf = (at, zone) => {
3115
+ const p = localParts(at, zone);
3116
+ return `${p.year}-${p.month}-${p.day}`;
3117
+ };
3118
+ function onToday(row, plan3, now, orgZone) {
3119
+ const at = row[plan3.atColumn];
3120
+ if (typeof at !== "string" || Number.isNaN(Date.parse(at))) return false;
3121
+ const zoneValue = plan3.zoneColumn ? row[plan3.zoneColumn] : null;
3122
+ const zone = typeof zoneValue === "string" && zoneValue ? zoneValue : orgZone;
3123
+ if (dayOf(at, zone) === dayOf(now, zone)) return true;
3124
+ const until = plan3.untilColumn ? row[plan3.untilColumn] : null;
3125
+ return Date.parse(at) <= now && typeof until === "string" && !Number.isNaN(Date.parse(until)) && Date.parse(until) > now;
3126
+ }
3127
+ async function reachableIds(db, plan3, now) {
3128
+ const orgZone = (await loadGeneralSettings(db)).timezone;
3129
+ const cols = [plan3.atColumn, plan3.untilColumn, plan3.zoneColumn].filter(
3130
+ (c) => c !== null
3131
+ );
3132
+ const at = ident(plan3.atColumn);
3133
+ const { rows } = await db.executeQuery(
3134
+ CompiledQuery.raw(
3135
+ `SELECT id, ${cols.map(ident).join(", ")} FROM ${ident(plan3.target.source)} WHERE ${at} IS NOT NULL AND julianday(${at}) >= julianday(?) AND julianday(${at}) <= julianday(?) LIMIT 2000`,
3136
+ [new Date(now - BEFORE_MS).toISOString(), new Date(now + AFTER_MS).toISOString()]
3137
+ )
3138
+ );
3139
+ return rows.filter((r) => onToday(r, plan3, now, orgZone)).map((r) => String(r.id));
3140
+ }
3141
+ async function reachable(db, objectName9, plan3, id2, now) {
3142
+ const object = getObject(objectName9);
3143
+ if (!object) return false;
3144
+ let targetId = id2;
3145
+ if (plan3.relationColumn) {
3146
+ const { rows: rows2 } = await db.executeQuery(
3147
+ CompiledQuery.raw(
3148
+ `SELECT ${ident(plan3.relationColumn)} AS rel FROM ${ident(object.source)} WHERE id = ?`,
3149
+ [id2]
3150
+ )
3151
+ );
3152
+ const rel = rows2[0]?.rel;
3153
+ if (typeof rel !== "string" || !rel) return false;
3154
+ targetId = rel;
3155
+ }
3156
+ const cols = [plan3.atColumn, plan3.untilColumn, plan3.zoneColumn].filter(
3157
+ (c) => c !== null
3158
+ );
3159
+ const { rows } = await db.executeQuery(
3160
+ CompiledQuery.raw(
3161
+ `SELECT ${cols.map(ident).join(", ")} FROM ${ident(plan3.target.source)} WHERE id = ?`,
3162
+ [targetId]
3163
+ )
3164
+ );
3165
+ const row = rows[0];
3166
+ if (!row) return false;
3167
+ return onToday(row, plan3, now, (await loadGeneralSettings(db)).timezone);
3168
+ }
3169
+ async function holdRoleToday(db, limits, operation, input, now = Date.now()) {
3170
+ if (!limits) return input;
3171
+ const record = input ?? {};
3172
+ const object = record.object;
3173
+ if (typeof object !== "string" || !Object.hasOwn(limits, object)) return input;
3174
+ const plan3 = planOf(object, limits[object]);
3175
+ const refuse3 = () => new ForbiddenError(
3176
+ `${operation} on ${object} is not open to this role: it reaches today's records only`,
3177
+ { rule: "role_today", object, operation }
3178
+ );
3179
+ if (!plan3) throw refuse3();
3180
+ if (operation === "record.list") {
3181
+ const ids = await reachableIds(db, plan3, now);
3182
+ const condition = {
3183
+ field: plan3.relation ?? "id",
3184
+ op: "in",
3185
+ // An empty list matches nothing; a value no record has keeps the predicate valid.
3186
+ value: ids.length ? ids : ["none"]
3187
+ };
3188
+ const filter = record.filter ? { and: [record.filter, condition] } : condition;
3189
+ return { ...record, filter };
3190
+ }
3191
+ if (operation === "record.get" || operation === "record.update") {
3192
+ const id2 = String(record.id ?? "");
3193
+ if (!await reachable(db, object, plan3, id2, now)) throw new NotFoundError(object, id2);
3194
+ return input;
3195
+ }
3196
+ throw refuse3();
3197
+ }
3198
+
3040
3199
  // ../core/src/pack-roles.ts
3041
3200
  var PACK_ROLE_READS = ["record.get", "record.list"];
3042
3201
  var PACK_ROLE_NAME_RE = /^([a-z][a-z0-9]{1,29})\.([a-z][a-zA-Z0-9]{0,39})$/;
@@ -3052,7 +3211,8 @@ function held(name, role) {
3052
3211
  extension,
3053
3212
  label: role?.label ?? name,
3054
3213
  permissions: Object.freeze([...role?.permissions ?? []]),
3055
- read: Object.freeze([...role?.read ?? []])
3214
+ read: Object.freeze([...role?.read ?? []]),
3215
+ ...role?.today ? { today: Object.freeze({ ...role.today }) } : {}
3056
3216
  });
3057
3217
  }
3058
3218
  async function loadStaffRights(db, userId) {
@@ -3139,6 +3299,12 @@ async function touchesPersonApproves(db, operation, input) {
3139
3299
  (name) => Object.hasOwn(settings, name) && settings[name]?.personApproves === true
3140
3300
  );
3141
3301
  }
3302
+ case "person.merge": {
3303
+ const ids = [input.survivorId, input.mergedId].filter(
3304
+ (id2) => typeof id2 === "string"
3305
+ );
3306
+ return hasLiveLink(db, ids);
3307
+ }
3142
3308
  default:
3143
3309
  return false;
3144
3310
  }
@@ -3724,6 +3890,7 @@ async function invokeOnce(op, rawInput, ctx, attempt) {
3724
3890
  parsed.success ? refreshSchemaRegistry(ctx.db.query) : null
3725
3891
  ]);
3726
3892
  const { packRole, grants } = rights;
3893
+ const roleToday = packRole?.today ?? ctx.roleToday;
3727
3894
  if (packRole && !packRoleReaches(packRole, op)) {
3728
3895
  const error = packRoleRefusal(packRole, op);
3729
3896
  const gate2 = evaluateGate(
@@ -3761,8 +3928,15 @@ async function invokeOnce(op, rawInput, ctx, attempt) {
3761
3928
  );
3762
3929
  let decision = gate.decision;
3763
3930
  if (op.bookkeeping && decision === "review") decision = "auto";
3931
+ if (op.hostStep && ctx.origin.surface === "system" && decision === "review") decision = "auto";
3764
3932
  const forced = op.alwaysReview === true || Array.isArray(op.alwaysReview) && op.alwaysReview.includes(ctx.actor) || !ctx.approval && ALWAYS_REVIEWED_PUBLISHERS.includes(ctx.actor) && await touchesPersonApproves(ctx.db.query, op.name, input);
3765
3933
  if (forced && decision === "auto" && !ctx.approval) decision = "review";
3934
+ if (ctx.approval?.approvedBy === ADJUDICATOR_PRINCIPAL && ALWAYS_REVIEWED_PUBLISHERS.includes(ctx.actor) && await touchesPersonApproves(ctx.db.query, op.name, input)) {
3935
+ throw new ConflictError(
3936
+ "This now changes something only a person approves, so it waits for a person.",
3937
+ { rule: "person_approves" }
3938
+ );
3939
+ }
3766
3940
  let reviewSource = forced ? "always" : gate.floorDecision === "review" ? "floor" : gate.policyDecision === "review" ? "policy" : "dependency";
3767
3941
  const provisionalRefs = op.risk === "read" ? [] : findProvisionalIds(rawInput);
3768
3942
  if (decision === "auto" && provisionalRefs.length && !ctx.approval && !ctx.simulate) {
@@ -3839,6 +4013,7 @@ async function invokeOnce(op, rawInput, ctx, attempt) {
3839
4013
  floor: ctx.floor ?? {},
3840
4014
  grantedPermissions: ctx.grantedPermissions,
3841
4015
  permissionGrants: packRole ? [] : grants,
4016
+ ...roleToday ? { roleToday } : {},
3842
4017
  reason: ctx.reason,
3843
4018
  ...ctx.approval ? {
3844
4019
  approval: {
@@ -4106,7 +4281,8 @@ async function invokeOnce(op, rawInput, ctx, attempt) {
4106
4281
  }
4107
4282
  let result2;
4108
4283
  try {
4109
- result2 = await op.handler(input, handlerCtx);
4284
+ const limited = roleToday ? await holdRoleToday(ctx.db.query, roleToday, op.name, input, Date.parse(now)) : input;
4285
+ result2 = await op.handler(limited, handlerCtx);
4110
4286
  } catch (error) {
4111
4287
  if (ctx.simulate && op.risk === "read" && isDryRunRefusal(error)) {
4112
4288
  return notRunRead(error);
@@ -4513,6 +4689,11 @@ function outsideError(error) {
4513
4689
  if (typed.code === "conflict" && (offerRule === "offer_held" || offerRule === "offer_changed")) {
4514
4690
  return typed;
4515
4691
  }
4692
+ if (typed.code === "not_found") return typed;
4693
+ if (typed.code === "conflict" && typed.details?.rule === "state_closed") {
4694
+ return typed;
4695
+ }
4696
+ if (typed.code === "rate_limited") return typed;
4516
4697
  console.error("outside call failed", errorForLog(error));
4517
4698
  if (typed.code === "conflict")
4518
4699
  return new ConflictError("A record with that value already exists");
@@ -4650,7 +4831,7 @@ async function invokeOutside(op, rawInput, ctx) {
4650
4831
  }
4651
4832
  };
4652
4833
  const records = recordAccess(reader, {
4653
- create: (object, values) => createVisible(seam, object, values),
4834
+ create: (object, values, options) => createVisible(seam, object, values, options),
4654
4835
  update: (object, id2, values, options) => updateVisible(seam, object, id2, values, options)
4655
4836
  });
4656
4837
  const signIn = principal.kind === "customer" ? () => loadCustomerSignIn(ctx.db.query, principal.customerId, principal.personId) : void 0;
@@ -4723,7 +4904,9 @@ async function invokeOutside(op, rawInput, ctx) {
4723
4904
  if (isRead && (writes.length || changes.length || activities.length)) {
4724
4905
  throw new OperationError("internal", `${op.name} is a read but queued writes`);
4725
4906
  }
4726
- await assertVisibleWrites(reader, changes, checkedBySeam, madeByHost);
4907
+ await assertVisibleWrites(reader, changes, checkedBySeam, madeByHost, (statement) => {
4908
+ writes.push(statement);
4909
+ });
4727
4910
  } catch (error) {
4728
4911
  return fail(error);
4729
4912
  }
@@ -8562,9 +8745,9 @@ async function planOrganisations(reader, input) {
8562
8745
  };
8563
8746
  return { headers, mapping, suggestions, rows, counts: counts2, queue };
8564
8747
  }
8565
- async function assignImported(ctx, objectName8, records) {
8748
+ async function assignImported(ctx, objectName9, records) {
8566
8749
  const owners = /* @__PURE__ */ new Map();
8567
- const object = getObject(objectName8);
8750
+ const object = getObject(objectName9);
8568
8751
  if (!object || !records.length) return owners;
8569
8752
  for (const record of records) {
8570
8753
  const assignment = await assignOwner(ctx, object, record);
@@ -8859,15 +9042,15 @@ var allowanceViewSchema = external_exports.object({
8859
9042
  ),
8860
9043
  period
8861
9044
  });
8862
- async function readAllowance(ctx, objectName8, id2, at) {
8863
- const object = getObject(objectName8);
9045
+ async function readAllowance(ctx, objectName9, id2, at) {
9046
+ const object = getObject(objectName9);
8864
9047
  const def = object ? holderOf(object) : void 0;
8865
- if (!object || !def) throw new NotFoundError(objectName8, id2);
9048
+ if (!object || !def) throw new NotFoundError(objectName9, id2);
8866
9049
  await ctx.records.get(object.name, id2).catch(() => {
8867
- throw new NotFoundError(objectName8, id2);
9050
+ throw new NotFoundError(objectName9, id2);
8868
9051
  });
8869
9052
  const terms = await storedTerms(ctx, { object: object.name, id: id2 });
8870
- if (!terms) throw new NotFoundError(objectName8, id2);
9053
+ if (!terms) throw new NotFoundError(objectName9, id2);
8871
9054
  const keying = keyingAt(terms, at);
8872
9055
  const current = periodOf(at, keying.per, keying.zone);
8873
9056
  const counted = await ctx.db.selectFrom("core_allowance_period").select(["used", "uses"]).where("object_type", "=", object.name).where("record_id", "=", id2).where("period", "=", current.key).where("zone", "=", keying.zone).executeTakeFirst();
@@ -19014,7 +19197,8 @@ async function grantable(ctx) {
19014
19197
  const labels = {
19015
19198
  "records:publish": "Publish versions of publishable records (programs)",
19016
19199
  "orders:refund": "Refund orders and keep late payments",
19017
- "subscriptions:manage": "End or keep going customers' subscriptions"
19200
+ "subscriptions:manage": "End or keep going customers' subscriptions",
19201
+ "people:link": "Link a parent or guardian to a child, and end the link"
19018
19202
  };
19019
19203
  return [
19020
19204
  ...GRANTABLE_PERMISSIONS.map((permission) => ({
@@ -19614,8 +19798,8 @@ var DAY_MS = 24 * 60 * 60 * 1e3;
19614
19798
  function eraseRequestDueAt(requestedAt, days) {
19615
19799
  return new Date(Date.parse(requestedAt) + days * DAY_MS).toISOString();
19616
19800
  }
19617
- async function openEraseRequest(db, personId) {
19618
- const row = await db.selectFrom("core_erase_request").select(["id", "person_id", "customer_id", "requested_at", "due_at"]).where("person_id", "=", personId).where("status", "=", "open").executeTakeFirst();
19801
+ async function openEraseRequest(db, personId2) {
19802
+ const row = await db.selectFrom("core_erase_request").select(["id", "person_id", "customer_id", "requested_at", "due_at"]).where("person_id", "=", personId2).where("status", "=", "open").executeTakeFirst();
19619
19803
  return row ? {
19620
19804
  id: row.id,
19621
19805
  personId: row.person_id,
@@ -19675,8 +19859,8 @@ var mePersonSchema = external_exports.object({
19675
19859
  });
19676
19860
  var READABLE = personObject.customer?.read ?? [];
19677
19861
  async function myPerson(ctx) {
19678
- const { personId } = customerOf(ctx);
19679
- const record = await ctx.records.get("person", personId);
19862
+ const { personId: personId2 } = customerOf(ctx);
19863
+ const record = await ctx.records.get("person", personId2);
19680
19864
  const values = Object.fromEntries(READABLE.map((name) => [name, record.values[name] ?? null]));
19681
19865
  return mePersonSchema.parse({ ...values, id: record.id });
19682
19866
  }
@@ -19720,11 +19904,11 @@ var meUpdate = defineOperation({
19720
19904
  audiences: ["customer"],
19721
19905
  mcp: { expose: false },
19722
19906
  async handler(input, ctx) {
19723
- const { personId } = customerOf(ctx);
19907
+ const { personId: personId2 } = customerOf(ctx);
19724
19908
  const values = Object.fromEntries(
19725
19909
  Object.entries(input).filter(([, value]) => value !== void 0)
19726
19910
  );
19727
- if (Object.keys(values).length) await ctx.records.update("person", personId, values);
19911
+ if (Object.keys(values).length) await ctx.records.update("person", personId2, values);
19728
19912
  return ctx.afterCommit(() => myPerson(ctx));
19729
19913
  }
19730
19914
  });
@@ -19851,8 +20035,8 @@ var meDeleteAccount = defineOperation({
19851
20035
  hostInternal: true,
19852
20036
  mcp: { expose: false },
19853
20037
  async handler(_input, ctx) {
19854
- const { customerId: customerId2, personId } = customerOf(ctx);
19855
- const account = await ctx.db.selectFrom("core_customer").select("id").where("id", "=", customerId2).where("person_id", "=", personId).executeTakeFirst();
20038
+ const { customerId: customerId2, personId: personId2 } = customerOf(ctx);
20039
+ const account = await ctx.db.selectFrom("core_customer").select("id").where("id", "=", customerId2).where("person_id", "=", personId2).executeTakeFirst();
19856
20040
  if (!account) throw new NotFoundError("customer account", customerId2);
19857
20041
  const sessions = await ctx.db.selectFrom("core_customer_session").select((eb) => eb.fn.countAll().as("n")).where("customer_id", "=", customerId2).executeTakeFirst();
19858
20042
  ctx.write(
@@ -19860,10 +20044,10 @@ var meDeleteAccount = defineOperation({
19860
20044
  ctx.db.deleteFrom("core_customer_session").where("customer_id", "=", customerId2),
19861
20045
  ...endCustomerDeviceSessions(ctx.db, [customerId2])
19862
20046
  );
19863
- let request = await openEraseRequest(ctx.db, personId);
20047
+ let request = await openEraseRequest(ctx.db, personId2);
19864
20048
  if (!request) {
19865
20049
  const created = await createEraseRequestStatements(ctx.db, {
19866
- personId,
20050
+ personId: personId2,
19867
20051
  customerId: customerId2,
19868
20052
  requestedAt: ctx.now,
19869
20053
  dueAt: eraseRequestDueAt(ctx.now, await loadEraseDueDays(ctx.db))
@@ -21507,15 +21691,23 @@ var recordSchema4 = external_exports.object({
21507
21691
  });
21508
21692
  var myCreate = defineOperation({
21509
21693
  name: "my.create",
21510
- description: "From a tool called by a customer: create a record that belongs to that customer. The customer field is set by the host to the caller and cannot be given. Other values must be fields the object lists as writable by its customer, or that the tool lists in customerFields. Returns the record as the customer may see it.",
21511
- input: external_exports.object({ object: objectName5, values: valuesSchema.default({}) }),
21694
+ description: "From a tool called by a customer: create a record that belongs to that customer. The customer field is set by the host to the caller and cannot be given; with forPersonId it is set to that Person instead, only when they are a live dependant of the caller (a child staff linked to them) and the object lets guardians write its records; anyone else is not found. Other values must be fields the object lists as writable by its customer, or that the tool lists in customerFields. Returns the record as the customer may see it.",
21695
+ input: external_exports.object({
21696
+ object: objectName5,
21697
+ values: valuesSchema.default({}),
21698
+ forPersonId: external_exports.string().min(1).max(64).optional().describe(
21699
+ "A dependant of the caller to make it for (ADR 0540); left out, it is the caller's own"
21700
+ )
21701
+ }),
21512
21702
  output: recordSchema4,
21513
21703
  permission: "records:write",
21514
21704
  risk: "write",
21515
21705
  audiences: ["customer"],
21516
21706
  toolOnly: true,
21517
21707
  async handler(input, ctx) {
21518
- const { id: id2 } = await ctx.records.create(input.object, input.values);
21708
+ const { id: id2 } = await ctx.records.create(input.object, input.values, {
21709
+ forPersonId: input.forPersonId
21710
+ });
21519
21711
  return ctx.afterCommit(() => ctx.records.get(input.object, id2));
21520
21712
  }
21521
21713
  });
@@ -22195,11 +22387,11 @@ function fieldValue(object, row, field) {
22195
22387
  const column = definition ? viewColumnOf(definition) : null;
22196
22388
  return column ? row[column] : void 0;
22197
22389
  }
22198
- async function placeOf(db, object, recordId4, tax, position) {
22390
+ async function placeOf(db, object, recordId5, tax, position) {
22199
22391
  const declared = tax.place;
22200
22392
  if (!declared) return void 0;
22201
22393
  let holder = object;
22202
- let row = await readRow(db, object, recordId4);
22394
+ let row = await readRow(db, object, recordId5);
22203
22395
  if (declared.via && row) {
22204
22396
  const target = object.fields.find((f) => f.name === declared.via)?.options?.to;
22205
22397
  const id2 = fieldValue(object, row, declared.via);
@@ -22283,8 +22475,8 @@ var KIND_WORDS2 = {
22283
22475
  part: "Towards the balance: "
22284
22476
  };
22285
22477
  async function openCheckout(ctx, row, input) {
22286
- const origins = await loadReturnOrigins(ctx.db);
22287
- if (!isAllowedReturnUrl(input.returnUrl, origins)) {
22478
+ const origins2 = await loadReturnOrigins(ctx.db);
22479
+ if (!isAllowedReturnUrl(input.returnUrl, origins2)) {
22288
22480
  throw new ValidationError("The return address is not on this deployment's list of sites", {
22289
22481
  field: "returnUrl",
22290
22482
  rule: "return_origin"
@@ -22334,208 +22526,736 @@ async function openCheckout(ctx, row, input) {
22334
22526
  };
22335
22527
  }
22336
22528
 
22337
- // ../core/src/subscriptions/grants.ts
22338
- var GRANTING = /* @__PURE__ */ new Set([
22339
- "trialing",
22340
- "active",
22341
- "past_due",
22342
- "unpaid",
22343
- "paused"
22344
- ]);
22345
- function grantedState(grants, state) {
22346
- if (state === "expired") return grants.states.ended;
22347
- return Object.hasOwn(grants.states, state) ? grants.states[state] : null;
22348
- }
22349
- function grantUntil(row, now) {
22350
- const ends = [];
22351
- if (row.state === "ended" || row.state === "expired") ends.push(row.ended_at ?? now);
22352
- if (row.cancel_at_period_end === 1 && row.current_period_end) ends.push(row.current_period_end);
22353
- if (row.cancel_at) ends.push(row.cancel_at);
22354
- if (row.state === "past_due" && row.failing_since) {
22355
- ends.push(
22356
- new Date(Date.parse(row.failing_since) + PAST_DUE_GRACE_DAYS * 864e5).toISOString()
22357
- );
22358
- }
22359
- return ends.length ? [...ends].sort()[0] : null;
22529
+ // ../core/src/subscriptions/changes.ts
22530
+ var HOUR = 36e5;
22531
+ var DAY2 = 24 * HOUR;
22532
+ var ASKED_LIFE_MS = DAY2;
22533
+ var WAITING_LIFE_MS = 7 * DAY2;
22534
+ var PRORATION_MATCH_MS = 2 * DAY2;
22535
+ var LATE_READ_MS = 3 * DAY2;
22536
+ var MAX_PAUSE_DAYS = 366;
22537
+ var plus = (iso2, ms) => new Date(Date.parse(iso2) + ms).toISOString();
22538
+ function isOpen(change, now) {
22539
+ return (change.state === "requested" || change.state === "waiting") && Date.parse(change.expires_at) > Date.parse(now);
22540
+ }
22541
+ async function openChange(db, subscriptionId2, now) {
22542
+ const row = await db.selectFrom("core_subscription_change").selectAll().where("subscription_id", "=", subscriptionId2).where("state", "in", ["requested", "waiting"]).executeTakeFirst() ?? null;
22543
+ if (!row) return { open: null, stale: null };
22544
+ return isOpen(row, now) ? { open: row, stale: null } : { open: null, stale: row };
22545
+ }
22546
+ function closeStale(ctx, stale) {
22547
+ if (!stale) return;
22548
+ ctx.write(
22549
+ ctx.db.updateTable("core_subscription_change").set({ state: "lapsed", action_url: null, updated_at: ctx.now }).where("id", "=", stale.id).where("state", "=", stale.state)
22550
+ );
22360
22551
  }
22361
- function grantsOf(planObject) {
22362
- const plan3 = getObject(planObject);
22363
- const grants = plan3?.sellable?.recurring?.grants;
22364
- const granted = grants ? getObject(grants.object) : void 0;
22365
- if (!plan3 || !grants || !granted?.states) return null;
22366
- return { plan: plan3, grants, granted };
22552
+ async function lateChange(ctx, row, read, invoice, paid) {
22553
+ const change = await ctx.db.selectFrom("core_subscription_change").selectAll().where("subscription_id", "=", row.id).orderBy("requested_at", "desc").executeTakeFirst() ?? null;
22554
+ if (!change || isOpen(change, ctx.now)) return null;
22555
+ if (!["requested", "waiting", "lapsed"].includes(change.state)) return null;
22556
+ if (change.call_outcome === "refused") return null;
22557
+ if (Date.parse(change.expires_at) + LATE_READ_MS < Date.parse(ctx.now)) return null;
22558
+ const sameTerms = read.currency === row.currency && (read.interval === null || read.interval === row.interval);
22559
+ const shows = change.kind === "pause" ? (
22560
+ // The read carries no resume date: a pause is matched only while its own window is open,
22561
+ // started (or due) and not past the date it resumes on.
22562
+ read.status === "paused" && change.pause_until !== null && Date.parse(ctx.now) < Date.parse(change.pause_until) && Date.parse(read.observedAt) >= Date.parse(change.pause_from ?? change.requested_at)
22563
+ ) : change.kind === "downgrade" ? sameTerms && read.amount === change.to_amount : sameTerms && read.amount === change.to_amount && paid && invoice?.billingReason === "subscription_update" && change.to_amount !== null && invoice.amountPaid > 0 && invoice.amountPaid <= change.to_amount - change.from_amount;
22564
+ if (!shows) return null;
22565
+ const revived = {
22566
+ ...change,
22567
+ state: change.kind === "downgrade" && change.state === "waiting" ? "waiting" : "requested",
22568
+ expires_at: plus(ctx.now, ASKED_LIFE_MS)
22569
+ };
22570
+ ctx.write(
22571
+ ctx.db.updateTable("core_subscription_change").set({ state: revived.state, expires_at: revived.expires_at, updated_at: ctx.now }).where("id", "=", change.id).where("state", "=", change.state)
22572
+ );
22573
+ return revived;
22367
22574
  }
22368
- async function tellStaff(ctx, row, title, body) {
22369
- const plan3 = await notifyStatements(
22370
- ctx.db,
22371
- {
22372
- to: [{ role: "admin" }],
22373
- type: "system.message",
22374
- title,
22375
- body,
22376
- link: { kind: "record", object: "subscription", id: row.id },
22377
- dedupeKey: `subscription.grant:${row.id}:${title}`,
22378
- source: { actor: "system" }
22379
- },
22380
- ctx.now
22575
+ function requestedBy(ctx) {
22576
+ const caller2 = ctx.principal;
22577
+ return caller2.kind === "customer" ? `customer:${caller2.customerId}` : caller2.kind === "staff" ? `staff:${caller2.userId}` : "public";
22578
+ }
22579
+ async function claimChangeSlot(ctx, row) {
22580
+ const { open, stale } = await openChange(ctx.db, row.id, ctx.now);
22581
+ closeStale(ctx, stale);
22582
+ if (!open) return;
22583
+ throw new ConflictError(
22584
+ open.kind === "pause" ? "A pause is already asked for on this subscription: end or withdraw it first" : open.state === "waiting" ? `This subscription already changes to ${open.to_plan_title} when its period ends, on ${open.effective_at?.slice(0, 10)}` : `A change to ${open.to_plan_title} is waiting for the payment provider`,
22585
+ { subscription: row.id, change: open.id, rule: "change_open" }
22381
22586
  );
22382
- ctx.write(...plan3.statements);
22383
22587
  }
22384
- async function followSubscriptionGrant(ctx, row) {
22385
- const declared = grantsOf(row.plan_object);
22386
- if (!declared) return;
22387
- const { plan: plan3, grants, granted } = declared;
22388
- const states = granted.states;
22389
- if (!states) return;
22390
- const existing = await ctx.db.selectFrom("core_subscription_grant").select(["object_type", "record_id"]).where("subscription_id", "=", row.id).executeTakeFirst();
22391
- const state = grantedState(grants, row.state);
22392
- const until = grantUntil(row, ctx.now);
22393
- if (!existing) {
22394
- if (!GRANTING.has(row.state) || !state) return;
22395
- if (!row.holder_person_id) {
22396
- await tellStaff(
22397
- ctx,
22398
- row,
22399
- "A subscription has no one to hold what it gives",
22400
- `Subscription ${row.id} (${row.plan_title}) is running, and its holder is not known, so nothing was granted. Set its person, then it is granted with the next event.`
22401
- );
22402
- return;
22403
- }
22404
- const sources = Object.values(grants.set);
22405
- const planRow = sources.some((s) => s.startsWith("item.")) ? await readGrantItem(ctx, plan3, row.plan_id) : void 0;
22406
- const from = (source) => {
22407
- if (source === "item") return row.plan_id;
22408
- if (source.startsWith("item.")) return grantFieldValue(plan3, planRow, source.slice(5));
22409
- if (source === "subscription") return row.id;
22410
- if (source === "subscription.holder") return row.holder_person_id;
22411
- if (source === "subscription.payer") return row.payer_person_id;
22412
- return null;
22413
- };
22414
- const values = {
22415
- ...Object.fromEntries(Object.entries(grants.set).map(([field, s]) => [field, from(s)])),
22416
- [states.field]: state
22417
- };
22418
- if (grants.from) values[grants.from] = row.current_period_start ?? ctx.now;
22419
- if (grants.until && until) values[grants.until] = until;
22420
- const id2 = await createRecord(ctx, granted, values, { by: "host", checkReferences: false });
22421
- ctx.write(
22422
- ctx.db.insertInto("core_subscription_grant").values({
22423
- subscription_id: row.id,
22424
- object_type: granted.name,
22425
- record_id: id2,
22426
- created_at: ctx.now
22427
- })
22588
+ async function requireActive(ctx, row, what) {
22589
+ if (row.state !== "active") {
22590
+ throw new ConflictError(`A subscription that is ${row.state} cannot be ${what}`, {
22591
+ subscription: row.id,
22592
+ state: row.state,
22593
+ rule: "state"
22594
+ });
22595
+ }
22596
+ if (row.cancel_at_period_end === 1 || row.cancel_at !== null) {
22597
+ throw new ConflictError(
22598
+ `This subscription is set to end: keep it going first, then it can be ${what}`,
22599
+ { subscription: row.id, rule: "ending" }
22428
22600
  );
22429
- return;
22430
22601
  }
22431
- const object = getObject(existing.object_type);
22432
- const stateField = object?.states ? object.fields.find((f) => f.name === object.states?.field) : void 0;
22433
- const stateColumn = stateField ? viewColumnOf(stateField) : null;
22434
- if (!object?.states || !stateColumn) return;
22435
- const untilField = grants.until ? object.fields.find((f) => f.name === grants.until) : void 0;
22436
- const untilColumn = untilField ? viewColumnOf(untilField) : null;
22437
- const current = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).selectAll().where("id", "=", existing.record_id).executeTakeFirst();
22438
- if (!current) return;
22439
- const finals = new Set(object.states.moves.filter((m) => m.final).map((m) => m.to));
22440
- const now = current[stateColumn];
22441
- if (typeof now === "string" && finals.has(now)) return;
22442
- const change = {};
22443
- if (state && now !== state) change[object.states.field] = state;
22444
- if (grants.until && untilColumn) {
22445
- const stored = current[untilColumn];
22446
- const storedAt = typeof stored === "string" && stored ? Date.parse(stored) : null;
22447
- const untilAt = until ? Date.parse(until) : null;
22448
- if (storedAt !== untilAt) change[grants.until] = until;
22602
+ if (row.amount <= 0) {
22603
+ throw new ValidationError(`A subscription with nothing to pay cannot be ${what}`, {
22604
+ rule: "total"
22605
+ });
22449
22606
  }
22450
- if (!Object.keys(change).length) return;
22451
- await updateRecord(ctx, object, existing.record_id, change, { by: "host" });
22452
- }
22453
- var periodRefunded = async (ctx, move) => {
22454
- if (move.to.id !== "refunded") return;
22455
- const order = await loadOrderRow(ctx.db, move.id);
22456
- if (!order.subscription_id) return;
22457
- const sub = await loadSubscriptionRow(ctx.db, order.subscription_id).catch(() => null);
22458
- if (!sub || !grantsOf(sub.plan_object) || sub.state === "ended" || sub.state === "expired") {
22459
- return;
22607
+ if (row.current_period_end && row.current_period_end > ctx.now) return row;
22608
+ const fresh = await readFromProvider(ctx, row);
22609
+ if (fresh && fresh.status === "active" && fresh.amount === row.amount && fresh.currency === row.currency && !fresh.cancelAtPeriodEnd && fresh.cancelAt === null && fresh.currentPeriodEnd !== null && fresh.currentPeriodEnd > ctx.now) {
22610
+ return {
22611
+ ...row,
22612
+ current_period_start: fresh.currentPeriodStart,
22613
+ current_period_end: fresh.currentPeriodEnd
22614
+ };
22460
22615
  }
22461
- await tellStaff(
22462
- ctx,
22463
- sub,
22464
- "A refunded period's membership keeps running",
22465
- `Order ${move.id}, a paid period of subscription ${sub.id} (${sub.plan_title}), was refunded in full. The subscription, and what it grants, keep running: end the subscription if they should not.`
22616
+ throw new ConflictError(
22617
+ "This subscription's period has ended and the payment provider does not show it renewed as agreed yet: try again once it has",
22618
+ { subscription: row.id, rule: "period_ended" }
22466
22619
  );
22467
- };
22468
- onRecordMove("order", periodRefunded);
22469
-
22470
- // ../core/src/orders/guests.ts
22471
- var hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
22472
- function newOrderToken() {
22473
- return hex(crypto.getRandomValues(new Uint8Array(32)).buffer);
22474
- }
22475
- var ORDER_TOKEN = /^[0-9a-f]{64}$/;
22476
- async function hashOrderToken(token) {
22477
- return hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)));
22478
- }
22479
- async function orderForToken(db, id2, token, now) {
22480
- if (!ORDER_TOKEN.test(token)) return null;
22481
- const hash = await hashOrderToken(token);
22482
- const row = await db.selectFrom("core_order").selectAll().where((eb) => eb.or([eb("access_hash", "=", hash), eb("email_link_hash", "=", hash)])).executeTakeFirst();
22483
- if (!row || row.id !== id2) return null;
22484
- if (row.access_until !== null && row.access_until <= now) return null;
22485
- return row;
22486
22620
  }
22487
- async function resolveBuyer(ctx, address2) {
22488
- const email = normaliseCustomerEmail(address2);
22489
- const refused = () => new ValidationError("That email address cannot be used", { field: "email" });
22490
- if (!email) throw refused();
22491
- if ((await erasedAddresses(ctx.db, [email])).size > 0) throw refused();
22492
- const matches = await sameEmailPeople(ctx.db, email);
22493
- if (matches.length === 1) return { email, personId: matches[0], created: false };
22494
- if (matches.length > 1) {
22495
- const plan3 = await notifyStatements(
22496
- ctx.db,
22497
- {
22498
- to: [{ role: "admin" }],
22499
- type: "system.message",
22500
- title: "An order was placed with an address several people have",
22501
- body: `${matches.length} people have ${email}. The order belongs to none of them yet: merge them, then set the order's person.`,
22502
- link: { kind: "record", object: "person", id: matches[0] },
22503
- dedupeKey: `order.several_people:${email}`,
22504
- source: { actor: "system" }
22505
- },
22506
- ctx.now
22621
+ async function readFromProvider(ctx, row) {
22622
+ try {
22623
+ const target = await paymentsTarget(ctx.db);
22624
+ if (target.provider !== row.provider) return null;
22625
+ const result2 = await callSubscriptionGatekeeper(
22626
+ ctx.integrations,
22627
+ target,
22628
+ "getSubscription",
22629
+ row.provider_ref
22507
22630
  );
22508
- ctx.write(...plan3.statements);
22509
- return { email, personId: null, created: false };
22510
- }
22511
- const creator = await creatorFor(ctx.db, email);
22512
- if (!creator) throw new ConfigError("There is no admin to create the buyer's Person for");
22513
- const { personCreate: personCreate2 } = await import("./person-WIQQ7ITU.js");
22514
- const asCreator = Object.create(ctx, {
22515
- user: { value: creator },
22516
- actor: { value: "automation" },
22517
- principal: { value: staffPrincipal(creator) },
22518
- // The Person is the host's to create for the order: not the guest's write.
22519
- recordChange: { value: (change) => recordHostChange(ctx, change) }
22520
- });
22521
- const input = personCreate2.input.parse({ emails: [{ email, primary: true }] });
22522
- const person = await personCreate2.handler(input, asCreator);
22523
- return { email, personId: person.id, created: true };
22524
- }
22525
-
22526
- // ../core/src/subscriptions/periods.ts
22527
- function periodFlag(terms, invoice, termsChanged) {
22528
- if (termsChanged || invoice.currency !== terms.currency) return "not_as_agreed";
22529
- if (invoice.amountPaid < terms.amount) return "paid_less";
22530
- if (invoice.amountPaid > terms.amount) return "paid_more";
22531
- return null;
22631
+ const read = result2.value;
22632
+ return read && read.ref === row.provider_ref ? read : null;
22633
+ } catch {
22634
+ return null;
22635
+ }
22532
22636
  }
22533
- var FLAG_WORDS = {
22534
- paid_less: "less than its price (a coupon or the payer's balance at the provider, say)",
22535
- paid_more: "more than its price",
22637
+ async function requestPlanChange(ctx, row, input) {
22638
+ row = await requireActive(ctx, row, "changed");
22639
+ if (input.planId === row.plan_id) {
22640
+ throw new ValidationError("This is the plan the subscription is on", {
22641
+ field: "planId",
22642
+ rule: "same_plan"
22643
+ });
22644
+ }
22645
+ const [plan3] = await priceLines(
22646
+ ctx.db,
22647
+ [{ object: row.plan_object, id: input.planId, quantity: 1 }],
22648
+ row.currency,
22649
+ ctx.now,
22650
+ callerOf(ctx),
22651
+ { plans: true }
22652
+ );
22653
+ if (!plan3?.recurring) throw new ValidationError("This is not a plan", { rule: "not_for_sale" });
22654
+ if (plan3.recurring.interval !== row.interval || plan3.unitPrice <= 0) {
22655
+ throw new ValidationError(
22656
+ `A subscription changes only to a plan paid every ${row.interval}, with a price`,
22657
+ { field: "planId", rule: "interval" }
22658
+ );
22659
+ }
22660
+ await claimChangeSlot(ctx, row);
22661
+ const kind = plan3.unitPrice > row.amount ? "upgrade" : "downgrade";
22662
+ const id2 = newId("subscriptionChange");
22663
+ const samePrice = plan3.unitPrice === row.amount;
22664
+ const periodEnd = row.current_period_end;
22665
+ const effectiveAt = kind === "downgrade" ? periodEnd : null;
22666
+ ctx.write(
22667
+ ctx.db.insertInto("core_subscription_change").values({
22668
+ id: id2,
22669
+ subscription_id: row.id,
22670
+ kind,
22671
+ state: samePrice ? "waiting" : "requested",
22672
+ from_plan_id: row.plan_id,
22673
+ from_plan_title: row.plan_title,
22674
+ from_amount: row.amount,
22675
+ to_plan_id: plan3.recordId,
22676
+ to_plan_title: plan3.title,
22677
+ to_amount: plan3.unitPrice,
22678
+ pause_from: null,
22679
+ pause_until: null,
22680
+ effective_at: effectiveAt,
22681
+ expires_at: samePrice ? plus(periodEnd, WAITING_LIFE_MS) : plus(ctx.now, ASKED_LIFE_MS),
22682
+ call_outcome: null,
22683
+ call_error: null,
22684
+ action_url: null,
22685
+ end_outcome: null,
22686
+ end_error: null,
22687
+ end_at: null,
22688
+ reason: input.reason,
22689
+ requested_by: requestedBy(ctx),
22690
+ requested_at: ctx.now,
22691
+ applied_at: null,
22692
+ updated_at: ctx.now
22693
+ })
22694
+ );
22695
+ const out2 = (asked) => ({
22696
+ id: row.id,
22697
+ changeId: id2,
22698
+ kind,
22699
+ effectiveAt,
22700
+ amount: plan3.unitPrice,
22701
+ currency: row.currency,
22702
+ asked,
22703
+ requested: true
22704
+ });
22705
+ if (samePrice) return afterCommit(async () => out2("not_needed"));
22706
+ return afterCommit(async () => {
22707
+ const asked = await askProvider(ctx, row, id2, "call", "changeSubscription", {
22708
+ subscriptionId: row.id,
22709
+ subscriptionRef: row.provider_ref,
22710
+ changeId: id2,
22711
+ amount: plan3.unitPrice,
22712
+ currency: row.currency,
22713
+ interval: row.interval,
22714
+ description: plan3.title.slice(0, 200) || plan3.recordId,
22715
+ when: kind === "upgrade" ? "now" : "next_period",
22716
+ taxed: row.tax_code !== null,
22717
+ reason: input.reason
22718
+ });
22719
+ return out2(asked);
22720
+ });
22721
+ }
22722
+ async function withdrawPlanChange(ctx, row, reason2) {
22723
+ if (ctx.principal.kind !== "staff") {
22724
+ throw new ValidationError("Only staff withdraw a plan change", { rule: "staff" });
22725
+ }
22726
+ const { open, stale } = await openChange(ctx.db, row.id, ctx.now);
22727
+ const change = open ?? stale;
22728
+ if (!change) {
22729
+ throw new ConflictError("No plan change is waiting on this subscription", {
22730
+ subscription: row.id,
22731
+ rule: "no_change"
22732
+ });
22733
+ }
22734
+ if (change.kind === "pause") {
22735
+ throw new ConflictError("This is a pause: end or withdraw it with subscription.unpause", {
22736
+ subscription: row.id,
22737
+ change: change.id,
22738
+ rule: "pause"
22739
+ });
22740
+ }
22741
+ const asked = change.call_outcome !== "refused";
22742
+ const putBack = change.kind === "downgrade" && change.to_amount !== change.from_amount && (change.state === "waiting" || asked);
22743
+ const voidIt = change.kind === "upgrade" && change.state === "requested" && asked && open !== null;
22744
+ if (!putBack && !voidIt) {
22745
+ ctx.write(
22746
+ ctx.db.updateTable("core_subscription_change").set({ state: "withdrawn", action_url: null, updated_at: ctx.now }).where("id", "=", change.id).where("state", "=", change.state)
22747
+ );
22748
+ return afterCommit(async () => ({
22749
+ id: row.id,
22750
+ changeId: change.id,
22751
+ asked: "not_needed"
22752
+ }));
22753
+ }
22754
+ return afterCommit(async () => {
22755
+ const outcome2 = putBack ? await askProvider(ctx, row, change.id, "end", "changeSubscription", {
22756
+ subscriptionId: row.id,
22757
+ subscriptionRef: row.provider_ref,
22758
+ // A fresh id each attempt (round three): a retry follows a fresh read at the gatekeeper,
22759
+ // never the cached answer of a failed one.
22760
+ changeId: `${change.id}_b${Date.now().toString(36)}`,
22761
+ amount: change.from_amount,
22762
+ currency: row.currency,
22763
+ interval: row.interval,
22764
+ description: change.from_plan_title.slice(0, 200) || change.from_plan_id,
22765
+ when: "next_period",
22766
+ taxed: row.tax_code !== null,
22767
+ reason: reason2
22768
+ }) : await askProvider(ctx, row, change.id, "end", "voidPendingUpdate", {
22769
+ subscriptionId: row.id,
22770
+ subscriptionRef: row.provider_ref,
22771
+ changeId: change.id,
22772
+ reason: reason2
22773
+ });
22774
+ if (outcome2 === "sent") {
22775
+ await recordOutcome(ctx, change.id, "withdraw", { state: "withdrawn", action_url: null }, [
22776
+ "requested",
22777
+ "waiting"
22778
+ ]);
22779
+ }
22780
+ return { id: row.id, changeId: change.id, asked: outcome2 };
22781
+ });
22782
+ }
22783
+ async function pauseBounds(ctx, row) {
22784
+ const object = getObject(row.plan_object);
22785
+ const declared = object?.sellable?.recurring?.pause;
22786
+ if (!object || !declared) return null;
22787
+ const planRow = await readGrantItem(ctx, object, row.plan_id);
22788
+ const days = (field, fallback) => {
22789
+ const value = field ? grantFieldValue(object, planRow, field) : null;
22790
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
22791
+ };
22792
+ const min = days(declared.minDays, 1);
22793
+ return {
22794
+ min,
22795
+ max: Math.max(min, Math.min(MAX_PAUSE_DAYS, days(declared.maxDays, MAX_PAUSE_DAYS)))
22796
+ };
22797
+ }
22798
+ function moment(value, field) {
22799
+ const at = Date.parse(value);
22800
+ if (Number.isNaN(at)) throw new ValidationError(`${field} must be a moment`, { field });
22801
+ return new Date(at).toISOString();
22802
+ }
22803
+ async function requestPause(ctx, row, input) {
22804
+ if (ctx.principal.kind !== "staff") {
22805
+ throw new ValidationError("Only staff pause a subscription", { rule: "staff" });
22806
+ }
22807
+ const bounds = await pauseBounds(ctx, row);
22808
+ if (!bounds) {
22809
+ throw new ValidationError("Subscriptions to this plan are not paused", { rule: "no_pause" });
22810
+ }
22811
+ row = await requireActive(ctx, row, "paused");
22812
+ const from = input.from ? moment(input.from, "from") : null;
22813
+ if (from !== null && from <= ctx.now) {
22814
+ throw new ValidationError("A pause starts now or later", { field: "from", rule: "past" });
22815
+ }
22816
+ const until = moment(input.until, "until");
22817
+ const days = (Date.parse(until) - Date.parse(from ?? ctx.now)) / DAY2;
22818
+ if (days < bounds.min || days > bounds.max) {
22819
+ throw new ValidationError(
22820
+ `A pause of this plan is from ${bounds.min} to ${bounds.max} days; this is ${Math.round(days * 10) / 10}`,
22821
+ { field: "until", rule: "pause_length", min: bounds.min, max: bounds.max }
22822
+ );
22823
+ }
22824
+ await claimChangeSlot(ctx, row);
22825
+ const id2 = newId("subscriptionChange");
22826
+ ctx.write(
22827
+ ctx.db.insertInto("core_subscription_change").values({
22828
+ id: id2,
22829
+ subscription_id: row.id,
22830
+ kind: "pause",
22831
+ state: "requested",
22832
+ from_plan_id: row.plan_id,
22833
+ from_plan_title: row.plan_title,
22834
+ from_amount: row.amount,
22835
+ to_plan_id: null,
22836
+ to_plan_title: null,
22837
+ to_amount: null,
22838
+ pause_from: from,
22839
+ pause_until: until,
22840
+ effective_at: from ?? ctx.now,
22841
+ // A day after it was due to start, never shown paused: lapsed.
22842
+ expires_at: plus(from ?? ctx.now, ASKED_LIFE_MS),
22843
+ call_outcome: null,
22844
+ call_error: null,
22845
+ action_url: null,
22846
+ end_outcome: null,
22847
+ end_error: null,
22848
+ end_at: null,
22849
+ reason: input.reason,
22850
+ requested_by: requestedBy(ctx),
22851
+ requested_at: ctx.now,
22852
+ applied_at: null,
22853
+ updated_at: ctx.now
22854
+ })
22855
+ );
22856
+ return afterCommit(async () => {
22857
+ const asked = await askProvider(ctx, row, id2, "call", "pauseSubscription", {
22858
+ subscriptionId: row.id,
22859
+ subscriptionRef: row.provider_ref,
22860
+ pauseId: id2,
22861
+ from,
22862
+ until,
22863
+ reason: input.reason
22864
+ });
22865
+ return {
22866
+ id: row.id,
22867
+ changeId: id2,
22868
+ from,
22869
+ until,
22870
+ asked,
22871
+ requested: true
22872
+ };
22873
+ });
22874
+ }
22875
+ async function requestUnpause(ctx, row, reason2) {
22876
+ if (ctx.principal.kind !== "staff") {
22877
+ throw new ValidationError("Only staff end a pause", { rule: "staff" });
22878
+ }
22879
+ const { open, stale } = await openChange(ctx.db, row.id, ctx.now);
22880
+ const asked = open ?? stale;
22881
+ const scheduled = asked?.kind === "pause" ? asked : null;
22882
+ if (row.state !== "paused" && !scheduled) {
22883
+ throw new ConflictError("This subscription is not paused, and no pause is asked for", {
22884
+ subscription: row.id,
22885
+ state: row.state
22886
+ });
22887
+ }
22888
+ const pause = row.state === "paused" ? await ctx.db.selectFrom("core_subscription_change").selectAll().where("subscription_id", "=", row.id).where("kind", "=", "pause").where("state", "in", ["applied", "requested"]).orderBy("requested_at", "desc").executeTakeFirst() ?? null : scheduled;
22889
+ if (!pause) {
22890
+ throw new ConflictError(
22891
+ "This subscription was paused at the payment provider, not by the host: resume it there",
22892
+ { subscription: row.id, rule: "provider_pause" }
22893
+ );
22894
+ }
22895
+ const withdrawing = row.state !== "paused";
22896
+ return afterCommit(async () => {
22897
+ const outcome2 = await askProvider(ctx, row, pause.id, "end", "unpauseSubscription", {
22898
+ subscriptionId: row.id,
22899
+ subscriptionRef: row.provider_ref,
22900
+ pauseId: pause.id,
22901
+ reason: reason2
22902
+ });
22903
+ if (withdrawing && outcome2 === "sent") {
22904
+ await recordOutcome(ctx, pause.id, "withdraw", { state: "withdrawn" }, ["requested"]);
22905
+ }
22906
+ return {
22907
+ id: row.id,
22908
+ asked: outcome2,
22909
+ requested: true
22910
+ };
22911
+ });
22912
+ }
22913
+ function outcomeOf2(result2) {
22914
+ if (result2.applied.length) return { outcome: "sent", error: null };
22915
+ if (result2.pending.length) return { outcome: "pending", error: null };
22916
+ const failed = result2.failed?.[0];
22917
+ if (failed && (failed.outcome === "refused" || failed.outcome === "retryable")) {
22918
+ return { outcome: "refused", error: failed.message.slice(0, 500) };
22919
+ }
22920
+ return {
22921
+ outcome: "unknown",
22922
+ error: failed ? failed.message.slice(0, 500) : "The payment provider's answer did not say whether it changed"
22923
+ };
22924
+ }
22925
+ async function recordOutcome(ctx, changeId, what, values, fromStates) {
22926
+ const at = (/* @__PURE__ */ new Date()).toISOString();
22927
+ const updated = await ctx.db.updateTable("core_subscription_change").set({ ...values, updated_at: at }).where("id", "=", changeId).where("state", "in", fromStates).executeTakeFirst();
22928
+ const written = Number(updated.numUpdatedRows ?? 0) > 0;
22929
+ await ctx.db.insertInto("core_audit").values({
22930
+ id: newId("audit"),
22931
+ at,
22932
+ operation: "subscription.change.outcome",
22933
+ risk: "write",
22934
+ // The host's own record of what the provider answered, not a caller's act.
22935
+ actor: "automation",
22936
+ user_id: null,
22937
+ origin: JSON.stringify({ surface: "system", automationId: "subscription.change.outcome" }),
22938
+ input: JSON.stringify({ changeId, what, by: ctx.operation ?? null }),
22939
+ result: JSON.stringify(
22940
+ written ? { written: true, values } : { written: false, values, why: "the change had moved on: nothing was written" }
22941
+ ),
22942
+ gate_decision: "auto",
22943
+ outcome: "ok",
22944
+ error: null
22945
+ }).execute();
22946
+ return written;
22947
+ }
22948
+ async function askProvider(ctx, row, changeId, which, method, request) {
22949
+ const at = (/* @__PURE__ */ new Date()).toISOString();
22950
+ const record = (outcome3, error2) => which === "call" ? recordOutcome(
22951
+ ctx,
22952
+ changeId,
22953
+ "call",
22954
+ {
22955
+ call_outcome: outcome3,
22956
+ call_error: error2,
22957
+ ...outcome3 === "refused" ? { state: "lapsed" } : {}
22958
+ },
22959
+ ["requested", "waiting"]
22960
+ ) : recordOutcome(
22961
+ ctx,
22962
+ changeId,
22963
+ "end",
22964
+ { end_outcome: outcome3, end_error: error2, end_at: at },
22965
+ ["requested", "waiting", "applied"]
22966
+ );
22967
+ const target = await paymentsTarget(ctx.db);
22968
+ if (target.provider !== row.provider) {
22969
+ const message = `This subscription is with ${row.provider}, and payments now use ${target.provider}`;
22970
+ await record("refused", message);
22971
+ throw new ConflictError(message, { rule: "provider" });
22972
+ }
22973
+ let result2;
22974
+ try {
22975
+ result2 = await callSubscriptionGatekeeper(ctx.integrations, target, method, request);
22976
+ } catch (error2) {
22977
+ await record("unknown", error2 instanceof Error ? error2.message.slice(0, 500) : String(error2));
22978
+ return "unknown";
22979
+ }
22980
+ const { outcome: outcome2, error } = outcomeOf2(result2);
22981
+ await record(outcome2, error);
22982
+ if (outcome2 === "refused") {
22983
+ throw new ConflictError(`The payment provider refused it, so nothing changed: ${error}`, {
22984
+ subscription: row.id,
22985
+ change: changeId,
22986
+ rule: "provider_refused"
22987
+ });
22988
+ }
22989
+ return outcome2;
22990
+ }
22991
+ function alsoAgreed(open) {
22992
+ return open && open.kind !== "pause" ? open.to_amount : null;
22993
+ }
22994
+ function followChange(ctx, row, read, change) {
22995
+ if (!change || !isOpen(change, ctx.now)) return { row, planChanged: false };
22996
+ const set = (values) => ctx.write(
22997
+ ctx.db.updateTable("core_subscription_change").set({ ...values, updated_at: ctx.now }).where("id", "=", change.id).where("state", "=", change.state)
22998
+ );
22999
+ if (change.kind === "pause") {
23000
+ if (change.state === "requested" && read.status === "paused") {
23001
+ set({ state: "applied", applied_at: ctx.now });
23002
+ }
23003
+ return { row, planChanged: false };
23004
+ }
23005
+ const sameTerms = read.currency === row.currency && (read.interval === null || read.interval === row.interval);
23006
+ const shown = sameTerms && read.amount === change.to_amount;
23007
+ const toPlan = () => ({
23008
+ ...row,
23009
+ plan_id: change.to_plan_id ?? row.plan_id,
23010
+ plan_title: change.to_plan_title ?? row.plan_title,
23011
+ amount: change.to_amount ?? row.amount
23012
+ });
23013
+ if (change.kind === "upgrade") {
23014
+ if (change.state !== "requested" || !shown) return { row, planChanged: false };
23015
+ set({ state: "applied", applied_at: ctx.now, effective_at: ctx.now, action_url: null });
23016
+ postChange(ctx, row, change);
23017
+ return { row: toPlan(), planChanged: true };
23018
+ }
23019
+ const samePrice = change.to_amount === row.amount;
23020
+ if (change.state === "waiting" && !samePrice && sameTerms && read.amount === row.amount) {
23021
+ set({ state: "withdrawn" });
23022
+ return { row, planChanged: false };
23023
+ }
23024
+ if (change.state === "requested") {
23025
+ if (!shown) return { row, planChanged: false };
23026
+ const billedNew = read.currentPeriodStart !== null && Date.parse(read.currentPeriodStart) > Date.parse(change.requested_at);
23027
+ const effective2 = billedNew ? read.currentPeriodStart ?? ctx.now : read.currentPeriodEnd ?? change.effective_at ?? ctx.now;
23028
+ if (billedNew) {
23029
+ set({ state: "applied", applied_at: ctx.now, effective_at: effective2 });
23030
+ postChange(ctx, row, change);
23031
+ return { row: toPlan(), planChanged: true };
23032
+ }
23033
+ set({
23034
+ state: "waiting",
23035
+ effective_at: effective2,
23036
+ expires_at: plus(effective2, WAITING_LIFE_MS)
23037
+ });
23038
+ return { row, planChanged: false };
23039
+ }
23040
+ const effective = change.effective_at ?? ctx.now;
23041
+ const nextPeriod = read.currentPeriodStart !== null && Date.parse(read.currentPeriodStart) >= Date.parse(effective);
23042
+ if (!nextPeriod) return { row, planChanged: false };
23043
+ if (!shown && !samePrice) return { row, planChanged: false };
23044
+ set({ state: "applied", applied_at: ctx.now });
23045
+ postChange(ctx, row, change);
23046
+ return { row: toPlan(), planChanged: true };
23047
+ }
23048
+ function upgradeNeedsAction(ctx, change, invoice) {
23049
+ if (!change || change.kind !== "upgrade" || change.state !== "requested" || invoice.status !== "open" || invoice.billingReason !== "subscription_update" || !invoice.hostedUrl) {
23050
+ return false;
23051
+ }
23052
+ ctx.write(
23053
+ ctx.db.updateTable("core_subscription_change").set({ action_url: invoice.hostedUrl, updated_at: ctx.now }).where("id", "=", change.id).where("state", "=", "requested")
23054
+ );
23055
+ return true;
23056
+ }
23057
+ function postChange(ctx, row, change) {
23058
+ if (!row.payer_person_id) return;
23059
+ ctx.postActivity({
23060
+ subject: `Plan changed: ${change.from_plan_title} to ${change.to_plan_title}`,
23061
+ payload: {
23062
+ kind: "subscription.plan_changed",
23063
+ subscriptionId: row.id,
23064
+ changeId: change.id,
23065
+ from: change.from_plan_id,
23066
+ to: change.to_plan_id,
23067
+ amount: change.to_amount,
23068
+ currency: row.currency
23069
+ },
23070
+ links: [{ object: "person", id: row.payer_person_id }]
23071
+ });
23072
+ }
23073
+ async function expectedPart(db, row, invoice, now, known = null) {
23074
+ if (invoice.currency !== row.currency || invoice.amountPaid <= 0) return null;
23075
+ const stored = await db.selectFrom("core_subscription_change").selectAll().where("subscription_id", "=", row.id).where("state", "in", ["requested", "applied", "lapsed"]).orderBy("requested_at", "desc").limit(5).execute();
23076
+ const changes = stored.map((c) => known && c.id === known.id ? known : c);
23077
+ for (const change of changes) {
23078
+ if (change.kind === "upgrade" && change.to_amount !== null && invoice.billingReason === "subscription_update") {
23079
+ const live = change.state === "requested" ? isOpen(change, now) : change.applied_at !== null && Date.parse(change.applied_at) + PRORATION_MATCH_MS > Date.parse(now);
23080
+ if (live && invoice.amountPaid <= change.to_amount - change.from_amount) {
23081
+ return {
23082
+ title: `${change.to_plan_title}: the rest of the period (upgrade from ${change.from_plan_title})`,
23083
+ planId: change.to_plan_id ?? row.plan_id
23084
+ };
23085
+ }
23086
+ }
23087
+ if (change.kind === "pause" && change.state === "applied" && change.applied_at) {
23088
+ const after = invoice.periodStart && invoice.periodStart >= change.applied_at;
23089
+ const first = await db.selectFrom("core_order").select("id").where("subscription_id", "=", row.id).where("period_start", ">=", change.applied_at).executeTakeFirst();
23090
+ if (after && !first && invoice.amountPaid <= row.amount) {
23091
+ return {
23092
+ title: `${row.plan_title} (after a pause: the paused time credited)`,
23093
+ planId: row.plan_id
23094
+ };
23095
+ }
23096
+ }
23097
+ }
23098
+ return null;
23099
+ }
23100
+ function declinedUpgradeWords(change, amountDue, currency2) {
23101
+ return `The charge of ${formatMoney(amountDue, currency2)} for the upgrade to ${change.to_plan_title} failed. The subscription stays on ${change.from_plan_title} and keeps running; the upgrade applies only if the payer pays it (the provider keeps it for up to 23 hours).`;
23102
+ }
23103
+
23104
+ // ../core/src/subscriptions/grants.ts
23105
+ var GRANTING = /* @__PURE__ */ new Set([
23106
+ "trialing",
23107
+ "active",
23108
+ "past_due",
23109
+ "unpaid",
23110
+ "paused"
23111
+ ]);
23112
+ function grantedState(grants, state) {
23113
+ if (state === "expired") return grants.states.ended;
23114
+ return Object.hasOwn(grants.states, state) ? grants.states[state] : null;
23115
+ }
23116
+ function grantUntil(row, now) {
23117
+ const ends = [];
23118
+ if (row.state === "ended" || row.state === "expired") ends.push(row.ended_at ?? now);
23119
+ if (row.cancel_at_period_end === 1 && row.current_period_end) ends.push(row.current_period_end);
23120
+ if (row.cancel_at) ends.push(row.cancel_at);
23121
+ if (row.state === "past_due" && row.failing_since) {
23122
+ ends.push(
23123
+ new Date(Date.parse(row.failing_since) + PAST_DUE_GRACE_DAYS * 864e5).toISOString()
23124
+ );
23125
+ }
23126
+ return ends.length ? [...ends].sort()[0] : null;
23127
+ }
23128
+ function grantsOf(planObject) {
23129
+ const plan3 = getObject(planObject);
23130
+ const grants = plan3?.sellable?.recurring?.grants;
23131
+ const granted = grants ? getObject(grants.object) : void 0;
23132
+ if (!plan3 || !grants || !granted?.states) return null;
23133
+ return { plan: plan3, grants, granted };
23134
+ }
23135
+ async function tellStaff(ctx, row, title, body) {
23136
+ const plan3 = await notifyStatements(
23137
+ ctx.db,
23138
+ {
23139
+ to: [{ role: "admin" }],
23140
+ type: "system.message",
23141
+ title,
23142
+ body,
23143
+ link: { kind: "record", object: "subscription", id: row.id },
23144
+ dedupeKey: `subscription.grant:${row.id}:${title}`,
23145
+ source: { actor: "system" }
23146
+ },
23147
+ ctx.now
23148
+ );
23149
+ ctx.write(...plan3.statements);
23150
+ }
23151
+ async function followSubscriptionGrant(ctx, row, options = {}) {
23152
+ const declared = grantsOf(row.plan_object);
23153
+ if (!declared) return;
23154
+ const { plan: plan3, grants, granted } = declared;
23155
+ const states = granted.states;
23156
+ if (!states) return;
23157
+ const existing = await ctx.db.selectFrom("core_subscription_grant").select(["object_type", "record_id"]).where("subscription_id", "=", row.id).executeTakeFirst();
23158
+ const state = grantedState(grants, row.state);
23159
+ const until = grantUntil(row, ctx.now);
23160
+ if (!existing) {
23161
+ if (!GRANTING.has(row.state) || !state) return;
23162
+ if (!row.holder_person_id) {
23163
+ await tellStaff(
23164
+ ctx,
23165
+ row,
23166
+ "A subscription has no one to hold what it gives",
23167
+ `Subscription ${row.id} (${row.plan_title}) is running, and its holder is not known, so nothing was granted. Set its person, then it is granted with the next event.`
23168
+ );
23169
+ return;
23170
+ }
23171
+ const sources = Object.values(grants.set);
23172
+ const planRow = sources.some((s) => s.startsWith("item.")) ? await readGrantItem(ctx, plan3, row.plan_id) : void 0;
23173
+ const from = (source) => {
23174
+ if (source === "item") return row.plan_id;
23175
+ if (source.startsWith("item.")) return grantFieldValue(plan3, planRow, source.slice(5));
23176
+ if (source === "subscription") return row.id;
23177
+ if (source === "subscription.holder") return row.holder_person_id;
23178
+ if (source === "subscription.payer") return row.payer_person_id;
23179
+ return null;
23180
+ };
23181
+ const values = {
23182
+ ...Object.fromEntries(Object.entries(grants.set).map(([field, s]) => [field, from(s)])),
23183
+ [states.field]: state
23184
+ };
23185
+ if (grants.from) values[grants.from] = row.current_period_start ?? ctx.now;
23186
+ if (grants.until && until) values[grants.until] = until;
23187
+ const id2 = await createRecord(ctx, granted, values, { by: "host", checkReferences: false });
23188
+ ctx.write(
23189
+ ctx.db.insertInto("core_subscription_grant").values({
23190
+ subscription_id: row.id,
23191
+ object_type: granted.name,
23192
+ record_id: id2,
23193
+ created_at: ctx.now
23194
+ })
23195
+ );
23196
+ return;
23197
+ }
23198
+ const object = getObject(existing.object_type);
23199
+ const stateField = object?.states ? object.fields.find((f) => f.name === object.states?.field) : void 0;
23200
+ const stateColumn = stateField ? viewColumnOf(stateField) : null;
23201
+ if (!object?.states || !stateColumn) return;
23202
+ const untilField = grants.until ? object.fields.find((f) => f.name === grants.until) : void 0;
23203
+ const untilColumn = untilField ? viewColumnOf(untilField) : null;
23204
+ const current = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).selectAll().where("id", "=", existing.record_id).executeTakeFirst();
23205
+ if (!current) return;
23206
+ const finals = new Set(object.states.moves.filter((m) => m.final).map((m) => m.to));
23207
+ const now = current[stateColumn];
23208
+ if (typeof now === "string" && finals.has(now)) return;
23209
+ const change = {};
23210
+ if (state && now !== state) change[object.states.field] = state;
23211
+ if (options.planChanged) {
23212
+ const planRow = await readGrantItem(ctx, plan3, row.plan_id);
23213
+ for (const [field, source] of Object.entries(grants.set)) {
23214
+ if (source === "item") change[field] = row.plan_id;
23215
+ else if (source.startsWith("item.")) {
23216
+ change[field] = grantFieldValue(plan3, planRow, source.slice(5));
23217
+ }
23218
+ }
23219
+ }
23220
+ if (grants.until && untilColumn) {
23221
+ const stored = current[untilColumn];
23222
+ const storedAt = typeof stored === "string" && stored ? Date.parse(stored) : null;
23223
+ const untilAt = until ? Date.parse(until) : null;
23224
+ if (storedAt !== untilAt) change[grants.until] = until;
23225
+ }
23226
+ if (!Object.keys(change).length) return;
23227
+ await updateRecord(ctx, object, existing.record_id, change, { by: "host" });
23228
+ }
23229
+ var periodRefunded = async (ctx, move) => {
23230
+ if (move.to.id !== "refunded") return;
23231
+ const order = await loadOrderRow(ctx.db, move.id);
23232
+ if (!order.subscription_id) return;
23233
+ const sub = await loadSubscriptionRow(ctx.db, order.subscription_id).catch(() => null);
23234
+ if (!sub || !grantsOf(sub.plan_object) || sub.state === "ended" || sub.state === "expired") {
23235
+ return;
23236
+ }
23237
+ await tellStaff(
23238
+ ctx,
23239
+ sub,
23240
+ "A refunded period's membership keeps running",
23241
+ `Order ${move.id}, a paid period of subscription ${sub.id} (${sub.plan_title}), was refunded in full. The subscription, and what it grants, keep running: end the subscription if they should not.`
23242
+ );
23243
+ };
23244
+ onRecordMove("order", periodRefunded);
23245
+
23246
+ // ../core/src/subscriptions/periods.ts
23247
+ function periodFlag(terms, invoice, termsChanged) {
23248
+ if (termsChanged || invoice.currency !== terms.currency) return "not_as_agreed";
23249
+ if (invoice.amountPaid < terms.amount) return "paid_less";
23250
+ if (invoice.amountPaid > terms.amount) return "paid_more";
23251
+ return null;
23252
+ }
23253
+ var FLAG_WORDS = {
23254
+ paid_less: "less than its price (a coupon or the payer's balance at the provider, say)",
23255
+ paid_more: "more than its price",
22536
23256
  not_as_agreed: "on terms that are not the ones agreed"
22537
23257
  };
22538
- async function recordPaidPeriod(ctx, sub, event, invoice, termsChanged = false) {
23258
+ async function recordPaidPeriod(ctx, sub, event, invoice, termsChanged = false, part = null) {
22539
23259
  const none = (outcome2, orderId2 = null) => ({
22540
23260
  outcome: outcome2,
22541
23261
  orderId: orderId2,
@@ -22546,7 +23266,7 @@ async function recordPaidPeriod(ctx, sub, event, invoice, termsChanged = false)
22546
23266
  if (seen) return none("period_duplicate", seen.id);
22547
23267
  const amount2 = invoice.amountPaid;
22548
23268
  const currency2 = invoice.currency;
22549
- const flag = periodFlag(sub, invoice, termsChanged);
23269
+ const flag = part ? null : periodFlag(sub, invoice, termsChanged);
22550
23270
  const tax = sub.tax_code && invoice.tax && invoice.tax.amount <= amount2 ? invoice.tax : null;
22551
23271
  const id2 = newId("order");
22552
23272
  const lineId = newId("orderLine");
@@ -22594,8 +23314,8 @@ async function recordPaidPeriod(ctx, sub, event, invoice, termsChanged = false)
22594
23314
  order_id: id2,
22595
23315
  position: 0,
22596
23316
  object_type: sub.plan_object,
22597
- record_id: sub.plan_id,
22598
- title: sub.plan_title,
23317
+ record_id: part?.planId ?? sub.plan_id,
23318
+ title: part?.title ?? sub.plan_title,
22599
23319
  quantity: 1,
22600
23320
  unit_price: amount2,
22601
23321
  line_total: amount2,
@@ -22711,8 +23431,8 @@ function reductionsOnly(row, read) {
22711
23431
  endReason: read.endReason ?? row.end_reason
22712
23432
  };
22713
23433
  }
22714
- function termsDiffer(row, read) {
22715
- return read.currency !== row.currency || read.amount !== row.amount || read.interval !== null && read.interval !== row.interval;
23434
+ function termsDiffer(row, read, other = null) {
23435
+ return read.currency !== row.currency || read.amount !== row.amount && read.amount !== other || read.interval !== null && read.interval !== row.interval;
22716
23436
  }
22717
23437
  var subscription = () => getObject("subscription") ?? subscriptionObject;
22718
23438
  function subscriptionSnapshot(row) {
@@ -22790,6 +23510,7 @@ async function applySubscriptionEvent(ctx, event, done) {
22790
23510
  let row;
22791
23511
  let moved = false;
22792
23512
  let terms = false;
23513
+ let change = null;
22793
23514
  if (!existing) {
22794
23515
  const made = await createFromCheckout(ctx, event);
22795
23516
  if ("refused" in made) {
@@ -22819,7 +23540,19 @@ async function applySubscriptionEvent(ctx, event, done) {
22819
23540
  return nothing("subscription_mismatch");
22820
23541
  }
22821
23542
  row = existing;
22822
- terms = termsDiffer(existing, read);
23543
+ const found = await openChange(ctx.db, existing.id, ctx.now);
23544
+ change = found.open;
23545
+ if (!change && read.observedAt >= existing.observed_at && !FINAL.has(existing.state)) {
23546
+ change = await lateChange(
23547
+ ctx,
23548
+ existing,
23549
+ read,
23550
+ event.invoice,
23551
+ event.trigger === "invoice_paid" && event.invoice?.status === "paid"
23552
+ );
23553
+ }
23554
+ if (!change) closeStale(ctx, found.stale);
23555
+ terms = termsDiffer(existing, read, alsoAgreed(change));
22823
23556
  if (terms) {
22824
23557
  await tellStaff2(
22825
23558
  ctx,
@@ -22832,7 +23565,8 @@ async function applySubscriptionEvent(ctx, event, done) {
22832
23565
  if (read.observedAt >= existing.observed_at && !FINAL.has(existing.state)) {
22833
23566
  const applied = terms ? reductionsOnly(existing, read) : read;
22834
23567
  if (applied) {
22835
- row = await moveFromRead(ctx, existing, applied);
23568
+ const followed = terms ? { row: existing, planChanged: false } : followChange(ctx, existing, read, change);
23569
+ row = await moveFromRead(ctx, existing, applied, followed.row, followed.planChanged);
22836
23570
  moved = true;
22837
23571
  }
22838
23572
  }
@@ -22845,7 +23579,17 @@ async function applySubscriptionEvent(ctx, event, done) {
22845
23579
  switch (event.trigger) {
22846
23580
  case "invoice_paid": {
22847
23581
  if (!invoice) break;
22848
- const period2 = await recordPaidPeriod(ctx, row, event, invoice, terms);
23582
+ const part = terms ? null : await expectedPart(ctx.db, row, invoice, ctx.now, change);
23583
+ const period2 = await recordPaidPeriod(ctx, row, event, invoice, terms, part);
23584
+ if (!part && invoice.billingReason === "subscription_update" && invoice.amountPaid > 0) {
23585
+ await tellStaff2(
23586
+ ctx,
23587
+ "An upgrade's charge was paid, and no upgrade is waiting for it",
23588
+ `Invoice ${invoice.ref} of subscription ${row.id} (${row.plan_title}), raised by the provider for a change of plan, was paid ${formatMoney(invoice.amountPaid, invoice.currency)}, and no upgrade the host asked for is open to take it. It is recorded as an order. Check the subscription's price with the provider, and refund the order if no upgrade applies.`,
23589
+ row.id,
23590
+ `subscription.update_paid:${event.provider}:${invoice.ref}`
23591
+ );
23592
+ }
22849
23593
  outcome2 = period2.outcome;
22850
23594
  orderId2 = period2.orderId;
22851
23595
  orderState = period2.orderId ? "paid" : null;
@@ -22854,6 +23598,17 @@ async function applySubscriptionEvent(ctx, event, done) {
22854
23598
  }
22855
23599
  case "invoice_payment_failed":
22856
23600
  if (!invoice) break;
23601
+ if (change?.kind === "upgrade" && change.state === "requested" && invoice.billingReason === "subscription_update" && read.status === "active") {
23602
+ await tellStaff2(
23603
+ ctx,
23604
+ "A plan upgrade's charge failed",
23605
+ `Subscription ${row.id}: ${declinedUpgradeWords(change, invoice.amountDue, invoice.currency)}`,
23606
+ row.id,
23607
+ `subscription.upgrade_failed:${event.provider}:${invoice.ref}`
23608
+ );
23609
+ outcome2 = "upgrade_failed";
23610
+ break;
23611
+ }
22857
23612
  await tellStaff2(
22858
23613
  ctx,
22859
23614
  "A subscription's payment failed",
@@ -22864,6 +23619,10 @@ async function applySubscriptionEvent(ctx, event, done) {
22864
23619
  outcome2 = "payment_failed";
22865
23620
  break;
22866
23621
  case "invoice_action_required":
23622
+ if (invoice && moved && upgradeNeedsAction(ctx, change, invoice)) {
23623
+ outcome2 = "action_required";
23624
+ break;
23625
+ }
22867
23626
  if (!invoice?.hostedUrl || !moved || invoice.status !== "open" || !OWING.has(row.state)) {
22868
23627
  break;
22869
23628
  }
@@ -22885,6 +23644,15 @@ async function applySubscriptionEvent(ctx, event, done) {
22885
23644
  default:
22886
23645
  break;
22887
23646
  }
23647
+ if (moved && existing && row.state === "paused" && existing.state !== "paused" && change?.kind !== "pause") {
23648
+ await tellStaff2(
23649
+ ctx,
23650
+ "A subscription was changed at the provider",
23651
+ `The ${event.provider} subscription ${read.ref} was paused, and no pause the host asked for explains it. Subscription ${row.id} (${row.plan_title}) is mirrored as paused. Pause and end pauses in the host, never in the provider's dashboard.`,
23652
+ row.id,
23653
+ `subscription.paused_at_provider:${event.provider}:${row.id}:${read.observedAt}`
23654
+ );
23655
+ }
22888
23656
  if (moved && row.state === "ended" && row.end_reason === "payment_failed") {
22889
23657
  await tellStaff2(
22890
23658
  ctx,
@@ -23021,8 +23789,8 @@ async function trialConfirmed(ctx, row) {
23021
23789
  `subscription.second_trial:${row.provider}:${row.id}`
23022
23790
  );
23023
23791
  }
23024
- async function moveFromRead(ctx, row, read) {
23025
- const next = fromRead(row, read, ctx.now);
23792
+ async function moveFromRead(ctx, row, read, planned = row, planChanged = false) {
23793
+ const next = fromRead(planned, read, ctx.now);
23026
23794
  const before = subscriptionSnapshot(row);
23027
23795
  const outcome2 = await applyTransition(
23028
23796
  ctx,
@@ -23046,7 +23814,7 @@ async function moveFromRead(ctx, row, read) {
23046
23814
  after: subscriptionSnapshot(next)
23047
23815
  });
23048
23816
  if (next.state !== row.state) postSubscriptionMove(ctx, next, row.state);
23049
- await followSubscriptionGrant(ctx, next);
23817
+ await followSubscriptionGrant(ctx, next, { planChanged });
23050
23818
  if (next.trial_end && !row.trial_end) await trialConfirmed(ctx, next);
23051
23819
  return next;
23052
23820
  }
@@ -23133,9 +23901,14 @@ async function applyVerifiedPayment(ctx, payment) {
23133
23901
  };
23134
23902
  if (row.state !== "pending" && row.state !== "part_paid") {
23135
23903
  record("late");
23904
+ const owed = await (await import("./moves-E2HKYCTK.js")).oweLateRefund(ctx, row.id, {
23905
+ paymentRef: payment.paymentRef ?? null,
23906
+ amount: payment.amount,
23907
+ orderState: row.state
23908
+ });
23136
23909
  await tellStaff3(
23137
23910
  "A payment arrived for an order that had closed",
23138
- `Order ${row.id} is ${row.state}, and ${money(payment.amount, currency2)} was paid on it. Honour it or refund it.`,
23911
+ `Order ${row.id} is ${row.state}, and ${money(payment.amount, currency2)} was paid on it. ` + (owed ? "What it paid for was no longer held: its refund is being asked for, for a person to approve." : "Honour it or refund it."),
23139
23912
  "late_payment"
23140
23913
  );
23141
23914
  return { outcome: "late", orderId: row.id };
@@ -23203,7 +23976,7 @@ var taxReport = external_exports.object({
23203
23976
  country: external_exports.string().regex(/^[A-Z]{2}$/).nullable(),
23204
23977
  lines: external_exports.array(external_exports.object({ ref: id, amount: minor })).max(100)
23205
23978
  });
23206
- var moment = external_exports.iso.datetime({ offset: true }).transform((t) => new Date(t).toISOString());
23979
+ var moment2 = external_exports.iso.datetime({ offset: true }).transform((t) => new Date(t).toISOString());
23207
23980
  var reason = external_exports.string().regex(/^[a-z_]{1,60}$/).nullable();
23208
23981
  var subscriptionRead = external_exports.object({
23209
23982
  provider,
@@ -23224,14 +23997,14 @@ var subscriptionRead = external_exports.object({
23224
23997
  currency,
23225
23998
  interval: external_exports.enum(["week", "month", "year"]).nullable(),
23226
23999
  cancelAtPeriodEnd: external_exports.boolean(),
23227
- cancelAt: moment.nullable().default(null),
23228
- trialEnd: moment.nullable(),
23229
- currentPeriodStart: moment.nullable(),
23230
- currentPeriodEnd: moment.nullable(),
23231
- canceledAt: moment.nullable(),
23232
- endedAt: moment.nullable(),
24000
+ cancelAt: moment2.nullable().default(null),
24001
+ trialEnd: moment2.nullable(),
24002
+ currentPeriodStart: moment2.nullable(),
24003
+ currentPeriodEnd: moment2.nullable(),
24004
+ canceledAt: moment2.nullable(),
24005
+ endedAt: moment2.nullable(),
23233
24006
  endReason: reason,
23234
- observedAt: moment
24007
+ observedAt: moment2
23235
24008
  });
23236
24009
  var invoiceRead = external_exports.object({
23237
24010
  ref: id,
@@ -23240,11 +24013,11 @@ var invoiceRead = external_exports.object({
23240
24013
  amountDue: minor,
23241
24014
  currency,
23242
24015
  paymentRef: id.nullable(),
23243
- periodStart: moment.nullable(),
23244
- periodEnd: moment.nullable(),
24016
+ periodStart: moment2.nullable(),
24017
+ periodEnd: moment2.nullable(),
23245
24018
  billingReason: reason,
23246
24019
  attemptCount: minor,
23247
- nextAttemptAt: moment.nullable(),
24020
+ nextAttemptAt: moment2.nullable(),
23248
24021
  hostedUrl: external_exports.url({ protocol: /^https$/ }).max(2e3).nullable(),
23249
24022
  tax: external_exports.object({
23250
24023
  amount: minor,
@@ -23634,7 +24407,9 @@ async function requestRefund(ctx, row, input) {
23634
24407
  { order: row.id, state: row.state }
23635
24408
  );
23636
24409
  }
23637
- const payments = (await refundablePayments(ctx, row.id)).filter((p) => p.refundable > 0);
24410
+ const payments = (await refundablePayments(ctx, row.id)).filter(
24411
+ (p) => p.refundable > 0 && (input.paymentRef === void 0 || p.paymentRef === input.paymentRef)
24412
+ );
23638
24413
  const available = payments.reduce((sum, p) => sum + p.refundable, 0);
23639
24414
  if (available <= 0) {
23640
24415
  throw new ConflictError("Everything paid on this order has been refunded or asked for", {
@@ -23656,7 +24431,7 @@ async function requestRefund(ctx, row, input) {
23656
24431
  if (left <= 0) break;
23657
24432
  const amount2 = Math.min(left, payment.refundable);
23658
24433
  left -= amount2;
23659
- const id2 = newId("refund");
24434
+ const id2 = input.refundId ? input.refundId(refunds.length) : newId("refund");
23660
24435
  const result2 = await requestProviderRefund(
23661
24436
  ctx.integrations,
23662
24437
  target,
@@ -23707,6 +24482,44 @@ async function requestRefund(ctx, row, input) {
23707
24482
  return { refunds, pending };
23708
24483
  }
23709
24484
 
24485
+ // ../core/src/orders/refund-due.ts
24486
+ var dueRefundPrefix = (rowId, attempt) => `rfd_${rowId.replace(/^rdu_/, "")}_${attempt}_`;
24487
+ async function requestDueRefund(ctx, id2) {
24488
+ const due = await ctx.db.selectFrom("core_sellable_refund_due").selectAll().where("id", "=", id2).executeTakeFirst();
24489
+ if (!due || due.state !== "asking") {
24490
+ return { state: "skipped", refunds: [], note: "not claimed" };
24491
+ }
24492
+ const mark = (state, note) => ctx.write(
24493
+ ctx.db.updateTable("core_sellable_refund_due").set({ state, note, updated_at: ctx.now }).where("id", "=", id2).where("state", "=", "asking")
24494
+ );
24495
+ const order = await loadOrderRow(ctx.db, due.order_id);
24496
+ const prefix2 = dueRefundPrefix(due.id, due.attempt);
24497
+ try {
24498
+ const left = due.payment_ref ? (await refundablePayments(ctx, order.id)).find((p) => p.paymentRef === due.payment_ref)?.refundable ?? 0 : null;
24499
+ const amount2 = left !== null && due.amount ? Math.min(due.amount, left) : void 0;
24500
+ const asked = await requestRefund(ctx, order, {
24501
+ reason: due.reason,
24502
+ refundId: (n) => `${prefix2}${n}`,
24503
+ ...due.payment_ref ? { paymentRef: due.payment_ref } : {},
24504
+ ...amount2 ? { amount: amount2 } : {}
24505
+ });
24506
+ if (asked.refunds.some((r) => r.pendingActionId === null)) {
24507
+ throw new OperationError(
24508
+ "forbidden",
24509
+ "The approval policy did not put the refund in front of a person"
24510
+ );
24511
+ }
24512
+ mark("asked", null);
24513
+ return { state: "asked", refunds: asked.refunds, note: null };
24514
+ } catch (error) {
24515
+ const conflict = error.code === "conflict";
24516
+ if (!conflict) throw error;
24517
+ const note = error.message;
24518
+ mark("skipped", note);
24519
+ return { state: "skipped", refunds: [], note };
24520
+ }
24521
+ }
24522
+
23710
24523
  // ../core/src/operations/order.ts
23711
24524
  var orderId = external_exports.string().min(1).max(64).describe("Order id (ord_\u2026)");
23712
24525
  var when = external_exports.string().nullable();
@@ -23890,7 +24703,7 @@ var orderStart = defineOperation({
23890
24703
  auditSummary: (output) => ({ id: output.id }),
23891
24704
  async handler(input, ctx) {
23892
24705
  const caller2 = ctx.principal;
23893
- let personId;
24706
+ let personId2;
23894
24707
  let email;
23895
24708
  let token = null;
23896
24709
  if (caller2.kind === "customer") {
@@ -23901,20 +24714,20 @@ var orderStart = defineOperation({
23901
24714
  }
23902
24715
  const account = await ctx.db.selectFrom("core_customer").select("email").where("id", "=", caller2.customerId).executeTakeFirst();
23903
24716
  if (!account) throw new NotFoundError("customer", caller2.customerId);
23904
- personId = caller2.personId;
24717
+ personId2 = caller2.personId;
23905
24718
  email = account.email;
23906
24719
  } else {
23907
24720
  if (!input.email) {
23908
24721
  throw new ValidationError("An order needs the buyer's email address", { field: "email" });
23909
24722
  }
23910
24723
  const buyer = await resolveBuyer(ctx, input.email);
23911
- personId = buyer.personId;
24724
+ personId2 = buyer.personId;
23912
24725
  email = buyer.email;
23913
24726
  if (caller2.kind === "public") token = newOrderToken();
23914
24727
  }
23915
24728
  const started = await createOrder(ctx, {
23916
24729
  lines: input.lines,
23917
- personId,
24730
+ personId: personId2,
23918
24731
  email,
23919
24732
  placedAs: caller2.kind,
23920
24733
  pay: input.pay,
@@ -24047,6 +24860,7 @@ var orderSetPerson = defineOperation({
24047
24860
  callerMover(ctx)
24048
24861
  );
24049
24862
  await grantsFollowPerson(ctx, row.id, input.personId);
24863
+ await movesFollowPerson(ctx, row.id, input.personId);
24050
24864
  return fromRow3(next, await linesOf(ctx, row.id), true);
24051
24865
  }
24052
24866
  });
@@ -24393,76 +25207,406 @@ var orderSettingsUpdate = defineOperation({
24393
25207
  "Replaces the admin's product tax codes, by object (e.g. ticketing.tickettype \u2192 txcd_50010001). Only objects that declare a tax code may be given one; an object left out is taxed at its pack's code."
24394
25208
  )
24395
25209
  }),
24396
- output: orderSettings.extend({ previous: orderSettings }),
24397
- permission: "settings:manage",
24398
- risk: "write",
24399
- actors: ["human"],
24400
- mcp: { expose: false },
25210
+ output: orderSettings.extend({ previous: orderSettings }),
25211
+ permission: "settings:manage",
25212
+ risk: "write",
25213
+ actors: ["human"],
25214
+ mcp: { expose: false },
25215
+ async handler(input, ctx) {
25216
+ if (Object.values(input).every((value) => value === void 0)) {
25217
+ throw new ValidationError(
25218
+ "Pass currency, expiryMinutes, minPartPayment, returnOrigins, tax or taxCodes"
25219
+ );
25220
+ }
25221
+ for (const object of Object.keys(input.taxCodes ?? {})) {
25222
+ if (!getObject(object)?.sellable?.tax) {
25223
+ throw new ValidationError(
25224
+ `${object} declares no tax code, so it is not taxed and cannot be given one`,
25225
+ { field: "taxCodes", object }
25226
+ );
25227
+ }
25228
+ }
25229
+ const previous = await loadSettings(ctx);
25230
+ const next = {
25231
+ currency: input.currency ?? previous.currency,
25232
+ expiryMinutes: input.expiryMinutes ?? previous.expiryMinutes,
25233
+ minPartPayment: input.minPartPayment ?? previous.minPartPayment,
25234
+ returnOrigins: input.returnOrigins ? [...new Set(input.returnOrigins)] : previous.returnOrigins,
25235
+ tax: input.tax ?? previous.tax,
25236
+ taxCodes: input.taxCodes ?? previous.taxCodes
25237
+ };
25238
+ const store2 = (key, field) => {
25239
+ const value = JSON.stringify(next[field]);
25240
+ ctx.write(
25241
+ ctx.db.insertInto("core_settings").values({ key, value, updated_at: ctx.now, updated_by: ctx.user.id }).onConflict(
25242
+ (oc) => oc.column("key").doUpdateSet({ value, updated_at: ctx.now, updated_by: ctx.user.id })
25243
+ )
25244
+ );
25245
+ ctx.recordChange({
25246
+ object: "settings",
25247
+ id: key,
25248
+ action: "update",
25249
+ before: { [field]: previous[field] },
25250
+ after: { [field]: next[field] }
25251
+ });
25252
+ };
25253
+ if (input.currency !== void 0) store2(ORDER_CURRENCY_SETTING, "currency");
25254
+ if (input.expiryMinutes !== void 0) store2(ORDER_EXPIRY_SETTING, "expiryMinutes");
25255
+ if (input.minPartPayment !== void 0) store2(ORDER_MIN_PART_SETTING, "minPartPayment");
25256
+ if (input.returnOrigins !== void 0) store2(ORDER_RETURN_ORIGINS_SETTING, "returnOrigins");
25257
+ if (input.tax !== void 0) store2(ORDER_TAX_SETTING, "tax");
25258
+ if (input.taxCodes !== void 0) store2(ORDER_TAX_CODES_SETTING, "taxCodes");
25259
+ return { ...next, previous };
25260
+ }
25261
+ });
25262
+ var orderStartHeld = defineOperation({
25263
+ name: "order.startHeld",
25264
+ description: "From a pack's tool: make a record that is bought when it is made (a drop-in booking for a class) and start its order, in one step. The record is held for the order (a place in the class) while it is unpaid, and the host prices it: a caller never sends a price. Paying on the provider's page (order.checkout) moves it on; the order expiring unpaid releases it. `values` are the record's fields a customer may set (its class); whose it is is the caller, or with forPersonId a child staff linked to them. A guest gives their email address and is matched to no one until the payment is verified (the answer is the same whatever it matches). The record's own rules apply as for the caller's own booking (when booking opens and closes, booked by staff only, places left, one per person). Returns the order; a guest also gets `token`, shown once.",
25265
+ input: external_exports.object({
25266
+ object: external_exports.string().min(1).max(80).describe("The object to make a record of, e.g. bookings.booking"),
25267
+ values: external_exports.record(external_exports.string().max(80), external_exports.unknown()).default({}).describe("The record's fields a customer may set, e.g. { class: <id> }"),
25268
+ forPersonId: external_exports.string().min(1).max(64).optional().describe("A child linked to the signed-in customer to make it for (ADR 0540)"),
25269
+ email: external_exports.string().trim().max(320).optional().describe("The buyer's address: required for a guest; a signed-in customer passes none")
25270
+ }),
25271
+ output: orderSchema.extend({
25272
+ recordId: external_exports.string().describe("The record made and held for the order"),
25273
+ token: external_exports.string().nullable().describe("A guest's key to this order. Null for everyone else.")
25274
+ }),
25275
+ permission: "records:write",
25276
+ risk: "write",
25277
+ audiences: ["staff", "customer", "public"],
25278
+ hostInternal: true,
25279
+ toolOnly: true,
25280
+ mcp: { expose: false },
25281
+ auditSummary: (output) => ({ id: output.id, recordId: output.recordId }),
25282
+ async handler(input, ctx) {
25283
+ const started = await startHeld(ctx, input);
25284
+ return {
25285
+ ...fromRow3(started.row, started.lines.map(toLine), isStaff(ctx)),
25286
+ recordId: started.recordId,
25287
+ token: started.token
25288
+ };
25289
+ }
25290
+ });
25291
+ var orderReleaseUnsettled = defineOperation({
25292
+ name: "order.releaseUnsettled",
25293
+ description: "Platform use only (the minute cron): release one paid guest drop-in still held for no one (an address several People share, not settled by staff) once booking for it has closed: its place goes back and its refund is owed, for a person to approve. One record per call.",
25294
+ input: external_exports.object({ object: external_exports.string().min(1).max(80), recordId: external_exports.string().min(1).max(64) }),
25295
+ output: external_exports.object({ released: external_exports.boolean() }),
25296
+ permission: "records:write",
25297
+ risk: "write",
25298
+ actors: ["automation"],
25299
+ mcp: { expose: false },
25300
+ async handler(input, ctx) {
25301
+ return { released: await releaseUnsettledGuest(ctx, input.object, input.recordId) };
25302
+ }
25303
+ });
25304
+ var orderRefundDue = defineOperation({
25305
+ name: "order.refundDue",
25306
+ description: "Platform use only (the minute cron): ask for a refund the host owes, recorded when a record bought with its order (a drop-in booking) was cancelled in time or by the gym. Asks as order.refund does: nothing is sent; each refund waits in the Approvals inbox for a person with the refund permission (an AI can never approve one).",
25307
+ input: external_exports.object({ id: external_exports.string().min(1).max(64) }),
25308
+ output: external_exports.object({
25309
+ state: external_exports.enum(["asked", "skipped"]),
25310
+ refunds: external_exports.array(
25311
+ external_exports.object({
25312
+ id: external_exports.string(),
25313
+ paymentRef: external_exports.string(),
25314
+ amount: external_exports.number(),
25315
+ pendingActionId: external_exports.string().nullable()
25316
+ })
25317
+ ),
25318
+ note: external_exports.string().nullable()
25319
+ }),
25320
+ permission: "orders:refund",
25321
+ // As order.refund: the refund is the gatekeeper's outbound action, reviewed on its own, always.
25322
+ risk: "outbound",
25323
+ bookkeeping: true,
25324
+ actors: ["automation"],
25325
+ mcp: { expose: false },
25326
+ async handler(input, ctx) {
25327
+ return requestDueRefund(ctx, input.id);
25328
+ }
25329
+ });
25330
+ var orderOperations = [
25331
+ orderStart,
25332
+ orderStartHeld,
25333
+ orderRefundDue,
25334
+ orderReleaseUnsettled,
25335
+ orderGet,
25336
+ orderList,
25337
+ orderView,
25338
+ orderCancel,
25339
+ orderExtendBalanceDue,
25340
+ orderSetPerson,
25341
+ orderOverdue,
25342
+ orderCheckout,
25343
+ orderApplyPaymentEvent,
25344
+ orderExpireDue,
25345
+ orderPaidLate,
25346
+ orderHonourLate,
25347
+ orderRefund,
25348
+ orderPayments,
25349
+ orderSettingsGet,
25350
+ orderSettingsUpdate
25351
+ ];
25352
+
25353
+ // ../core/src/operations/person-link.ts
25354
+ var personId = external_exports.string().min(1).max(64);
25355
+ var linkId = external_exports.string().min(1).max(64).describe("The link's id (pln_\u2026)");
25356
+ var linkSchema = external_exports.object({
25357
+ id: external_exports.string(),
25358
+ kind: external_exports.literal("guardian"),
25359
+ guardian: external_exports.object({ id: external_exports.string(), name: external_exports.string().nullable() }),
25360
+ dependant: external_exports.object({ id: external_exports.string(), name: external_exports.string().nullable() }),
25361
+ note: external_exports.string().nullable(),
25362
+ createdAt: external_exports.string(),
25363
+ createdBy: external_exports.string(),
25364
+ endedAt: external_exports.string().nullable(),
25365
+ endedBy: external_exports.string().nullable(),
25366
+ endReason: external_exports.string().nullable(),
25367
+ warning: external_exports.string().nullable().describe(
25368
+ "Set when the child's record has an email that is also the parent's or another account's: signing in with it would open that account as the child's"
25369
+ )
25370
+ });
25371
+ async function namesOf(ctx, ids) {
25372
+ const wanted = [...new Set(ids)];
25373
+ if (!wanted.length) return /* @__PURE__ */ new Map();
25374
+ const rows = await ctx.db.selectFrom(visibleSource(ctx, "person")).select(["id", "display_name"]).where("id", "in", wanted).execute();
25375
+ return new Map(rows.map((row) => [row.id, row.display_name]));
25376
+ }
25377
+ function toLink(row, names, warning = null) {
25378
+ return {
25379
+ warning,
25380
+ id: row.id,
25381
+ kind: "guardian",
25382
+ guardian: { id: row.guardian_id, name: names.get(row.guardian_id) ?? null },
25383
+ dependant: { id: row.dependant_id, name: names.get(row.dependant_id) ?? null },
25384
+ note: row.note,
25385
+ createdAt: row.created_at,
25386
+ createdBy: row.created_by,
25387
+ endedAt: row.ended_at,
25388
+ endedBy: row.ended_by,
25389
+ endReason: row.end_reason
25390
+ };
25391
+ }
25392
+ async function loadLink(ctx, id2) {
25393
+ return await ctx.db.selectFrom("core_person_link").selectAll().where("id", "=", id2).executeTakeFirst();
25394
+ }
25395
+ async function requireLivePerson(ctx, id2) {
25396
+ const names = await namesOf(ctx, [id2]);
25397
+ const name = names.get(id2);
25398
+ if (name === void 0) throw new NotFoundError("person", id2);
25399
+ return name;
25400
+ }
25401
+ var personLinkAdd = defineOperation({
25402
+ name: "person.link.add",
25403
+ description: "Link a guardian (a parent) to a dependant (a child) they may act for: while the link is live the guardian, signed in on the gym's site or app, books, cancels and joins waitlists for the dependant, and reads the dependant's bookings and what their memberships and passes have left, and nothing else of theirs. The dependant may have no email and no account. A dependant may have several guardians, a guardian several dependants. Refused when the two are already linked either way. Only a person on the staff with people:link can do this: never the assistant, an MCP client or code. Audited.",
25404
+ input: external_exports.object({
25405
+ guardianId: personId.describe("The parent or guardian (per_\u2026)"),
25406
+ dependantId: personId.describe("The child they may act for (per_\u2026)"),
25407
+ note: external_exports.string().trim().max(500).optional().describe("Why, e.g. mother, legal guardian")
25408
+ }),
25409
+ output: linkSchema,
25410
+ permission: "people:link",
25411
+ risk: "write",
25412
+ actors: ["human"],
25413
+ mcp: { expose: false },
25414
+ async handler(input, ctx) {
25415
+ if (input.guardianId === input.dependantId) {
25416
+ throw new ValidationError("A person cannot be their own guardian");
25417
+ }
25418
+ const guardianName = await requireLivePerson(ctx, input.guardianId);
25419
+ const dependantName = await requireLivePerson(ctx, input.dependantId);
25420
+ const existing = await ctx.db.selectFrom("core_person_link").select(["guardian_id"]).where("kind", "=", GUARDIAN_LINK).where("ended_at", "is", null).where(
25421
+ (eb) => eb.or([
25422
+ eb.and([
25423
+ eb("guardian_id", "=", input.guardianId),
25424
+ eb("dependant_id", "=", input.dependantId)
25425
+ ]),
25426
+ eb.and([
25427
+ eb("guardian_id", "=", input.dependantId),
25428
+ eb("dependant_id", "=", input.guardianId)
25429
+ ])
25430
+ ])
25431
+ ).executeTakeFirst();
25432
+ if (existing) {
25433
+ throw new ConflictError(
25434
+ existing.guardian_id === input.guardianId ? "These two are already linked." : "The other way round is already linked: the dependant is this person's guardian.",
25435
+ { rule: "person_link" }
25436
+ );
25437
+ }
25438
+ const id2 = newId("personLink");
25439
+ ctx.write(
25440
+ ctx.db.insertInto("core_person_link").values({
25441
+ id: id2,
25442
+ kind: GUARDIAN_LINK,
25443
+ guardian_id: input.guardianId,
25444
+ dependant_id: input.dependantId,
25445
+ note: input.note || null,
25446
+ created_by: ctx.user.id,
25447
+ created_at: ctx.now
25448
+ })
25449
+ );
25450
+ ctx.postActivity({
25451
+ subject: "Guardian linked",
25452
+ payload: { kind: "person_link", action: "added", linkId: id2 },
25453
+ links: [
25454
+ { object: "person", id: input.guardianId },
25455
+ { object: "person", id: input.dependantId }
25456
+ ]
25457
+ });
25458
+ return toLink(
25459
+ {
25460
+ id: id2,
25461
+ kind: GUARDIAN_LINK,
25462
+ guardian_id: input.guardianId,
25463
+ dependant_id: input.dependantId,
25464
+ note: input.note || null,
25465
+ created_by: ctx.user.id,
25466
+ created_at: ctx.now,
25467
+ ended_at: null,
25468
+ ended_by: null,
25469
+ end_reason: null
25470
+ },
25471
+ /* @__PURE__ */ new Map([
25472
+ [input.guardianId, guardianName],
25473
+ [input.dependantId, dependantName]
25474
+ ]),
25475
+ // Linked anyway: staff are told, and fix the child's record (ADR 0540).
25476
+ await sharedEmailWarning(ctx.db, input.guardianId, input.dependantId)
25477
+ );
25478
+ }
25479
+ });
25480
+ var personLinkEnd = defineOperation({
25481
+ name: "person.link.end",
25482
+ description: "End a family link: from that moment the guardian reads nothing of the dependant's and books nothing for them. Bookings they already made stay (cancel them separately if needed); the answer says how many (stays). The link is kept, ended, with who ended it and why. Only a person on the staff with people:link can do this. Audited.",
25483
+ input: external_exports.object({
25484
+ id: linkId,
25485
+ reason: external_exports.string().trim().max(500).optional()
25486
+ }),
25487
+ output: linkSchema.extend({
25488
+ stays: external_exports.array(external_exports.object({ object: external_exports.string(), label: external_exports.string(), count: external_exports.number() })).describe("Live records the guardian made for the dependant (bookings): they stay")
25489
+ }),
25490
+ permission: "people:link",
25491
+ risk: "write",
25492
+ actors: ["human"],
25493
+ mcp: { expose: false },
25494
+ async handler(input, ctx) {
25495
+ const row = await loadLink(ctx, input.id);
25496
+ if (!row) throw new NotFoundError("person link", input.id);
25497
+ if (row.ended_at) {
25498
+ throw new ConflictError("This link has already ended.", { rule: "person_link_ended" });
25499
+ }
25500
+ ctx.write(
25501
+ ctx.db.updateTable("core_person_link").set({ ended_at: ctx.now, ended_by: ctx.user.id, end_reason: input.reason || null }).where("id", "=", input.id).where("ended_at", "is", null)
25502
+ );
25503
+ ctx.postActivity({
25504
+ subject: "Guardian link ended",
25505
+ payload: { kind: "person_link", action: "ended", linkId: input.id },
25506
+ links: [
25507
+ { object: "person", id: row.guardian_id },
25508
+ { object: "person", id: row.dependant_id }
25509
+ ]
25510
+ });
25511
+ const names = await namesOf(ctx, [row.guardian_id, row.dependant_id]);
25512
+ const stays = await recordsMadeFor(ctx.db, row.guardian_id, row.dependant_id);
25513
+ return {
25514
+ ...toLink(
25515
+ { ...row, ended_at: ctx.now, ended_by: ctx.user.id, end_reason: input.reason || null },
25516
+ names
25517
+ ),
25518
+ stays
25519
+ };
25520
+ }
25521
+ });
25522
+ var personLinkList = defineOperation({
25523
+ name: "person.link.list",
25524
+ description: "A person's family links: the guardians who may act for them and the dependants they may act for, live ones first, with names, who made each and when, and (with ended) the links that have ended. Read-only.",
25525
+ input: external_exports.object({
25526
+ personId: personId.describe("The person (per_\u2026)"),
25527
+ ended: external_exports.boolean().default(false).describe("Include links that have ended")
25528
+ }),
25529
+ output: external_exports.object({ items: external_exports.array(linkSchema) }),
25530
+ permission: "records:read",
25531
+ risk: "read",
25532
+ mcp: { idempotent: true },
25533
+ async handler(input, ctx) {
25534
+ let query = ctx.db.selectFrom("core_person_link").selectAll().where(
25535
+ (eb) => eb.or([eb("guardian_id", "=", input.personId), eb("dependant_id", "=", input.personId)])
25536
+ );
25537
+ if (!input.ended) query = query.where("ended_at", "is", null);
25538
+ const rows = await query.orderBy(sql`ended_at IS NOT NULL`).orderBy("created_at", "desc").limit(200).execute();
25539
+ const names = await namesOf(
25540
+ ctx,
25541
+ rows.flatMap((row) => [row.guardian_id, row.dependant_id])
25542
+ );
25543
+ const linker = holdsPermission(ctx.user, ctx.permissionGrants, "people:link");
25544
+ const items = [];
25545
+ for (const row of rows) {
25546
+ const warning = row.ended_at || !linker ? null : await sharedEmailWarning(ctx.db, row.guardian_id, row.dependant_id);
25547
+ items.push(toLink(row, names, warning));
25548
+ }
25549
+ return { items };
25550
+ }
25551
+ });
25552
+ var personLinkMergePlan = defineOperation({
25553
+ name: "person.link.mergePlan",
25554
+ description: "What merging one person (mergedId) into another (survivorId) would do to their family links: how many move, how many end (a duplicate, or one whose other way round is linked: never a two-way link), how many are deleted (links between the two) and how many past links move as history. A merge that touches a live link waits for a person's approval when anyone but a person asks for it. Read-only.",
25555
+ input: external_exports.object({ survivorId: personId, mergedId: personId }),
25556
+ output: external_exports.object({
25557
+ moved: external_exports.number(),
25558
+ ended: external_exports.number(),
25559
+ deleted: external_exports.number(),
25560
+ history: external_exports.number(),
25561
+ needs: external_exports.literal("people:link").nullable().describe(
25562
+ "The permission the merge needs because it moves a live link, when the caller lacks it"
25563
+ )
25564
+ }),
25565
+ permission: "records:read",
25566
+ risk: "read",
25567
+ mcp: { idempotent: true },
24401
25568
  async handler(input, ctx) {
24402
- if (Object.values(input).every((value) => value === void 0)) {
24403
- throw new ValidationError(
24404
- "Pass currency, expiryMinutes, minPartPayment, returnOrigins, tax or taxCodes"
24405
- );
24406
- }
24407
- for (const object of Object.keys(input.taxCodes ?? {})) {
24408
- if (!getObject(object)?.sellable?.tax) {
24409
- throw new ValidationError(
24410
- `${object} declares no tax code, so it is not taxed and cannot be given one`,
24411
- { field: "taxCodes", object }
24412
- );
24413
- }
24414
- }
24415
- const previous = await loadSettings(ctx);
24416
- const next = {
24417
- currency: input.currency ?? previous.currency,
24418
- expiryMinutes: input.expiryMinutes ?? previous.expiryMinutes,
24419
- minPartPayment: input.minPartPayment ?? previous.minPartPayment,
24420
- returnOrigins: input.returnOrigins ? [...new Set(input.returnOrigins)] : previous.returnOrigins,
24421
- tax: input.tax ?? previous.tax,
24422
- taxCodes: input.taxCodes ?? previous.taxCodes
25569
+ const plan3 = await planMergeLinks(ctx.db, input.survivorId, input.mergedId);
25570
+ const needs = plan3.movesLive && !holdsPermission(ctx.user, ctx.permissionGrants, "people:link") ? "people:link" : null;
25571
+ return {
25572
+ moved: plan3.moved,
25573
+ ended: plan3.ended,
25574
+ deleted: plan3.deleted,
25575
+ history: plan3.history,
25576
+ needs
24423
25577
  };
24424
- const store2 = (key, field) => {
24425
- const value = JSON.stringify(next[field]);
24426
- ctx.write(
24427
- ctx.db.insertInto("core_settings").values({ key, value, updated_at: ctx.now, updated_by: ctx.user.id }).onConflict(
24428
- (oc) => oc.column("key").doUpdateSet({ value, updated_at: ctx.now, updated_by: ctx.user.id })
24429
- )
24430
- );
24431
- ctx.recordChange({
24432
- object: "settings",
24433
- id: key,
24434
- action: "update",
24435
- before: { [field]: previous[field] },
24436
- after: { [field]: next[field] }
24437
- });
25578
+ }
25579
+ });
25580
+ var familyMember = external_exports.object({ personId: external_exports.string(), name: external_exports.string() });
25581
+ var meFamily = defineOperation({
25582
+ name: "me.family",
25583
+ description: "Your family, as a signed-in customer: yourself, the dependants (children) the gym has linked to you, whom you may book for, and the guardians linked to you, each with their name and id. Only live links; the gym's staff make and end them. Read-only.",
25584
+ input: external_exports.object({}),
25585
+ output: external_exports.object({
25586
+ self: familyMember,
25587
+ dependants: external_exports.array(familyMember),
25588
+ guardians: external_exports.array(familyMember)
25589
+ }),
25590
+ permission: "records:read",
25591
+ risk: "read",
25592
+ audiences: ["customer"],
25593
+ mcp: { expose: false },
25594
+ async handler(_input, ctx) {
25595
+ const family = await ctx.records.family();
25596
+ if (!family.self) throw new OperationError("internal", "me.family is for a customer's call");
25597
+ return {
25598
+ self: family.self,
25599
+ dependants: [...family.dependants],
25600
+ guardians: [...family.guardians]
24438
25601
  };
24439
- if (input.currency !== void 0) store2(ORDER_CURRENCY_SETTING, "currency");
24440
- if (input.expiryMinutes !== void 0) store2(ORDER_EXPIRY_SETTING, "expiryMinutes");
24441
- if (input.minPartPayment !== void 0) store2(ORDER_MIN_PART_SETTING, "minPartPayment");
24442
- if (input.returnOrigins !== void 0) store2(ORDER_RETURN_ORIGINS_SETTING, "returnOrigins");
24443
- if (input.tax !== void 0) store2(ORDER_TAX_SETTING, "tax");
24444
- if (input.taxCodes !== void 0) store2(ORDER_TAX_CODES_SETTING, "taxCodes");
24445
- return { ...next, previous };
24446
25602
  }
24447
25603
  });
24448
- var orderOperations = [
24449
- orderStart,
24450
- orderGet,
24451
- orderList,
24452
- orderView,
24453
- orderCancel,
24454
- orderExtendBalanceDue,
24455
- orderSetPerson,
24456
- orderOverdue,
24457
- orderCheckout,
24458
- orderApplyPaymentEvent,
24459
- orderExpireDue,
24460
- orderPaidLate,
24461
- orderHonourLate,
24462
- orderRefund,
24463
- orderPayments,
24464
- orderSettingsGet,
24465
- orderSettingsUpdate
25604
+ var personLinkOperations = [
25605
+ personLinkAdd,
25606
+ personLinkEnd,
25607
+ personLinkList,
25608
+ personLinkMergePlan,
25609
+ meFamily
24466
25610
  ];
24467
25611
 
24468
25612
  // ../core/src/operations/person-with-record.ts
@@ -26835,8 +27979,8 @@ var stateResolveOperations = [stateResolve];
26835
27979
 
26836
27980
  // ../core/src/subscriptions/subscriptions.ts
26837
27981
  var RUNNING = /* @__PURE__ */ new Set(["trialing", "active", "past_due"]);
26838
- function requireReturnUrl(url, origins) {
26839
- if (!isAllowedReturnUrl(url, origins)) {
27982
+ function requireReturnUrl(url, origins2) {
27983
+ if (!isAllowedReturnUrl(url, origins2)) {
26840
27984
  throw new ValidationError("The return address is not on this deployment's list of sites", {
26841
27985
  field: "returnUrl",
26842
27986
  rule: "return_origin"
@@ -26853,7 +27997,7 @@ async function startSubscription(ctx, input) {
26853
27997
  { field: "offerId", rule: "offer_sign_in" }
26854
27998
  );
26855
27999
  }
26856
- let personId;
28000
+ let personId2;
26857
28001
  let email;
26858
28002
  if (caller2.kind === "customer") {
26859
28003
  if (input.email !== void 0) {
@@ -26863,7 +28007,7 @@ async function startSubscription(ctx, input) {
26863
28007
  }
26864
28008
  const account = await ctx.db.selectFrom("core_customer").select("email").where("id", "=", caller2.customerId).executeTakeFirst();
26865
28009
  if (!account) throw new NotFoundError("customer", caller2.customerId);
26866
- personId = caller2.personId;
28010
+ personId2 = caller2.personId;
26867
28011
  email = account.email;
26868
28012
  } else {
26869
28013
  if (!input.email) {
@@ -26872,16 +28016,16 @@ async function startSubscription(ctx, input) {
26872
28016
  });
26873
28017
  }
26874
28018
  const buyer = await resolveBuyer(ctx, input.email);
26875
- personId = buyer.personId;
28019
+ personId2 = buyer.personId;
26876
28020
  email = buyer.email;
26877
28021
  }
26878
- if (!personId) {
28022
+ if (!personId2) {
26879
28023
  throw new ConflictError(
26880
28024
  "That address belongs to more than one person here, so a subscription cannot be started for it until staff merge them",
26881
28025
  { rule: "payer" }
26882
28026
  );
26883
28027
  }
26884
- const holderPersonId = await holderFor(ctx, personId, input.holderPersonId);
28028
+ const holderPersonId = await holderFor(ctx, personId2, input.holderPersonId);
26885
28029
  const { currency: currency2 } = setup;
26886
28030
  if (!currency2) {
26887
28031
  throw new ConfigError("No currency is set for orders yet, so nothing can be sold");
@@ -26902,13 +28046,13 @@ async function startSubscription(ctx, input) {
26902
28046
  }
26903
28047
  const target = setup.target ?? await paymentsTarget(ctx.db);
26904
28048
  const proved = caller2.kind === "customer" || caller2.kind === "staff";
26905
- const earlier = proved ? await latestCustomerRef(ctx, personId, target.provider) : null;
28049
+ const earlier = proved ? await latestCustomerRef(ctx, personId2, target.provider) : null;
26906
28050
  const taxCode = await loadOrderTax(ctx.db) ? taxCodeOf(getObject(plan3.object), await loadOrderTaxCodes(ctx.db)) : null;
26907
28051
  const allowed = caller2.kind === "customer" ? "yes" : caller2.kind === "staff" ? ctx.actor === "human" && holdsPermission(ctx.user, ctx.permissionGrants, "subscriptions:manage") ? "yes" : "no_permission" : "guest";
26908
28052
  const openedBy = caller2.kind === "customer" ? `customer:${caller2.customerId}` : caller2.kind === "staff" ? `staff:${caller2.userId}` : "public";
26909
28053
  const offer = input.offerId ? await prepareOfferTake(ctx, {
26910
28054
  offerId: input.offerId,
26911
- personId,
28055
+ personId: personId2,
26912
28056
  email,
26913
28057
  plan: { object: plan3.object, id: plan3.recordId },
26914
28058
  target
@@ -26986,7 +28130,7 @@ async function startSubscription(ctx, input) {
26986
28130
  ref: opened.ref,
26987
28131
  // The payer, and who holds what it grants: the same Person unless staff named another
26988
28132
  // (ADR 0487; stage 32b).
26989
- payer_person_id: personId,
28133
+ payer_person_id: personId2,
26990
28134
  holder_person_id: holderPersonId,
26991
28135
  email,
26992
28136
  placed_as: caller2.kind,
@@ -27160,8 +28304,8 @@ async function openPortal(ctx, returnUrl) {
27160
28304
  }
27161
28305
  return portal.url;
27162
28306
  }
27163
- async function latestCustomerRef(ctx, personId, provider2) {
27164
- const row = await ctx.db.selectFrom("core_subscription").select("customer_ref").where("payer_person_id", "=", personId).where("provider", "=", provider2).where("customer_ref", "is not", null).orderBy("created_at", "desc").orderBy("id", "desc").executeTakeFirst();
28307
+ async function latestCustomerRef(ctx, personId2, provider2) {
28308
+ const row = await ctx.db.selectFrom("core_subscription").select("customer_ref").where("payer_person_id", "=", personId2).where("provider", "=", provider2).where("customer_ref", "is not", null).orderBy("created_at", "desc").orderBy("id", "desc").executeTakeFirst();
27165
28309
  return row?.customer_ref ?? null;
27166
28310
  }
27167
28311
  async function targetFor(ctx, row) {
@@ -27200,7 +28344,28 @@ var subscriptionSchema = external_exports.object({
27200
28344
  payerPersonId: external_exports.string().nullable().optional(),
27201
28345
  email: external_exports.string().nullable().optional(),
27202
28346
  endReason: external_exports.string().nullable().optional(),
27203
- failingSince: when2.optional()
28347
+ failingSince: when2.optional(),
28348
+ change: external_exports.object({
28349
+ id: external_exports.string(),
28350
+ kind: external_exports.enum(["upgrade", "downgrade", "pause"]),
28351
+ state: external_exports.enum(["requested", "waiting", "applied", "lapsed", "withdrawn"]).describe(
28352
+ "requested: asked of the provider (an upgrade waits for its charge to be paid); waiting: a downgrade from the next period, or a pause not yet started; applied: the pause it is in; lapsed: an upgrade whose charge was never paid"
28353
+ ),
28354
+ toPlanId: external_exports.string().nullable(),
28355
+ toPlanTitle: external_exports.string().nullable(),
28356
+ toAmount: external_exports.number().nullable(),
28357
+ pauseFrom: when2,
28358
+ pauseUntil: when2.describe("When a pause ends and the provider charges again"),
28359
+ effectiveAt: when2.describe("When a downgrade takes effect (its period's end)"),
28360
+ requestedAt: external_exports.string(),
28361
+ callOutcome: external_exports.enum(["sent", "pending", "unknown", "refused"]).nullable().describe(
28362
+ "What came of asking the provider: unknown means it may or may not have reached it, and the provider's next event decides; staff can withdraw it"
28363
+ ),
28364
+ actionUrl: when2.describe(
28365
+ "The provider's page to confirm an upgrade's charge, while it waits"
28366
+ ),
28367
+ endOutcome: external_exports.enum(["sent", "pending", "unknown", "refused"]).nullable().describe("What came of ending a pause early: refused or unknown, ask again")
28368
+ }).nullable().optional().describe("A plan change or a pause asked for and not yet over, or the pause it is in")
27204
28369
  });
27205
28370
  var text5 = (value) => value == null ? null : String(value);
27206
28371
  var isStaff2 = (ctx) => ctx.principal.kind === "staff";
@@ -27226,6 +28391,21 @@ function fromRecord2(record, staff) {
27226
28391
  actionUrl: text5(v.actionUrl),
27227
28392
  createdAt: String(v.createdAt),
27228
28393
  holderPersonId: text5(v.holderPersonId),
28394
+ change: v.changeId ? {
28395
+ id: String(v.changeId),
28396
+ kind: v.changeKind,
28397
+ state: v.changeState,
28398
+ toPlanId: text5(v.changeToPlanId),
28399
+ toPlanTitle: text5(v.changeToPlanTitle),
28400
+ toAmount: v.changeToAmount == null ? null : Number(v.changeToAmount),
28401
+ pauseFrom: text5(v.pauseFrom),
28402
+ pauseUntil: text5(v.pauseUntil),
28403
+ effectiveAt: text5(v.changeEffectiveAt),
28404
+ requestedAt: String(v.changeRequestedAt),
28405
+ callOutcome: v.changeCallOutcome ?? null,
28406
+ actionUrl: text5(v.changeActionUrl),
28407
+ endOutcome: v.changeEndOutcome ?? null
28408
+ } : null,
27229
28409
  ...staff ? {
27230
28410
  payerPersonId: text5(v.payerPersonId),
27231
28411
  email: text5(v.email),
@@ -27297,7 +28477,7 @@ var subscriptionGet = defineOperation({
27297
28477
  });
27298
28478
  var subscriptionList = defineOperation({
27299
28479
  name: "subscription.list",
27300
- description: "A page of subscriptions, newest first unless sorted otherwise. Filter on state, planObject, planId, payerPersonId, holderPersonId, cancelAtPeriodEnd, currentPeriodEnd, failingSince. A signed-in customer sees the ones they pay for only. Pass nextCursor back as cursor for the next page. Read-only.",
28480
+ description: "A page of subscriptions, newest first unless sorted otherwise. Filter on state, planObject, planId, payerPersonId, holderPersonId, cancelAtPeriodEnd, currentPeriodEnd, failingSince, changeKind, changeState, pauseUntil. Each shows its plan change or pause (`change`). A signed-in customer sees the ones they pay for only. Pass nextCursor back as cursor for the next page. Read-only.",
27301
28481
  input: external_exports.object({
27302
28482
  filter: filterSchema.optional(),
27303
28483
  sort: sortSchema.optional(),
@@ -27379,13 +28559,137 @@ var subscriptionPortal = defineOperation({
27379
28559
  return { url: await openPortal(ctx, input.returnUrl) };
27380
28560
  }
27381
28561
  });
28562
+ var subscriptionChange = defineOperation({
28563
+ name: "subscription.change",
28564
+ description: "Move a subscription to another plan of the same kind (a membership from 3 a week to unlimited). A dearer plan is an upgrade: it takes effect now, and the payment provider charges the rest of the current period at once, prorated; the new plan applies only once that charge is paid, so nothing is given that was not paid for. A cheaper (or same-priced) plan is a downgrade: nothing is refunded or prorated, the member keeps the current plan until its period ends, and the new price is charged from the next period. What the subscription grants (a membership's classes) follows the plan when it takes effect. Only an active subscription not set to end, with no other change waiting. A signed-in customer changes their own, to a plan on sale; staff any, with subscriptions:manage. Asked of the payment provider: the subscription shows the change once the provider confirms it. A person decides, not an AI assistant.",
28565
+ input: external_exports.object({
28566
+ id: subscriptionId,
28567
+ planId: external_exports.string().min(1).max(64).describe("The plan to move to (a record of the same object)"),
28568
+ reason: external_exports.string().trim().min(1).max(500).default("Changed by the payer").describe("Why")
28569
+ }),
28570
+ output: external_exports.object({
28571
+ id: external_exports.string(),
28572
+ changeId: external_exports.string(),
28573
+ kind: external_exports.enum(["upgrade", "downgrade"]),
28574
+ effectiveAt: external_exports.string().nullable().describe("When a downgrade takes effect (the period's end); null for an upgrade: once paid"),
28575
+ amount: external_exports.number().describe("The new plan's price per period, minor units, tax included"),
28576
+ currency: external_exports.string(),
28577
+ asked: external_exports.enum(["sent", "pending", "unknown", "not_needed"]).describe(
28578
+ "sent: the provider was asked; unknown: it may or may not have been (its next event decides); not_needed: the same price, nothing to ask"
28579
+ ),
28580
+ requested: external_exports.literal(true)
28581
+ }),
28582
+ permission: "subscriptions:manage",
28583
+ risk: "write",
28584
+ // Opened to customers (a reviewed change, ADR 0402; ADR 0530): a member changes their own plan
28585
+ // on the web (decision 5), through the host's rules (the plan priced by the host, one change at
28586
+ // a time, an upgrade applied only once paid).
28587
+ audiences: ["staff", "customer"],
28588
+ actors: ["human"],
28589
+ hostInternal: true,
28590
+ mcp: { expose: false },
28591
+ auditSummary: (output, input) => ({
28592
+ subscriptionId: output.id,
28593
+ changeId: output.changeId,
28594
+ planId: input.planId,
28595
+ kind: output.kind,
28596
+ amount: output.amount
28597
+ }),
28598
+ async handler(input, ctx) {
28599
+ const row = await subscriptionForChange(ctx, input.id);
28600
+ return requestPlanChange(ctx, row, { planId: input.planId, reason: input.reason });
28601
+ }
28602
+ });
28603
+ var subscriptionPause = defineOperation({
28604
+ name: "subscription.pause",
28605
+ description: "Pause a subscription for a set time (a membership frozen for an injury or travel): from now or a later moment until a moment, within the plan's shortest and longest pause. While it is paused the payment provider charges nothing, and what the subscription gives stops (no classes, no access); on the end date the provider resumes it and charges a new period, less the unused time of the period it was paused in. Only an active subscription not set to end, on a plan that allows pauses, with no other change waiting. Staff only, with subscriptions:manage; a member asks staff. Asked of the payment provider: the subscription shows it paused once the provider confirms. A person decides, not an AI assistant.",
28606
+ input: external_exports.object({
28607
+ id: subscriptionId,
28608
+ from: external_exports.string().max(40).optional().describe("When the pause starts (ISO 8601, later than now); left out: now"),
28609
+ until: external_exports.string().min(1).max(40).describe("When it ends and charging starts again (ISO 8601)"),
28610
+ reason: external_exports.string().trim().min(1).max(500).describe("Why (an injury, travel)")
28611
+ }),
28612
+ output: external_exports.object({
28613
+ id: external_exports.string(),
28614
+ changeId: external_exports.string(),
28615
+ from: external_exports.string().nullable(),
28616
+ until: external_exports.string(),
28617
+ asked: external_exports.enum(["sent", "pending", "unknown"]),
28618
+ requested: external_exports.literal(true)
28619
+ }),
28620
+ permission: "subscriptions:manage",
28621
+ risk: "write",
28622
+ audiences: ["staff"],
28623
+ actors: ["human"],
28624
+ mcp: { expose: false },
28625
+ auditSummary: (output) => ({
28626
+ subscriptionId: output.id,
28627
+ changeId: output.changeId,
28628
+ from: output.from,
28629
+ until: output.until
28630
+ }),
28631
+ async handler(input, ctx) {
28632
+ const row = await subscriptionForChange(ctx, input.id);
28633
+ return requestPause(ctx, row, input);
28634
+ }
28635
+ });
28636
+ var subscriptionUnpause = defineOperation({
28637
+ name: "subscription.unpause",
28638
+ description: "End a subscription's pause now, before its date: the payment provider resumes it and charges a new period from today, and what it gives starts again once the provider confirms. Or withdraw a pause asked for later that has not started. Staff only, with subscriptions:manage. A person decides, not an AI assistant.",
28639
+ input: external_exports.object({
28640
+ id: subscriptionId,
28641
+ reason: external_exports.string().trim().min(1).max(500).default("Back early").describe("Why")
28642
+ }),
28643
+ output: external_exports.object({
28644
+ id: external_exports.string(),
28645
+ asked: external_exports.enum(["sent", "pending", "unknown"]).describe(
28646
+ "unknown: it may or may not have reached the provider; ask again if it stays paused"
28647
+ ),
28648
+ requested: external_exports.literal(true)
28649
+ }),
28650
+ permission: "subscriptions:manage",
28651
+ risk: "write",
28652
+ audiences: ["staff"],
28653
+ actors: ["human"],
28654
+ mcp: { expose: false },
28655
+ async handler(input, ctx) {
28656
+ const row = await subscriptionForChange(ctx, input.id);
28657
+ return requestUnpause(ctx, row, input.reason);
28658
+ }
28659
+ });
28660
+ var subscriptionChangeWithdraw = defineOperation({
28661
+ name: "subscription.change.withdraw",
28662
+ description: "Withdraw a subscription's plan change that has not taken effect: one stuck waiting for the payment provider, one whose outcome is unknown, or a downgrade waiting for its period (undo it). A downgrade the provider may already show is put back there: the old price from the next invoice, nothing prorated. An upgrade's pending charge is voided at the provider, so it can no longer be paid (with nothing pending there, it was voided or expired already). The change closes only once the provider is asked; refused or unknown, it stays open and is asked again. A pause is ended with subscription.unpause. Staff only, with subscriptions:manage. A person decides, not an AI assistant.",
28663
+ input: external_exports.object({
28664
+ id: subscriptionId,
28665
+ reason: external_exports.string().trim().min(1).max(500).describe("Why")
28666
+ }),
28667
+ output: external_exports.object({
28668
+ id: external_exports.string(),
28669
+ changeId: external_exports.string(),
28670
+ asked: external_exports.enum(["sent", "pending", "unknown", "not_needed"])
28671
+ }),
28672
+ permission: "subscriptions:manage",
28673
+ risk: "write",
28674
+ audiences: ["staff"],
28675
+ actors: ["human"],
28676
+ mcp: { expose: false },
28677
+ async handler(input, ctx) {
28678
+ const row = await subscriptionForChange(ctx, input.id);
28679
+ return withdrawPlanChange(ctx, row, input.reason);
28680
+ }
28681
+ });
27382
28682
  var subscriptionOperations = [
27383
28683
  subscriptionStart,
27384
28684
  subscriptionGet,
27385
28685
  subscriptionList,
27386
28686
  subscriptionCancel,
27387
28687
  subscriptionResume,
27388
- subscriptionPortal
28688
+ subscriptionPortal,
28689
+ subscriptionChange,
28690
+ subscriptionPause,
28691
+ subscriptionUnpause,
28692
+ subscriptionChangeWithdraw
27389
28693
  ];
27390
28694
 
27391
28695
  // ../core/src/operations/subscription-offer.ts
@@ -28591,6 +29895,127 @@ var supportOperations = [
28591
29895
  supportSessionStart
28592
29896
  ];
28593
29897
 
29898
+ // ../core/src/operations/timed-moves.ts
29899
+ var TIMED_MOVE_LOOKBACK_DAYS = 14;
29900
+ var origins = (rule) => typeof rule.from === "string" ? [rule.from] : rule.from;
29901
+ var ident2 = (name) => `"${name.replaceAll('"', '""')}"`;
29902
+ function planOf2(object, index) {
29903
+ const rule = object.states?.after?.[index];
29904
+ const stateField = object.states?.field;
29905
+ if (!rule || !stateField) return null;
29906
+ const column = (o, name) => {
29907
+ const field2 = o.fields.find((f) => f.name === name);
29908
+ return field2 ? viewColumnOf(field2) : null;
29909
+ };
29910
+ const stateColumn = column(object, stateField);
29911
+ if (!stateColumn) return null;
29912
+ const parts = rule.at.split(".");
29913
+ if (parts.length === 1) {
29914
+ const atColumn2 = column(object, rule.at);
29915
+ return atColumn2 ? {
29916
+ object,
29917
+ rule,
29918
+ index,
29919
+ stateColumn,
29920
+ atSource: object.source,
29921
+ atColumn: atColumn2,
29922
+ relationColumn: null
29923
+ } : null;
29924
+ }
29925
+ const [relation, field] = parts;
29926
+ const rel = object.fields.find((f) => f.name === relation);
29927
+ const target = rel?.options?.to ? getObject(rel.options.to) : void 0;
29928
+ const relationColumn = rel ? viewColumnOf(rel) : null;
29929
+ const atColumn = target ? column(target, field) : null;
29930
+ if (!target || !relationColumn || !atColumn) return null;
29931
+ return {
29932
+ object,
29933
+ rule,
29934
+ index,
29935
+ stateColumn,
29936
+ atSource: target.source,
29937
+ atColumn,
29938
+ relationColumn
29939
+ };
29940
+ }
29941
+ function dueQuery(plan3, now, limit, id2, offset = 0) {
29942
+ const minutes = plan3.rule.minutesAfter ?? 0;
29943
+ const latest = new Date(now - minutes * 6e4).toISOString();
29944
+ const earliest = new Date(
29945
+ now - minutes * 6e4 - TIMED_MOVE_LOOKBACK_DAYS * 864e5
29946
+ ).toISOString();
29947
+ const states = origins(plan3.rule);
29948
+ const r = ident2(plan3.object.source);
29949
+ const at = plan3.relationColumn ? `JOIN ${ident2(plan3.atSource)} a ON a.id = r.${ident2(plan3.relationColumn)}` : "";
29950
+ const moment3 = plan3.relationColumn ? `a.${ident2(plan3.atColumn)}` : `r.${ident2(plan3.atColumn)}`;
29951
+ const params = [...states];
29952
+ let sql2 = `SELECT r.id AS id, r.${ident2(plan3.stateColumn)} AS state FROM ${r} r ${at} WHERE r.${ident2(plan3.stateColumn)} IN (${states.map(() => "?").join(", ")}) AND ${moment3} IS NOT NULL AND julianday(${moment3}) <= julianday(?) AND julianday(${moment3}) > julianday(?)`;
29953
+ params.push(latest, earliest);
29954
+ if (plan3.rule.ifAnyIn?.length && plan3.relationColumn) {
29955
+ const rel = ident2(plan3.relationColumn);
29956
+ sql2 += ` AND EXISTS (SELECT 1 FROM ${r} s WHERE s.${rel} = r.${rel} AND s.id != r.id AND s.${ident2(plan3.stateColumn)} IN (${plan3.rule.ifAnyIn.map(() => "?").join(", ")}))`;
29957
+ params.push(...plan3.rule.ifAnyIn);
29958
+ }
29959
+ if (id2 !== void 0) {
29960
+ sql2 += " AND r.id = ?";
29961
+ params.push(id2);
29962
+ }
29963
+ sql2 += ` ORDER BY julianday(${moment3}), r.id LIMIT ? OFFSET ?`;
29964
+ params.push(limit, offset);
29965
+ return CompiledQuery.raw(sql2, params);
29966
+ }
29967
+ var stateAfter = defineOperation({
29968
+ name: "state.after",
29969
+ description: "Platform use only (the minute cron, as the host): make one record's timed move (a declaration's `states.after`, such as a booking still booked after its class becoming a no-show), from the state it was read in or not at all, once it is due.",
29970
+ input: external_exports.object({
29971
+ object: external_exports.string().min(1).max(81),
29972
+ id: external_exports.string().min(1).max(64),
29973
+ rule: external_exports.number().int().min(0).max(3).describe("Which of the object's timed moves"),
29974
+ from: external_exports.string().min(1).max(100).describe("The state it was read in")
29975
+ }),
29976
+ output: external_exports.object({ id: external_exports.string(), state: external_exports.string() }),
29977
+ permission: "records:write",
29978
+ risk: "write",
29979
+ actors: ["automation"],
29980
+ hostStep: true,
29981
+ mcp: { expose: false },
29982
+ auditSummary: (output) => ({ moved: output.id, to: output.state }),
29983
+ async handler(input, ctx) {
29984
+ if (ctx.origin.surface !== "system") {
29985
+ throw new ForbiddenError("state.after is the host's own step: only the platform calls it", {
29986
+ rule: "timed_move",
29987
+ reason: "host_only"
29988
+ });
29989
+ }
29990
+ const object = getObject(input.object);
29991
+ const plan3 = object ? planOf2(object, input.rule) : null;
29992
+ if (!object || !plan3 || !object.states) {
29993
+ throw new ValidationError(`${input.object} has no such timed move`, { field: "rule" });
29994
+ }
29995
+ if (!origins(plan3.rule).includes(input.from)) {
29996
+ throw new ValidationError(`The timed move does not leave ${input.from}`, { field: "from" });
29997
+ }
29998
+ const stored = await loadRecord(ctx, object, input.id);
29999
+ if (!stored) throw new NotFoundError(object.name, input.id);
30000
+ const { rows } = await ctx.db.executeQuery(dueQuery(plan3, Date.parse(ctx.now), 1, input.id));
30001
+ if (!rows.length) {
30002
+ throw new ConflictError(`${object.label} is no longer due to move`, {
30003
+ rule: "timed_move",
30004
+ reason: "not_due"
30005
+ });
30006
+ }
30007
+ await updateRecord(
30008
+ ctx,
30009
+ object,
30010
+ input.id,
30011
+ { [object.states.field]: plan3.rule.to },
30012
+ { by: "host", from: input.from }
30013
+ );
30014
+ return { id: input.id, state: plan3.rule.to };
30015
+ }
30016
+ });
30017
+ var timedMoveOperations = [stateAfter];
30018
+
28594
30019
  // ../core/src/operations/trash.ts
28595
30020
  var TRASH_LIST_OBJECTS = ["person", "organisation", "activity", "task", "media"];
28596
30021
  var trashItemSchema = external_exports.object({
@@ -28750,6 +30175,10 @@ var trashPurge = defineOperation({
28750
30175
  );
28751
30176
  }
28752
30177
  }
30178
+ queueEraseLinks(
30179
+ ctx,
30180
+ purged.filter((r) => r.object === "person").map((r) => r.id)
30181
+ );
28753
30182
  queueEraseAllowances(
28754
30183
  ctx,
28755
30184
  purged.filter((r) => r.object === "person").map((r) => r.id)
@@ -29821,6 +31250,151 @@ ${names.map((n) => `- ${n}`).join("\n") || "(none)"}`
29821
31250
  });
29822
31251
  var voiceOperations = [voicePrefsGet, voicePrefsUpdate, voicePreview, dictationCleanup];
29823
31252
 
31253
+ // ../core/src/operations/waitlist.ts
31254
+ var objectName8 = external_exports.string().min(1).max(81);
31255
+ var recordId4 = external_exports.string().min(1).max(64);
31256
+ function assertSystem(ctx, name) {
31257
+ if (ctx.origin.surface !== "system") {
31258
+ throw new ForbiddenError(`${name} is the host's own step: only the platform calls it`, {
31259
+ rule: "waitlist",
31260
+ reason: "host_only"
31261
+ });
31262
+ }
31263
+ }
31264
+ var waitlistPromote = defineOperation({
31265
+ name: "waitlist.promote",
31266
+ description: "Platform use only (the minute cron, as the host): move one waiter of a waitlist into the place the waitlist holds for it, from waiting or not at all, before the cut-off. Spends what the move spends. Refused when the record is no longer waiting, the cut-off has passed (rule waitlist, reason closed), there is no place (rule capacity) or the spend is refused (rule allowance).",
31267
+ input: external_exports.object({
31268
+ object: objectName8,
31269
+ id: recordId4,
31270
+ on: recordId4.describe("The record it waits on (the class): it must still be")
31271
+ }),
31272
+ output: external_exports.object({ id: external_exports.string(), promoted: external_exports.literal(true) }),
31273
+ permission: "records:write",
31274
+ risk: "write",
31275
+ actors: ["automation"],
31276
+ hostStep: true,
31277
+ mcp: { expose: false },
31278
+ auditSummary: (output) => ({ promoted: output.id }),
31279
+ async handler(input, ctx) {
31280
+ assertSystem(ctx, "waitlist.promote");
31281
+ const t = requireWaitlist(input.object);
31282
+ const stored = await loadRecord(ctx, t.object, input.id);
31283
+ if (!stored) throw new NotFoundError(t.object.name, input.id);
31284
+ const field = t.object.states?.field;
31285
+ if (stored.values[field] !== t.waitlist.state || stored.values[t.claims.on] !== input.on) {
31286
+ throw new ConflictError(`${t.object.label} is no longer waiting`, {
31287
+ rule: "waitlist",
31288
+ reason: "moved_meanwhile"
31289
+ });
31290
+ }
31291
+ if (!await beforeCutoff(ctx, t, stored.values)) {
31292
+ throw new ConflictError(
31293
+ "The waitlist has closed: nobody is moved in this close to the start",
31294
+ {
31295
+ rule: "waitlist",
31296
+ reason: "closed"
31297
+ }
31298
+ );
31299
+ }
31300
+ await updateRecord(
31301
+ ctx,
31302
+ t.object,
31303
+ input.id,
31304
+ {
31305
+ [field]: t.waitlist.promote,
31306
+ ...t.waitlist.promotedAt ? { [t.waitlist.promotedAt]: ctx.now } : {}
31307
+ },
31308
+ { by: "host", from: t.waitlist.state }
31309
+ );
31310
+ return { id: input.id, promoted: true };
31311
+ }
31312
+ });
31313
+ var waitlistPassOver = defineOperation({
31314
+ name: "waitlist.passOver",
31315
+ description: "Platform use only (the minute cron, as the host): note on a waiter that it could not be moved in when a place was free, and why (its spend was refused). It stays waiting.",
31316
+ input: external_exports.object({
31317
+ object: objectName8,
31318
+ id: recordId4,
31319
+ on: recordId4,
31320
+ reason: external_exports.string().min(1).max(200)
31321
+ }),
31322
+ output: external_exports.object({ id: external_exports.string() }),
31323
+ permission: "records:write",
31324
+ risk: "write",
31325
+ actors: ["automation"],
31326
+ hostStep: true,
31327
+ mcp: { expose: false },
31328
+ async handler(input, ctx) {
31329
+ assertSystem(ctx, "waitlist.passOver");
31330
+ const t = requireWaitlist(input.object);
31331
+ const stored = await loadRecord(ctx, t.object, input.id);
31332
+ if (!stored) throw new NotFoundError(t.object.name, input.id);
31333
+ if (stored.values[t.object.states?.field] !== t.waitlist.state) {
31334
+ throw new ConflictError(`${t.object.label} is no longer waiting`, {
31335
+ rule: "waitlist",
31336
+ reason: "moved_meanwhile"
31337
+ });
31338
+ }
31339
+ const values = {};
31340
+ if (t.waitlist.passedOverAt) values[t.waitlist.passedOverAt] = ctx.now;
31341
+ if (t.waitlist.passedOverReason) values[t.waitlist.passedOverReason] = input.reason;
31342
+ if (Object.keys(values).length) {
31343
+ await updateRecord(ctx, t.object, input.id, values, { by: "host" });
31344
+ }
31345
+ return { id: input.id };
31346
+ }
31347
+ });
31348
+ var waitlistRelease = defineOperation({
31349
+ name: "waitlist.release",
31350
+ description: "Platform use only (the minute cron, as the host): give back to everyone the places a waitlist holds on one record (a class) that were held at or before `before` and that nobody waiting could take, or that the cut-off has reached.",
31351
+ input: external_exports.object({
31352
+ object: objectName8.describe("The claimant object whose waitlist it is"),
31353
+ on: recordId4.describe("The record whose places are held"),
31354
+ before: external_exports.string().datetime()
31355
+ }),
31356
+ output: external_exports.object({ on: external_exports.string() }),
31357
+ permission: "records:write",
31358
+ risk: "write",
31359
+ actors: ["automation"],
31360
+ hostStep: true,
31361
+ mcp: { expose: false },
31362
+ async handler(input, ctx) {
31363
+ assertSystem(ctx, "waitlist.release");
31364
+ const t = requireWaitlist(input.object);
31365
+ ctx.write(...releaseHoldsStatements(t, input.on, ctx.now, { before: input.before }));
31366
+ return { on: input.on };
31367
+ }
31368
+ });
31369
+ var waitlistPositionOperation = defineOperation({
31370
+ name: "waitlist.position",
31371
+ description: "Where a waiting record (a booking on a class's waitlist) stands: its position (1 is next) and how many are waiting. Staff any; a signed-in customer only their own record (anyone else's is not found). Never who the others are. Null position when it is not waiting.",
31372
+ input: external_exports.object({ object: objectName8, id: recordId4 }),
31373
+ output: external_exports.object({
31374
+ position: external_exports.number().int().nullable(),
31375
+ waiting: external_exports.number().int().nullable()
31376
+ }),
31377
+ permission: "records:read",
31378
+ risk: "read",
31379
+ audiences: ["staff", "customer"],
31380
+ hostInternal: true,
31381
+ mcp: { idempotent: true },
31382
+ async handler(input, ctx) {
31383
+ const t = requireWaitlist(input.object);
31384
+ await ctx.records.get(t.object.name, input.id).catch(() => {
31385
+ throw new NotFoundError(t.object.name, input.id);
31386
+ });
31387
+ const at = await waitlistPosition(ctx.db, t, input.id);
31388
+ return { position: at?.position ?? null, waiting: at?.waiting ?? null };
31389
+ }
31390
+ });
31391
+ var waitlistOperations = [
31392
+ waitlistPromote,
31393
+ waitlistPassOver,
31394
+ waitlistRelease,
31395
+ waitlistPositionOperation
31396
+ ];
31397
+
29824
31398
  // ../core/src/operations/index.ts
29825
31399
  var coreOperations = [
29826
31400
  ...personOperations,
@@ -29873,6 +31447,7 @@ var coreOperations = [
29873
31447
  ...publicReadOperations,
29874
31448
  ...accessOperations,
29875
31449
  ...stateResolveOperations,
31450
+ ...timedMoveOperations,
29876
31451
  ...notificationOperations,
29877
31452
  ...notificationDeliveryOperations,
29878
31453
  ...assistantOperations,
@@ -29893,13 +31468,15 @@ var coreOperations = [
29893
31468
  ...deviceSessionOperations,
29894
31469
  ...customerOperations,
29895
31470
  ...meOperations,
31471
+ ...personLinkOperations,
29896
31472
  ...orderOperations,
29897
31473
  ...subscriptionOperations,
29898
31474
  ...subscriptionOfferOperations,
29899
31475
  ...myOperations,
29900
31476
  ...capacityOperations,
29901
31477
  ...recurringOperations,
29902
- ...allowanceOperations
31478
+ ...allowanceOperations,
31479
+ ...waitlistOperations
29903
31480
  ];
29904
31481
 
29905
31482
  // ../core/src/registry.ts