@mj-biz-apps/orders-core-entities-server 5.48.0 → 5.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/ChangeSubscriptionProductOperation.d.ts +45 -0
  2. package/dist/ChangeSubscriptionProductOperation.d.ts.map +1 -0
  3. package/dist/ChangeSubscriptionProductOperation.js +198 -0
  4. package/dist/ChangeSubscriptionProductOperation.js.map +1 -0
  5. package/dist/ContractIncrease.d.ts +60 -0
  6. package/dist/ContractIncrease.d.ts.map +1 -0
  7. package/dist/ContractIncrease.js +108 -0
  8. package/dist/ContractIncrease.js.map +1 -0
  9. package/dist/GetRenewalWorklistOperation.d.ts +52 -0
  10. package/dist/GetRenewalWorklistOperation.d.ts.map +1 -0
  11. package/dist/GetRenewalWorklistOperation.js +361 -0
  12. package/dist/GetRenewalWorklistOperation.js.map +1 -0
  13. package/dist/OrderEntityServer.d.ts +14 -0
  14. package/dist/OrderEntityServer.d.ts.map +1 -1
  15. package/dist/OrderEntityServer.js +57 -0
  16. package/dist/OrderEntityServer.js.map +1 -1
  17. package/dist/RenewalPassMode.d.ts +40 -0
  18. package/dist/RenewalPassMode.d.ts.map +1 -0
  19. package/dist/RenewalPassMode.js +63 -0
  20. package/dist/RenewalPassMode.js.map +1 -0
  21. package/dist/RenewalPricing.d.ts +209 -0
  22. package/dist/RenewalPricing.d.ts.map +1 -0
  23. package/dist/RenewalPricing.js +396 -0
  24. package/dist/RenewalPricing.js.map +1 -0
  25. package/dist/SetRenewalSettingsOperation.d.ts +34 -0
  26. package/dist/SetRenewalSettingsOperation.d.ts.map +1 -0
  27. package/dist/SetRenewalSettingsOperation.js +135 -0
  28. package/dist/SetRenewalSettingsOperation.js.map +1 -0
  29. package/dist/SpawnRenewalsOperation.d.ts +83 -105
  30. package/dist/SpawnRenewalsOperation.d.ts.map +1 -1
  31. package/dist/SpawnRenewalsOperation.js +352 -467
  32. package/dist/SpawnRenewalsOperation.js.map +1 -1
  33. package/dist/SubscriptionEntityServer.d.ts +10 -2
  34. package/dist/SubscriptionEntityServer.d.ts.map +1 -1
  35. package/dist/SubscriptionEntityServer.js +16 -1
  36. package/dist/SubscriptionEntityServer.js.map +1 -1
  37. package/dist/index.d.ts +9 -2
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +7 -1
  40. package/dist/index.js.map +1 -1
  41. package/package.json +2 -2
@@ -15,9 +15,19 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
15
15
  * "Is a renewal an order the customer approves, or one the system places for them?" — BOTH, and
16
16
  * `AutoRenew` is the switch. `AutoRenew = true` means the customer has already consented to
17
17
  * recurring billing, so the system places a CONFIRMED order: it books, it invoices, and coverage
18
- * continues without a gap. `AutoRenew = false` means it does not renew, full stop — this operation
19
- * skips it and the term simply ends. Reminder-and-approve for the second case is a communication
20
- * flow, not a booking one, and does not belong here.
18
+ * continues without a gap. `AutoRenew = false` means it does not renew, full stop — the scheduled
19
+ * pass skips it and the term simply ends. Reminder-and-approve for the second case is a
20
+ * communication flow, not a booking one, and does not belong here.
21
+ *
22
+ * TWO WAYS IN. The scheduled pass selects for itself: every subscription whose latest term expires
23
+ * inside its lead window and whose holder consented. The Renewals page instead names the
24
+ * subscriptions a person ticked (`SubscriptionIDs`), and for those the lead window and the consent
25
+ * switch are the person's call, not the selection's: a subscription with auto-renew OFF is placed as
26
+ * a DRAFT, an ordinary order somebody confirms once the customer agrees, while one with auto-renew
27
+ * ON is confirmed and invoiced exactly as the pass would have done it, only earlier. `PlaceAs`
28
+ * overrides that default either way. Everything else — eligibility, pricing, the term, the
29
+ * idempotency guards, the booking path — is the same code, so a renewal placed from the page is
30
+ * indistinguishable from one the pass placed.
21
31
  *
22
32
  * The order is placed at LEAD TIME, not on the expiry date, which is how subscription billing
23
33
  * actually works: the invoice goes out before the period it covers. The order carries a one-row
@@ -35,22 +45,19 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
35
45
  * 2. an explicit check for a live renewal line that has not yet produced a term — one drafted or
36
46
  * quoted by hand for this cycle. Earlier cycles' renewals each booked a term, so they do not
37
47
  * count, and a subscription keeps renewing cycle after cycle.
38
- * Running the operation twice in a row is a no-op, and that is asserted by the check suite.
48
+ * Running the operation twice in a row is a no-op, and that is asserted by the check suite. A draft
49
+ * this operation places from the page is held by the second guard like any other draft: the pass
50
+ * will not place a confirmed order beside it.
39
51
  *
