@go-avro/avro-js 0.1.15 → 1.6.1-rc1

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 (51) hide show
  1. package/dist/auth/AuthManager.d.ts +32 -0
  2. package/dist/auth/AuthManager.js +138 -43
  3. package/dist/client/QueryClient.d.ts +68 -2
  4. package/dist/client/QueryClient.js +310 -96
  5. package/dist/client/cache.d.ts +24 -0
  6. package/dist/client/cache.js +51 -0
  7. package/dist/client/core/fetch.js +58 -49
  8. package/dist/client/core/policy.d.ts +17 -0
  9. package/dist/client/core/policy.js +35 -0
  10. package/dist/client/core/xhr.js +16 -14
  11. package/dist/client/hooks/bills.js +10 -14
  12. package/dist/client/hooks/catalog_items.js +18 -8
  13. package/dist/client/hooks/chats.js +2 -8
  14. package/dist/client/hooks/companies.js +11 -5
  15. package/dist/client/hooks/events.js +56 -47
  16. package/dist/client/hooks/groups.js +11 -26
  17. package/dist/client/hooks/jobs.js +3 -8
  18. package/dist/client/hooks/labels.js +11 -26
  19. package/dist/client/hooks/messages.js +21 -24
  20. package/dist/client/hooks/months.js +28 -22
  21. package/dist/client/hooks/payouts.js +3 -8
  22. package/dist/client/hooks/prepayments.js +28 -22
  23. package/dist/client/hooks/proposal.js +1 -0
  24. package/dist/client/hooks/routes.js +8 -6
  25. package/dist/client/hooks/sessions.js +21 -31
  26. package/dist/client/hooks/skills.js +6 -4
  27. package/dist/client/hooks/teams.js +6 -4
  28. package/dist/client/hooks/timecards.js +7 -7
  29. package/dist/client/hooks/waivers.js +6 -4
  30. package/dist/client/persist.js +21 -2
  31. package/dist/client/realtime.d.ts +21 -1
  32. package/dist/client/realtime.js +183 -51
  33. package/dist/types/api/Bill.js +2 -1
  34. package/dist/types/api/Company.d.ts +2 -0
  35. package/dist/types/api/Email.d.ts +3 -9
  36. package/dist/types/api/EmailNotification.d.ts +1 -1
  37. package/dist/types/api/Job.js +8 -4
  38. package/dist/types/api/LineItem.d.ts +4 -0
  39. package/dist/types/api/LineItem.js +10 -2
  40. package/dist/types/api/Prepayment.js +2 -1
  41. package/dist/types/api/Route.js +2 -1
  42. package/dist/types/api/RouteJob.js +2 -1
  43. package/dist/types/api/Session.js +2 -1
  44. package/dist/types/api/Task.d.ts +27 -2
  45. package/dist/types/api/Task.js +44 -8
  46. package/dist/types/api/_Event.js +2 -1
  47. package/dist/types/api/assignData.d.ts +9 -0
  48. package/dist/types/api/assignData.js +17 -0
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +7 -2
@@ -27,12 +27,17 @@ function searchAware(filters) {
27
27
  const q = filters.query;
28
28
  return typeof q === 'string' && q.length > 0 ? 'unknown' : 'match';
29
29
  }
30
+ /**
31
+ * Backend id filters: non-empty `unknown_ids` means "only these ids";
32
+ * otherwise `known_ids` means "exclude these ids".
33
+ */
30
34
  function withIds(filters, item) {
31
35
  const known = filters.known_ids;
32
36
  const unknown = filters.unknown_ids;
33
- if (Array.isArray(known) && known.length > 0 && !known.includes(item.id))
34
- return 'nomatch';
35
- if (Array.isArray(unknown) && unknown.length > 0 && unknown.includes(item.id))
37
+ if (Array.isArray(unknown) && unknown.length > 0) {
38
+ return unknown.includes(item.id) ? null : 'nomatch';
39
+ }
40
+ if (Array.isArray(known) && known.length > 0 && known.includes(item.id))
36
41
  return 'nomatch';
37
42
  return null;
38
43
  }
