@mj-biz-apps/orders-ng 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 (53) hide show
  1. package/dist/lib/form-panels/external-invoices.panel.d.ts +2 -1
  2. package/dist/lib/form-panels/external-invoices.panel.d.ts.map +1 -1
  3. package/dist/lib/form-panels/external-invoices.panel.js +5 -4
  4. package/dist/lib/form-panels/external-invoices.panel.js.map +1 -1
  5. package/dist/lib/pages/receivables/external-invoicing-queue.page.js +5 -5
  6. package/dist/lib/pages/receivables/external-invoicing-queue.page.js.map +1 -1
  7. package/dist/lib/pages/subscriptions/renewals-page.model.d.ts +214 -0
  8. package/dist/lib/pages/subscriptions/renewals-page.model.d.ts.map +1 -0
  9. package/dist/lib/pages/subscriptions/renewals-page.model.js +663 -0
  10. package/dist/lib/pages/subscriptions/renewals-page.model.js.map +1 -0
  11. package/dist/lib/pages/subscriptions/renewals.page.d.ts +236 -0
  12. package/dist/lib/pages/subscriptions/renewals.page.d.ts.map +1 -0
  13. package/dist/lib/pages/subscriptions/renewals.page.js +2249 -0
  14. package/dist/lib/pages/subscriptions/renewals.page.js.map +1 -0
  15. package/dist/lib/pages/subscriptions/subscriptions.page.d.ts.map +1 -0
  16. package/dist/lib/pages/{receivables → subscriptions}/subscriptions.page.js +1 -1
  17. package/dist/lib/pages/subscriptions/subscriptions.page.js.map +1 -0
  18. package/dist/lib/panels/external-invoice-view.d.ts +13 -3
  19. package/dist/lib/panels/external-invoice-view.d.ts.map +1 -1
  20. package/dist/lib/panels/external-invoice-view.js +20 -4
  21. package/dist/lib/panels/external-invoice-view.js.map +1 -1
  22. package/dist/lib/panels/money-format.d.ts +16 -6
  23. package/dist/lib/panels/money-format.d.ts.map +1 -1
  24. package/dist/lib/panels/money-format.js +6 -5
  25. package/dist/lib/panels/money-format.js.map +1 -1
  26. package/dist/lib/panels/multi-select.component.d.ts +60 -0
  27. package/dist/lib/panels/multi-select.component.d.ts.map +1 -0
  28. package/dist/lib/panels/multi-select.component.js +293 -0
  29. package/dist/lib/panels/multi-select.component.js.map +1 -0
  30. package/dist/lib/panels/stat-tile.component.d.ts +3 -1
  31. package/dist/lib/panels/stat-tile.component.d.ts.map +1 -1
  32. package/dist/lib/panels/stat-tile.component.js +64 -17
  33. package/dist/lib/panels/stat-tile.component.js.map +1 -1
  34. package/dist/lib/panels/worklist-table.component.d.ts +35 -12
  35. package/dist/lib/panels/worklist-table.component.d.ts.map +1 -1
  36. package/dist/lib/panels/worklist-table.component.js +126 -67
  37. package/dist/lib/panels/worklist-table.component.js.map +1 -1
  38. package/dist/lib/sections/orders-sections.component.d.ts +23 -6
  39. package/dist/lib/sections/orders-sections.component.d.ts.map +1 -1
  40. package/dist/lib/sections/orders-sections.component.js +146 -16
  41. package/dist/lib/sections/orders-sections.component.js.map +1 -1
  42. package/dist/lib/sections/section-nav.model.d.ts +14 -5
  43. package/dist/lib/sections/section-nav.model.d.ts.map +1 -1
  44. package/dist/lib/sections/section-nav.model.js +18 -7
  45. package/dist/lib/sections/section-nav.model.js.map +1 -1
  46. package/dist/public-api.d.ts +7 -4
  47. package/dist/public-api.d.ts.map +1 -1
  48. package/dist/public-api.js +10 -7
  49. package/dist/public-api.js.map +1 -1
  50. package/package.json +2 -2
  51. package/dist/lib/pages/receivables/subscriptions.page.d.ts.map +0 -1
  52. package/dist/lib/pages/receivables/subscriptions.page.js.map +0 -1
  53. /package/dist/lib/pages/{receivables → subscriptions}/subscriptions.page.d.ts +0 -0