40
52
  * WHAT IT RENEWS AT (golive #304)
41
53
  * Not what the customer last paid. A first-term discount lapses, a product with a successor renews
42
54
  * as the successor at its own list price, and an annual increase applies when the new term crosses
43
- * an anniversary of the subscription's start: `PriceRenewal` in orders-entities decides, and this
44
- * operation gathers its inputs. The increase is the subscription's `RenewalIncreasePercent`, else the
45
- * product's, else the nearest category's, else the company's `OrderCompanyPolicy`. The price and how
46
- * it was reached are reported on every candidate, preview included, written into the order's notes
47
- * and logged on the renewal event, so the figure can be checked before a live pass books it.
48
- *
49
- * A line that bought several terms at once (golive #338: 24 months stated on a 12-month type) at a
50
- * typed price (`PriceOverridden`) has a price covering all of them, while the renewal buys one term.
51
- * That price is cut to one term's share of it (`PriorTermShare`) before the rules above apply. An
52
- * engine-priced line already carries one term's price, whatever period it states, and is not cut. Every candidate also reports the
53
- * renewal term's start and end, decided by the same subscription behaviour the confirm runs.
55
+ * an anniversary of the subscription's start: `PriceRenewal` in orders-entities decides, and
56
+ * `RenewalPricer` (./RenewalPricing.ts) gathers its inputs. The increase is the subscription's
57
+ * `RenewalIncreasePercent`, else the product's, else the nearest category's, else the company's
58
+ * `OrderCompanyPolicy`. The price and how it was reached are reported on every candidate, preview
59
+ * included, written into the order's notes and logged on the renewal event, so the figure can be
60
+ * checked before a live pass books it.
54
61
  *
55
62
  * PROMOTIONS THAT CARRY INTO RENEWALS (#289)
56
63
  * A promotion with `AppliesToRenewals` set is presented again on each automatic renewal of a
@@ -69,53 +76,75 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
69
76
  * so extension, term creation, GL resolution and recognition are all the SAME code
70
77
  * POLICY: SubscriptionBehavior (IsRenewal bypasses ConcurrencyMode — a renewal is not a second
71
78
  * concurrent subscription, it is this one continuing)
72
- * PRICING: orders-entities PriceRenewal / ResolveRenewalIncrease / RenewalCrossesAnniversary
79
+ * PRICING: ./RenewalPricing.ts, over orders-entities PriceRenewal / ResolveRenewalIncrease / RenewalCrossesAnniversary
73
80
  * PROMOS: ./RenewalPromotions.ts (which codes, and what became of them); OrderPricingService for the preview
81
+ * PAGE: ./GetRenewalWorklistOperation.ts reads the same subjects for the Renewals page, which calls this with SubscriptionIDs
74
82
  * TABLES: __mj_BizAppsOrders.{Subscription,SubscriptionTerm,SubscriptionType,OrderHeader,OrderLine,OrderHeaderPaymentSchedule,
75
83
  * Product,ProductCategory,OrderCompanyPolicy,OrderAdjustment,PromotionCode,Promotion}
76
84
  */
77
85
  import { BaseRemotableOperation, LogError, RunView, } from '@memberjunction/core';
78
86
  import { RegisterClass } from '@memberjunction/global';
79
- import { OrdersSpawnRenewalsOperation as OrdersSpawnRenewalsOperationBase, AsDateValue, BuildLinePriceContext, LoadOrdersEngine, OrderPricingService, OrdersEngine, PriceRenewal, PriorTermShare, RenewalCrossesAnniversary, ResolvePrice, ResolveRenewalIncrease, } from '@mj-biz-apps/orders-entities';
80
- import { RequireOptionalDay, RequireOptionalUUID, RequireUUID } from './sql-guards.js';
87
+ import { OrdersSpawnRenewalsOperation as OrdersSpawnRenewalsOperationBase, OrderPricingService, RENEWABLE_STATUSES, } from '@mj-biz-apps/orders-entities';
88
+ import { RequireOptionalDay, RequireOptionalUUID, RequireUUID, RequireUUIDs } from './sql-guards.js';
81
89
  import { CalendarDayOrToday } from './calendar-day.js';
82
- import { MultiTermLineMonths, ResolveSubscriptionTypeID, SubscriptionBehaviorFor, SubscriptionTypeRulesFrom, } from './SubscriptionBehavior.js';
83
- import { NotProviderBilledSql } from './ProviderBilledSubscriptions.js';
90
+ import { IsProviderBilled, NotProviderBilledSql } from './ProviderBilledSubscriptions.js';
84
91
  import { MarkAsOrdersOwnWrite } from './OrderLineEntityServer.js';
85
92
  import { RenewalDueDate, RenewalScheduleRows } from './PaymentScheduleBehavior.js';
86
93
  import { ORDER_HEADER_PAYMENT_SCHEDULE_ENTITY } from './entity-names.js';
87
- import { ClassifyRenewalPromotionCodes, RenewalPromotionNote, SelectRenewalPromotionCodes, } from './RenewalPromotions.js';
88
- const SUBSCRIPTION_ENTITY = 'MJ_BizApps_Orders: Subscriptions';
89
- const SUBSCRIPTION_TERM_ENTITY = 'MJ_BizApps_Orders: Subscription Terms';
90
- const SUBSCRIPTION_TYPE_ENTITY = 'MJ_BizApps_Orders: Subscription Types';
94
+ import { ClassifyRenewalPromotionCodes, RenewalPromotionNote, } from './RenewalPromotions.js';
95
+ import { DayAfter, EffectiveLeadDays, NonSubscriptionSuccessorRefusal, RenewalPricer, } from './RenewalPricing.js';
96
+ // Re-exported for the callers and tests that have always imported it from here.
97
+ export { NonSubscriptionSuccessorRefusal };
91
98
  const SUBSCRIPTION_EVENT_ENTITY = 'MJ_BizApps_Orders: Subscription Events';
92
99
  const ORDER_HEADER_ENTITY = 'MJ_BizApps_Orders: Order Headers';
93
100
  const ORDER_LINE_ENTITY = 'MJ_BizApps_Orders: Order Lines';
94
101
  const ORDER_LINE_CHOICE_ENTITY = 'MJ_BizApps_Orders: Order Line Choices';
95
- const ORDER_COMPANY_POLICY_ENTITY = 'MJ_BizApps_Orders: Order Company Policies';
102
+ /** Term statuses a renewal can continue from. */
103
+ const RENEWABLE_TERM_STATUSES = ['Scheduled', 'Active'];
96
104
  /**
97
- * Why a successor chain cannot be renewed onto, or null when it can (#869).
98
- *
99
- * A successor that resolves no subscription type would book the renewal as a plain line with no
100
- * term, and every later pass would then skip the subscription as already renewed. So the candidate
101
- * is skipped with this reason instead. The subscription's own product (the first entry) is not
102
- * checked: it already holds the subscription.
105
+ * Which renewal order a subscription renews on: one per selling company, customer (holder
106
+ * organization and beneficiary person), expiring term end date, placement and renewal card. Two
107
+ * subscriptions with the same key renew on ONE order with a line each. Exported so the rule can
108
+ * be read and tested on its own.
103
109
  */
104
- export function NonSubscriptionSuccessorRefusal(chain) {
105
- for (let i = 1; i < chain.length; i++) {
106
- if (chain[i].SubscriptionTypeID)
107
- continue;
108
- return (`${chain[i - 1].Name} names ${chain[i].Name} as its successor, but ${chain[i].Name} is not a subscription ` +
109
- `product (neither it nor its product type has a subscription type), so the renewal cannot be placed on it. ` +
110
- `Give ${chain[i].Name} a subscription type or change the successor.`);
111
- }
112
- return null;
110
+ export function RenewalGroupKey(due, placeAs) {
111
+ const part = (v) => (v == null ? '' : String(v).toLowerCase());
112
+ return [part(due.CompanyID), part(due.HolderOrganizationID), part(due.BeneficiaryPersonID), part(due.TermEndDate), placeAs, part(due.DefaultCustomerPaymentMethodID)].join('|');
113
113
  }
114
+ /** The columns both selections read, under the aliases the rest of the file uses. */
115
+ const SUBJECT_COLUMNS = `
116
+ s.ID AS SubscriptionID,
117
+ s.SubscriptionNumber,
118
+ s.Status AS SubscriptionStatus,
119
+ s.SubscriptionTypeID,
120
+ s.CompanyID,
121
+ s.ProductID,
122
+ s.HolderOrganizationID,
123
+ s.BeneficiaryPersonID,
124
+ s.AutoRenew,
125
+ s.ProviderSubscriptionID,
126
+ s.RenewalLeadDays AS SubscriptionRenewalLeadDays,
127
+ t.RenewalLeadDays AS TypeRenewalLeadDays,
128
+ s.StartDate AS SubscriptionStartDate,
129
+ s.RenewalIncreasePercent AS SubscriptionIncreasePercent,
130
+ s.CarryDiscountOnRenewal,
131
+ s.DefaultCustomerPaymentMethodID,
132
+ l.ID AS TermID,
133
+ l.TermNumber,
134
+ l.StartDate AS TermStartDate,
135
+ l.EndDate AS TermEndDate,
136
+ l.Status AS TermStatus,
137
+ l.Quantity AS TermQuantity,
138
+ l.OrderLineID`;
114
139
  let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRenewalsOperationBase {
115
140
  async InternalExecute(input, provider, user) {
116
141
  // Caller-supplied ids reach SQL filter text downstream. Validated here,
117
142
  // at the boundary, so every frame below this one can trust them.
118
143
  RequireOptionalUUID(input.SubscriptionID, 'SubscriptionID');
144
+ const selected = input.SubscriptionIDs?.length ? RequireUUIDs(input.SubscriptionIDs, 'SubscriptionIDs') : null;
145
+ if (input.PlaceAs !== undefined && input.PlaceAs !== 'Confirmed' && input.PlaceAs !== 'Draft') {
146
+ return { Success: false, Message: `PlaceAs takes 'Confirmed' or 'Draft', not '${String(input.PlaceAs)}'.`, Candidates: [], Placed: 0, Skipped: 0 };
147
+ }
119
148
  // "Due" is decided against `date` columns, so the as-of value is a calendar day (#209):
120
149
  // an instant answers the UTC day, and an evening run would spawn tomorrow's renewals a day
121
150
  // early. Validated at the boundary like the id above, because a renewal pass silently run
@@ -128,28 +157,49 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
128
157
  return { Success: false, Message: String(e.message), Candidates: [], Placed: 0, Skipped: 0 };
129
158
  }
130
159
  const asOf = await CalendarDayOrToday(input.AsOfDate, provider, user);
131
- const candidates = await this.findDue(provider, user, asOf, input.SubscriptionID);
132
160
  const out = { Success: true, Candidates: [], Placed: 0, Skipped: 0 };
161
+ const candidates = selected
162
+ ? await this.findSelected(provider, selected, out)
163
+ : await this.findDue(provider, user, asOf, input.SubscriptionID);
164
+ const pricer = new RenewalPricer(provider, user);
133
165
  const limit = input.MaxCount ?? Number.MAX_SAFE_INTEGER;
134
166
  /**
135
- * Orders this pass has committed to: PLACED on a live pass, WOULD-place on a preview.
167
+ * ONE ORDER PER CUSTOMER PER RENEWAL DATE. Subscriptions that renew together (`RenewalGroupKey`:
168
+ * same selling company, holder and beneficiary, expiring term end, placement and renewal
169
+ * card, and no carried promotion codes) go on one order with one line each, so a customer
170
+ * who bought three products together gets one renewal order and one invoice, not three. A
171
+ * product added mid-term joins only when it was co-terminated to end on the same day;
172
+ * otherwise it ends on its own date and renews on its own order.
136
173
  *
137
- * Counted separately from `Placed` because the cap has to bind identically in both modes.
138
- * Keyed on `Placed`, it never binds on a preview — `Placed` stays 0 — so the preview
139
- * enumerates every due subscription while the live pass stops at the cap, and the list a
140
- * person confirms at the go-live gate is not the list the first live pass produces. A
141
- * candidate the idempotency guard rejects does not consume the cap: nothing was placed.
174
+ * The cap counts ORDERS, placed on a live pass and would-place on a preview, so it binds
175
+ * identically in both modes and the list a person confirms at the go-live gate is the list
176
+ * the first live pass produces. A subscription joining an order already counted costs
177
+ * nothing; one that would open a new order past the cap waits for the next pass, unlisted,
178
+ * as before. A guard rejection or a pricing failure does not consume the cap: nothing was
179
+ * placed. (A member carrying promotion codes renews on its own order, decided only once it
180
+ * is priced, so a pass can overshoot the cap by that one order; its base key is not counted
181
+ * as open, so a code-free sibling cannot open a second one on its account. A group that
182
+ * fails and is retried one member at a time, below, can overshoot it the same way.)
142
183
  */
143
- let committed = 0;
184
+ const groups = new Map();
185
+ /** Each order's 1-based number in this pass, assigned when its group opens. */
186
+ const groupIndex = new Map();
144
187
  for (const due of candidates) {
145
- if (committed >= limit)
146
- break;
188
+ const placeAs = input.PlaceAs ?? (selected && !due.AutoRenew ? 'Draft' : 'Confirmed');
189
+ const baseKey = RenewalGroupKey(due, placeAs);
190
+ // Past the cap, a subscription that would OPEN an order waits for the next pass, unlisted;
191
+ // one that JOINS an order already open still goes on it. `continue`, not `break`: a later
192
+ // candidate may belong to an open order, and breaking would split a customer across passes.
193
+ if (groups.size >= limit && !groups.has(baseKey))
194
+ continue;
147
195
  const candidate = {
148
196
  SubscriptionID: due.SubscriptionID,
149
197
  SubscriptionNumber: due.SubscriptionNumber,
150
198
  ProductID: due.ProductID,
151
199
  CurrentTermEnd: due.TermEndDate,
152
- LeadDays: due.SubscriptionRenewalLeadDays ?? due.TypeRenewalLeadDays ?? 0,
200
+ LeadDays: EffectiveLeadDays(due),
201
+ AutoRenew: !!due.AutoRenew,
202
+ OrderStatus: placeAs,
153
203
  };
154
204
  out.Candidates.push(candidate);
155
205
  // Second idempotency guard — see the header. Cheap, and it is the one that saves a
@@ -164,7 +214,7 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
164
214
  // not consume the cap.
165
215
  let priced;
166
216
  try {
167
- priced = await this.priceRenewal(provider, user, due);
217
+ priced = await pricer.Price(due);
168
218
  }
169
219
  catch (err) {
170
220
  const message = err instanceof Error ? err.message : String(err);
@@ -180,6 +230,7 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
180
230
  candidate.IncreaseSource = priced.Price.IncreaseSource;
181
231
  candidate.UnitPrice = priced.Price.UnitPrice;
182
232
  candidate.DiscountPct = priced.Price.DiscountPct;
233
+ candidate.Quantity = priced.Quantity;
183
234
  if (priced.Term) {
184
235
  candidate.RenewalTermStart = priced.Term.Start;
185
236
  candidate.RenewalTermEnd = priced.Term.End;
@@ -202,30 +253,55 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
202
253
  }
203
254
  }
204
255
  out.Skipped++;
205
- committed++;
206
- continue;
207
256
  }
208
- try {
209
- const order = await this.placeRenewal(provider, user, due, priced, asOf.toISOString().slice(0, 10));
210
- candidate.OrderID = order.ID;
211
- candidate.OrderNumber = order.Number;
212
- if (order.Promotions)
213
- this.reportPromotions(candidate, order.Promotions);
214
- out.Placed++;
215
- committed++;
216
- }
217
- catch (err) {
218
- // One subscription's failure must not stop the batch — an unattended job that
219
- // aborts on the first bad row silently stops renewing everyone behind it.
220
- const message = err instanceof Error ? err.message : String(err);
221
- LogError(`Orders.SpawnRenewals: ${due.SubscriptionNumber} failed: ${message}`);
222
- candidate.SkippedReason = message;
223
- out.Skipped++;
257
+ // Carried promotion codes are presented at ORDER level, where the engine applies each to
258
+ // every line it targets. A line that carried a code therefore renews alone, so a code one
259
+ // purchase earned never discounts a sibling that did not carry it.
260
+ const key = priced.PromotionCodes.length ? `${baseKey}|codes|${due.SubscriptionID}` : baseKey;
261
+ const members = groups.get(key) ?? [];
262
+ members.push({ due, priced, candidate, placeAs });
263
+ groups.set(key, members);
264
+ if (!groupIndex.has(key))
265
+ groupIndex.set(key, groupIndex.size + 1);
266
+ candidate.OrderGroup = groupIndex.get(key);
267
+ }
268
+ let placedSubscriptions = 0;
269
+ if (!input.Preview) {
270
+ const day = asOf.toISOString().slice(0, 10);
271
+ let nextGroup = groupIndex.size;
272
+ for (const members of groups.values()) {
273
+ // One order's failure must not stop the batch — an unattended job that aborts on
274
+ // the first bad row silently stops renewing everyone behind it.
275
+ if (await this.tryPlaceGroup(provider, user, members, day, !!selected, out)) {
276
+ placedSubscriptions += members.length;
277
+ continue;
278
+ }
279
+ if (members.length === 1) {
280
+ out.Skipped++;
281
+ continue;
282
+ }
283
+ // ONE MEMBER'S FAILURE HOLDS BACK ONLY ITSELF. The group's order is one transaction,
284
+ // so a member that cannot be booked (an unresolved GL account, a refused line) rolled
285
+ // every sibling back with it. Retried one member at a time, the healthy ones place
286
+ // on orders of their own and only the broken one waits, which is what the pass did
287
+ // before orders were grouped: a scheduled pass that skipped the whole customer
288
+ // would repeat that every night until someone fixed the one subscription.
289
+ members.forEach((m, i) => {
290
+ // Each now stands for an order of its own: the first keeps the group's number.
291
+ if (i > 0)
292
+ m.candidate.OrderGroup = ++nextGroup;
293
+ });
294
+ for (const m of members) {
295
+ if (await this.tryPlaceGroup(provider, user, [m], day, !!selected, out))
296
+ placedSubscriptions++;
297
+ else
298
+ out.Skipped++;
299
+ }
224
300
  }
225
301
  }
226
302
  out.Message =
227
- `${out.Candidates.length} subscription(s) due as of ${asOf.toISOString().slice(0, 10)}; ` +
228
- `${out.Placed} renewal order(s) placed, ${out.Skipped} skipped.`;
303
+ `${out.Candidates.length} subscription(s) ${selected ? 'selected' : 'due'} as of ${asOf.toISOString().slice(0, 10)}; ` +
304
+ `${out.Placed} renewal order(s) placed for ${placedSubscriptions} subscription(s), ${out.Skipped} skipped.`;
229
305
  return out;
230
306
  }
231
307
  /**
@@ -246,27 +322,7 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
246
322
  SELECT st.*, ROW_NUMBER() OVER (PARTITION BY st.SubscriptionID ORDER BY st.TermNumber DESC) AS rn
247
323
  FROM __mj_BizAppsOrders.SubscriptionTerm st
248
324
  )
249
- SELECT
250
- s.ID AS SubscriptionID,
251
- s.SubscriptionNumber,
252
- s.Status AS SubscriptionStatus,
253
- s.SubscriptionTypeID,
254
- s.CompanyID,
255
- s.ProductID,
256
- s.HolderOrganizationID,
257
- s.BeneficiaryPersonID,
258
- s.RenewalLeadDays AS SubscriptionRenewalLeadDays,
259
- t.RenewalLeadDays AS TypeRenewalLeadDays,
260
- s.StartDate AS SubscriptionStartDate,
261
- s.RenewalIncreasePercent AS SubscriptionIncreasePercent,
262
- s.CarryDiscountOnRenewal,
263
- s.DefaultCustomerPaymentMethodID,
264
- l.ID AS TermID,
265
- l.TermNumber,
266
- l.StartDate AS TermStartDate,
267
- l.EndDate AS TermEndDate,
268
- l.Quantity AS TermQuantity,
269
- l.OrderLineID
325
+ SELECT${SUBJECT_COLUMNS}
270
326
  FROM __mj_BizAppsOrders.Subscription s
271
327
  JOIN __mj_BizAppsOrders.SubscriptionType t ON t.ID = s.SubscriptionTypeID
272
328
  JOIN latest l ON l.SubscriptionID = s.ID AND l.rn = 1
@@ -285,6 +341,56 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
285
341
  `));
286
342
  return Array.isArray(rows) ? rows : [];
287
343
  }
344
+ /**
345
+ * The subscriptions a person named, each with its latest term, whatever the switch or the window
346
+ * say. The rules the scheduled selection puts in its WHERE are applied here instead, so an
347
+ * ineligible choice comes back as a skipped candidate with its reason: a person who ticked a
348
+ * cancelled subscription is told so, where the pass would simply not have seen it.
349
+ */
350
+ async findSelected(provider, ids, out) {
351
+ const db = provider;
352
+ const wanted = [...new Set(ids.map((id) => id.toLowerCase()))];
353
+ const list = wanted.map((id) => `'${id}'`).join(',');
354
+ const rows = (await db.ExecuteSQL(`
355
+ WITH latest AS (
356
+ SELECT st.*, ROW_NUMBER() OVER (PARTITION BY st.SubscriptionID ORDER BY st.TermNumber DESC) AS rn
357
+ FROM __mj_BizAppsOrders.SubscriptionTerm st
358
+ )
359
+ SELECT${SUBJECT_COLUMNS}
360
+ FROM __mj_BizAppsOrders.Subscription s
361
+ JOIN __mj_BizAppsOrders.SubscriptionType t ON t.ID = s.SubscriptionTypeID
362
+ LEFT JOIN latest l ON l.SubscriptionID = s.ID AND l.rn = 1
363
+ WHERE s.ID IN (${list})
364
+ ORDER BY l.EndDate, s.SubscriptionNumber
365
+ `));
366
+ const found = Array.isArray(rows) ? rows : [];
367
+ const seen = new Set(found.map((r) => String(r.SubscriptionID).toLowerCase()));
368
+ for (const id of wanted) {
369
+ if (seen.has(id))
370
+ continue;
371
+ out.Candidates.push({ SubscriptionID: id, SubscriptionNumber: '—', ProductID: '', CurrentTermEnd: '', LeadDays: 0, SkippedReason: 'no such subscription' });
372
+ out.Skipped++;
373
+ }
374
+ const eligible = [];
375
+ for (const row of found) {
376
+ const refusal = SelectedRenewalRefusal(row);
377
+ if (!refusal) {
378
+ eligible.push(row);
379
+ continue;
380
+ }
381
+ out.Candidates.push({
382
+ SubscriptionID: row.SubscriptionID,
383
+ SubscriptionNumber: row.SubscriptionNumber,
384
+ ProductID: row.ProductID,
385
+ CurrentTermEnd: row.TermEndDate ?? '',
386
+ LeadDays: EffectiveLeadDays(row),
387
+ AutoRenew: !!row.AutoRenew,
388
+ SkippedReason: refusal,
389
+ });
390
+ out.Skipped++;
391
+ }
392
+ return eligible;
393
+ }
288
394
  /**
289
395
  * True when a renewal order for this cycle already exists.
290
396
  *
@@ -308,17 +414,39 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
308
414
  return Array.isArray(pending) && pending.length > 0;
309
415
  }
310
416
  /**
311
- * Place the renewal as an ordinary confirmed order.
312
- *
313
- * Deliberately NOT a special write path: routing it through `OrderEntityServer.Save` means the
314
- * extension, the new term, GL resolution, the recognition schedule and the all-or-none
315
- * guarantee are the same code that handles a customer purchase. A bespoke renewal writer would
316
- * be a second implementation of booking, drifting from the first.
317
- *
318
- * `invoiceDay` is the pass's as-of day, `YYYY-MM-DD`: the renewal invoice date. The one-row
319
- * schedule the order carries is due that day plus the customer's terms, capped at the order date (#305).
417
+ * Place a group's order and report it on every member; on failure, record the reason on every
418
+ * member and say so. Counts the order in `out.Placed`; the caller decides what a failure counts
419
+ * as, since a failed group is retried a member at a time.
420
+ */
421
+ async tryPlaceGroup(provider, user, members, invoiceDay, selectedByPerson, out) {
422
+ try {
423
+ const order = await this.placeRenewalGroup(provider, user, members, invoiceDay, members[0].placeAs, selectedByPerson);
424
+ for (const m of members) {
425
+ m.candidate.OrderID = order.ID;
426
+ m.candidate.OrderNumber = order.Number;
427
+ delete m.candidate.SkippedReason;
428
+ if (order.Promotions)
429
+ this.reportPromotions(m.candidate, order.Promotions);
430
+ }
431
+ out.Placed++;
432
+ return true;
433
+ }
434
+ catch (err) {
435
+ const message = err instanceof Error ? err.message : String(err);
436
+ LogError(`Orders.SpawnRenewals: ${members.map((m) => m.due.SubscriptionNumber).join(', ')} failed: ${message}`);
437
+ for (const m of members)
438
+ m.candidate.SkippedReason = message;
439
+ return false;
440
+ }
441
+ }
442
+ /**
443
+ * Place ONE renewal order for a group of subscriptions that renew together (one line each), as a
444
+ * draft or confirmed, inside one transaction: all of it or none of it. The header comes from the
445
+ * first member; the group key guarantees every member agrees on it.
320
446
  */
321
- async placeRenewal(provider, user, due, priced, invoiceDay) {
447
+ async placeRenewalGroup(provider, user, members, invoiceDay, placeAs, selectedByPerson) {
448
+ const first = members[0].due;
449
+ const numbers = members.map((m) => m.due.SubscriptionNumber).join(', ');
322
450
  const dbProvider = provider;
323
451
  await dbProvider.BeginTransaction();
324
452
  try {
@@ -327,64 +455,69 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
327
455
  order.OrderType = 'Sale';
328
456
  // Dated the day AFTER the expiring term, so the new term starts where the old one ends
329
457
  // and the ledger shows the sale in the period it belongs to — not on the day the job
330
- // happened to run.
331
- order.OrderDate = this.dayAfter(due.TermEndDate);
458
+ // happened to run. Every member ends on the same day (the group key).
459
+ order.OrderDate = DayAfter(first.TermEndDate);
332
460
  // A catch-up run (an as-of day before today) invoices the instalment on that day, the day
333
461
  // its due date is counted from, so it does not book it today (#831). An as-of day in the
334
462
  // future still invoices today: AR is never dated ahead of the day it is raised.
335
463
  const today = (await CalendarDayOrToday(null, provider, user)).toISOString().slice(0, 10);
336
464
  order.InstalmentInvoiceDay = invoiceDay < today ? invoiceDay : null;
337
- order.CompanyID = due.CompanyID;
338
- order.BillToOrganizationID = due.HolderOrganizationID;
339
- order.BillToPersonID = due.BeneficiaryPersonID;
340
- order.Notes = this.renewalNotes(due, priced);
341
- const line = await provider.GetEntityObject(ORDER_LINE_ENTITY, user);
342
- // Orders writing its own line. An app that froze this line freezes what a PERSON
343
- // may change, not Orders closing its own books (#206 item 1).
344
- MarkAsOrdersOwnWrite(line);
345
- line.NewRecord();
346
- // The successor when the subscription moves to one; booking then moves the subscription
347
- // onto it (OrderEntityServer.touchExistingSubscription).
348
- line.ProductID = priced.ProductID;
349
- line.LineNumber = 1;
350
- // Per-LINE (D61): renewal is a line-level act, so one order could renew several
351
- // subscriptions. Naming the target also removes the guesswork from resolution — the
352
- // engine renews exactly this one rather than searching by subscriber and product.
353
- line.RenewsSubscriptionID = due.SubscriptionID;
354
- // The subscription's own subscriber, carried onto the line's ship-to so the renewal
355
- // lands on the same holder even when the order's customer differs.
356
- line.ShipToOrganizationID = due.HolderOrganizationID;
357
- line.ShipToPersonID = due.BeneficiaryPersonID;
358
- // What `priceRenewal` decided (golive #304). Stated on the line, so pricing keeps it rather
359
- // than resolving today's list price. It is the pass's own deliberate price, not a typed
360
- // concession, so the order is told which lines it priced: the concession gate and the
361
- // below-engine review leave them alone while their price is unchanged.
362
- line.Quantity = priced.Quantity;
363
- line.UnitPrice = priced.Price.UnitPrice;
364
- line.DiscountPct = priced.Price.DiscountPct;
365
- order.MarkRenewalPriced(line);
465
+ order.CompanyID = first.CompanyID;
466
+ order.BillToOrganizationID = first.HolderOrganizationID;
467
+ order.BillToPersonID = first.BeneficiaryPersonID;
468
+ order.Notes = this.renewalNotes(members, null, placeAs, selectedByPerson);
469
+ const codes = [...new Set(members.flatMap((m) => m.priced.PromotionCodes.map((c) => c.Code)))];
470
+ let lineNumber = 0;
471
+ for (const { due, priced } of members) {
472
+ const line = await provider.GetEntityObject(ORDER_LINE_ENTITY, user);
473
+ // Orders writing its own line. An app that froze this line freezes what a PERSON
474
+ // may change, not Orders closing its own books (#206 item 1).
475
+ MarkAsOrdersOwnWrite(line);
476
+ line.NewRecord();
477
+ // The successor when the subscription moves to one; booking then moves the subscription
478
+ // onto it (OrderEntityServer.touchExistingSubscription).
479
+ line.ProductID = priced.ProductID;
480
+ line.LineNumber = ++lineNumber;
481
+ // Per-LINE (D61): renewal is a line-level act, which is what lets one order renew
482
+ // several subscriptions. Naming the target also removes the guesswork from resolution:
483
+ // the engine renews exactly this one rather than searching by subscriber and product.
484
+ line.RenewsSubscriptionID = due.SubscriptionID;
485
+ // The subscription's own subscriber, carried onto the line's ship-to so the renewal
486
+ // lands on the same holder even when the order's customer differs.
487
+ line.ShipToOrganizationID = due.HolderOrganizationID;
488
+ line.ShipToPersonID = due.BeneficiaryPersonID;
489
+ // What the pricer decided (golive #304). Stated on the line, so pricing keeps it rather
490
+ // than resolving today's list price. It is the pass's own deliberate price, not a typed
491
+ // concession, so the order is told which lines it priced: the concession gate and the
492
+ // below-engine review leave them alone while their price is unchanged.
493
+ line.Quantity = priced.Quantity;
494
+ line.UnitPrice = priced.Price.UnitPrice;
495
+ line.DiscountPct = priced.Price.DiscountPct;
496
+ order.MarkRenewalPriced(line);
497
+ // Attached rather than assigned — see the note in CancelSubscriptionOperation.
498
+ order.Lines.Add(line);
499
+ // The buyer's choices carry forward (#291). A conditional entitlement is granted only on a
500
+ // line that carries its choice, so a renewal without them would silently drop the access
501
+ // the buyer chose. They ride in the line's graph and save with the draft.
502
+ for (const choice of await this.loadSourceChoices(provider, user, due.OrderLineID)) {
503
+ const row = await line.Choices.Create();
504
+ row.GroupKey = choice.GroupKey;
505
+ row.GroupLabel = choice.GroupLabel;
506
+ row.OptionValue = choice.OptionValue;
507
+ row.OptionLabel = choice.OptionLabel;
508
+ }
509
+ }
366
510
  // Promotions that carry into renewals (#289), through the ordinary promotion path: the
367
511
  // engine decides whether each still applies, and writes the discount as an adjustment.
368
- if (priced.PromotionCodes.length) {
369
- order.PromotionCodes.Codes = priced.PromotionCodes.map((c) => c.Code);
370
- }
371
- // Attached rather than assigned — see the note in CancelSubscriptionOperation.
372
- order.Lines.Add(line);
373
- // The buyer's choices carry forward (#291). A conditional entitlement is granted only on a
374
- // line that carries its choice, so a renewal without them would silently drop the access
375
- // the buyer chose. They ride in the line's graph and save with the draft.
376
- for (const choice of await this.loadSourceChoices(provider, user, due.OrderLineID)) {
377
- const row = await line.Choices.Create();
378
- row.GroupKey = choice.GroupKey;
379
- row.GroupLabel = choice.GroupLabel;
380
- row.OptionValue = choice.OptionValue;
381
- row.OptionLabel = choice.OptionLabel;
512
+ // (A member carrying codes is always alone on its order; see the grouping note.)
513
+ if (codes.length) {
514
+ order.PromotionCodes.Codes = codes;
382
515
  }
383
516
  // DRAFT FIRST, THEN THE SCHEDULE, THEN CONFIRM (#305). The renewal is invoiced on the day
384
517
  // this pass runs, not on its term start, so it carries a one-row schedule due today and
385
518
  // D92 books it that way: no AR at confirm, and the instalment — due on or before the
386
519
  // order date — is issued inside the same confirm, dated when it is issued. The row must
387
- // tie to the line's gross, and that gross exists only once pricing has written the line,
520
+ // tie to the lines' gross, and that gross exists only once pricing has written the lines,
388
521
  // which is what the draft save does. All of it sits in this transaction.
389
522
  order.Status = 'Draft';
390
523
  if (!(await order.Save())) {
@@ -393,22 +526,33 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
393
526
  // What became of the carried promotions, known once the draft's pricing has run. Written
394
527
  // into the notes before the confirm, which re-decides the same codes on the same date.
395
528
  let promotions = null;
396
- if (priced.PromotionCodes.length) {
397
- promotions = ClassifyRenewalPromotionCodes(priced.PromotionCodes.map((c) => c.Code), order.UnusablePromotionCodes, await this.appliedCodes(provider, order.ID, priced.PromotionCodes));
398
- order.Notes = this.renewalNotes(due, priced, promotions);
529
+ if (codes.length) {
530
+ const presented = members.flatMap((m) => m.priced.PromotionCodes);
531
+ promotions = ClassifyRenewalPromotionCodes(codes, order.UnusablePromotionCodes, await this.appliedCodes(provider, order.ID, presented));
532
+ order.Notes = this.renewalNotes(members, promotions, placeAs, selectedByPerson);
399
533
  }
400
- // Due on the invoice day plus the customer's terms, capped at the order date (#305
401
- // review). `resolveDueDate` is the confirm's own terms walk, run now so the row can use
402
- // it; confirm then sees the date already set and leaves it. A subscription with a renewal
403
- // card is due on the order date, the day `ChargeRenewals` first charges the card (#289).
404
- await order.resolveDueDate();
405
- const rowDueDate = RenewalDueDate(invoiceDay, order.OrderDate, order.DueDate, !!due.DefaultCustomerPaymentMethodID);
406
- await this.addRenewalSchedule(provider, user, order.ID, String(order.CompanyID), order.Lines.Items, rowDueDate);
407
- order.Status = 'Confirmed';
408
- if (!(await order.Save())) {
409
- throw new Error(`Failed to book renewal order ${order.OrderNumber} of ${due.SubscriptionNumber}: ${order.LatestResult?.CompleteMessage ?? 'unknown error'}`);
534
+ if (placeAs === 'Draft') {
535
+ // The notes may have changed above; a draft's second save is the ordinary draft save.
536
+ if (promotions && !(await order.Save())) {
537
+ throw new Error(`Failed to save the renewal draft ${order.OrderNumber} of ${numbers}: ${order.LatestResult?.CompleteMessage ?? 'unknown error'}`);
538
+ }
539
+ }
540
+ else {
541
+ // Due on the invoice day plus the customer's terms, capped at the order date (#305
542
+ // review). `resolveDueDate` is the confirm's own terms walk, run now so the row can use
543
+ // it; confirm then sees the date already set and leaves it. A subscription with a renewal
544
+ // card is due on the order date, the day `ChargeRenewals` first charges the card (#289).
545
+ await order.resolveDueDate();
546
+ const rowDueDate = RenewalDueDate(invoiceDay, order.OrderDate, order.DueDate, !!first.DefaultCustomerPaymentMethodID);
547
+ await this.addRenewalSchedule(provider, user, order.ID, String(order.CompanyID), order.Lines.Items, rowDueDate);
548
+ order.Status = 'Confirmed';
549
+ if (!(await order.Save())) {
550
+ throw new Error(`Failed to book renewal order ${order.OrderNumber} of ${numbers}: ${order.LatestResult?.CompleteMessage ?? 'unknown error'}`);
551
+ }
552
+ }
553
+ for (const { due, priced } of members) {
554
+ await this.logEvent(provider, user, due, priced, order.ID, promotions, placeAs, selectedByPerson);
410
555
  }
411
- await this.logEvent(provider, user, due, priced, order.ID, promotions);
412
556
  await dbProvider.CommitTransaction();
413
557
  return { ID: order.ID, Number: order.OrderNumber, Promotions: promotions };
414
558
  }
@@ -439,168 +583,6 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
439
583
  }
440
584
  }
441
585
  }
442
- /**
443
- * What the renewal line is written with: product, quantity and price (golive #304).
444
- *
445
- * Read-only, so a preview runs it too. Throws with a reason a person can act on when the
446
- * renewal cannot be priced; the caller skips that candidate.
447
- */
448
- async priceRenewal(provider, user, due) {
449
- const source = await this.loadSourceLine(provider, user, due.OrderLineID);
450
- if (!source) {
451
- throw new Error(`The order line that bought term ${due.TermNumber} (${due.OrderLineID}) no longer exists, ` +
452
- `so there is no price to renew at.`);
453
- }
454
- const chain = await this.loadSuccessorChain(provider, due.ProductID);
455
- const notSubscription = NonSubscriptionSuccessorRefusal(chain);
456
- if (notSubscription)
457
- throw new Error(notSubscription);
458
- const product = chain[chain.length - 1];
459
- const movesToSuccessor = chain.length > 1;
460
- const quantity = this.renewalQuantity(due);
461
- const renewalDay = this.dayAfter(due.TermEndDate);
462
- const carry = !!due.CarryDiscountOnRenewal;
463
- await LoadOrdersEngine(provider, user);
464
- const priorLineMonths = this.priorLineMonths(due, source);
465
- const share = priorLineMonths == null ? 1 : PriorTermShare(priorLineMonths, this.termMonthsOf(due));
466
- // A list price is resolved only where the rule needs one: the successor's as of the renewal
467
- // day, or the prior product's as of the prior order when a price typed below it may lapse.
468
- const successorList = movesToSuccessor
469
- ? await this.listPrice(provider, user, { ...source, ProductID: product.ID, Quantity: quantity, UnitPrice: null, ProductPriceID: null }, renewalDay)
470
- : undefined;
471
- const priorList = !movesToSuccessor && source.PriceOverridden && !carry
472
- ? await this.listPrice(provider, user, { ...source, Quantity: quantity }, null)
473
- : null;
474
- const increase = ResolveRenewalIncrease({
475
- Subscription: due.SubscriptionIncreasePercent,
476
- Product: product.RenewalIncreasePercent,
477
- Categories: await this.loadCategoryIncreases(provider, product.ProductCategoryID),
478
- Company: await this.loadCompanyIncrease(provider, user, due.CompanyID),
479
- });
480
- let price;
481
- try {
482
- price = PriceRenewal({
483
- PriorUnitPrice: Number(source.UnitPrice),
484
- PriorTermShare: share,
485
- PriorDiscountPct: source.DiscountPct,
486
- PriorPriceOverridden: !!source.PriceOverridden,
487
- PriorListPrice: priorList,
488
- SuccessorListPrice: successorList,
489
- CarryDiscount: carry,
490
- Increase: increase,
491
- ApplyIncrease: RenewalCrossesAnniversary(due.SubscriptionStartDate, due.TermStartDate, renewalDay),
492
- });
493
- }
494
- catch (err) {
495
- throw new Error(`${due.SubscriptionNumber} moves to ${product.Name} at renewal, but ` +
496
- `${err instanceof Error ? err.message : String(err)}. Add a price for ${product.Name}.`);
497
- }
498
- return {
499
- ProductID: product.ID,
500
- ProductName: product.Name,
501
- MovesToSuccessor: movesToSuccessor,
502
- Quantity: quantity,
503
- Price: price,
504
- // Only a typed price is cut (see `PriceRenewal`), so only that one is reported as a share.
505
- PriorLineMonths: share < 1 && source.PriceOverridden ? priorLineMonths : null,
506
- Term: this.renewalTerm(due, product),
507
- PromotionCodes: await this.loadRenewalPromotionCodes(provider, source),
508
- };
509
- }
510
- /**
511
- * The months the source line's price covers when that line bought earlier terms too, or null
512
- * (golive #338). Read from the line's service period, which the confirm sets to the whole coverage.
513
- */
514
- priorLineMonths(due, source) {
515
- const day = (v) => (v ? new Date(`${new Date(v).toISOString().slice(0, 10)}T00:00:00Z`) : null);
516
- return MultiTermLineMonths(day(source.ServicePeriodStart), day(source.ServicePeriodEnd), day(due.TermStartDate));
517
- }
518
- /**
519
- * The term length of the subscription's own type: the length the confirm split the source line
520
- * by. Throws when the type cannot be read, since renewing at the whole line's price would bill
521
- * the customer for every term the line already paid for.
522
- */
523
- termMonthsOf(due) {
524
- const rules = this.rulesFor(due.SubscriptionTypeID);
525
- if (!rules) {
526
- throw new Error(`${due.SubscriptionNumber}'s subscription type (${due.SubscriptionTypeID}) was not found, so the share ` +
527
- `of its multi-term line one renewal term is worth cannot be worked out.`);
528
- }
529
- return SubscriptionBehaviorFor(rules).TermMonths(rules);
530
- }
531
- /**
532
- * The term the renewal buys, decided the way the confirm decides it: the renewal product's
533
- * subscription type and behaviour, continuing the subscription from the day after its latest term.
534
- * Null when that cannot be decided here (no type, an unregistered driver, a rejection); the
535
- * confirm then reports the reason itself.
536
- */
537
- renewalTerm(due, product) {
538
- const typeID = ResolveSubscriptionTypeID(product.SubscriptionTypeID, OrdersEngine.Instance.ProductTypeByID(product.ProductTypeID)?.DefaultSubscriptionTypeID ?? null);
539
- const rules = this.rulesFor(typeID);
540
- if (!rules)
541
- return null;
542
- try {
543
- const holder = { OrganizationID: due.HolderOrganizationID ?? null, PersonID: due.BeneficiaryPersonID ?? null };
544
- const decision = SubscriptionBehaviorFor(rules).Decide({
545
- Rules: rules,
546
- PurchaseDate: this.dayAfter(due.TermEndDate),
547
- Amount: 0,
548
- Existing: {
549
- ID: due.SubscriptionID,
550
- Status: due.SubscriptionStatus,
551
- HolderOrganizationID: holder.OrganizationID,
552
- BeneficiaryPersonID: holder.PersonID,
553
- LatestTermEnd: new Date(due.TermEndDate),
554
- LatestTermNumber: due.TermNumber,
555
- },
556
- Subscriber: holder,
557
- IsRenewal: true,
558
- });
559
- const term = decision.Term;
560
- if (!term)
561
- return null;
562
- return { Start: term.StartDate.toISOString().slice(0, 10), End: term.EndDate.toISOString().slice(0, 10) };
563
- }
564
- catch (err) {
565
- LogError(`Orders.SpawnRenewals: ${due.SubscriptionNumber} renewal term not decided: ${err instanceof Error ? err.message : String(err)}`);
566
- return null;
567
- }
568
- }
569
- /** A subscription type's rules from the engine cache, or null when the type is not there. */
570
- rulesFor(subscriptionTypeID) {
571
- const cached = OrdersEngine.Instance.SubscriptionTypeByID(subscriptionTypeID);
572
- return cached ? SubscriptionTypeRulesFrom(cached) : null;
573
- }
574
- /**
575
- * The codes the renewal presents: those recorded on the line that bought the expiring term whose
576
- * promotion carries into renewals (#289). A promotion's adjustment rows always name a line; an
577
- * order-level promotion writes one per line, so the source line's own rows are complete.
578
- */
579
- async loadRenewalPromotionCodes(provider, source) {
580
- const orderID = RequireUUID(String(source.OrderHeaderID), 'OrderHeaderID');
581
- const lineID = RequireUUID(String(source.ID), 'OrderLineID');
582
- const db = provider;
583
- const rows = (await db.ExecuteSQL(`
584
- SELECT pc.ID AS PromotionCodeID, pc.Code, p.AppliesToRenewals, MIN(oa.Sequence) AS FirstSequence
585
- FROM __mj_BizAppsOrders.OrderAdjustment oa
586
- JOIN __mj_BizAppsOrders.PromotionCode pc ON pc.ID = oa.PromotionCodeID
587
- JOIN __mj_BizAppsOrders.Promotion p ON p.ID = pc.PromotionID
588
- WHERE oa.OrderHeaderID = '${orderID}'
589
- AND oa.OrderLineID = '${lineID}'
590
- GROUP BY pc.ID, pc.Code, p.AppliesToRenewals
591
- ORDER BY MIN(oa.Sequence), pc.Code
592
- `));
593
- if (!Array.isArray(rows))
594
- return [];
595
- const keep = new Set(SelectRenewalPromotionCodes(rows.map((r) => ({ Code: r.Code, AppliesToRenewals: !!r.AppliesToRenewals }))).map((c) => c.toLowerCase()));
596
- const out = [];
597
- for (const r of rows) {
598
- if (!keep.delete(String(r.Code).trim().toLowerCase()))
599
- continue;
600
- out.push({ PromotionCodeID: String(r.PromotionCodeID), Code: String(r.Code).trim(), AppliesToRenewals: true });
601
- }
602
- return out;
603
- }
604
586
  /** The presented codes the engine wrote a discount for on this order, read from its adjustment rows. */
605
587
  async appliedCodes(provider, orderID, presented) {
606
588
  const id = RequireUUID(String(orderID), 'OrderHeaderID');
@@ -636,7 +618,7 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
636
618
  CompanyID: due.CompanyID,
637
619
  BillToPersonID: due.BeneficiaryPersonID,
638
620
  BillToOrganizationID: due.HolderOrganizationID,
639
- OrderDate: this.dayAfter(due.TermEndDate),
621
+ OrderDate: DayAfter(due.TermEndDate),
640
622
  ShipToAddressID: null,
641
623
  Lines: [line],
642
624
  PromotionCodes: codes,
@@ -651,147 +633,29 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
651
633
  candidate.RenewalPromotionCodes = outcome.Applied;
652
634
  candidate.UnusableRenewalPromotionCodes = outcome.Unusable;
653
635
  }
654
- /**
655
- * The subscription's product followed along `SuccessorProductID` while the next product is
656
- * Active: a successor that is still a draft, or already retired, is not one to renew onto.
657
- * The subscription's own product comes first; the last entry is what the renewal is placed on.
658
- */
659
- async loadSuccessorChain(provider, productID) {
660
- const db = provider;
661
- const rows = (await db.ExecuteSQL(`
662
- WITH chain AS (
663
- SELECT p.ID, p.Name, p.Status, p.ProductCategoryID, p.RenewalIncreasePercent, p.SuccessorProductID,
664
- p.SubscriptionTypeID, p.ProductTypeID, 0 AS Depth
665
- FROM __mj_BizAppsOrders.Product p
666
- WHERE p.ID = '${productID}'
667
- UNION ALL
668
- SELECT n.ID, n.Name, n.Status, n.ProductCategoryID, n.RenewalIncreasePercent, n.SuccessorProductID,
669
- n.SubscriptionTypeID, n.ProductTypeID, c.Depth + 1
670
- FROM chain c
671
- JOIN __mj_BizAppsOrders.Product n ON n.ID = c.SuccessorProductID
672
- WHERE c.Depth < 20 AND n.Status = 'Active'
673
- )
674
- SELECT c.ID, c.Name, c.Status, c.ProductCategoryID, c.RenewalIncreasePercent, c.SuccessorProductID,
675
- COALESCE(p.SubscriptionTypeID, pt.DefaultSubscriptionTypeID) AS SubscriptionTypeID, c.ProductTypeID
676
- FROM chain c
677
- JOIN __mj_BizAppsOrders.Product p ON p.ID = c.ID
678
- LEFT JOIN __mj_BizAppsOrders.ProductType pt ON pt.ID = p.ProductTypeID
679
- ORDER BY c.Depth
680
- `));
681
- if (!Array.isArray(rows) || rows.length === 0) {
682
- throw new Error(`The subscription's product (${productID}) no longer exists, so there is nothing to renew.`);
683
- }
684
- // Successors that loop back would otherwise walk to the depth cap; stop at the first repeat.
685
- const seen = new Set();
686
- const chain = [];
687
- for (const row of rows) {
688
- const key = String(row.ID).toLowerCase();
689
- if (seen.has(key))
690
- break;
691
- seen.add(key);
692
- chain.push(row);
693
- }
694
- return chain;
695
- }
696
- /** `RenewalIncreasePercent` of a category and each ancestor, the category itself first. */
697
- async loadCategoryIncreases(provider, categoryID) {
698
- if (!categoryID)
699
- return [];
700
- const db = provider;
701
- const rows = (await db.ExecuteSQL(`
702
- WITH chain AS (
703
- SELECT c.ID, c.ParentProductCategoryID, c.RenewalIncreasePercent, 0 AS Depth
704
- FROM __mj_BizAppsOrders.ProductCategory c
705
- WHERE c.ID = '${categoryID}'
706
- UNION ALL
707
- SELECT p.ID, p.ParentProductCategoryID, p.RenewalIncreasePercent, ch.Depth + 1
708
- FROM chain ch
709
- JOIN __mj_BizAppsOrders.ProductCategory p ON p.ID = ch.ParentProductCategoryID
710
- WHERE ch.Depth < 20
711
- )
712
- SELECT RenewalIncreasePercent FROM chain ORDER BY Depth
713
- `));
714
- return Array.isArray(rows) ? rows.map((r) => (r.RenewalIncreasePercent == null ? null : Number(r.RenewalIncreasePercent))) : [];
715
- }
716
- /** The selling company's `OrderCompanyPolicy.RenewalIncreasePercent`; null when it has no policy row. */
717
- async loadCompanyIncrease(provider, user, companyID) {
718
- const rv = new RunView(provider);
719
- const result = await rv.RunView({
720
- EntityName: ORDER_COMPANY_POLICY_ENTITY,
721
- ExtraFilter: `ID='${companyID}'`,
722
- Fields: ['RenewalIncreasePercent'],
723
- ResultType: 'simple',
724
- BypassCache: true,
725
- }, user);
726
- const value = result?.Results?.[0]?.RenewalIncreasePercent;
727
- return value == null ? null : Number(value);
728
- }
729
- /**
730
- * What the pricing engine charges for `line`'s product, for the customer on `line`'s order. As of
731
- * that order's date, or as of `asOf` when given. Null when no rule prices the product.
732
- */
733
- async listPrice(provider, user, line, asOf) {
734
- const ctx = await BuildLinePriceContext(line, provider, user);
735
- if (!ctx)
736
- return null;
737
- if (asOf)
738
- ctx.AsOf = AsDateValue(asOf) ?? ctx.AsOf;
739
- const resolved = await ResolvePrice(ctx, provider, user);
740
- return resolved ? Number(resolved.UnitPrice) : null;
741
- }
742
- /** The renewal order's notes: what it renews, how its price was reached, and what its promotions did. */
743
- renewalNotes(due, priced, promotions) {
744
- const p = priced.Price;
636
+ /** The renewal order's notes: one line per subscription it renews (what, who asked, how its price was reached), then what the promotions did. */
637
+ renewalNotes(members, promotions, placeAs, selectedByPerson) {
745
638
  const money = (n) => n.toFixed(2);
746
- const base = { PriorPrice: 'prior price', PriorList: 'prior list price', SuccessorList: 'list price' }[p.BaseSource];
747
- // A multi-term prior line: say the base is one term's share, so the figure reads against the line.
748
- const share = p.BaseSource === 'PriorPrice' && priced.PriorLineMonths != null
749
- ? ` (one term of a ${Math.round(priced.PriorLineMonths * 100) / 100}-month line)`
750
- : '';
751
- const parts = [`Automatic renewal of ${due.SubscriptionNumber} (term ${due.TermNumber + 1})`];
752
- if (priced.MovesToSuccessor)
753
- parts.push(`onto successor product ${priced.ProductName}`);
754
- const increase = p.IncreasePercent > 0 ? ` + ${p.IncreasePercent}% annual increase (${p.IncreaseSource.toLowerCase()})` : '';
755
- const discount = p.DiscountPct > 0 ? `, discount ${Math.round(p.DiscountPct * 10000) / 100}% continued` : '';
756
- const price = `${parts.join(' ')}. Unit price ${money(p.UnitPrice)}: ${base} ${money(p.BasePrice)}${share}${increase}${discount}.`;
639
+ const how = selectedByPerson ? (placeAs === 'Draft' ? 'Renewal draft' : 'Renewal') : 'Automatic renewal';
640
+ const lines = members.map(({ due, priced }) => {
641
+ const p = priced.Price;
642
+ const base = { PriorPrice: 'prior price', PriorList: 'prior list price', SuccessorList: 'list price' }[p.BaseSource];
643
+ // A multi-term prior line: say the base is one term's share, so the figure reads against the line.
644
+ const share = p.BaseSource === 'PriorPrice' && priced.PriorLineMonths != null
645
+ ? ` (one term of a ${Math.round(priced.PriorLineMonths * 100) / 100}-month line)`
646
+ : '';
647
+ const parts = [`${how} of ${due.SubscriptionNumber} (term ${due.TermNumber + 1})`];
648
+ if (selectedByPerson)
649
+ parts.push('placed from the Renewals page');
650
+ if (priced.MovesToSuccessor)
651
+ parts.push(`onto successor product ${priced.ProductName}`);
652
+ const increase = p.IncreasePercent > 0 ? ` + ${p.IncreasePercent}% annual increase (${p.IncreaseSource.toLowerCase()})` : '';
653
+ const discount = p.DiscountPct > 0 ? `, discount ${Math.round(p.DiscountPct * 10000) / 100}% continued` : '';
654
+ return `${parts.join(' ')}. Unit price ${money(p.UnitPrice)}: ${base} ${money(p.BasePrice)}${share}${increase}${discount}.`;
655
+ });
656
+ const head = members.length > 1 ? [`${members.length} subscriptions renewed together: same customer, same term end.`] : [];
757
657
  const promotionNote = promotions ? RenewalPromotionNote(promotions) : '';
758
- return promotionNote ? `${price} ${promotionNote}` : price;
759
- }
760
- /**
761
- * Quantity for the renewal: the seats the expiring term covers (#589).
762
- *
763
- * Not the source line's quantity. A PRORATED source line carries a scaled quantity — the short
764
- * first period into a calendar anchor (D54) — so 10 seats over half a period read 5, and the
765
- * renewal billed and granted 5 seats for a full period. The term records the seats as bought.
766
- */
767
- renewalQuantity(due) {
768
- return Math.max(1, Number(due.TermQuantity));
769
- }
770
- dayAfter(date) {
771
- const d = new Date(date);
772
- return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1));
773
- }
774
- async loadSourceLine(provider, user, orderLineID) {
775
- const rv = new RunView(provider);
776
- const result = await rv.RunView({
777
- EntityName: ORDER_LINE_ENTITY,
778
- ExtraFilter: `ID='${orderLineID}'`,
779
- Fields: [
780
- 'ID',
781
- 'OrderHeaderID',
782
- 'ProductID',
783
- 'Quantity',
784
- 'UnitPrice',
785
- 'DiscountPct',
786
- 'PriceOverridden',
787
- 'ProductPriceID',
788
- 'ServicePeriodStart',
789
- 'ServicePeriodEnd',
790
- ],
791
- ResultType: 'simple',
792
- BypassCache: true,
793
- }, user);
794
- return result?.Results?.[0] ?? null;
658
+ return [...head, ...lines, ...(promotionNote ? [promotionNote] : [])].join('\n');
795
659
  }
796
660
  /** The choices recorded on the line that bought the expiring term, in group and option order. */
797
661
  async loadSourceChoices(provider, user, orderLineID) {
@@ -806,7 +670,7 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
806
670
  }, user);
807
671
  return result?.Results ?? [];
808
672
  }
809
- async logEvent(provider, user, due, priced, orderID, promotions) {
673
+ async logEvent(provider, user, due, priced, orderID, promotions, placeAs, selectedByPerson) {
810
674
  const event = await provider.GetEntityObject(SUBSCRIPTION_EVENT_ENTITY, user);
811
675
  event.NewRecord();
812
676
  event.SubscriptionID = due.SubscriptionID;
@@ -816,7 +680,9 @@ let SpawnRenewalsOperation = class SpawnRenewalsOperation extends OrdersSpawnRen
816
680
  event.Set('EventData', JSON.stringify({
817
681
  RenewedTermNumber: due.TermNumber,
818
682
  ExpiringTermEnd: due.TermEndDate,
819
- LeadDays: due.SubscriptionRenewalLeadDays ?? due.TypeRenewalLeadDays ?? 0,
683
+ LeadDays: EffectiveLeadDays(due),
684
+ OrderStatus: placeAs,
685
+ Placement: selectedByPerson ? 'Selected' : 'Pass',
820
686
  FromProductID: due.ProductID,
821
687
  RenewalProductID: priced.ProductID,
822
688
  BasePrice: priced.Price.BasePrice,
@@ -840,6 +706,25 @@ SpawnRenewalsOperation = __decorate([
840
706
  RegisterClass(BaseRemotableOperation, 'Orders.SpawnRenewals')
841
707
  ], SpawnRenewalsOperation);
842
708
  export { SpawnRenewalsOperation };
709
+ /**
710
+ * Why a subscription a person named cannot have a renewal placed, or null when it can: the same
711
+ * rules the scheduled selection applies in SQL, minus the lead window and the auto-renew switch,
712
+ * which are the person's call. Exported so the Renewals page and its tests read one rule.
713
+ */
714
+ export function SelectedRenewalRefusal(row) {
715
+ if (!RENEWABLE_STATUSES.includes(row.SubscriptionStatus)) {
716
+ return `the subscription is ${row.SubscriptionStatus}, not Active or Trialing, so nothing renews it`;
717
+ }
718
+ if (IsProviderBilled(row)) {
719
+ return 'a payment gateway bills this subscription, so Orders places no renewal order for it';
720
+ }
721
+ if (!row.TermID)
722
+ return 'the subscription has no term to renew from';
723
+ if (!RENEWABLE_TERM_STATUSES.includes(String(row.TermStatus))) {
724
+ return `its latest term is ${row.TermStatus}, not Scheduled or Active, so there is nothing to continue`;
725
+ }
726
+ return null;
727
+ }
843
728
  /** Tree-shaking anchor — called from the server bootstrap so the registration is retained. */
844
729
  export function LoadSpawnRenewalsOperation() {
845
730
  // intentionally empty