@saasicat/persistence-testing 1.0.0-rc.0 → 1.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -113,13 +113,19 @@ function persistenceAdapterContract(options) {
113
113
  plan: "STARTER",
114
114
  planVersionId: oldVersion.planVersionId
115
115
  });
116
- await adapter.tenantSubscriptionWrite.changePlanImmediate("tenant-plan-change", {
117
- planId: "PRO",
118
- cycle: "YEARLY",
119
- periodStart: null,
120
- periodEnd: null,
121
- nextStatus: null
122
- });
116
+ const change = await adapter.tenantSubscriptionWrite.changePlanImmediate(
117
+ "tenant-plan-change",
118
+ {
119
+ planId: "PRO",
120
+ cycle: "YEARLY",
121
+ periodStart: null,
122
+ periodEnd: null,
123
+ nextStatus: null,
124
+ // The row has no cancellation, so this claims it.
125
+ expectedCanceledAt: null
126
+ }
127
+ );
128
+ assert.equal(change.claimed, true, "the plan write did not claim the row");
123
129
  const changed = await adapter.subscriptionRepository.findByTenantId("tenant-plan-change");
124
130
  assert.ok(changed, "changed subscription expected");
125
131
  assert.equal(changed.plan, "PRO");
@@ -170,7 +176,8 @@ function persistenceAdapterContract(options) {
170
176
  cycle: "MONTHLY",
171
177
  periodStart: null,
172
178
  periodEnd: null,
173
- nextStatus: null
179
+ nextStatus: null,
180
+ expectedCanceledAt: null
174
181
  },