@@ -0,0 +1,663 @@
1
+ import { FormatDate, FormatMoney } from '../../panels/money-format.js';
2
+ /** Every day on the Renewals page is written MM/DD/YYYY: finance reads this list, and that is how finance writes a date. */
3
+ export const RENEWALS_DATE = { Numeric: true };
4
+ /** How far ahead the page can look. The first entry is the default: finance's lead time is 90 days. */
5
+ export const RENEWAL_WINDOWS = [
6
+ { Days: 90, Label: 'Next 90 days' },
7
+ { Days: 30, Label: 'Next 30 days' },
8
+ { Days: 60, Label: 'Next 60 days' },
9
+ { Days: 180, Label: 'Next 6 months' },
10
+ { Days: 365, Label: 'Next 12 months' },
11
+ ];
12
+ /** The states the scheduled pass will still act on. */
13
+ const AUTO_STATES = ['DueNow', 'Scheduled'];
14
+ /** The states where a person has to place the renewal, or let it end. */
15
+ const MANUAL_STATES = ['WillEnd', 'Ended', 'Lapsed'];
16
+ /** The states where a renewal order already exists. */
17
+ const PLACED_STATES = ['Renewed', 'RenewalPending'];
18
+ /** Whether a row belongs to a preset. `all` is everything in the window. */
19
+ export function MatchesPreset(row, preset) {
20
+ switch (preset) {
21
+ case 'auto':
22
+ return AUTO_STATES.includes(row.State);
23
+ case 'manual':
24
+ return MANUAL_STATES.includes(row.State);
25
+ case 'placed':
26
+ return PLACED_STATES.includes(row.State);
27
+ case 'attention':
28
+ return NeedsAttention(row);
29
+ default:
30
+ return true;
31
+ }
32
+ }
33
+ /**
34
+ * A row somebody should look at before the pass does: a renewal that could not be priced, an
35
+ * expiring term one day long (a data defect: the pass would renew from the wrong day and skip the
36
+ * increase), a term that lapsed with auto-renew on (the pass will not revive it), or a draft
37
+ * renewal nobody confirmed for a term that has already ended.
38
+ */
39
+ export function NeedsAttention(row) {
40
+ if (row.ProjectionProblem)
41
+ return true;
42
+ if (OneDayTerm(row))
43
+ return true;
44
+ if (row.State === 'Lapsed')
45
+ return true;
46
+ if (row.State === 'RenewalPending' && row.DaysUntilEnd < 0)
47
+ return true;
48
+ return false;
49
+ }
50
+ /**
51
+ * An expiring term that starts and ends on the same day. The cutover load split a line whose legacy
52
+ * dates ran a year inclusive into a twelve-month term plus this one-day remainder, so the renewal
53
+ * would start the day AFTER the anniversary and never cross one: the increase is skipped and the new
54
+ * term sits a day off for good. Flagged so the data gets fixed before the pass renews from it.
55
+ */
56
+ export function OneDayTerm(row) {
57
+ return !!row.TermStartDate && row.TermStartDate === row.TermEndDate;
58
+ }
59
+ /** The muted warning under the Ends column, or null. */
60
+ export function TermWarning(row) {
61
+ return OneDayTerm(row) ? 'one-day term: check the data' : null;
62
+ }
63
+ /** Whether a renewal order may be placed for this row from the page. Mirrors the operation's own refusals. */
64
+ export function CanPlaceRenewal(row) {
65
+ if (row.RenewalOrderID || row.ProviderBilled)
66
+ return false;
67
+ return AUTO_STATES.includes(row.State) || MANUAL_STATES.includes(row.State);
68
+ }
69
+ /** Case-insensitive match over the things people search a renewal list by. */
70
+ export function MatchesSearch(row, text) {
71
+ const needle = text.trim().toLowerCase();
72
+ if (!needle)
73
+ return true;
74
+ const hay = [
75
+ row.SubscriptionNumber,
76
+ row.ContactName,
77
+ row.AccountName,
78
+ row.CompanyName,
79
+ row.ProductName,
80
+ row.ProjectedProductName,
81
+ row.CurrentOrderNumber,
82
+ row.RenewalOrderNumber,
83
+ ];
84
+ return hay.some((v) => !!v && String(v).toLowerCase().includes(needle));
85
+ }
86
+ /** The state as a short label for the chip. */
87
+ export function RenewalStateLabel(state) {
88
+ switch (state) {
89
+ case 'Renewed':
90
+ return 'Renewed';
91
+ case 'RenewalPending':
92
+ return 'Draft placed';
93
+ case 'DueNow':
94
+ return 'Due for renewal';
95
+ case 'Scheduled':
96
+ return 'Auto-renews';
97
+ case 'Lapsed':
98
+ return 'Lapsed';
99
+ case 'WillEnd':
100
+ return 'Will end';
101
+ case 'Ended':
102
+ return 'Ended';
103
+ case 'ProviderBilled':
104
+ return 'Gateway billed';
105
+ case 'Inactive':
106
+ return 'Not renewable';
107
+ default:
108
+ return String(state);
109
+ }
110
+ }
111
+ /** The chip variant for a state: success for settled, warning for "somebody should look", outline for the rest. */
112
+ export function RenewalStateChipClass(state) {
113
+ switch (state) {
114
+ case 'Renewed':
115
+ return 'mjo-chip--success';
116
+ case 'RenewalPending':
117
+ case 'Scheduled':
118
+ case 'DueNow':
119
+ return 'mjo-chip--info';
120
+ case 'WillEnd':
121
+ case 'Ended':
122
+ case 'Lapsed':
123
+ return 'mjo-chip--warning';
124
+ default:
125
+ return 'mjo-chip--outline';
126
+ }
127
+ }
128
+ /** The muted line under the state chip: when the pass will act, or why nothing will. */
129
+ export function RenewalStateNote(row) {
130
+ switch (row.State) {
131
+ case 'Scheduled':
132
+ return row.AutoRenewOn ? `on ${FormatDate(row.AutoRenewOn, RENEWALS_DATE)}` : null;
133
+ case 'DueNow':
134
+ return 'in the lead window';
135
+ case 'Renewed':
136
+ return row.RenewalTermEnd ? `through ${FormatDate(row.RenewalTermEnd, RENEWALS_DATE)}` : null;
137
+ case 'RenewalPending':
138
+ return 'awaiting confirmation';
139
+ case 'WillEnd':
140
+ return 'auto-renew is off';
141
+ case 'Ended':
142
+ return 'auto-renew was off';
143
+ case 'Lapsed':
144
+ return 'ended before the pass';
145
+ case 'Inactive':
146
+ return row.Status;
147
+ default:
148
+ return null;
149
+ }
150
+ }
151
+ /** "in 32d", "today", "ended 3d ago". */
152
+ export function EndsNote(daysUntilEnd) {
153
+ if (daysUntilEnd < 0)
154
+ return `ended ${-daysUntilEnd}d ago`;
155
+ if (daysUntilEnd === 0)
156
+ return 'ends today';
157
+ return `in ${daysUntilEnd}d`;
158
+ }
159
+ /** The renewal price column: the placed order's price when there is one, else the projection, else a dash. */
160
+ export function RenewalPriceDisplay(row) {
161
+ if (row.RenewalOrderID && row.RenewalUnitPrice != null)
162
+ return FormatMoney(row.RenewalUnitPrice);
163
+ if (row.ProjectedUnitPrice != null)
164
+ return FormatMoney(row.ProjectedUnitPrice);
165
+ return '—';
166
+ }
167
+ /**
168
+ * The percentage a placed renewal moved from the current term's unit price: `5` for 5% up, `-3`
169
+ * for 3% down, `0` for the same price. Null when either price is missing or the current price is
170
+ * zero (a free term has no base to move from). Two decimals.
171
+ */
172
+ export function PriceChangePercent(current, renewal) {
173
+ if (current == null || renewal == null || !(current > 0))
174
+ return null;
175
+ return Math.round((renewal / current - 1) * 10000) / 100;
176
+ }
177
+ /**
178
+ * The increase, under the renewal price, so the two read together. For a projection: the increase
179
+ * the pricer applied and where it was set ("projected · +5% (subscription)"), or why the price
180
+ * moved without one ("successor list", "discount lapses", "no increase"). For a placed renewal:
181
+ * how far the order's price actually moved from the current term ("+5% vs current", "same price").
182
+ * Seats follow when there is more than one.
183
+ */
184
+ export function RenewalPriceNote(row) {
185
+ const parts = [];
186
+ if (row.RenewalOrderID) {
187
+ const change = PriceChangePercent(row.CurrentUnitPrice, row.RenewalUnitPrice);
188
+ if (change != null)
189
+ parts.push(change === 0 ? 'same price' : `${change > 0 ? '+' : '−'}${TrimPercent(Math.abs(change))}% vs current`);
190
+ if (row.RenewalQuantity != null && row.RenewalQuantity !== 1)
191
+ parts.push(`× ${row.RenewalQuantity}`);
192
+ return parts.length ? parts.join(' · ') : null;
193
+ }
194
+ if (row.ProjectionProblem)
195
+ return 'could not be priced';
196
+ if (row.ProjectedUnitPrice == null)
197
+ return null;
198
+ parts.push('projected');
199
+ if (row.ProjectedIncreasePercent && row.ProjectedIncreasePercent > 0) {
200
+ parts.push(`+${TrimPercent(row.ProjectedIncreasePercent)}% (${String(row.ProjectedIncreaseSource ?? '').toLowerCase()})`);
201
+ }
202
+ else if (row.ProjectedIncreaseApplied === false && row.ProjectedIncreaseSetPercent) {
203
+ parts.push(`${TrimPercent(row.ProjectedIncreaseSetPercent)}% set, not applied: no anniversary this term`);
204
+ }
205
+ else if (row.ProjectedBasePriceSource === 'SuccessorList') {
206
+ parts.push('successor list');
207
+ }
208
+ else if (row.ProjectedBasePriceSource === 'PriorList') {
209
+ parts.push('discount lapses');
210
+ }
211
+ else {
212
+ parts.push('no increase');
213
+ }
214
+ if (row.ProjectedQuantity != null && row.ProjectedQuantity !== 1)
215
+ parts.push(`× ${row.ProjectedQuantity}`);
216
+ return parts.join(' · ');
217
+ }
218
+ export const NO_FACETS = { Companies: [], Products: [] };
219
+ /**
220
+ * The choices for one facet, drawn from the rows in the window: only the companies (or products)
221
+ * that actually have a subscription ending, sorted by name. `countRows` are the rows the count is
222
+ * taken over, normally the rows the OTHER facet leaves, so a product's count answers "how many of
223
+ * these, for the companies I picked", and drops to 0 rather than disappearing when none remain.
224
+ */
225
+ export function FacetOptions(rows, key, countRows = rows) {
226
+ const id = (r) => (key === 'Company' ? r.CompanyID : r.ProductID);
227
+ const name = (r) => (key === 'Company' ? r.CompanyName : r.ProductName) || '(none)';
228
+ const counts = new Map();
229
+ for (const r of countRows)
230
+ counts.set(id(r), (counts.get(id(r)) ?? 0) + 1);
231
+ const seen = new Map();
232
+ for (const r of rows) {
233
+ if (!seen.has(id(r)))
234
+ seen.set(id(r), { Value: id(r), Text: name(r), Count: counts.get(id(r)) ?? 0 });
235
+ }
236
+ return [...seen.values()].sort((a, b) => a.Text.localeCompare(b.Text, undefined, { sensitivity: 'base' }) || (a.Value < b.Value ? -1 : 1));
237
+ }
238
+ /** Whether a row survives the facets. An empty facet keeps everything. */
239
+ export function MatchesFacets(row, facets) {
240
+ if (facets.Companies.length && !facets.Companies.includes(row.CompanyID))
241
+ return false;
242
+ if (facets.Products.length && !facets.Products.includes(row.ProductID))
243
+ return false;
244
+ return true;
245
+ }
246
+ /** The "Filtered by" chips for the current facets, one per ticked company or product. */
247
+ export function AppliedFacets(facets, companies, products) {
248
+ const chip = (key, id, options) => ({
249
+ key: `${key}:${id}`,
250
+ label: key,
251
+ value: options.find((o) => o.Value === id)?.Text ?? id,
252
+ });
253
+ return [...facets.Companies.map((id) => chip('Company', id, companies)), ...facets.Products.map((id) => chip('Product', id, products))];
254
+ }
255
+ /** The facets with any product tick that the offered options no longer include removed. Same object when nothing changes. */
256
+ export function PruneProducts(facets, offered) {
257
+ const ids = new Set(offered.map((o) => o.Value));
258
+ if (facets.Products.every((p) => ids.has(p)))
259
+ return facets;
260
+ return { ...facets, Products: facets.Products.filter((p) => ids.has(p)) };
261
+ }
262
+ /** The facets without the one a chip's key names. An unknown key changes nothing. */
263
+ export function RemoveFacet(facets, chipKey) {
264
+ const at = chipKey.indexOf(':');
265
+ const key = chipKey.slice(0, at);
266
+ const id = chipKey.slice(at + 1);
267
+ if (key === 'Company')
268
+ return { ...facets, Companies: facets.Companies.filter((v) => v !== id) };
269
+ if (key === 'Product')
270
+ return { ...facets, Products: facets.Products.filter((v) => v !== id) };
271
+ return facets;
272
+ }
273
+ /* ── The subscription's own increase ───────────────────────────────────────── */
274
+ /**
275
+ * What the subscription itself says about its increase, for the side panel: its own rate when one
276
+ * is set, else what it inherits (known only where a projection ran), else that nothing is set.
277
+ */
278
+ export function SubscriptionIncreaseNote(row) {
279
+ if (row.SubscriptionIncreasePercent != null)
280
+ return `${TrimPercent(row.SubscriptionIncreasePercent)}% · set on this subscription`;
281
+ const source = row.ProjectedIncreaseSetSource ?? row.ProjectedIncreaseSource;
282
+ const percent = row.ProjectedIncreaseSetPercent ?? row.ProjectedIncreasePercent;
283
+ if (source && source !== 'None' && source !== 'Subscription' && percent) {
284
+ return `Not set · inherits ${TrimPercent(percent)}% from the ${source.toLowerCase()}`;
285
+ }
286
+ return 'Not set · inherits from the product, its category or the company (none set)';
287
+ }
288
+ /**
289
+ * The rate to prefill the update dialog with: the one rate every chosen subscription already holds
290
+ * (null when they all inherit), or `undefined` when they differ and the field should start empty.
291
+ */
292
+ export function SharedIncrease(rows) {
293
+ if (!rows.length)
294
+ return undefined;
295
+ const first = rows[0].SubscriptionIncreasePercent ?? null;
296
+ return rows.every((r) => (r.SubscriptionIncreasePercent ?? null) === first) ? first : undefined;
297
+ }
298
+ /** What the page says after `Orders.SetRenewalSettings` ran. */
299
+ export function SettingsUpdateText(output) {
300
+ const failed = output.Changes.filter((c) => c.Error);
301
+ const detail = failed.length
302
+ ? ` ${failed
303
+ .slice(0, 3)
304
+ .map((c) => `${c.SubscriptionNumber ?? c.SubscriptionID}: ${c.Error}`)
305
+ .join('; ')}${failed.length > 3 ? `; and ${failed.length - 3} more` : ''}.`
306
+ : '';
307
+ const tail = output.Updated ? ' No order was changed; the next renewal each one places follows the new settings.' : '';
308
+ return {
309
+ Tone: !output.Success ? 'error' : failed.length ? 'warning' : 'success',
310
+ Text: `${output.Message ?? ''}${detail}${tail}`.trim(),
311
+ };
312
+ }
313
+ /* ── Changing the product ──────────────────────────────────────────────────── */
314
+ /** "Betty (converted pricing) ×3, rasa.io Newsletter ×1": what the chosen rows are on now, most common first. */
315
+ export function CurrentProductsNote(rows) {
316
+ const counts = new Map();
317
+ for (const r of rows)
318
+ counts.set(r.ProductName, (counts.get(r.ProductName) ?? 0) + 1);
319
+ return [...counts.entries()]
320
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
321
+ .map(([name, n]) => (rows.length > 1 ? `${name} ×${n}` : name))
322
+ .join(', ');
323
+ }
324
+ /**
325
+ * What the page says after `Orders.SpawnRenewals` placed orders: one entry per ORDER, not per
326
+ * subscription, since a customer's subscriptions renew together on one order; then who was skipped.
327
+ */
328
+ export function PlacedText(candidates, placed) {
329
+ const done = candidates.filter((c) => c.OrderID);
330
+ const skipped = candidates.filter((c) => !c.OrderID);
331
+ const orders = new Map();
332
+ for (const c of done) {
333
+ const key = String(c.OrderID);
334
+ if (!orders.has(key))
335
+ orders.set(key, `${c.OrderNumber ?? c.OrderID} (${c.OrderStatus === 'Draft' ? 'draft' : 'confirmed'})`);
336
+ }
337
+ const list = [...orders.values()].slice(0, 5).join(', ');
338
+ const head = `${placed} renewal order${placed === 1 ? '' : 's'} created` +
339
+ (done.length ? ` for ${done.length} subscription${done.length === 1 ? '' : 's'}` : '') +
340
+ `${list ? `: ${list}${orders.size > 5 ? ', …' : ''}` : ''}.`;
341
+ const tail = skipped.length
342
+ ? ` ${skipped.length} skipped: ${skipped
343
+ .slice(0, 3)
344
+ .map((c) => `${c.SubscriptionNumber} (${c.SkippedReason ?? 'no reason reported'})`)
345
+ .join('; ')}${skipped.length > 3 ? `, and ${skipped.length - 3} more` : ''}.`
346
+ : '';
347
+ return head + tail;
348
+ }
349
+ /**
350
+ * The rows among `rows` that have a renewal order pending (placed, not yet booked), as a warning for a
351
+ * dialog whose change does not reach that order, ending in `consequence`. Null when none is pending.
352
+ */
353
+ export function PendingRenewalWarning(rows, consequence) {
354
+ const pending = rows.filter((r) => r.RenewalOrderID && !r.RenewalBooked);
355
+ if (!pending.length)
356
+ return null;
357
+ const order = (r) => `${r.RenewalOrderNumber ?? 'an order'}${r.RenewalOrderStatus ? ` (${r.RenewalOrderStatus})` : ''}`;
358
+ const who = pending.length === 1
359
+ ? `${pending[0].SubscriptionNumber} has renewal order ${order(pending[0])} pending`
360
+ : `${pending.length} of the selected subscriptions have a renewal order pending: ${pending
361
+ .slice(0, 3)
362
+ .map(order)
363
+ .join(', ')}${pending.length > 3 ? `, and ${pending.length - 3} more` : ''}`;
364
+ return `${who}. ${consequence}`;
365
+ }
366
+ /** What the page says after `Orders.ChangeSubscriptionProduct` ran. */
367
+ export function ProductChangeText(output) {
368
+ const failed = output.Changes.filter((c) => c.Error);
369
+ const warned = output.Changes.filter((c) => c.Changed && c.Warning);
370
+ const list = (items, text) => `${items
371
+ .slice(0, 3)
372
+ .map(text)
373
+ .join('; ')}${items.length > 3 ? `; and ${items.length - 3} more` : ''}.`;
374
+ const detail = [
375
+ failed.length ? ` ${list(failed, (c) => `${c.SubscriptionNumber ?? c.SubscriptionID}: ${c.Error}`)}` : '',
376
+ warned.length ? ` ${list(warned, (c) => `${c.SubscriptionNumber ?? c.SubscriptionID}: ${c.Warning}`)}` : '',
377
+ ].join('');
378
+ const tail = output.Updated ? ' Booked orders and deals are unchanged; the next renewal uses the new product at the current price plus increase.' : '';
379
+ return {
380
+ Tone: !output.Success ? 'error' : failed.length ? 'warning' : 'success',
381
+ Text: `${output.Message ?? ''}${detail}${tail}`.trim(),
382
+ };
383
+ }
384
+ /* ── Selected rows a renewal cannot be placed for ─────────────────────────── */
385
+ /**
386
+ * "2 · already renewed (1), billed by a payment gateway (1)": the ticked rows the create-renewals
387
+ * dialog leaves out, with why, for its Excluded line, so a person is never surprised by a count
388
+ * smaller than their selection. Null when every ticked row can be placed.
389
+ */
390
+ export function ExclusionNote(excluded) {
391
+ if (!excluded.length)
392
+ return null;
393
+ const reason = (r) => {
394
+ if (r.ProviderBilled)
395
+ return 'billed by a payment gateway';
396
+ if (r.State === 'Renewed')
397
+ return 'already renewed';
398
+ if (r.State === 'RenewalPending')
399
+ return 'a renewal draft already exists';
400
+ if (r.State === 'Inactive')
401
+ return `not renewable (${r.Status.toLowerCase()})`;
402
+ return 'cannot be renewed from here';
403
+ };
404
+ const counts = new Map();
405
+ for (const r of excluded)
406
+ counts.set(reason(r), (counts.get(reason(r)) ?? 0) + 1);
407
+ const list = [...counts.entries()]
408
+ .sort((a, b) => b[1] - a[1])
409
+ .map(([why, n]) => `${why} (${n})`)
410
+ .join(', ');
411
+ return `${excluded.length} · ${list}`;
412
+ }
413
+ export const RENEWALS_STATE_KEY = 'mjOrders.renewals.filters';
414
+ const PRESETS = ['all', 'auto', 'manual', 'placed', 'attention'];
415
+ /** The saved state, or null when there is none or it cannot be read. Anything malformed falls back field by field. */
416
+ export function ReadPageState(storage, key = RENEWALS_STATE_KEY) {
417
+ try {
418
+ const raw = storage?.getItem(key);
419
+ if (!raw)
420
+ return null;
421
+ const parsed = JSON.parse(raw);
422
+ const ids = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.length > 0) : []);
423
+ const window = RENEWAL_WINDOWS.some((w) => w.Days === parsed.WindowDays) ? parsed.WindowDays : RENEWAL_WINDOWS[0].Days;
424
+ const preset = PRESETS.includes(parsed.Preset) ? parsed.Preset : 'all';
425
+ return { WindowDays: window, Companies: ids(parsed.Companies), Products: ids(parsed.Products), Preset: preset };
426
+ }
427
+ catch {
428
+ return null;
429
+ }
430
+ }
431
+ /** Save the state. Storage that is missing or refuses is not an error: the page simply starts fresh next time. */
432
+ export function WritePageState(storage, state, key = RENEWALS_STATE_KEY) {
433
+ try {
434
+ storage?.setItem(key, JSON.stringify(state));
435
+ }
436
+ catch {
437
+ /* preferences simply do not persist */
438
+ }
439
+ }
440
+ /** The facets with any company tick the offered options no longer include removed. Same object when nothing changes. */
441
+ export function PruneCompanies(facets, offered) {
442
+ const ids = new Set(offered.map((o) => o.Value));
443
+ if (facets.Companies.every((c) => ids.has(c)))
444
+ return facets;
445
+ return { ...facets, Companies: facets.Companies.filter((c) => ids.has(c)) };
446
+ }
447
+ const MONEY = '#,##0.00';
448
+ /**
449
+ * The list as a spreadsheet: one row per subscription, the same facts the grid shows plus the ones
450
+ * the side panel holds, in words a reader outside the app understands ("Auto-renews", "Yes"). The
451
+ * renewal price column carries the placed order's price when there is one, else the projection,
452
+ * and the increase column the percentage behind it, so a finance reviewer can total and sort
453
+ * without opening the page.
454
+ */
455
+ export function BuildRenewalsExport(rows) {
456
+ const Columns = [
457
+ { name: 'Subscription', displayName: 'Subscription', dataType: 'string' },
458
+ { name: 'Customer', displayName: 'Customer', dataType: 'string' },
459
+ { name: 'Account', displayName: 'Account', dataType: 'string' },
460
+ { name: 'Company', displayName: 'Company', dataType: 'string' },
461
+ { name: 'Product', displayName: 'Product', dataType: 'string' },
462
+ { name: 'SubscriptionType', displayName: 'Subscription type', dataType: 'string' },
463
+ { name: 'Status', displayName: 'Status', dataType: 'string' },
464
+ { name: 'AutoRenew', displayName: 'Auto-renew', dataType: 'string' },
465
+ { name: 'RenewalState', displayName: 'Renewal', dataType: 'string' },
466
+ { name: 'AutoRenewsOn', displayName: 'Auto-renews on', dataType: 'dateonly' },
467
+ { name: 'SubscribedSince', displayName: 'Subscribed since', dataType: 'dateonly' },
468
+ { name: 'TermNumber', displayName: 'Term', dataType: 'number' },
469
+ { name: 'TermStart', displayName: 'Term start', dataType: 'dateonly' },
470
+ { name: 'TermEnd', displayName: 'Term end', dataType: 'dateonly' },
471
+ { name: 'DaysUntilEnd', displayName: 'Days until end', dataType: 'number' },
472
+ { name: 'CurrentOrder', displayName: 'Current order', dataType: 'string' },
473
+ { name: 'CurrentOrderDate', displayName: 'Current order date', dataType: 'dateonly' },
474
+ { name: 'CurrentOrderStatus', displayName: 'Current order status', dataType: 'string' },
475
+ { name: 'CurrentPrice', displayName: 'Current price', dataType: 'number', numberFormat: MONEY },
476
+ { name: 'CurrentQuantity', displayName: 'Current qty', dataType: 'number' },
477
+ { name: 'CurrentTotal', displayName: 'Current total', dataType: 'number', numberFormat: MONEY },
478
+ { name: 'CurrentBalance', displayName: 'Still owed', dataType: 'number', numberFormat: MONEY },
479
+ { name: 'RenewalOrder', displayName: 'Renewal order', dataType: 'string' },
480
+ { name: 'RenewalOrderDate', displayName: 'Renewal order date', dataType: 'dateonly' },
481
+ { name: 'RenewalOrderStatus', displayName: 'Renewal order status', dataType: 'string' },
482
+ { name: 'RenewalPrice', displayName: 'Renewal price', dataType: 'number', numberFormat: MONEY },
483
+ { name: 'RenewalQuantity', displayName: 'Renewal qty', dataType: 'number' },
484
+ { name: 'RenewalTotal', displayName: 'Renewal total', dataType: 'number', numberFormat: MONEY },
485
+ { name: 'RenewalPriceBasis', displayName: 'Renewal price basis', dataType: 'string' },
486
+ { name: 'IncreasePercent', displayName: 'Increase %', dataType: 'number', numberFormat: '0.00' },
487
+ { name: 'IncreaseSource', displayName: 'Increase set on', dataType: 'string' },
488
+ { name: 'IncreaseApplied', displayName: 'Increase applied', dataType: 'string' },
489
+ { name: 'SubscriptionIncreasePercent', displayName: 'Subscription increase %', dataType: 'number', numberFormat: '0.00' },
490
+ { name: 'RenewalTermStart', displayName: 'Renewal term start', dataType: 'dateonly' },
491
+ { name: 'RenewalTermEnd', displayName: 'Renewal term end', dataType: 'dateonly' },
492
+ { name: 'ProjectionProblem', displayName: 'Pricing problem', dataType: 'string' },
493
+ ];
494
+ const basis = (r) => {
495
+ if (r.RenewalOrderID)
496
+ return 'Placed order';
497
+ if (r.ProjectionProblem)
498
+ return null;
499
+ if (r.ProjectedUnitPrice == null)
500
+ return null;
501
+ return { PriorPrice: 'Current undiscounted price', PriorList: 'Current list price', SuccessorList: 'Successor list price' }[r.ProjectedBasePriceSource ?? 'PriorPrice'];
502
+ };
503
+ const Rows = rows.map((r) => {
504
+ const placed = !!r.RenewalOrderID;
505
+ return {
506
+ Subscription: r.SubscriptionNumber,
507
+ Customer: r.ContactName ?? null,
508
+ Account: r.AccountName ?? null,
509
+ Company: r.CompanyName,
510
+ Product: r.ProductName,
511
+ SubscriptionType: r.SubscriptionTypeName,
512
+ Status: r.Status,
513
+ AutoRenew: r.AutoRenew ? 'Yes' : 'No',
514
+ RenewalState: RenewalStateLabel(r.State),
515
+ AutoRenewsOn: r.AutoRenewOn ?? null,
516
+ SubscribedSince: r.StartDate,
517
+ TermNumber: r.TermNumber,
518
+ TermStart: r.TermStartDate,
519
+ TermEnd: r.TermEndDate,
520
+ DaysUntilEnd: r.DaysUntilEnd,
521
+ CurrentOrder: r.CurrentOrderNumber ?? null,
522
+ CurrentOrderDate: r.CurrentOrderDate ?? null,
523
+ CurrentOrderStatus: r.CurrentOrderStatus ?? null,
524
+ CurrentPrice: r.CurrentUnitPrice ?? null,
525
+ CurrentQuantity: r.CurrentQuantity ?? null,
526
+ CurrentTotal: r.CurrentLineTotal ?? null,
527
+ CurrentBalance: r.CurrentOrderBalance ?? null,
528
+ RenewalOrder: r.RenewalOrderNumber ?? null,
529
+ RenewalOrderDate: r.RenewalOrderDate ?? null,
530
+ RenewalOrderStatus: r.RenewalOrderStatus ?? null,
531
+ RenewalPrice: placed ? (r.RenewalUnitPrice ?? null) : (r.ProjectedUnitPrice ?? null),
532
+ RenewalQuantity: placed ? (r.RenewalQuantity ?? null) : (r.ProjectedQuantity ?? null),
533
+ RenewalTotal: placed ? (r.RenewalLineTotal ?? null) : (r.ProjectedLineTotal ?? null),
534
+ RenewalPriceBasis: basis(r),
535
+ IncreasePercent: placed ? PriceChangePercent(r.CurrentUnitPrice, r.RenewalUnitPrice) : (r.ProjectedUnitPrice == null ? null : (r.ProjectedIncreasePercent ?? 0)),
536
+ IncreaseSource: placed ? (PriceChangePercent(r.CurrentUnitPrice, r.RenewalUnitPrice) == null ? null : 'Actual, vs current price') : r.ProjectedIncreaseSetPercent ? (r.ProjectedIncreaseSetSource ?? null) : r.ProjectedIncreasePercent ? (r.ProjectedIncreaseSource ?? null) : null,
537
+ IncreaseApplied: placed || r.ProjectedUnitPrice == null ? null : r.ProjectedIncreaseApplied === false && r.ProjectedIncreaseSetPercent ? 'No: no anniversary this term' : r.ProjectedIncreasePercent ? 'Yes' : 'None set',
538
+ SubscriptionIncreasePercent: r.SubscriptionIncreasePercent ?? null,
539
+ RenewalTermStart: placed ? (r.RenewalTermStart ?? null) : (r.ProjectedTermStart ?? null),
540
+ RenewalTermEnd: placed ? (r.RenewalTermEnd ?? null) : (r.ProjectedTermEnd ?? null),
541
+ ProjectionProblem: r.ProjectionProblem ?? null,
542
+ };
543
+ });
544
+ return { Columns, Rows };
545
+ }
546
+ /**
547
+ * How the projected price was reached, as three short lines rather than a paragraph: the base
548
+ * price and where it came from, the increase and whether it applied, and the new term. Null when
549
+ * there is no projection; a single "Cannot price" line when the pricer refused.
550
+ */
551
+ export function ProjectionLines(row) {
552
+ if (row.ProjectionProblem)
553
+ return [{ Label: 'Cannot price', Text: row.ProjectionProblem }];
554
+ if (row.ProjectedUnitPrice == null)
555
+ return null;
556
+ const base = {
557
+ PriorPrice: 'current price',
558
+ PriorList: 'list price, discount lapses',
559
+ SuccessorList: `list price of ${row.ProjectedProductName ?? 'the successor'}`,
560
+ }[row.ProjectedBasePriceSource ?? 'PriorPrice'];
561
+ const level = (source) => (source ? String(source).toLowerCase() : 'none');
562
+ const increase = row.ProjectedIncreasePercent && row.ProjectedIncreasePercent > 0
563
+ ? `+${TrimPercent(row.ProjectedIncreasePercent)}% · set on the ${level(row.ProjectedIncreaseSource)}`
564
+ : row.ProjectedIncreaseApplied === false && row.ProjectedIncreaseSetPercent
565
+ ? `${TrimPercent(row.ProjectedIncreaseSetPercent)}% set on the ${level(row.ProjectedIncreaseSetSource)} · not applied: no anniversary this term`
566
+ : 'none set';
567
+ const out = [
568
+ { Label: 'Base', Text: `${FormatMoney(row.ProjectedBasePrice)} · ${base}` },
569
+ { Label: 'Increase', Text: increase },
570
+ ];
571
+ if (row.ProjectedTermStart && row.ProjectedTermEnd) {
572
+ out.push({ Label: 'New term', Text: `${FormatDate(row.ProjectedTermStart, RENEWALS_DATE)} – ${FormatDate(row.ProjectedTermEnd, RENEWALS_DATE)}` });
573
+ }
574
+ return out;
575
+ }
576
+ function TrimPercent(value) {
577
+ return String(Math.round(value * 100) / 100);
578
+ }
579
+ export function SummarizePlacement(candidates, placeAs = 'Draft') {
580
+ const placeable = candidates.filter((c) => !c.SkippedReason);
581
+ const skipped = candidates.filter((c) => !!c.SkippedReason);
582
+ const total = placeable.reduce((s, c) => s + Number(c.UnitPrice ?? 0) * Number(c.Quantity ?? 1) * (1 - Number(c.DiscountPct ?? 0)), 0);
583
+ const n = placeable.length;
584
+ const orders = new Set(placeable.map((c, i) => (c.OrderGroup == null ? `own-${i}` : `group-${c.OrderGroup}`))).size;
585
+ const how = placeAs === 'Confirmed' ? 'confirmed' : 'drafts';
586
+ const message = n
587
+ ? orders === n
588
+ ? `${n} renewal order${n === 1 ? '' : 's'} will be created as ${n === 1 && how === 'drafts' ? 'a draft' : how}, ${FormatMoney(total)} before tax.`
589
+ : `${n} subscriptions will renew on ${orders} renewal order${orders === 1 ? '' : 's'}, created as ${how}, ${FormatMoney(total)} before tax.`
590
+ : 'Nothing can be placed for the rows you ticked.';
591
+ const detail = skipped.length
592
+ ? `${skipped.length} will be skipped: ${skipped
593
+ .slice(0, 3)
594
+ .map((c) => `${c.SubscriptionNumber} (${c.SkippedReason})`)
595
+ .join('; ')}${skipped.length > 3 ? `, and ${skipped.length - 3} more` : ''}.`
596
+ : '';
597
+ return { Placeable: placeable, Orders: orders, Skipped: skipped, Total: Math.round(total * 100) / 100, Message: message, Detail: detail };
598
+ }
599
+ /**
600
+ * Warnings for the create-renewals dialog about subscriptions bought together. The engine puts one
601
+ * customer's subscriptions ending the same day on one renewal order, so the thing to catch is a
602
+ * sibling that would be LEFT OUT: a person renewing one product by hand may not notice the other
603
+ * bought with it is ending too, and renewing it later puts it on a second order.
604
+ */
605
+ export function SharedOrderWarnings(selected, all) {
606
+ const chosen = new Set(selected.map((r) => r.SubscriptionID));
607
+ const orders = new Map();
608
+ for (const r of selected)
609
+ if (r.CurrentOrderID && !orders.has(r.CurrentOrderID))
610
+ orders.set(r.CurrentOrderID, r);
611
+ const leftOut = [];
612
+ for (const [orderID, row] of orders) {
613
+ const siblings = all.filter((r) => r.CurrentOrderID === orderID && !chosen.has(r.SubscriptionID) && !r.RenewalOrderID);
614
+ if (siblings.length)
615
+ leftOut.push(`${row.CurrentOrderNumber ?? 'an order'} (${siblings.map((r) => r.ProductName).join(', ')})`);
616
+ }
617
+ if (!leftOut.length)
618
+ return [];
619
+ return [
620
+ `Other subscriptions from the same original order${leftOut.length === 1 ? '' : 's'} are ending in this window and are not selected: ${leftOut.slice(0, 3).join('; ')}${leftOut.length > 3 ? `; and ${leftOut.length - 3} more` : ''}. Renewed later, they would go on a separate order.`,
621
+ ];
622
+ }
623
+ /** The order the renewal states sort in: what needs a person first, then what the pass handles, then what is done. */
624
+ const STATE_ORDER = ['Lapsed', 'Ended', 'WillEnd', 'DueNow', 'Scheduled', 'RenewalPending', 'Renewed', 'ProviderBilled', 'Inactive'];
625
+ export function CompareRows(a, b, key) {
626
+ const text = (v) => (v ?? '').toLowerCase();
627
+ const value = (row) => {
628
+ switch (key) {
629
+ case 'ContactName':
630
+ return text(row.ContactName ?? row.AccountName);
631
+ case 'CompanyName':
632
+ return text(row.CompanyName);
633
+ case 'ProductName':
634
+ return text(row.ProductName);
635
+ case 'StartDate':
636
+ return row.StartDate;
637
+ case 'Status':
638
+ return text(row.Status);
639
+ case 'AutoRenew':
640
+ return row.AutoRenew ? 0 : 1;
641
+ case 'State':
642
+ return STATE_ORDER.indexOf(row.State);
643
+ case 'CurrentOrderNumber':
644
+ return text(row.CurrentOrderNumber);
645
+ case 'CurrentUnitPrice':
646
+ return row.CurrentUnitPrice ?? -1;
647
+ case 'RenewalOrderNumber':
648
+ return text(row.RenewalOrderNumber);
649
+ case 'RenewalPrice':
650
+ return row.RenewalOrderID ? (row.RenewalUnitPrice ?? -1) : (row.ProjectedUnitPrice ?? -1);
651
+ default:
652
+ return row.TermEndDate;
653
+ }
654
+ };
655
+ const x = value(a);
656
+ const y = value(b);
657
+ if (x < y)
658
+ return -1;
659
+ if (x > y)
660
+ return 1;
661
+ return a.SubscriptionNumber < b.SubscriptionNumber ? -1 : a.SubscriptionNumber > b.SubscriptionNumber ? 1 : 0;
662
+ }
663
+ //# sourceMappingURL=renewals-page.model.js.map