@@ -67,13 +72,18 @@ function isPaidStatus(status) {
67
72
  function isBilledStatus(status) {
68
73
  return status === 'BILLED' || status === 'EXTERNALLY_BILLED';
69
74
  }
70
- /** Shared by events / months / prepayments (line-item lists). */
75
+ /**
76
+ * Shared by events / months / prepayments (line-item lists). Mirrors the
77
+ * backend: the `unbilled`/`billed`/`paid` flags are OR-combined status
78
+ * buckets defaulting to `true`/`false`/`false`; "unbilled" is `CREATED`
79
+ * only, and in-flight statuses (`PROCESSING`, `PENDING_AUTOBILL`) are in
80
+ * no bucket, so no list returns them.
81
+ */
71
82
  function matchLineItems(filters, item) {
72
83
  const byIds = withIds(filters, item);
73
84
  if (byIds)
74
85
  return byIds;
75
- const parentKey = typeof filters.jobId === 'string' ? 'job_id' : null;
76
- if (parentKey && filters.jobId && item[parentKey] !== filters.jobId)
86
+ if (typeof filters.jobId === 'string' && filters.jobId && item.job_id !== filters.jobId)
77
87
  return 'nomatch';
78
88
  if (typeof filters.taskId === 'string' && filters.taskId && item.task_id !== filters.taskId)
79
89
  return 'nomatch';
@@ -85,26 +95,26 @@ function matchLineItems(filters, item) {
85
95
  return 'nomatch';
86
96
  const status = item.status;
87
97
  if (status !== undefined) {
88
- const paid = isPaidStatus(status);
89
- const billed = isBilledStatus(status);
90
- const unbilled = !paid && !billed;
91
- if (filters.paid === false && paid)
92
- return 'nomatch';
93
- if (filters.billed === false && billed)
94
- return 'nomatch';
95
- if (filters.unbilled === false && unbilled)
98
+ const wantUnbilled = filters.unbilled === undefined ? true : filters.unbilled === true;
99
+ const wantBilled = filters.billed === true;
100
+ const wantPaid = filters.paid === true;
101
+ const inBucket = (isPaidStatus(status) && wantPaid) ||
102
+ (isBilledStatus(status) && wantBilled) ||
103
+ (status === 'CREATED' && wantUnbilled);
104
+ if (!inBucket)
96
105
  return 'nomatch';
97
106
  }
98
107
  return searchAware(filters);
99
108
  }
109
+ /** Backend: `paid: true` = fully-paid only; `paid: false` = no paid filter. */
100
110
  function matchBills(filters, item) {
101
111
  const byIds = withIds(filters, item);
102
112
  if (byIds)
103
113
  return byIds;
104
114
  const status = item.status;
105
- if (typeof filters.paid === 'boolean' && status !== undefined) {
115
+ if (filters.paid === true && status !== undefined) {
106
116
  const paid = status === 'PAID' || status === 'MANUALLY_PAID';
107
- if (filters.paid !== paid)
117
+ if (!paid)
108
118
  return 'nomatch';
109
119
  }
110
120
  const hard = ['created_from', 'created_to', 'paid_from', 'paid_to', 'amount_min', 'amount_max'];
@@ -142,8 +152,10 @@ function matchTimecards(filters, item) {
142
152
  return 'nomatch';
143
153
  if (filters.status && item.status !== filters.status)
144
154
  return 'nomatch';
145
- if (filters.periodStart && item.period_start !== filters.periodStart)
146
- return 'nomatch';
155
+ // The backend snaps period_start to the enclosing pay period, so the
156
+ // requested instant can't be compared to item.start client-side.
157
+ if (filters.periodStart)
158
+ return 'unknown';
147
159
  return 'match';
148
160
  }
149
161
  function matchPayouts(filters, item) {
@@ -164,7 +176,12 @@ function matchPayouts(filters, item) {
164
176
  return 'unknown';
165
177
  return searchAware(filters);
166
178
  }
167
- const bulk = (method) => (client, ids) => client[method]({ unknown_ids: ids, amt: ids.length });
179
+ const bulk = (method, extra = {}) => (client, ids) => client[method]({ ...extra, unknown_ids: ids, amt: ids.length });
180
+ /** Line-item list endpoints default to unbilled-only: ask for every bucket. */
181
+ const ALL_LINE_ITEM_STATUSES = { unbilled: true, billed: true, paid: true };
182
+ /** Single-entity GET (404/403 is treated as gone by the applier). */
183
+ const getOne = (path) => (client, id) => client.get({ path: path(id) });
184
+ const COMPANY_EMBEDS = [['companies'], ['/company/list']];
168
185
  export const REGISTRY = {
169
186
  job: {
170
187
  ns: 'jobs',
@@ -175,7 +192,7 @@ export const REGISTRY = {
175
192
  event: {
176
193
  ns: 'events',
177
194
  construct: constructEvent,
178
- fetchMany: bulk('fetchEvents'),
195
+ fetchMany: bulk('fetchEvents', ALL_LINE_ITEM_STATUSES),
179
196
  listMatch: matchLineItems,
180
197
  },
181
198
  route: {
@@ -185,13 +202,31 @@ export const REGISTRY = {
185
202
  listMatch: searchAware,
186
203
  },
187
204
  team: { ns: 'teams', fetchMany: bulk('fetchTeams'), listMatch: searchAware },
188
- group: { ns: 'groups', fetchMany: bulk('fetchGroups'), listMatch: searchAware },
189
- label: { ns: 'labels', fetchMany: bulk('fetchLabels'), listMatch: searchAware },
190
- skill: { ns: 'skills', fetchMany: bulk('fetchSkills'), listMatch: searchAware },
205
+ // Labels, groups, skills and catalog items are also embedded in the
206
+ // company payload, so their changes must refresh it too.
207
+ group: {
208
+ ns: 'groups',
209
+ fetchOne: getOne((id) => `/group/${id}`),
210
+ listMatch: searchAware,
211
+ alsoInvalidate: COMPANY_EMBEDS,
212
+ },
213
+ label: {
214
+ ns: 'labels',
215
+ fetchOne: getOne((id) => `/label/${id}`),
216
+ listMatch: searchAware,
217
+ alsoInvalidate: COMPANY_EMBEDS,
218
+ },
219
+ skill: {
220
+ ns: 'skills',
221
+ fetchMany: bulk('fetchSkills'),
222
+ listMatch: searchAware,
223
+ alsoInvalidate: COMPANY_EMBEDS,
224
+ },
225
+ // No single-item GET exists: catalog items only live on the company.
191
226
  catalog_item: {
192
227
  ns: 'catalog_items',
193
- fetchOne: (client, id) => client.get({ path: `/catalog_item/${id}` }),
194
- listMatch: searchAware,
228
+ invalidateOnly: true,
229
+ alsoInvalidate: COMPANY_EMBEDS,
195
230
  },
196
231
  proposal: {
197
232
  ns: 'proposals',
@@ -203,10 +238,14 @@ export const REGISTRY = {
203
238
  ns: 'proposal_terms',
204
239
  fetchOne: (client, id) => client.get({ path: `/proposal_terms/${id}` }),
205
240
  },
206
- month: { ns: 'months', fetchMany: bulk('fetchMonths'), listMatch: matchLineItems },
241
+ month: {
242
+ ns: 'months',
243
+ fetchMany: bulk('fetchMonths', ALL_LINE_ITEM_STATUSES),
244
+ listMatch: matchLineItems,
245
+ },
207
246
  prepayment: {
208
247
  ns: 'prepayments',
209
- fetchMany: bulk('fetchPrepayments'),
248
+ fetchMany: bulk('fetchPrepayments', ALL_LINE_ITEM_STATUSES),
210
249
  listMatch: matchLineItems,
211
250
  },
212
251
  bill: {
@@ -272,7 +311,13 @@ export function removeEntity(qc, ns, id) {
272
311
  qc.removeQueries({ queryKey: keys.detail(ns, id), exact: true });
273
312
  qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => (old ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old));
274
313
  }
275
- export function upsertEntity(qc, spec, item) {
314
+ /**
315
+ * Write an entity into its detail entry and every list it belongs in.
316
+ * `company` is the company the change came from: list scopes are company
317
+ * ids, so another company's lists are left alone (a member of two
318
+ * companies keeps both companies' lists cached).
319
+ */
320
+ export function upsertEntity(qc, spec, item, company) {
276
321
  const id = item?.id;
277
322
  if (!id)
278
323
  return;
@@ -282,6 +327,9 @@ export function upsertEntity(qc, spec, item) {
282
327
  .findAll({ predicate: (q) => q.queryKey[0] === spec.ns && isListKey(q.queryKey) });
283
328
  for (const query of lists) {
284
329
  const key = query.queryKey;
330
+ const scope = listScope(key);
331
+ if (company && scope && scope !== company)
332
+ continue;
285
333
  const verdict = spec.listMatch
286
334
  ? spec.listMatch(listFilters(key), item, listScope(key))
287
335
  : searchAware(listFilters(key));
@@ -300,12 +348,6 @@ export function upsertEntity(qc, spec, item) {
300
348
  return mapList(old, (items) => items.map((x) => (x?.id === id ? item : x)));
301
349
  return insertInto(old, item);
302
350
  });
303
- // A fresh insert into a server-ordered paged list: settle order.
304
- if (verdict === 'match' &&
305
- key[1] === 'infinite' &&
306
- !listHas(query.state.data, id)) {
307
- qc.invalidateQueries({ queryKey: key, exact: true });
308
- }
309
351
  }
310
352
  }
311
353
  export function matchesList(type, key, item) {
@@ -323,15 +365,49 @@ export function invalidateType(qc, spec) {
323
365
  // ─── Applying batches ───────────────────────────────────────────────
324
366
  const FETCH_COALESCE_MS = 50;
325
367
  const FETCH_CHUNK = 100;
368
+ /** A fetch failure that means "this entity is gone or no longer visible". */
369
+ function isGoneError(err) {
370
+ const status = err?.status;
371
+ return status === 404 || status === 403;
372
+ }
373
+ /** Drop an id from every list in `ns`; mark (don't drop) its detail stale. */
374
+ function dropFromLists(qc, ns, id) {
375
+ qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => (old ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old));
376
+ qc.invalidateQueries({ queryKey: keys.detail(ns, id), exact: true });
377
+ }
326
378
  export class ChangeApplier {
327
379
  constructor(client, qc) {
328
380
  this.client = client;
329
381
  this.qc = qc;
330
382
  this.pending = new Map();
331
383
  this.timer = null;
384
+ /**
385
+ * Latest change sequence per `type:id`. Every change (enqueue, inline
386
+ * data, delete) takes a fresh number; a fetch only applies results for
387
+ * ids whose number is unchanged since it started, so an in-flight
388
+ * fetch can't resurrect a deleted entity or overwrite a newer one.
389
+ */
390
+ this.seq = 0;
391
+ this.latest = new Map();
392
+ /** Company each pending `type:id` change came from (see upsertEntity). */
393
+ this.companyOf = new Map();
394
+ this.inflight = new Map();
395
+ }
396
+ mark(type, id) {
397
+ this.latest.set(`${type}:${id}`, ++this.seq);
398
+ }
399
+ /** Settle a change applied inline: only an in-flight fetch needs the mark. */
400
+ markApplied(type, id) {
401
+ this.pending.get(type)?.delete(id);
402
+ const key = `${type}:${id}`;
403
+ if ((this.inflight.get(key) ?? 0) > 0)
404
+ this.mark(type, id);
405
+ else
406
+ this.latest.delete(key);
332
407
  }
333
408
  apply(payload) {
334
409
  const entries = Array.isArray(payload?.changes) ? payload.changes : [];
410
+ const company = payload?.company ?? null;
335
411
  for (const entry of entries) {
336
412
  const spec = REGISTRY[entry.type];
337
413
  if (!spec)
@@ -346,19 +422,23 @@ export class ChangeApplier {
346
422
  if (!entry.id)
347
423
  continue;
348
424
  if (entry.op === 'delete') {
425
+ this.markApplied(entry.type, entry.id);
349
426
  removeEntity(this.qc, spec.ns, entry.id);
350
427
  spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
351
428
  continue;
352
429
  }
353
430
  if (entry.data !== undefined && entry.data !== null) {
354
- upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data);
431
+ this.markApplied(entry.type, entry.id);
432
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data, company);
355
433
  spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
356
434
  continue;
357
435
  }
436
+ this.companyOf.set(`${entry.type}:${entry.id}`, company);
358
437
  this.enqueue(entry.type, entry.id);
359
438
  }
360
439
  }
361
440
  enqueue(type, id) {
441
+ this.mark(type, id);
362
442
  let set = this.pending.get(type);
363
443
  if (!set) {
364
444
  set = new Set();
@@ -375,7 +455,9 @@ export class ChangeApplier {
375
455
  async flush() {
376
456
  const batches = Array.from(this.pending.entries());
377
457
  this.pending.clear();
378
- await Promise.all(batches.map(([type, ids]) => this.fetchAndApply(type, [...ids])));
458
+ await Promise.all(batches
459
+ .filter(([, ids]) => ids.size > 0)
460
+ .map(([type, ids]) => this.fetchAndApply(type, [...ids])));
379
461
  }
380
462
  /** True when some mounted hook is currently observing this namespace. */
381
463
  isObserved(ns) {
@@ -395,40 +477,87 @@ export class ChangeApplier {
395
477
  invalidateType(this.qc, spec);
396
478
  return;
397
479
  }
480
+ const started = new Map(ids.map((id) => [id, this.latest.get(`${type}:${id}`)]));
481
+ // Only ids with no newer change since this fetch began may be applied.
482
+ const current = (id) => this.latest.get(`${type}:${id}`) === started.get(id);
483
+ const settle = (id) => {
484
+ const key = `${type}:${id}`;
485
+ const left = (this.inflight.get(key) ?? 1) - 1;
486
+ if (left > 0) {
487
+ this.inflight.set(key, left);
488
+ return;
489
+ }
490
+ this.inflight.delete(key);
491
+ if (current(id)) {
492
+ this.latest.delete(key);
493
+ this.companyOf.delete(key);
494
+ }
495
+ };
496
+ ids.forEach((id) => {
497
+ const key = `${type}:${id}`;
498
+ this.inflight.set(key, (this.inflight.get(key) ?? 0) + 1);
499
+ });
398
500
  try {
399
- let raws = [];
501
+ const found = new Map();
502
+ const gone = new Set();
503
+ let failed = false;
400
504
  if (spec.fetchMany) {
401
505
  for (let i = 0; i < ids.length; i += FETCH_CHUNK) {
402
506
  const chunk = ids.slice(i, i + FETCH_CHUNK);
403
507
  const got = await spec.fetchMany(this.client, chunk);
404
- raws = raws.concat(Array.isArray(got) ? got : []);
508
+ for (const raw of Array.isArray(got) ? got : []) {
509
+ if (raw?.id)
510
+ found.set(raw.id, raw);
511
+ }
405
512
  }
513
+ // The bulk endpoint is authoritative for the ids it was asked for.
514
+ for (const id of ids)
515
+ if (!found.has(id))
516
+ gone.add(id);
406
517
  }
407
518
  else if (spec.fetchOne) {
408
519
  const results = await Promise.allSettled(ids.map((id) => spec.fetchOne(this.client, id)));
409
- raws = results
410
- .filter((r) => r.status === 'fulfilled')
411
- .map((r) => r.value)
412
- .filter(Boolean);
520
+ results.forEach((r, i) => {
521
+ const id = ids[i];
522
+ if (r.status === 'fulfilled') {
523
+ if (r.value?.id)
524
+ found.set(r.value.id, r.value);
525
+ else
526
+ gone.add(id);
527
+ }
528
+ else if (isGoneError(r.reason)) {
529
+ gone.add(id);
530
+ }
531
+ else {
532
+ // Transient failure: not evidence of deletion.
533
+ failed = true;
534
+ console.error(`[realtime] fetch ${type} ${id} failed:`, r.reason);
535
+ }
536
+ });
413
537
  }
414
538
  else {
539
+ ids.forEach(settle);
415
540
  invalidateType(this.qc, spec);
416
541
  return;
417
542
  }
418
- const seen = new Set();
419
- for (const raw of raws) {
420
- if (!raw?.id)
543
+ for (const [id, raw] of found) {
544
+ if (!current(id))
421
545
  continue;
422
- seen.add(raw.id);
423
- upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw);
546
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw, this.companyOf.get(`${type}:${id}`));
547
+ }
548
+ for (const id of gone) {
549
+ if (current(id))
550
+ dropFromLists(this.qc, spec.ns, id);
424
551
  }
425
- for (const id of ids)
426
- if (!seen.has(id))
427
- removeEntity(this.qc, spec.ns, id);
428
- spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
552
+ ids.forEach(settle);
553
+ if (failed)
554
+ invalidateType(this.qc, spec);
555
+ else
556
+ spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
429
557
  }
430
558
  catch (err) {
431
559
  console.error(`[realtime] bulk fetch for ${type} failed:`, err);
560
+ ids.forEach(settle);
432
561
  invalidateType(this.qc, spec);
433
562
  }
434
563
  }
@@ -437,6 +566,9 @@ export class ChangeApplier {
437
566
  clearTimeout(this.timer);
438
567
  this.timer = null;
439
568
  this.pending.clear();
569
+ this.companyOf.clear();
570
+ this.latest.clear();
571
+ this.inflight.clear();
440
572
  }
441
573
  }
442
574
  /** Namespaces a mutation should refetch when no socket can deliver the change. */
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { LineItem } from './LineItem.js';
2
3
  export const BillStatus = {
3
4
  SENT: 'SENT',
@@ -17,7 +18,7 @@ export class Bill {
17
18
  this.customItems = () => (this.line_items ?? []).filter((item) => item.line_item_type === 'CUSTOM' || item.line_item_type === 'PROCESSING_FEE');
18
19
  this.topLevelItems = () => (this.line_items ?? []).filter((item) => !item.parent_id);
19
20
  this.childItems = (parentId) => (this.line_items ?? []).filter((item) => item.parent_id === parentId);
20
- Object.assign(this, init);
21
+ assignData(this, init);
21
22
  if (init?.line_items) {
22
23
  this.line_items = init.line_items.map((item) => new LineItem(item));
23
24
  }
@@ -61,4 +61,6 @@ export interface Company {
61
61
  default_pass_on_fees: boolean;
62
62
  require_team_for_clock_in: boolean;
63
63
  accepts_cash_payments: boolean;
64
+ /** IANA zone (e.g. `America/Chicago`) for route recurrence and bill days. */
65
+ timezone: string;
64
66
  }
@@ -3,21 +3,15 @@ export interface Email {
3
3
  id: string;
4
4
  company_id: string;
5
5
  name: string;
6
- mail_server: string;
7
- mail_port: number;
8
6
  mail_username: string;
9
- mail_password: string | null;
10
7
  mail_default_sender: string;
11
- mail_use_tls: boolean;
12
- mail_use_ssl: boolean;
13
8
  mail_api_key: string;
14
9
  is_company_wide: boolean;
15
10
  users: User[];
16
- type: 'OUTLOOK' | 'SMTP' | 'GMAIL';
11
+ type: 'OUTLOOK' | 'GMAIL';
17
12
  /**
18
- * False when an OAuth (Outlook/Gmail) account's grant was revoked or
19
- * expired: sends fail until someone signs in again. Always true for
20
- * SMTP accounts.
13
+ * False when the account's grant was revoked or expired: sends fail
14
+ * until someone signs in again.
21
15
  */
22
16
  connected: boolean;
23
17
  }
@@ -19,7 +19,7 @@ export interface EmailError {
19
19
  * raised before any provider could be selected (e.g. missing
20
20
  * billing email, no recipients).
21
21
  */
22
- provider: 'outlook' | 'gmail' | 'smtp' | 'unknown';
22
+ provider: 'outlook' | 'gmail' | 'unknown';
23
23
  }
24
24
  export type EmailType = 'bill' | 'proposal' | 'job' | 'generic';
25
25
  export interface EmailSucceededPayload {
@@ -1,4 +1,5 @@
1
- import { Task, TaskStatus } from './Task.js';
1
+ import { assignData } from './assignData.js';
2
+ import { Task, TaskStatus, getTaskOverdueness } from './Task.js';
2
3
  import { RouteJob } from './RouteJob.js';
3
4
  export class Job {
4
5
  constructor(init) {
@@ -10,11 +11,14 @@ export class Job {
10
11
  if (activeTasks.length === 0) {
11
12
  return 'N/A';
12
13
  }
14
+ const now = Date.now() / 1000;
15
+ const live = (t) => getTaskOverdueness(t, now);
13
16
  const mostOverdueTask = activeTasks.reduce((mostOverdue, t) => {
14
- if (!t.overdueness || t.overdueness <= 0) {
17
+ const overdueness = live(t);
18
+ if (!overdueness || overdueness <= 0) {
15
19
  return mostOverdue;
16
20
  }
17
- if (!mostOverdue || t.overdueness > (mostOverdue.overdueness ?? 0)) {
21
+ if (!mostOverdue || overdueness > (live(mostOverdue) ?? 0)) {
18
22
  return t;
19
23
  }
20
24
  return mostOverdue;
@@ -59,7 +63,7 @@ export class Job {
59
63
  this.isDone = (route) => {
60
64
  return this.portionDone(route) === 1;
61
65
  };
62
- Object.assign(this, init);
66
+ assignData(this, init);
63
67
  if (init?.tasks) {
64
68
  this.tasks = init.tasks.map((t) => new Task(t));
65
69
  }
@@ -1,5 +1,6 @@
1
1
  export declare const LineItemStatus: {
2
2
  readonly CREATED: "CREATED";
3
+ readonly PENDING_AUTOBILL: "PENDING_AUTOBILL";
3
4
  readonly EXTERNALLY_BILLED: "EXTERNALLY_BILLED";
4
5
  readonly BILLED: "BILLED";
5
6
  readonly PROCESSING: "PROCESSING";
@@ -38,5 +39,8 @@ export declare class LineItem {
38
39
  constructor(init?: Partial<LineItem>);
39
40
  isPaid: () => boolean;
40
41
  isBilled: () => boolean;
42
+ /** Matches the backend's "unbilled" bucket: `CREATED` only. */
41
43
  isUnbilled: () => boolean;
44
+ /** In flight: being auto-billed or a payment is processing (in no list bucket). */
45
+ isPending: () => boolean;
42
46
  }
@@ -1,5 +1,7 @@
1
+ import { assignData } from './assignData.js';
1
2
  export const LineItemStatus = {
2
3
  CREATED: 'CREATED',
4
+ PENDING_AUTOBILL: 'PENDING_AUTOBILL',
3
5
  EXTERNALLY_BILLED: 'EXTERNALLY_BILLED',
4
6
  BILLED: 'BILLED',
5
7
  PROCESSING: 'PROCESSING',
@@ -27,9 +29,15 @@ export class LineItem {
27
29
  return (this.status === LineItemStatus.BILLED ||
28
30
  this.status === LineItemStatus.EXTERNALLY_BILLED);
29
31
  };
32
+ /** Matches the backend's "unbilled" bucket: `CREATED` only. */
30
33
  this.isUnbilled = () => {
31
- return !this.isBilled() && !this.isPaid();
34
+ return this.status === LineItemStatus.CREATED;
32
35
  };
33
- Object.assign(this, init);
36
+ /** In flight: being auto-billed or a payment is processing (in no list bucket). */
37
+ this.isPending = () => {
38
+ return (this.status === LineItemStatus.PENDING_AUTOBILL ||
39
+ this.status === LineItemStatus.PROCESSING);
40
+ };
41
+ assignData(this, init);
34
42
  }
35
43
  }
@@ -1,7 +1,8 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { LineItem } from './LineItem.js';
2
3
  export class Prepayment extends LineItem {
3
4
  constructor(init) {
4
5
  super(init);
5
- Object.assign(this, init);
6
+ assignData(this, init);
6
7
  }
7
8
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { RouteJob } from './RouteJob.js';
2
3
  export const FrequencyType = {
3
4
  ONCE: 'ONCE',
@@ -84,7 +85,7 @@ export class Route {
84
85
  }
85
86
  return offset;
86
87
  };
87
- Object.assign(this, init);
88
+ assignData(this, init);
88
89
  if (init?.jobs) {
89
90
  this.jobs = init.jobs.map((j) => new RouteJob(j));
90
91
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  export class RouteJob {
2
3
  constructor(init) {
3
4
  this.getPredictedArrival = () => {
@@ -5,7 +6,7 @@ export class RouteJob {
5
6
  ? this.estimated_arrival_time
6
7
  : this.scheduled_arrival_time;
7
8
  };
8
- Object.assign(this, init);
9
+ assignData(this, init);
9
10
  this.tasks = (init?.tasks ?? []).map((t) => typeof t === 'string'
10
11
  ? { id: t, depends_on: [] }
11
12
  : { ...t, depends_on: t.depends_on ?? [] });
@@ -1,5 +1,6 @@
1
+ import { assignData } from './assignData.js';
1
2
  export class Session {
2
3
  constructor(init) {
3
- Object.assign(this, init);
4
+ assignData(this, init);
4
5
  }
5
6
  }
@@ -45,8 +45,19 @@ declare module './Task.js' {
45
45
  time_updated: number | null;
46
46
  status: TaskStatus;
47
47
  created_by: UserCompanyAssociation | null;
48
+ /**
49
+ * Overdueness as of `overdue_at`. It grows with time while nothing
50
+ * in the database changes, so no realtime event refreshes it:
51
+ * prefer `getOverdueness()`.
52
+ */
48
53
  overdueness: number | null;
54
+ /** Seconds overdue as of `overdue_at`; prefer `getOverdueTime()`. */
49
55
  overdue_time: number;
56
+ /**
57
+ * When (epoch seconds) `overdueness`/`overdue_time` were computed:
58
+ * when the server payload arrived, unless the copy carried one.
59
+ */
60
+ overdue_at: number;
50
61
  last_completed_event: _Event | null;
51
62
  current_event: _Event | null;
52
63
  /**
@@ -84,12 +95,25 @@ declare module './Task.js' {
84
95
  export declare const getTaskDelayUntil: (task: {
85
96
  delay_until?: number | null;
86
97
  }, now?: number) => number | null;
98
+ /**
99
+ * Seconds overdue at `now`, rolled forward from the server's snapshot.
100
+ * Mirrors the backend: the clock only moves the value forward, except that
101
+ * a delay stops counting once it has ended.
102
+ */
103
+ type OverdueSnapshot = Partial<Pick<Task, 'overdueness' | 'overdue_time' | 'overdue_at' | 'delay' | 'delay_until' | 'status' | 'frequency' | 'priority'>>;
104
+ export declare const getTaskOverdueTime: (task: OverdueSnapshot, now?: number) => number;
105
+ /** The backend's overdueness formula, evaluated at `now`. */
106
+ export declare const getTaskOverdueness: (task: OverdueSnapshot, now?: number) => number | null;
87
107
  export declare class Task {
88
108
  constructor(init?: Partial<Task>);
89
109
  getStatusLabel: () => "Active" | "Archived" | "Pending Activation" | "Draft" | "Pending Customer Approval" | "Pending Company Approval" | "Pending Payment";
90
110
  getUnroutedReasonLabel: () => string | null;
91
- isOverdue: () => boolean;
92
- getOverdueLabel: () => string;
111
+ /** Seconds overdue right now (negative: due in that many seconds). */
112
+ getOverdueTime: (now?: number) => number;
113
+ /** Overdueness right now; null when the server reported none. */
114
+ getOverdueness: (now?: number) => number | null;
115
+ isOverdue: (now?: number) => boolean;
116
+ getOverdueLabel: (now?: number) => string;
93
117
  /** End (epoch seconds) of this task's delay if it's still in effect. */
94
118
  getDelayUntil: (now?: number) => number | null;
95
119
  isDelayed: (now?: number) => boolean;
@@ -99,3 +123,4 @@ export declare class Task {
99
123
  getPrepaidMonthsRemaining: () => number;
100
124
  isDone: (route: Route) => boolean;
101
125
  }
126
+ export {};