175
182
  async (tx, callbackSubscriptionId) => {
176
183
  assert.equal(callbackSubscriptionId, subscriptionId);
@@ -217,11 +224,10 @@ function persistenceAdapterContract(options) {
217
224
  return;
218
225
  }
219
226
  const plan = await repository.create({
220
- projectKey: options.projectKey,
221
227
  planKey: "STANDARD",
222
228
  label: "Standard"
223
229
  });
224
- assert.equal(plan.projectKey, options.projectKey);
230
+ assert.equal(plan.planKey, "STANDARD");
225
231
  const firstDraft = await repository.createPlanVersionDraft({
226
232
  planId: "STANDARD",
227
233
  features: ["CORE"],
@@ -282,11 +288,10 @@ function persistenceAdapterContract(options) {
282
288
  return;
283
289
  }
284
290
  const bundle = await repository.create({
285
- projectKey: options.projectKey,
286
291
  bundleKey: "REPORTING",
287
292
  label: "Reporting"
288
293
  });
289
- assert.equal(bundle.projectKey, options.projectKey);
294
+ assert.equal(bundle.bundleKey, "REPORTING");
290
295
  const firstDraft = await repository.createDraft({
291
296
  bundleId: bundle.id,
292
297
  features: ["REPORTS"],
@@ -334,6 +339,375 @@ function persistenceAdapterContract(options) {
334
339
  second.id
335
340
  );
336
341
  });
342
+ test("a booking keeps the rhythm and the window it was made in", async (t) => {
343
+ const repository = harness.adapter.subscriptionBundleRepository;
344
+ const { seed } = harness;
345
+ if (!repository || !seed.createBundleVersion) {
346
+ t.skip("adapter provides no SubscriptionBundleRepository or bundle catalog");
347
+ return;
348
+ }
349
+ const { planVersionId } = await seed.createPlanVersion({
350
+ planKey: "PRO",
351
+ version: 1,
352
+ quotas: {},
353
+ features: ["CORE"],
354
+ published: true
355
+ });
356
+ const { subscriptionId } = await seed.createSubscription({
357
+ tenantId: "tenant-bundle-period",
358
+ plan: "PRO",
359
+ planVersionId,
360
+ billingCycle: "YEARLY"
361
+ });
362
+ const { bundleVersionId } = await seed.createBundleVersion({
363
+ bundleKey: "ANALYTICS",
364
+ features: ["REPORTS"]
365
+ });
366
+ const booked = await repository.add({
367
+ subscriptionId,
368
+ bundleVersionId,
369
+ startedAt: /* @__PURE__ */ new Date("2026-02-21T00:00:00.000Z"),
370
+ minimumTermEndsAt: null,
371
+ billingCycle: "MONTHLY",
372
+ currentPeriodStart: /* @__PURE__ */ new Date("2026-02-21T00:00:00.000Z"),
373
+ currentPeriodEnd: /* @__PURE__ */ new Date("2026-02-28T00:00:00.000Z")
374
+ });
375
+ assert.equal(booked.billingCycle, "MONTHLY");
376
+ const [readBack] = await repository.listBySubscription(subscriptionId);
377
+ assert.ok(readBack, "the booking must be readable back");
378
+ assert.equal(readBack.billingCycle, "MONTHLY");
379
+ assert.equal(
380
+ readBack.currentPeriodEnd?.toISOString(),
381
+ "2026-02-28T00:00:00.000Z",
382
+ "the period end must survive the round trip"
383
+ );
384
+ assert.equal(readBack.currentPeriodStart?.toISOString(), "2026-02-21T00:00:00.000Z");
385
+ const legacy = await repository.add({
386
+ subscriptionId,
387
+ bundleVersionId,
388
+ startedAt: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
389
+ minimumTermEndsAt: null
390
+ });
391
+ const legacyReadBack = await repository.findById(legacy.id);
392
+ assert.ok(legacyReadBack, "the legacy booking must be readable back");
393
+ assert.equal(legacyReadBack.billingCycle, null);
394
+ assert.equal(legacyReadBack.currentPeriodStart, null);
395
+ assert.equal(legacyReadBack.currentPeriodEnd, null);
396
+ });
397
+ test("a second cancellation of one booking is refused, not applied", async (t) => {
398
+ const repository = harness.adapter.subscriptionBundleRepository;
399
+ const { seed } = harness;
400
+ if (!repository || !seed.createBundleVersion) {
401
+ t.skip("adapter provides no SubscriptionBundleRepository or bundle catalog");
402
+ return;
403
+ }
404
+ const { planVersionId } = await seed.createPlanVersion({
405
+ planKey: "PRO",
406
+ version: 1,
407
+ quotas: {},
408
+ features: ["CORE"],
409
+ published: true
410
+ });
411
+ const { subscriptionId } = await seed.createSubscription({
412
+ tenantId: "tenant-double-cancel",
413
+ plan: "PRO",
414
+ planVersionId
415
+ });
416
+ const { bundleVersionId } = await seed.createBundleVersion({
417
+ bundleKey: "ANALYTICS",
418
+ features: ["REPORTS"]
419
+ });
420
+ const booking = await repository.add({
421
+ subscriptionId,
422
+ bundleVersionId,
423
+ startedAt: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
424
+ minimumTermEndsAt: null
425
+ });
426
+ const first = await repository.cancel(booking.id, {
427
+ canceledAt: /* @__PURE__ */ new Date("2026-03-01T00:00:00.000Z"),
428
+ canceledEffectiveAt: /* @__PURE__ */ new Date("2026-04-01T00:00:00.000Z")
429
+ });
430
+ assert.equal(first.canceledEffectiveAt?.toISOString(), "2026-04-01T00:00:00.000Z");
431
+ await assert.rejects(
432
+ () => repository.cancel(booking.id, {
433
+ canceledAt: /* @__PURE__ */ new Date("2026-03-02T00:00:00.000Z"),
434
+ canceledEffectiveAt: /* @__PURE__ */ new Date("2026-09-01T00:00:00.000Z")
435
+ }),
436
+ "a second cancellation must be refused"
437
+ );
438
+ const readBack = await repository.findById(booking.id);
439
+ assert.equal(
440
+ readBack?.canceledEffectiveAt?.toISOString(),
441
+ "2026-04-01T00:00:00.000Z",
442
+ "the first cancellation must still stand"
443
+ );
444
+ await repository.reactivate(booking.id);
445
+ const again = await repository.cancel(booking.id, {
446
+ canceledAt: /* @__PURE__ */ new Date("2026-03-02T00:00:00.000Z"),
447
+ canceledEffectiveAt: /* @__PURE__ */ new Date("2026-09-01T00:00:00.000Z")
448
+ });
449
+ assert.equal(again.canceledEffectiveAt?.toISOString(), "2026-09-01T00:00:00.000Z");
450
+ });
451
+ test("a subscription's bookings come back newest first", async (t) => {
452
+ const repository = harness.adapter.subscriptionBundleRepository;
453
+ const { seed } = harness;
454
+ if (!repository || !seed.createBundleVersion) {
455
+ t.skip("adapter provides no SubscriptionBundleRepository or bundle catalog");
456
+ return;
457
+ }
458
+ const { planVersionId } = await seed.createPlanVersion({
459
+ planKey: "PRO",
460
+ version: 1,
461
+ quotas: {},
462
+ features: ["CORE"],
463
+ published: true
464
+ });
465
+ const { subscriptionId } = await seed.createSubscription({
466
+ tenantId: "tenant-booking-order",
467
+ plan: "PRO",
468
+ planVersionId
469
+ });
470
+ for (const [key, startedAt] of [
471
+ ["OLDEST", "2026-01-01T00:00:00.000Z"],
472
+ ["MIDDLE", "2026-02-01T00:00:00.000Z"],
473
+ ["NEWEST", "2026-03-01T00:00:00.000Z"]
474
+ ]) {
475
+ const { bundleVersionId } = await seed.createBundleVersion({
476
+ bundleKey: key,
477
+ features: ["REPORTS"]
478
+ });
479
+ await repository.add({
480
+ subscriptionId,
481
+ bundleVersionId,
482
+ startedAt: new Date(startedAt),
483
+ minimumTermEndsAt: null
484
+ });
485
+ }
486
+ const listed = await repository.listBySubscription(subscriptionId);
487
+ assert.deepEqual(
488
+ listed.map((row) => row.startedAt.toISOString()),
489
+ [
490
+ "2026-03-01T00:00:00.000Z",
491
+ "2026-02-01T00:00:00.000Z",
492
+ "2026-01-01T00:00:00.000Z"
493
+ ]
494
+ );
495
+ });
496
+ test("a booking with no request date is active, whatever its effective date says", async (t) => {
497
+ const repository = harness.adapter.subscriptionBundleRepository;
498
+ const { seed } = harness;
499
+ if (!repository || !seed.createBundleVersion) {
500
+ t.skip("adapter provides no SubscriptionBundleRepository or bundle catalog");
501
+ return;
502
+ }
503
+ const { planVersionId } = await seed.createPlanVersion({
504
+ planKey: "PRO",
505
+ version: 1,
506
+ quotas: {},
507
+ features: ["CORE"],
508
+ published: true
509
+ });
510
+ const { subscriptionId } = await seed.createSubscription({
511
+ tenantId: "tenant-half-cancelled",
512
+ plan: "PRO",
513
+ planVersionId
514
+ });
515
+ const { bundleVersionId } = await seed.createBundleVersion({
516
+ bundleKey: "ANALYTICS",
517
+ features: ["REPORTS"]
518
+ });
519
+ const booking = await repository.add({
520
+ subscriptionId,
521
+ bundleVersionId,
522
+ startedAt: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
523
+ minimumTermEndsAt: null
524
+ });
525
+ await repository.cancel(booking.id, {
526
+ canceledAt: /* @__PURE__ */ new Date("2026-02-01T00:00:00.000Z"),
527
+ canceledEffectiveAt: /* @__PURE__ */ new Date("2026-03-01T00:00:00.000Z")
528
+ });
529
+ const clearRequestDate = harness.seed.clearBookingRequestDate;
530
+ if (!clearRequestDate) {
531
+ t.skip("adapter harness cannot write the half-cancelled shape");
532
+ return;
533
+ }
534
+ await clearRequestDate(booking.id);
535
+ const active = await repository.listActiveBySubscription(
536
+ subscriptionId,
537
+ /* @__PURE__ */ new Date("2026-06-01T00:00:00.000Z")
538
+ );
539
+ assert.equal(active.length, 1, "no request date means nobody asked to cancel it");
540
+ assert.equal(
541
+ await repository.countActiveByBundleVersionId(
542
+ bundleVersionId,
543
+ /* @__PURE__ */ new Date("2026-06-01T00:00:00.000Z")
544
+ ),
545
+ 1
546
+ );
547
+ });
548
+ test("discarding a draft cannot remove a version published meanwhile", async (t) => {
549
+ const catalog = harness.adapter.bundleRepository;
550
+ const discardDraft = catalog?.deleteDraft?.bind(catalog);
551
+ if (!catalog || !discardDraft) {
552
+ t.skip("adapter provides no BundleRepository");
553
+ return;
554
+ }
555
+ const bundle = await catalog.create({
556
+ bundleKey: "RACE",
557
+ label: "Race"
558
+ });
559
+ const draft = await catalog.createDraft({
560
+ bundleId: bundle.id,
561
+ features: ["REPORTS"],
562
+ quotas: {}
563
+ });
564
+ await catalog.publishDraft(draft.id, {
565
+ publishedByUserId: null,
566
+ publishedChanges: [],
567
+ nonRegressive: true,
568
+ validFrom: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
569
+ validUntil: null
570
+ });
571
+ await assert.rejects(
572
+ () => discardDraft(draft.id),
573
+ "a published version must not be discardable"
574
+ );
575
+ assert.ok(
576
+ await catalog.findVersionById(draft.id),
577
+ "and it must still be there afterwards"
578
+ );
579
+ });
580
+ test("publishing one draft twice claims it once, and the windows stay adjacent", async (t) => {
581
+ const catalog = harness.adapter.bundleRepository;
582
+ const publish = catalog?.publishDraft?.bind(catalog);
583
+ if (!catalog || !publish) {
584
+ t.skip("adapter provides no BundleRepository");
585
+ return;
586
+ }
587
+ const bundle = await catalog.create({
588
+ bundleKey: "CLAIM",
589
+ label: "Claim"
590
+ });
591
+ const first = await catalog.createDraft({
592
+ bundleId: bundle.id,
593
+ features: ["A"],
594
+ quotas: {}
595
+ });
596
+ await publish(first.id, {
597
+ publishedByUserId: null,
598
+ publishedChanges: [],
599
+ nonRegressive: true,
600
+ validFrom: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
601
+ validUntil: null
602
+ });
603
+ const second = await catalog.createDraft({
604
+ bundleId: bundle.id,
605
+ baseVersionId: first.id,
606
+ features: ["A", "B"],
607
+ quotas: {}
608
+ });
609
+ const publishedAt = /* @__PURE__ */ new Date("2026-03-01T00:00:00.000Z");
610
+ await publish(second.id, {
611
+ publishedByUserId: null,
612
+ publishedChanges: [],
613
+ nonRegressive: true,
614
+ validFrom: publishedAt,
615
+ validUntil: null
616
+ });
617
+ await assert.rejects(
618
+ () => publish(second.id, {
619
+ publishedByUserId: null,
620
+ publishedChanges: [],
621
+ nonRegressive: true,
622
+ validFrom: /* @__PURE__ */ new Date("2026-06-01T00:00:00.000Z"),
623
+ validUntil: null
624
+ }),
625
+ "a version that is already published must not be published again"
626
+ );
627
+ const successor = await catalog.findVersionById(second.id);
628
+ const predecessor = await catalog.findVersionById(first.id);
629
+ assert.equal(
630
+ successor?.validFrom && new Date(successor.validFrom).toISOString(),
631
+ publishedAt.toISOString(),
632
+ "the winning date must still stand"
633
+ );
634
+ assert.ok(predecessor?.supersededAt, "the predecessor must be superseded");
635
+ if (predecessor?.validUntil) {
636
+ const closesAt = new Date(predecessor.validUntil);
637
+ assert.equal(
638
+ closesAt.toISOString().slice(0, 10),
639
+ "2026-02-28",
640
+ "the predecessor must close the day before its successor opens"
641
+ );
642
+ }
643
+ });
644
+ test("a plan key names one plan for the whole installation", async (t) => {
645
+ const repository = harness.adapter.planRepository;
646
+ if (!repository) {
647
+ t.skip("adapter provides no PlanRepository");
648
+ return;
649
+ }
650
+ await repository.create({ planKey: "DOUBLE", label: "First" });
651
+ await assert.rejects(
652
+ () => repository.create({ planKey: "DOUBLE", label: "Second" }),
653
+ "a plan key is taken once"
654
+ );
655
+ });
656
+ test("a bundle key names one bundle for the whole installation", async (t) => {
657
+ const catalog = harness.adapter.bundleRepository;
658
+ if (!catalog) {
659
+ t.skip("adapter provides no BundleRepository");
660
+ return;
661
+ }
662
+ await catalog.create({ bundleKey: "DOUBLE", label: "First" });
663
+ await assert.rejects(
664
+ () => catalog.create({ bundleKey: "DOUBLE", label: "Second" }),
665
+ "a bundle key is taken once"
666
+ );
667
+ });
668
+ test("a retired plan still occupies its key", async (t) => {
669
+ const repository = harness.adapter.planRepository;
670
+ const retire = repository?.softDelete?.bind(repository);
671
+ const byKey = repository?.findByKey?.bind(repository);
672
+ if (!repository || !retire || !byKey) {
673
+ t.skip("adapter provides no PlanRepository");
674
+ return;
675
+ }
676
+ const plan = await repository.create({ planKey: "RETIRED_PLAN", label: "Retired" });
677
+ await retire(plan.id);
678
+ const stillThere = await byKey("RETIRED_PLAN");
679
+ assert.equal(stillThere?.id, plan.id, "the key is not free again");
680
+ assert.ok(stillThere?.deletedAt, "and the row says it is retired");
681
+ assert.equal(
682
+ (await repository.list({})).some((row) => row.id === plan.id),
683
+ false,
684
+ "a retired plan is not in the catalogue an operator browses"
685
+ );
686
+ });
687
+ test("a retired bundle still occupies its key", async (t) => {
688
+ const catalog = harness.adapter.bundleRepository;
689
+ const retire = catalog?.softDelete?.bind(catalog);
690
+ const byKey = catalog?.findByKey?.bind(catalog);
691
+ if (!catalog || !retire || !byKey) {
692
+ t.skip("adapter provides no BundleRepository");
693
+ return;
694
+ }
695
+ const bundle = await catalog.create({
696
+ bundleKey: "RETIRED_KEY",
697
+ label: "Retired"
698
+ });
699
+ assert.equal((await byKey("RETIRED_KEY"))?.id, bundle.id);
700
+ await retire(bundle.id);
701
+ const stillThere = await byKey("RETIRED_KEY");
702
+ assert.equal(stillThere?.id, bundle.id, "the key is not free again");
703
+ assert.ok(stillThere?.deletedAt, "and the row says it is retired");
704
+ const listed = await catalog.list({});
705
+ assert.equal(
706
+ listed.some((row) => row.id === bundle.id),
707
+ false,
708
+ "a retired bundle is not in the catalogue an operator browses"
709
+ );
710
+ });
337
711
  test("countByPlanVersionId counts current AND pending bindings in one query", async (t) => {
338
712
  const { seed, adapter } = harness;
339
713
  if (!adapter.subscriptionRepository.countByPlanVersionId) {
@@ -704,13 +1078,602 @@ function persistenceAdapterContract(options) {
704
1078
  assert.equal(seen?.id, subscriptionId);
705
1079
  assert.equal(seen?.tenantId, "tenant-a");
706
1080
  });
707
- test("immutable subscription contracts (append-only, terminate-only)", (t) => {
708
- if (!harness.adapter.subscriptionContractRepository) {
709
- t.skip("adapter provides no SubscriptionContractRepository \u2014 scenario pending");
1081
+ test("a contract keeps what was agreed, and ending it does not rewrite it", async (t) => {
1082
+ const contracts = harness.adapter.subscriptionContractRepository;
1083
+ if (!contracts) {
1084
+ t.skip("adapter provides no SubscriptionContractRepository");
1085
+ return;
1086
+ }
1087
+ const tenantId = "tenant-contract-lifecycle";
1088
+ const signedAt = /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z");
1089
+ const created = await contracts.create({
1090
+ tenantId,
1091
+ effectiveFrom: signedAt,
1092
+ priceSnapshot: {
1093
+ currency: "EUR",
1094
+ billingCycle: "monthly",
1095
+ subtotalNet: 29.9,
1096
+ discountNet: 0,
1097
+ totalNet: 29.9,
1098
+ vatRate: 19,
1099
+ totalGross: 35.58
1100
+ },
1101
+ entitlementSnapshot: {
1102
+ plan: "STANDARD",
1103
+ features: ["CORE"],
1104
+ quotas: { users: 5 }
1105
+ },
1106
+ originalBundleVersionIds: ["bundle-version-1"],
1107
+ termsSnapshot: { noticePeriodDays: 30 },
1108
+ lineItems: [
1109
+ {
1110
+ kind: "plan",
1111
+ sourceKey: "STANDARD",
1112
+ sourceVersionId: "plan-version-1",
1113
+ titleSnapshot: "Standard",
1114
+ descriptionSnapshot: "The plan as it was signed",
1115
+ quantity: 1,
1116
+ unit: null,
1117
+ priceNet: 19.9,
1118
+ priceGross: 23.68,
1119
+ billingCycle: "monthly",
1120
+ currency: "EUR",
1121
+ taxRate: 19,
1122
+ taxAmount: 3.78,
1123
+ minimumTermUntil: /* @__PURE__ */ new Date("2027-01-01T00:00:00.000Z"),
1124
+ featuresSnapshot: ["CORE"],
1125
+ quotaEffectsSnapshot: { users: 5 },
1126
+ metadata: { origin: "onboarding" }
1127
+ },
1128
+ {
1129
+ kind: "bundle",
1130
+ sourceKey: "EXTRA-SEATS",
1131
+ sourceVersionId: "bundle-version-1",
1132
+ titleSnapshot: "Extra seats",
1133
+ descriptionSnapshot: null,
1134
+ quantity: 1,
1135
+ unit: "seat",
1136
+ priceNet: 10,
1137
+ priceGross: 11.9,
1138
+ billingCycle: "monthly",
1139
+ currency: "EUR",
1140
+ taxRate: 19,
1141
+ taxAmount: 1.9,
1142
+ minimumTermUntil: null,
1143
+ featuresSnapshot: [],
1144
+ quotaEffectsSnapshot: { users: 5 },
1145
+ metadata: null
1146
+ }
1147
+ ]
1148
+ });
1149
+ assert.equal(created.status, "active");
1150
+ assert.equal(created.tenantId, tenantId);
1151
+ assert.equal(created.lineItems.length, 2);
1152
+ assert.deepEqual(created.originalBundleVersionIds, ["bundle-version-1"]);
1153
+ assert.deepEqual(created.termsSnapshot, { noticePeriodDays: 30 });
1154
+ const planLine = created.lineItems.find((item) => item.kind === "plan");
1155
+ assert.ok(planLine, "plan line expected");
1156
+ assert.equal(planLine.priceNet, 19.9, "money must survive the round trip unrounded");
1157
+ assert.equal(planLine.priceGross, 23.68);
1158
+ assert.equal(planLine.billingCycle, "monthly");
1159
+ assert.deepEqual(planLine.quotaEffectsSnapshot, { users: 5 });
1160
+ assert.equal(planLine.descriptionSnapshot, "The plan as it was signed");
1161
+ assert.equal(
1162
+ planLine.minimumTermUntil?.getTime(),
1163
+ (/* @__PURE__ */ new Date("2027-01-01T00:00:00.000Z")).getTime(),
1164
+ "the commitment is part of what was agreed"
1165
+ );
1166
+ assert.deepEqual(planLine.metadata, { origin: "onboarding" });
1167
+ assert.equal(planLine.currency, "EUR", "the line says what it was booked in");
1168
+ assert.equal(planLine.taxRate, 19, "the rate is a recorded fact, not the ratio");
1169
+ assert.equal(planLine.taxAmount, 3.78);
1170
+ assert.equal(
1171
+ Math.round((planLine.priceNet + planLine.taxAmount) * 100) / 100,
1172
+ planLine.priceGross,
1173
+ "the tax closes the gap between net and gross"
1174
+ );
1175
+ const bundleLine = created.lineItems.find((item) => item.kind === "bundle");
1176
+ assert.ok(bundleLine, "bundle line expected");
1177
+ assert.equal(bundleLine.descriptionSnapshot, null);
1178
+ assert.equal(bundleLine.unit, "seat");
1179
+ assert.equal(bundleLine.minimumTermUntil, null);
1180
+ assert.equal(bundleLine.metadata, null);
1181
+ const readBack = await contracts.findById(created.id);
1182
+ assert.ok(readBack, "contract expected by id");
1183
+ assert.equal(
1184
+ readBack.lineItems.length,
1185
+ 2,
1186
+ "lines belong to the contract, not the call"
1187
+ );
1188
+ assert.equal(
1189
+ (await contracts.findActiveByTenantId(
1190
+ tenantId,
1191
+ /* @__PURE__ */ new Date("2026-06-01T00:00:00.000Z")
1192
+ ))?.id,
1193
+ created.id
1194
+ );
1195
+ assert.equal(
1196
+ await contracts.findActiveByTenantId(
1197
+ tenantId,
1198
+ /* @__PURE__ */ new Date("2025-12-31T23:59:59.999Z")
1199
+ ),
1200
+ null,
1201
+ "a contract is not active before it starts"
1202
+ );
1203
+ const endsAt = /* @__PURE__ */ new Date("2026-07-01T00:00:00.000Z");
1204
+ const terminated = await contracts.terminate(created.id, {
1205
+ effectiveUntil: endsAt,
1206
+ status: null
1207
+ });
1208
+ assert.equal(
1209
+ terminated.status,
1210
+ "active",
1211
+ "a null status leaves the contract in the state it had"
1212
+ );
1213
+ assert.equal(terminated.effectiveUntil?.getTime(), endsAt.getTime());
1214
+ assert.equal(terminated.lineItems.length, 2, "ending a contract keeps its lines");
1215
+ assert.equal(
1216
+ terminated.priceSnapshot.totalNet,
1217
+ created.priceSnapshot.totalNet,
1218
+ "ending a contract does not restate its price"
1219
+ );
1220
+ const afterEnd = await contracts.findById(created.id);
1221
+ assert.ok(afterEnd, "a terminated contract is still readable");
1222
+ assert.equal(afterEnd.lineItems.length, 2);
1223
+ assert.equal(
1224
+ (await contracts.findActiveByTenantId(
1225
+ tenantId,
1226
+ /* @__PURE__ */ new Date("2026-06-30T00:00:00.000Z")
1227
+ ))?.id,
1228
+ created.id,
1229
+ "active up to the moment it ends"
1230
+ );
1231
+ assert.equal(
1232
+ await contracts.findActiveByTenantId(tenantId, endsAt),
1233
+ null,
1234
+ "and not at that moment"
1235
+ );
1236
+ });
1237
+ test("a successor takes over without erasing the contract it replaces", async (t) => {
1238
+ const contracts = harness.adapter.subscriptionContractRepository;
1239
+ if (!contracts) {
1240
+ t.skip("adapter provides no SubscriptionContractRepository");
1241
+ return;
1242
+ }
1243
+ const tenantId = "tenant-contract-succession";
1244
+ const handover = /* @__PURE__ */ new Date("2026-04-01T00:00:00.000Z");
1245
+ const lineAt = (priceNet, priceGross) => ({
1246
+ kind: "plan",
1247
+ sourceKey: "STANDARD",
1248
+ sourceVersionId: null,
1249
+ titleSnapshot: "Standard",
1250
+ descriptionSnapshot: null,
1251
+ quantity: 1,
1252
+ unit: null,
1253
+ priceNet,
1254
+ priceGross,
1255
+ billingCycle: "monthly",
1256
+ currency: "EUR",
1257
+ taxRate: 19,
1258
+ taxAmount: Math.round((priceGross - priceNet) * 100) / 100,
1259
+ minimumTermUntil: null,
1260
+ featuresSnapshot: [],
1261
+ quotaEffectsSnapshot: {},
1262
+ metadata: null
1263
+ });
1264
+ const priceAt = (net, gross) => ({
1265
+ currency: "EUR",
1266
+ billingCycle: "monthly",
1267
+ subtotalNet: net,
1268
+ discountNet: 0,
1269
+ totalNet: net,
1270
+ vatRate: 19,
1271
+ totalGross: gross
1272
+ });
1273
+ const first = await contracts.create({
1274
+ tenantId,
1275
+ effectiveFrom: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
1276
+ priceSnapshot: priceAt(19.9, 23.68),
1277
+ lineItems: [lineAt(19.9, 23.68)]
1278
+ });
1279
+ assert.equal(
1280
+ (await contracts.findActiveByTenantId(
1281
+ tenantId,
1282
+ /* @__PURE__ */ new Date("2026-03-31T00:00:00.000Z")
1283
+ ))?.id,
1284
+ first.id
1285
+ );
1286
+ await contracts.terminate(first.id, {
1287
+ effectiveUntil: handover,
1288
+ status: "superseded"
1289
+ });
1290
+ const second = await contracts.create({
1291
+ tenantId,
1292
+ effectiveFrom: handover,
1293
+ priceSnapshot: priceAt(24.9, 29.63),
1294
+ lineItems: [lineAt(24.9, 29.63)]
1295
+ });
1296
+ assert.equal(
1297
+ (await contracts.findActiveByTenantId(tenantId, handover))?.id,
1298
+ second.id,
1299
+ "the successor takes over at the moment the predecessor ends"
1300
+ );
1301
+ assert.equal(
1302
+ await contracts.findActiveByTenantId(
1303
+ tenantId,
1304
+ /* @__PURE__ */ new Date("2026-03-31T00:00:00.000Z")
1305
+ ),
1306
+ null,
1307
+ "a superseded contract is not live at any asOf"
1308
+ );
1309
+ const superseded = await contracts.findById(first.id);
1310
+ assert.equal(superseded?.status, "superseded");
1311
+ assert.equal(
1312
+ superseded?.priceSnapshot.totalNet,
1313
+ 19.9,
1314
+ "the replaced contract keeps the price it was signed at"
1315
+ );
1316
+ const history = await contracts.list({ tenantId });
1317
+ assert.equal(history.length, 2, "both contracts remain in the history");
1318
+ assert.deepEqual(
1319
+ history.map((contract) => contract.lineItems.map((item) => item.priceNet)),
1320
+ [[24.9], [19.9]]
1321
+ );
1322
+ assert.deepEqual(
1323
+ history.map((contract) => contract.id),
1324
+ [second.id, first.id],
1325
+ "newest first"
1326
+ );
1327
+ assert.deepEqual(
1328
+ (await contracts.list({ tenantId, asOf: /* @__PURE__ */ new Date("2026-03-31T00:00:00.000Z") })).map((contract) => contract.id),
1329
+ [first.id],
1330
+ "asOf narrows the history to what was in force then"
1331
+ );
1332
+ assert.deepEqual(
1333
+ (await contracts.list({ tenantId, status: "superseded" })).map(
1334
+ (contract) => contract.id
1335
+ ),
1336
+ [first.id]
1337
+ );
1338
+ });
1339
+ test("a line keeps the currency and the tax it was booked with", async (t) => {
1340
+ const contracts = harness.adapter.subscriptionContractRepository;
1341
+ if (!contracts) {
1342
+ t.skip("adapter provides no SubscriptionContractRepository");
710
1343
  return;
711
1344
  }
712
- assert.fail(
713
- "SubscriptionContractRepository present but the contract kit has no scenario yet \u2014 extend the kit"
1345
+ const tenantId = "tenant-contract-money-facts";
1346
+ const created = await contracts.create({
1347
+ tenantId,
1348
+ effectiveFrom: /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"),
1349
+ priceSnapshot: {
1350
+ currency: "CHF",
1351
+ billingCycle: "monthly",
1352
+ subtotalNet: 100,
1353
+ discountNet: 10,
1354
+ totalNet: 90,
1355
+ vatRate: 8.1,
1356
+ totalGross: 97.29
1357
+ },
1358
+ lineItems: [
1359
+ {
1360
+ kind: "plan",
1361
+ sourceKey: "STANDARD",
1362
+ sourceVersionId: null,
1363
+ titleSnapshot: "Standard",
1364
+ descriptionSnapshot: null,
1365
+ quantity: 1,
1366
+ unit: null,
1367
+ priceNet: 100,
1368
+ priceGross: 108.1,
1369
+ billingCycle: "monthly",
1370
+ // Not the installation this suite's other contracts
1371
+ // run under, and not a whole number of per cent —
1372
+ // a rate stored as an integer, or a currency taken
1373
+ // from a default, passes every other case here.
1374
+ currency: "CHF",
1375
+ taxRate: 8.1,
1376
+ taxAmount: 8.1,
1377
+ minimumTermUntil: null,
1378
+ featuresSnapshot: [],
1379
+ quotaEffectsSnapshot: {},
1380
+ metadata: null
1381
+ },
1382
+ {
1383
+ kind: "discount",
1384
+ sourceKey: "WELCOME10",
1385
+ sourceVersionId: null,
1386
+ titleSnapshot: "Welcome discount",
1387
+ descriptionSnapshot: null,
1388
+ quantity: 1,
1389
+ unit: null,
1390
+ priceNet: -10,
1391
+ priceGross: -10.81,
1392
+ billingCycle: "monthly",
1393
+ currency: "CHF",
1394
+ taxRate: 8.1,
1395
+ taxAmount: -0.81,
1396
+ minimumTermUntil: null,
1397
+ featuresSnapshot: [],
1398
+ quotaEffectsSnapshot: {},
1399
+ metadata: null
1400
+ }
1401
+ ]
1402
+ });
1403
+ const read = await contracts.findById(created.id);
1404
+ const plan = read?.lineItems.find((item) => item.kind === "plan");
1405
+ const discount = read?.lineItems.find((item) => item.kind === "discount");
1406
+ assert.ok(plan && discount, "both lines expected");
1407
+ assert.equal(plan.currency, "CHF");
1408
+ assert.equal(plan.taxRate, 8.1, "a fractional rate survives the column");
1409
+ assert.equal(plan.taxAmount, 8.1);
1410
+ assert.equal(discount.currency, "CHF");
1411
+ assert.equal(discount.taxRate, 8.1);
1412
+ assert.equal(discount.taxAmount, -0.81);
1413
+ for (const line of [plan, discount]) {
1414
+ assert.equal(
1415
+ Math.round((line.priceNet + line.taxAmount) * 100) / 100,
1416
+ line.priceGross,
1417
+ "net plus tax is gross, on every line"
1418
+ );
1419
+ }
1420
+ });
1421
+ const SETTINGS = {
1422
+ app: { name: "Demo" },
1423
+ currency: "EUR",
1424
+ vatRate: 19,
1425
+ tenantBilling: {
1426
+ cancellationNoticeDays: { monthly: 14, yearly: 90 },
1427
+ selfServiceBlockedPlans: { asTarget: ["ENTERPRISE"], asSource: [] }
1428
+ }
1429
+ };
1430
+ const SOURCE = "/srv/app/config/saas.yaml";
1431
+ const FIRST_START = /* @__PURE__ */ new Date("2026-09-01T06:30:00.000Z");
1432
+ const SECOND_START = /* @__PURE__ */ new Date("2026-09-02T06:30:00.000Z");
1433
+ const applied = (fingerprint, appliedAt, settings = SETTINGS) => ({ fingerprint, settings, source: SOURCE, appliedAt });
1434
+ const changeTo = (current, noticedAt, previous = SETTINGS) => ({ noticedAt, source: SOURCE, previous, current });
1435
+ const TWENTY = { ...SETTINGS, vatRate: 20 };
1436
+ const TWENTY_ONE = { ...SETTINGS, vatRate: 21 };
1437
+ test("no record before the first boot that could write one", async (t) => {
1438
+ const port = harness.adapter.appliedSettings;
1439
+ if (!port) {
1440
+ t.skip("adapter provides no AppliedSettingsPort");
1441
+ return;
1442
+ }
1443
+ assert.equal(await port.readApplied(), null);
1444
+ assert.deepEqual(await port.listChanges(), []);
1445
+ });
1446
+ test("the record comes back as it was written \u2014 values, source and moment", async (t) => {
1447
+ const port = harness.adapter.appliedSettings;
1448
+ if (!port) {
1449
+ t.skip("adapter provides no AppliedSettingsPort");
1450
+ return;
1451
+ }
1452
+ assert.equal(await port.writeApplied(applied("sha256-a", FIRST_START), null), true);
1453
+ const read = await port.readApplied();
1454
+ assert.ok(read, "a record expected");
1455
+ assert.equal(read.fingerprint, "sha256-a");
1456
+ assert.equal(read.source, SOURCE);
1457
+ assert.equal(read.appliedAt.toISOString(), FIRST_START.toISOString());
1458
+ assert.deepEqual(read.settings, SETTINGS);
1459
+ });
1460
+ test("writing again replaces the one row rather than adding a second", async (t) => {
1461
+ const port = harness.adapter.appliedSettings;
1462
+ if (!port) {
1463
+ t.skip("adapter provides no AppliedSettingsPort");
1464
+ return;
1465
+ }
1466
+ await port.writeApplied(applied("sha256-a", FIRST_START), null);
1467
+ assert.equal(
1468
+ await port.writeApplied(applied("sha256-b", SECOND_START, TWENTY), "sha256-a"),
1469
+ true
1470
+ );
1471
+ const read = await port.readApplied();
1472
+ assert.equal(read?.fingerprint, "sha256-b");
1473
+ assert.equal(read?.appliedAt.toISOString(), SECOND_START.toISOString());
1474
+ assert.equal((read?.settings).vatRate, 20);
1475
+ });
1476
+ test("the first record is written once: a second writer that read none is refused", async (t) => {
1477
+ const port = harness.adapter.appliedSettings;
1478
+ if (!port) {
1479
+ t.skip("adapter provides no AppliedSettingsPort");
1480
+ return;
1481
+ }
1482
+ assert.equal(await port.writeApplied(applied("sha256-a", FIRST_START), null), true);
1483
+ assert.equal(await port.writeApplied(applied("sha256-b", SECOND_START), null), false);
1484
+ assert.equal((await port.readApplied())?.fingerprint, "sha256-a");
1485
+ });
1486
+ test("a write guarded on a fingerprint the row no longer carries is refused", async (t) => {
1487
+ const port = harness.adapter.appliedSettings;
1488
+ if (!port) {
1489
+ t.skip("adapter provides no AppliedSettingsPort");
1490
+ return;
1491
+ }
1492
+ await port.writeApplied(applied("sha256-a", FIRST_START), null);
1493
+ assert.equal(
1494
+ await port.writeApplied(applied("sha256-b", SECOND_START), "sha256-a"),
1495
+ true
1496
+ );
1497
+ assert.equal(
1498
+ await port.writeApplied(applied("sha256-c", SECOND_START), "sha256-a"),
1499
+ false
1500
+ );
1501
+ const read = await port.readApplied();
1502
+ assert.equal(
1503
+ read?.fingerprint,
1504
+ "sha256-b",
1505
+ "the row stands as the first writer left it"
1506
+ );
1507
+ assert.equal(read?.appliedAt.toISOString(), SECOND_START.toISOString());
1508
+ });
1509
+ test("a change lands with the record it supersedes, and is listed newest first", async (t) => {
1510
+ const port = harness.adapter.appliedSettings;
1511
+ if (!port) {
1512
+ t.skip("adapter provides no AppliedSettingsPort");
1513
+ return;
1514
+ }
1515
+ await port.writeApplied(applied("sha256-a", FIRST_START), null);
1516
+ const first = await port.recordChange(
1517
+ changeTo(TWENTY, FIRST_START),
1518
+ applied("sha256-b", FIRST_START, TWENTY),
1519
+ "sha256-a"
1520
+ );
1521
+ const second = await port.recordChange(
1522
+ changeTo(TWENTY_ONE, SECOND_START, TWENTY),
1523
+ applied("sha256-c", SECOND_START, TWENTY_ONE),
1524
+ "sha256-b"
1525
+ );
1526
+ assert.ok(first && second, "both guards held");
1527
+ assert.ok(first.id && second.id && first.id !== second.id, "two distinct ids");
1528
+ assert.equal(first.acknowledgedAt, null);
1529
+ assert.equal(first.acknowledgedBy, null);
1530
+ assert.equal(
1531
+ (await port.readApplied())?.fingerprint,
1532
+ "sha256-c",
1533
+ "the record moved with the change"
1534
+ );
1535
+ const listed = await port.listChanges();
1536
+ assert.deepEqual(
1537
+ listed.map((c) => c.id),
1538
+ [second.id, first.id]
1539
+ );
1540
+ assert.deepEqual(listed[1].previous, SETTINGS);
1541
+ assert.equal(listed[1].current.vatRate, 20);
1542
+ assert.deepEqual(
1543
+ (await port.listChanges({ limit: 1 })).map((c) => c.id),
1544
+ [second.id]
1545
+ );
1546
+ });
1547
+ test("a change whose record has moved on is refused whole: no change, and the record as it was", async (t) => {
1548
+ const port = harness.adapter.appliedSettings;
1549
+ if (!port) {
1550
+ t.skip("adapter provides no AppliedSettingsPort");
1551
+ return;
1552
+ }
1553
+ await port.writeApplied(applied("sha256-a", FIRST_START), null);
1554
+ const refused = await port.recordChange(
1555
+ changeTo(TWENTY, SECOND_START),
1556
+ applied("sha256-b", SECOND_START, TWENTY),
1557
+ "sha256-stale"
1558
+ );
1559
+ assert.equal(refused, null);
1560
+ assert.deepEqual(await port.listChanges(), [], "no change without its record");
1561
+ const read = await port.readApplied();
1562
+ assert.equal(read?.fingerprint, "sha256-a");
1563
+ assert.equal(read?.appliedAt.toISOString(), FIRST_START.toISOString());
1564
+ });
1565
+ test("starts noticing the same difference at once record it once", async (t) => {
1566
+ const port = harness.adapter.appliedSettings;
1567
+ if (!port) {
1568
+ t.skip("adapter provides no AppliedSettingsPort");
1569
+ return;
1570
+ }
1571
+ await port.writeApplied(applied("sha256-a", FIRST_START), null);
1572
+ const attempts = await Promise.all(
1573
+ [1, 2, 3].map(
1574
+ () => port.recordChange(
1575
+ changeTo(TWENTY, SECOND_START),
1576
+ applied("sha256-b", SECOND_START, TWENTY),
1577
+ "sha256-a"
1578
+ )
1579
+ )
1580
+ );
1581
+ const recorded = attempts.filter((change) => change !== null);
1582
+ assert.equal(recorded.length, 1, "exactly one start records the change");
1583
+ assert.deepEqual(
1584
+ (await port.listChanges()).map((c) => c.id),
1585
+ [recorded[0]?.id]
1586
+ );
1587
+ assert.equal((await port.readApplied())?.fingerprint, "sha256-b");
1588
+ });
1589
+ test("several first starts write the record once", async (t) => {
1590
+ const port = harness.adapter.appliedSettings;
1591
+ if (!port) {
1592
+ t.skip("adapter provides no AppliedSettingsPort");
1593
+ return;
1594
+ }
1595
+ const written = await Promise.all(
1596
+ [1, 2, 3].map(() => port.writeApplied(applied("sha256-a", FIRST_START), null))
1597
+ );
1598
+ assert.equal(written.filter(Boolean).length, 1, "exactly one start writes it");
1599
+ assert.equal((await port.readApplied())?.fingerprint, "sha256-a");
1600
+ });
1601
+ test("changes are listed in the order they were recorded, latest first \u2014 not by the moment they carry", async (t) => {
1602
+ const port = harness.adapter.appliedSettings;
1603
+ if (!port) {
1604
+ t.skip("adapter provides no AppliedSettingsPort");
1605
+ return;
1606
+ }
1607
+ await port.writeApplied(applied("sha256-0", FIRST_START, {}), null);
1608
+ const earlierMove = await port.recordChange(
1609
+ changeTo({ vatRate: 1 }, SECOND_START, {}),
1610
+ applied("sha256-1", SECOND_START, { vatRate: 1 }),
1611
+ "sha256-0"
1612
+ );
1613
+ const laterMove = await port.recordChange(
1614
+ changeTo({ vatRate: 2 }, FIRST_START, { vatRate: 1 }),
1615
+ applied("sha256-2", FIRST_START, { vatRate: 2 }),
1616
+ "sha256-1"
1617
+ );
1618
+ assert.ok(earlierMove && laterMove, "both guards held");
1619
+ assert.deepEqual(
1620
+ (await port.listChanges()).map((c) => c.id),
1621
+ [laterMove.id, earlierMove.id]
1622
+ );
1623
+ assert.deepEqual(
1624
+ (await port.listChanges({ limit: 1 })).map((c) => c.id),
1625
+ [laterMove.id]
1626
+ );
1627
+ assert.deepEqual(
1628
+ (await port.listChanges()).map((c) => c.id),
1629
+ [laterMove.id, earlierMove.id],
1630
+ "the same order the second time it is asked"
1631
+ );
1632
+ });
1633
+ test("acknowledging a change is recorded once, and filters it out of what is owed", async (t) => {
1634
+ const port = harness.adapter.appliedSettings;
1635
+ if (!port) {
1636
+ t.skip("adapter provides no AppliedSettingsPort");
1637
+ return;
1638
+ }
1639
+ await port.writeApplied(applied("sha256-a", FIRST_START), null);
1640
+ const change = await port.recordChange(
1641
+ changeTo(TWENTY, FIRST_START),
1642
+ applied("sha256-b", FIRST_START, TWENTY),
1643
+ "sha256-a"
1644
+ );
1645
+ const open = await port.recordChange(
1646
+ changeTo(TWENTY_ONE, SECOND_START, TWENTY),
1647
+ applied("sha256-c", SECOND_START, TWENTY_ONE),
1648
+ "sha256-b"
1649
+ );
1650
+ assert.ok(change && open, "both guards held");
1651
+ const seenAt = /* @__PURE__ */ new Date("2026-09-03T08:00:00.000Z");
1652
+ const acknowledged = await port.acknowledgeChange(
1653
+ change.id,
1654
+ "web:ops@example.com:s1",
1655
+ seenAt
1656
+ );
1657
+ assert.equal(acknowledged?.acknowledgedAt?.toISOString(), seenAt.toISOString());
1658
+ assert.equal(acknowledged?.acknowledgedBy, "web:ops@example.com:s1");
1659
+ const again = await port.acknowledgeChange(
1660
+ change.id,
1661
+ "web:other@example.com:s2",
1662
+ /* @__PURE__ */ new Date("2026-09-04T08:00:00.000Z")
1663
+ );
1664
+ assert.equal(again?.acknowledgedAt?.toISOString(), seenAt.toISOString());
1665
+ assert.equal(again?.acknowledgedBy, "web:ops@example.com:s1");
1666
+ assert.deepEqual(
1667
+ (await port.listChanges({ acknowledged: false })).map((c) => c.id),
1668
+ [open.id]
1669
+ );
1670
+ assert.deepEqual(
1671
+ (await port.listChanges({ acknowledged: true })).map((c) => c.id),
1672
+ [change.id]
1673
+ );
1674
+ assert.equal(
1675
+ await port.acknowledgeChange("no-such-change", "web:ops@example.com:s1", seenAt),
1676
+ null
714
1677
  );
715
1678
  });
716
1679
  });