@go-avro/avro-js 1.6.6-rc9 → 1.7.1

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 (48) hide show
  1. package/dist/chat.d.ts +25 -0
  2. package/dist/chat.js +47 -0
  3. package/dist/client/QueryClient.d.ts +135 -26
  4. package/dist/client/QueryClient.js +115 -59
  5. package/dist/client/cache.d.ts +4 -0
  6. package/dist/client/cache.js +19 -0
  7. package/dist/client/core/uploads.js +226 -0
  8. package/dist/client/hooks/accounts.js +52 -0
  9. package/dist/client/hooks/bills.js +19 -17
  10. package/dist/client/hooks/catalog_items.js +16 -4
  11. package/dist/client/hooks/chats.js +26 -0
  12. package/dist/client/hooks/devices.js +17 -3
  13. package/dist/client/hooks/messages.js +54 -1
  14. package/dist/client/hooks/routes.js +4 -1
  15. package/dist/client/hooks/teams.js +4 -1
  16. package/dist/client/hooks/{proposal_terms.js → terms.js} +14 -14
  17. package/dist/client/realtime.d.ts +26 -3
  18. package/dist/client/realtime.js +94 -16
  19. package/dist/client/requests.d.ts +16 -11
  20. package/dist/index.d.ts +5 -1
  21. package/dist/index.js +4 -1
  22. package/dist/types/api/Account.d.ts +61 -0
  23. package/dist/types/api/Account.js +38 -0
  24. package/dist/types/api/AuditLog.d.ts +1 -1
  25. package/dist/types/api/Avro.d.ts +5 -0
  26. package/dist/types/api/Bill.d.ts +2 -2
  27. package/dist/types/api/BillPayment.d.ts +2 -2
  28. package/dist/types/api/CatalogItem.d.ts +3 -1
  29. package/dist/types/api/Company.d.ts +0 -2
  30. package/dist/types/api/Job.d.ts +4 -4
  31. package/dist/types/api/Job.js +11 -2
  32. package/dist/types/api/MemberState.d.ts +3 -0
  33. package/dist/types/api/Notification.d.ts +39 -0
  34. package/dist/types/api/Proposal.d.ts +2 -2
  35. package/dist/types/api/Task.d.ts +16 -0
  36. package/dist/types/api/Task.js +30 -3
  37. package/dist/types/api/{ProposalTerms.d.ts → Terms.d.ts} +3 -3
  38. package/dist/types/api/Terms.js +1 -0
  39. package/dist/types/api.d.ts +2 -2
  40. package/dist/types/api.js +2 -2
  41. package/dist/types/client.d.ts +125 -0
  42. package/dist/version.d.ts +1 -1
  43. package/dist/version.js +1 -1
  44. package/package.json +1 -1
  45. package/dist/types/api/Subscription.d.ts +0 -10
  46. /package/dist/client/{hooks/proposal_terms.d.ts → core/uploads.d.ts} +0 -0
  47. /package/dist/{types/api/ProposalTerms.js → client/hooks/accounts.d.ts} +0 -0
  48. /package/dist/{types/api/Subscription.js → client/hooks/terms.d.ts} +0 -0
@@ -29,6 +29,11 @@ export const VIEWER_SCOPE = 'mine';
29
29
  export function listScope(key) {
30
30
  return typeof key[2] === 'string' ? key[2] : '';
31
31
  }
32
+ /** The signed-in user's id, from the cached self profile (`['user']`). */
33
+ function viewerIdOf(qc) {
34
+ const id = qc.getQueryData(['user'])?.id;
35
+ return typeof id === 'string' ? id : undefined;
36
+ }
32
37
  function searchAware(filters) {
33
38
  const q = filters.query;
34
39
  return typeof q === 'string' && q.length > 0 ? 'unknown' : 'match';
@@ -72,6 +77,15 @@ function matchJobs(filters, item) {
72
77
  }
73
78
  return searchAware(filters);
74
79
  }
80
+ function matchCatalogItems(filters, item) {
81
+ if (typeof filters.industry === 'string' && filters.industry !== item.industry) {
82
+ return 'nomatch';
83
+ }
84
+ if (typeof filters.archived === 'boolean' && filters.archived !== item.archived) {
85
+ return 'nomatch';
86
+ }
87
+ return searchAware(filters);
88
+ }
75
89
  function isPaidStatus(status) {
76
90
  return status === 'PAID' || status === 'PREPAID' || status === 'EXTERNALLY_PAID';
77
91
  }
@@ -130,10 +144,15 @@ function matchBills(filters, item) {
130
144
  return 'unknown';
131
145
  return searchAware(filters);
132
146
  }
133
- function matchSessions(filters, item, scope) {
134
- // "mine" comes from GET /session (viewer-scoped): can't tell ownership here.
135
- if (scope === VIEWER_SCOPE)
136
- return 'unknown';
147
+ function matchSessions(filters, item, scope, viewerId) {
148
+ // "mine" is GET /session: the viewer's own open sessions. Without
149
+ // knowing the viewer, every session change in the company would
150
+ // refetch it on every client.
151
+ if (scope === VIEWER_SCOPE) {
152
+ if (!viewerId)
153
+ return 'unknown';
154
+ return item.user_id === viewerId && !item.time_ended ? 'match' : 'nomatch';
155
+ }
137
156
  // `unknown_ids` on the sessions endpoint means "fetch exactly these".
138
157
  const wanted = filters.unknown_ids;
139
158
  if (Array.isArray(wanted) && wanted.length > 0) {
@@ -193,6 +212,8 @@ const ALL_LINE_ITEM_STATUSES = { unbilled: true, billed: true, paid: true };
193
212
  /** Single-entity GET (404/403 is treated as gone by the applier). */
194
213
  const getOne = (path) => (client, id) => client.get({ path: path(id) });
195
214
  const COMPANY_EMBEDS = [['companies'], ['/company/list']];
215
+ /** Finance, bill, event and revenue aggregates all read line items and bills. */
216
+ const ANALYTICS = [['analytics']];
196
217
  export const REGISTRY = {
197
218
  job: {
198
219
  ns: 'jobs',
@@ -205,6 +226,7 @@ export const REGISTRY = {
205
226
  construct: constructEvent,
206
227
  fetchMany: bulk('fetchEvents', ALL_LINE_ITEM_STATUSES),
207
228
  listMatch: matchLineItems,
229
+ refreshThrottled: ANALYTICS,
208
230
  },
209
231
  route: {
210
232
  ns: 'routes',
@@ -233,11 +255,10 @@ export const REGISTRY = {
233
255
  listMatch: searchAware,
234
256
  alsoInvalidate: COMPANY_EMBEDS,
235
257
  },
236
- // No single-item GET exists: catalog items only live on the company.
237
258
  catalog_item: {
238
259
  ns: 'catalog_items',
239
- invalidateOnly: true,
240
- alsoInvalidate: COMPANY_EMBEDS,
260
+ fetchMany: bulk('fetchCatalogItems'),
261
+ listMatch: matchCatalogItems,
241
262
  },
242
263
  proposal: {
243
264
  ns: 'proposals',
@@ -245,34 +266,38 @@ export const REGISTRY = {
245
266
  fetchOne: (client, id) => client.get({ path: `/proposal/${id}` }),
246
267
  alsoInvalidate: [['tasks']],
247
268
  },
248
- proposal_terms: {
249
- ns: 'proposal_terms',
250
- fetchOne: (client, id) => client.get({ path: `/proposal_terms/${id}` }),
269
+ terms: {
270
+ ns: 'terms',
271
+ fetchOne: (client, id) => client.get({ path: `/terms/${id}` }),
251
272
  },
252
273
  month: {
253
274
  ns: 'months',
254
275
  fetchMany: bulk('fetchMonths', ALL_LINE_ITEM_STATUSES),
255
276
  listMatch: matchLineItems,
277
+ refreshThrottled: ANALYTICS,
256
278
  },
257
279
  prepayment: {
258
280
  ns: 'prepayments',
259
281
  fetchMany: bulk('fetchPrepayments', ALL_LINE_ITEM_STATUSES),
260
282
  listMatch: matchLineItems,
283
+ refreshThrottled: ANALYTICS,
261
284
  },
262
285
  bill: {
263
286
  ns: 'bills',
264
287
  construct: (d) => new Bill(d),
265
288
  fetchMany: bulk('fetchBills'),
266
289
  listMatch: matchBills,
290
+ refreshThrottled: ANALYTICS,
267
291
  },
268
292
  session: {
269
293
  ns: 'sessions',
270
294
  construct: (raw) => new Session(raw),
271
295
  fetchMany: bulk('fetchSessions'),
272
296
  listMatch: matchSessions,
273
- alsoInvalidate: [['analytics', 'sessions']],
297
+ refreshThrottled: [['analytics', 'sessions']],
274
298
  },
275
299
  checkin: { ns: 'checkins', listMatch: matchCheckins },
300
+ account: { ns: 'accounts', fetchMany: bulk('fetchAccounts'), listMatch: searchAware },
276
301
  waiver: { ns: 'waivers', fetchMany: bulk('fetchWaivers'), listMatch: searchAware },
277
302
  payout: { ns: 'payouts', fetchMany: bulk('fetchPayouts'), listMatch: matchPayouts },
278
303
  timecard: {
@@ -288,8 +313,10 @@ export const REGISTRY = {
288
313
  alsoInvalidate: [['/company/list'], ['companies', 'current']],
289
314
  },
290
315
  member: { ns: 'members', invalidateOnly: true, alsoInvalidate: [['users', 'company']] },
316
+ // Sent to the user's own room only. Their rows in member lists
317
+ // refresh through the `member` changes sent alongside.
291
318
  user: { ns: 'users', invalidateOnly: true, alsoInvalidate: [['user']] },
292
- plan: { ns: 'plans', invalidateOnly: true },
319
+ plan: { ns: 'plans', invalidateOnly: true, refreshThrottled: ANALYTICS },
293
320
  };
294
321
  function mapList(data, fn) {
295
322
  if (Array.isArray(data))
@@ -336,13 +363,14 @@ export function upsertEntity(qc, spec, item, company) {
336
363
  const lists = qc
337
364
  .getQueryCache()
338
365
  .findAll({ predicate: (q) => q.queryKey[0] === spec.ns && isListKey(q.queryKey) });
366
+ const viewerId = viewerIdOf(qc);
339
367
  for (const query of lists) {
340
368
  const key = query.queryKey;
341
369
  const scope = listScope(key);
342
370
  if (company && scope && scope !== company && scope !== VIEWER_SCOPE)
343
371
  continue;
344
372
  const verdict = spec.listMatch
345
- ? spec.listMatch(listFilters(key), item, listScope(key))
373
+ ? spec.listMatch(listFilters(key), item, scope, viewerId)
346
374
  : searchAware(listFilters(key));
347
375
  if (verdict === 'unknown') {
348
376
  qc.invalidateQueries({ queryKey: key, exact: true });
@@ -361,12 +389,12 @@ export function upsertEntity(qc, spec, item, company) {
361
389
  });
362
390
  }
363
391
  }
364
- export function matchesList(type, key, item) {
392
+ export function matchesList(type, key, item, viewerId) {
365
393
  const spec = REGISTRY[type];
366
394
  if (!spec || !isListKey(key))
367
395
  return 'nomatch';
368
396
  return spec.listMatch
369
- ? spec.listMatch(listFilters(key), item, listScope(key))
397
+ ? spec.listMatch(listFilters(key), item, listScope(key), viewerId)
370
398
  : searchAware(listFilters(key));
371
399
  }
372
400
  export function invalidateType(qc, spec) {
@@ -388,6 +416,9 @@ export function retryDenied(qc) {
388
416
  // ─── Applying batches ───────────────────────────────────────────────
389
417
  const FETCH_COALESCE_MS = 50;
390
418
  const FETCH_CHUNK = 100;
419
+ /** Aggregates (analytics) refresh at most this often per client. */
420
+ export const THROTTLED_REFRESH_MS = 60000;
421
+ const REFRESH_JITTER_MS = 5000;
391
422
  /** A fetch failure that means "this entity is gone or no longer visible". */
392
423
  function isGoneError(err) {
393
424
  const status = err?.status;
@@ -399,9 +430,15 @@ function dropFromLists(qc, ns, id) {
399
430
  qc.invalidateQueries({ queryKey: keys.detail(ns, id), exact: true });
400
431
  }
401
432
  export class ChangeApplier {
402
- constructor(client, qc) {
433
+ /**
434
+ * @param refreshMembers fetches the named members and patches them
435
+ * into the member lists (the same path presence uses), so a
436
+ * change to one member doesn't re-download every member.
437
+ */
438
+ constructor(client, qc, refreshMembers) {
403
439
  this.client = client;
404
440
  this.qc = qc;
441
+ this.refreshMembers = refreshMembers;
405
442
  this.pending = new Map();
406
443
  this.timer = null;
407
444
  /**
@@ -415,6 +452,28 @@ export class ChangeApplier {
415
452
  /** Company each pending `type:id` change came from (see upsertEntity). */
416
453
  this.companyOf = new Map();
417
454
  this.inflight = new Map();
455
+ /** Last run time and pending trailing timer per throttled key. */
456
+ this.lastRefresh = new Map();
457
+ this.refreshTimers = new Map();
458
+ }
459
+ /**
460
+ * Refresh `key` now if it hasn't refreshed within the window,
461
+ * otherwise once when the window ends. Leading runs are jittered so
462
+ * clients that all received the same change don't refetch in step.
463
+ */
464
+ refreshThrottled(key) {
465
+ const id = JSON.stringify(key);
466
+ if (this.refreshTimers.has(id))
467
+ return;
468
+ const last = this.lastRefresh.get(id);
469
+ const wait = last === undefined || Date.now() - last >= THROTTLED_REFRESH_MS
470
+ ? Math.random() * REFRESH_JITTER_MS
471
+ : last + THROTTLED_REFRESH_MS - Date.now();
472
+ this.refreshTimers.set(id, setTimeout(() => {
473
+ this.refreshTimers.delete(id);
474
+ this.lastRefresh.set(id, Date.now());
475
+ void this.qc.invalidateQueries({ queryKey: [...key] });
476
+ }, wait));
418
477
  }
419
478
  mark(type, id) {
420
479
  this.latest.set(`${type}:${id}`, ++this.seq);
@@ -435,6 +494,22 @@ export class ChangeApplier {
435
494
  const spec = REGISTRY[entry.type];
436
495
  if (!spec)
437
496
  continue;
497
+ spec.refreshThrottled?.forEach((k) => this.refreshThrottled(k));
498
+ // A named member: patch just that row on every client. No id
499
+ // (joins, leaves, group-wide permission edits) still means the
500
+ // whole list.
501
+ if (entry.type === 'member' && entry.id && this.refreshMembers) {
502
+ this.refreshMembers([entry.id]);
503
+ retryDenied(this.qc);
504
+ continue;
505
+ }
506
+ // The viewer's own profile; their member rows follow via
507
+ // `member` changes, so don't refetch the whole users namespace.
508
+ if (entry.type === 'user' && entry.id) {
509
+ this.qc.invalidateQueries({ queryKey: ['user'] });
510
+ this.qc.invalidateQueries({ queryKey: keys.detail('users', entry.id) });
511
+ continue;
512
+ }
438
513
  if (entry.op === 'invalidate' || spec.invalidateOnly) {
439
514
  invalidateType(this.qc, spec);
440
515
  if (entry.type === 'member')
@@ -590,6 +665,9 @@ export class ChangeApplier {
590
665
  if (this.timer)
591
666
  clearTimeout(this.timer);
592
667
  this.timer = null;
668
+ this.refreshTimers.forEach(clearTimeout);
669
+ this.refreshTimers.clear();
670
+ this.lastRefresh.clear();
593
671
  this.pending.clear();
594
672
  this.companyOf.clear();
595
673
  this.latest.clear();
@@ -191,15 +191,12 @@ export interface BillLineItemInput {
191
191
  /** Unit price in integer cents (default 0). */
192
192
  cost?: number;
193
193
  }
194
- /** A member recipient on a bill write (backend `BillUserIn`). */
195
- export interface BillUserInput {
196
- /** The member's user GUID. */
194
+ /** An autopay charge to attempt when a bill is created (backend `BillChargeIn`). */
195
+ export interface BillChargeInput {
196
+ /** User GUID; skipped unless they have the billing role on the bill's accounts. */
197
197
  id: string;
198
- /**
199
- * Create only: charge up to this many integer cents (>= 0) to the
200
- * user's autopay method. Fractional values are rejected.
201
- */
202
- amt?: number | null;
198
+ /** Integer cents (>= 0), capped at the bill's outstanding amount. */
199
+ amt: number;
203
200
  }
204
201
  /**
205
202
  * Body of `POST /company/<id>/bill` and `PUT /bill/<id>` (backend
@@ -217,8 +214,10 @@ export interface BillWritePayload {
217
214
  line_items?: BillLineItemInput[];
218
215
  /** Extra recipients as `[name, email]` pairs; replaces them. */
219
216
  manual_emails?: [string, string][];
220
- /** Replaces the member recipients. */
221
- users?: BillUserInput[];
217
+ /** Account GUIDs; replaces the accounts billed. */
218
+ accounts?: string[];
219
+ /** Autopay attempts; honored on creation only. */
220
+ charges?: BillChargeInput[];
222
221
  /** At most 256 characters; null clears it. */
223
222
  name?: string | null;
224
223
  /** Marks every item paid outside Avro. */
@@ -293,6 +292,7 @@ export interface CatalogItemUpdatePayload {
293
292
  industry?: CatalogIndustry | (string & {});
294
293
  /** A `CatalogPriceFormat` name, matched like `industry`. */
295
294
  price_format?: CatalogPriceFormat | (string & {});
295
+ archived?: boolean;
296
296
  /** Integer seconds between services; null clears it. */
297
297
  recommended_frequency?: number | null;
298
298
  /** Unix seconds (>= 0); null clears it. */
@@ -301,7 +301,7 @@ export interface CatalogItemUpdatePayload {
301
301
  recommended_expire_on?: number | null;
302
302
  /** Skill GUIDs; replaces the item's skills. */
303
303
  skills?: string[];
304
- /** ProposalTerms GUIDs; replaces the item's suggested terms. */
304
+ /** Terms GUIDs; replaces the item's suggested terms. */
305
305
  terms?: string[];
306
306
  /** Replaces the item's payment options. */
307
307
  payment_options?: PaymentOptionInput[];
@@ -423,6 +423,11 @@ export interface TaskWritePayload {
423
423
  payment_options?: PaymentOptionInput[];
424
424
  /** Price in integer cents; -1 means unset. */
425
425
  price?: number;
426
+ /**
427
+ * Units (or square feet) priced into `price` and the payment options; at
428
+ * least 1, null clears. Informational: prices are totals.
429
+ */
430
+ quantity?: number | null;
426
431
  priority?: boolean;
427
432
  /** Null unlinks the catalog item. */
428
433
  catalog_item_id?: string | null;
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export type { KeyValueStore, QueryPersistOptions } from './client/persist.js';
11
11
  import './client/core/xhr.js';
12
12
  import './client/core/fetch.js';
13
13
  import './client/core/utils.js';
14
+ import './client/core/uploads.js';
14
15
  import './client/hooks/address.js';
15
16
  import './client/hooks/root.js';
16
17
  import './client/hooks/jobs.js';
@@ -37,11 +38,14 @@ import './client/hooks/labels.js';
37
38
  import './client/hooks/groups.js';
38
39
  import './client/hooks/skills.js';
39
40
  import './client/hooks/proposal.js';
40
- import './client/hooks/proposal_terms.js';
41
+ import './client/hooks/terms.js';
41
42
  import './client/hooks/timecards.js';
42
43
  import './client/hooks/waivers.js';
44
+ import './client/hooks/accounts.js';
43
45
  import './client/hooks/email.js';
44
46
  export { defaultPassOnFeeMethod } from './billing/fees.js';
47
+ export { REACTION_CODE_POINTS, reactionGlyph, groupReactions, messageTime, isChatUnread, } from './chat.js';
48
+ export type { ReactionGroup } from './chat.js';
45
49
  export { reverseGeocode } from './geocode.js';
46
50
  export { fetchCensusFeatures } from './census.js';
47
51
  export { getDegradedServices } from './serviceStatus.js';
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ export { QueryPersister, IndexedDBStore, MemoryKeyValueStore, defaultKeyValueSto
7
7
  import './client/core/xhr.js';
8
8
  import './client/core/fetch.js';
9
9
  import './client/core/utils.js';
10
+ import './client/core/uploads.js';
10
11
  import './client/hooks/address.js';
11
12
  import './client/hooks/root.js';
12
13
  import './client/hooks/jobs.js';
@@ -33,11 +34,13 @@ import './client/hooks/labels.js';
33
34
  import './client/hooks/groups.js';
34
35
  import './client/hooks/skills.js';
35
36
  import './client/hooks/proposal.js';
36
- import './client/hooks/proposal_terms.js';
37
+ import './client/hooks/terms.js';
37
38
  import './client/hooks/timecards.js';
38
39
  import './client/hooks/waivers.js';
40
+ import './client/hooks/accounts.js';
39
41
  import './client/hooks/email.js';
40
42
  export { defaultPassOnFeeMethod } from './billing/fees.js';
43
+ export { REACTION_CODE_POINTS, reactionGlyph, groupReactions, messageTime, isChatUnread, } from './chat.js';
41
44
  export { reverseGeocode } from './geocode.js';
42
45
  export { fetchCensusFeatures } from './census.js';
43
46
  export { getDegradedServices } from './serviceStatus.js';
@@ -0,0 +1,61 @@
1
+ import type { UserCompanyAssociation } from './UserCompanyAssociation.js';
2
+ export declare const AccountPermission: {
3
+ readonly BILLING: "billing";
4
+ readonly SERVICE: "service";
5
+ };
6
+ export type AccountPermission = (typeof AccountPermission)[keyof typeof AccountPermission];
7
+ /** A company member on an account, and what they do there. */
8
+ export interface AccountMember {
9
+ id: string;
10
+ account_id: string;
11
+ user_company_id: string;
12
+ permissions: AccountPermission[];
13
+ }
14
+ /** A customer of the company: its people, jobs, and bills. */
15
+ export interface Account {
16
+ id: string;
17
+ company_id: string;
18
+ name: string;
19
+ address: string;
20
+ /** Seconds a bill has until it is due; null means no default terms. */
21
+ net_terms: number | null;
22
+ users: AccountMember[];
23
+ /** Job GUIDs. */
24
+ jobs: string[];
25
+ /** Bill GUIDs. */
26
+ bills: string[];
27
+ time_created: number | null;
28
+ time_updated: number | null;
29
+ }
30
+ /** A member to put on an account. */
31
+ export interface AccountMemberInput {
32
+ /** Member (user-company) GUID. */
33
+ id: string;
34
+ permissions?: AccountPermission[];
35
+ }
36
+ export interface AccountCreatePayload {
37
+ name: string;
38
+ address?: string;
39
+ /** Seconds a bill has until it is due; null removes the terms. */
40
+ net_terms?: number | null;
41
+ users?: AccountMemberInput[];
42
+ /** Job GUIDs. */
43
+ jobs?: string[];
44
+ }
45
+ /** Omitted fields are unchanged; `users` and `jobs` replace the current lists. */
46
+ export type AccountUpdatePayload = Partial<AccountCreatePayload>;
47
+ /** Every account the user is on, optionally only where they hold `role`. */
48
+ export declare function accountsOfUser(accounts: Account[], members: UserCompanyAssociation[], userId: string, role?: AccountPermission): Account[];
49
+ /** One account id per user (their first), without duplicates. */
50
+ export declare function accountIdsForUsers(accounts: Account[], members: UserCompanyAssociation[], userIds: string[], role?: AccountPermission): string[];
51
+ /** Member ids on the given accounts, once each, optionally only those holding `role`. */
52
+ export declare function accountMemberIds(accountIds: string[], accounts: Account[], role?: AccountPermission): string[];
53
+ /** User ids a bill is addressed to: its accounts' billing contacts and anyone who paid. */
54
+ export declare function billRecipientUserIds(bill: {
55
+ accounts: string[];
56
+ payments: {
57
+ user_id: string | null;
58
+ }[];
59
+ }, accounts: Account[], members: UserCompanyAssociation[]): string[];
60
+ /** When a bill issued now is due under the accounts' shortest terms; null if none set any. */
61
+ export declare function netTermsDueDate(accountIds: string[], accounts: Account[]): Date | null;
@@ -0,0 +1,38 @@
1
+ export const AccountPermission = {
2
+ BILLING: 'billing',
3
+ SERVICE: 'service',
4
+ };
5
+ /** Every account the user is on, optionally only where they hold `role`. */
6
+ export function accountsOfUser(accounts, members, userId, role) {
7
+ const member = members.find((candidate) => candidate.user.id === userId);
8
+ if (!member)
9
+ return [];
10
+ return accounts.filter((account) => account.users.some((row) => row.user_company_id === member.id && (!role || row.permissions.includes(role))));
11
+ }
12
+ /** One account id per user (their first), without duplicates. */
13
+ export function accountIdsForUsers(accounts, members, userIds, role) {
14
+ const ids = userIds.flatMap((userId) => accountsOfUser(accounts, members, userId, role)[0]?.id ?? []);
15
+ return [...new Set(ids)];
16
+ }
17
+ /** Member ids on the given accounts, once each, optionally only those holding `role`. */
18
+ export function accountMemberIds(accountIds, accounts, role) {
19
+ const ids = accounts
20
+ .filter((account) => accountIds.includes(account.id))
21
+ .flatMap((account) => account.users)
22
+ .filter((row) => !role || row.permissions.includes(role))
23
+ .map((row) => row.user_company_id);
24
+ return [...new Set(ids)];
25
+ }
26
+ /** User ids a bill is addressed to: its accounts' billing contacts and anyone who paid. */
27
+ export function billRecipientUserIds(bill, accounts, members) {
28
+ const contacts = accountMemberIds(bill.accounts, accounts, AccountPermission.BILLING).flatMap((memberId) => members.find((member) => member.id === memberId)?.user.id ?? []);
29
+ const payers = bill.payments.flatMap((payment) => payment.user_id ?? []);
30
+ return [...new Set([...contacts, ...payers])];
31
+ }
32
+ /** When a bill issued now is due under the accounts' shortest terms; null if none set any. */
33
+ export function netTermsDueDate(accountIds, accounts) {
34
+ const terms = accounts
35
+ .filter((account) => accountIds.includes(account.id) && account.net_terms !== null)
36
+ .map((account) => account.net_terms);
37
+ return terms.length > 0 ? new Date(Date.now() + Math.min(...terms) * 1000) : null;
38
+ }
@@ -12,7 +12,7 @@ export interface AuditLogEntry {
12
12
  time: number | null;
13
13
  actor: string;
14
14
  actor_id: string | null;
15
- entity_type: 'JOB' | 'TASK' | 'EVENT' | 'BILL' | 'COMPANY' | 'MEMBER' | 'GROUP';
15
+ entity_type: 'JOB' | 'TASK' | 'EVENT' | 'BILL' | 'PAYMENT' | 'COMPANY' | 'MEMBER' | 'GROUP';
16
16
  entity_id: string | null;
17
17
  entity_label: string;
18
18
  action: 'CREATED' | 'UPDATED' | 'DELETED';
@@ -165,6 +165,11 @@ export interface ErrorLogEntry {
165
165
  status?: number | null;
166
166
  message: string | null;
167
167
  traceback?: string | null;
168
+ /**
169
+ * Per-field problems of a rejected request (`"field: problem"`). A
170
+ * string when the list was too long and was stored truncated.
171
+ */
172
+ errors?: string[] | string | null;
168
173
  stack?: string | null;
169
174
  fatal?: boolean | null;
170
175
  platform?: string | null;
@@ -1,5 +1,4 @@
1
1
  import { BillPayment } from './BillPayment.js';
2
- import { BillUser } from './BillUser.js';
3
2
  import { CustomLineItem } from './CustomLineItem.js';
4
3
  import { LineItem } from './LineItem.js';
5
4
  import { PaymentType } from './PaymentType.js';
@@ -22,7 +21,8 @@ declare module './Bill.js' {
22
21
  /** Creator's user GUID; the string "None" for automatically created bills. */
23
22
  billed_by: string;
24
23
  manual_emails: string[][];
25
- users: BillUser[];
24
+ /** Accounts the bill was issued to. */
25
+ accounts: string[];
26
26
  status: BillStatus;
27
27
  enabled_payment_methods: PaymentType[];
28
28
  time_created: number | null;
@@ -8,8 +8,8 @@ export interface BillPayment {
8
8
  /** Null for payments recorded outside Stripe. */
9
9
  stripe_pi_id: string | null;
10
10
  payout_id: string | null;
11
- /** Payer's bill-user GUID; the string "None" when there is none. */
12
- bill_user_id: string;
11
+ /** GUID of the user who paid, when known. */
12
+ user_id: string | null;
13
13
  status: 'created' | 'processing' | 'succeeded' | 'failed' | 'canceled' | 'requires_action' | 'in_transit' | 'deposited';
14
14
  type: 'us_bank_account' | 'card';
15
15
  email_paid_by: string;
@@ -1,6 +1,6 @@
1
1
  import { PaymentOption } from './PaymentOption.js';
2
2
  export type CatalogIndustry = 'LAWNCARE' | 'SNOW_REMOVAL' | 'CLEANING' | 'OTHER';
3
- export type CatalogPriceFormat = 'FLAT_RATE' | 'PER_SQFT';
3
+ export type CatalogPriceFormat = 'FLAT_RATE' | 'PER_SQFT' | 'PER_UNIT';
4
4
  export interface CatalogItem {
5
5
  id: string;
6
6
  name: string;
@@ -8,6 +8,8 @@ export interface CatalogItem {
8
8
  description: string;
9
9
  industry: CatalogIndustry;
10
10
  price_format: CatalogPriceFormat;
11
+ /** Hidden from new proposals and the public catalog; kept for tasks. */
12
+ archived: boolean;
11
13
  payment_options: PaymentOption[];
12
14
  recommended_frequency: number | null;
13
15
  recommended_activate_on: number | null;
@@ -6,7 +6,6 @@ import { PaymentType } from './PaymentType.js';
6
6
  import { Plan } from './Plan.js';
7
7
  import { PlanPayment } from './PlanPayment.js';
8
8
  import { Skill } from './Skill.js';
9
- import { CatalogItem } from './CatalogItem.js';
10
9
  export interface Company {
11
10
  id: string;
12
11
  name: string;
@@ -14,7 +13,6 @@ export interface Company {
14
13
  address: string;
15
14
  emails: Email[];
16
15
  skills: Skill[];
17
- catalog_items: CatalogItem[];
18
16
  time_created: number | null;
19
17
  time_updated: number | null;
20
18
  /** Null without `can_read_company`. */
@@ -2,7 +2,6 @@ import { Task } from './Task.js';
2
2
  import { _Event } from './_Event.js';
3
3
  import type { CheckIn } from '../api.js';
4
4
  import { RouteJob } from './RouteJob.js';
5
- import { Subscription } from './Subscription.js';
6
5
  import { Route } from './Route.js';
7
6
  import type { TaskWritePayload } from '../../client/requests.js';
8
7
  declare module './Job.js' {
@@ -28,7 +27,8 @@ declare module './Job.js' {
28
27
  time_created: number | null;
29
28
  time_updated: number | null;
30
29
  routes: RouteJob[];
31
- subscribers: Subscription[];
30
+ /** Account GUIDs; empty unless the viewer can read subscriptions or is on one. */
31
+ accounts: string[];
32
32
  manual_emails: string[][];
33
33
  last_completed_event: _Event | null;
34
34
  current_event: _Event | null;
@@ -74,8 +74,8 @@ export interface JobUpdate {
74
74
  internal_notes?: string;
75
75
  external_notes?: string;
76
76
  serviced_by?: number;
77
- /** Member (user-company) or user GUIDs; replaces the subscriptions. */
78
- subscribers?: string[];
77
+ /** Account GUIDs; replaces the job's accounts. Customers can only change their own. */
78
+ accounts?: string[];
79
79
  /** Extra notification recipients as `[name, email]` pairs. */
80
80
  manual_emails?: [string, string][];
81
81
  /** Replaces the job's tasks: listed ones are upserted, unlisted deleted. */
@@ -50,7 +50,10 @@ export class Job {
50
50
  if (!this.tasks || this.tasks.length === 0) {
51
51
  return 0;
52
52
  }
53
- const routeJob = this.routes.find((r) => r.job_id === this.id);
53
+ // This route's stop: a job on several routes visits different tasks
54
+ // on each. Fall back to any stop if the route's isn't loaded.
55
+ const routeJob = this.routes.find((r) => r.job_id === this.id && r.route_id === route.id) ??
56
+ this.routes.find((r) => r.job_id === this.id);
54
57
  if (!routeJob) {
55
58
  return 0;
56
59
  }
@@ -58,7 +61,13 @@ export class Job {
58
61
  if (contextTasks.length === 0) {
59
62
  return 0;
60
63
  }
61
- return contextTasks.filter((t) => t.isDone?.(route)).length / contextTasks.length;
64
+ // Progress counts only what this visit should do: tasks not due until
65
+ // after the route's next visit (or inactive) are left out entirely.
66
+ const due = contextTasks.filter((t) => t.isDueOn?.(route) ?? true);
67
+ if (due.length === 0) {
68
+ return 1;
69
+ }
70
+ return due.filter((t) => t.isDone?.(route)).length / due.length;
62
71
  };
63
72
  this.isDone = (route) => {
64
73
  return this.portionDone(route) === 1;
@@ -2,6 +2,9 @@ import { Friendship } from './Friendship.js';
2
2
  export interface MemberState {
3
3
  /** The participant's user id. */
4
4
  id: string;
5
+ /** Shown to fellow members even when the member list hides them. */
6
+ first_name?: string;
7
+ last_name?: string;
5
8
  state: 'pending' | 'rejected' | 'typing' | 'present' | 'absent';
6
9
  friendship: Friendship | null;
7
10
  last_message_read_at: number | null;
@@ -15,6 +15,45 @@ export interface NotificationCreated {
15
15
  id: string;
16
16
  email_errors: NotificationEmailError[];
17
17
  }
18
+ /** One part of a notification email (`CreateNotificationPayload`). */
19
+ export interface NotificationBodyPart {
20
+ /** MIME type; `image/*` parts name an uploaded file in `content`. */
21
+ type: string;
22
+ /** The text itself, or the form field name of an uploaded file. */
23
+ content: string;
24
+ /** Inline attachment bytes (base64) instead of an uploaded file. */
25
+ content_b64?: string;
26
+ }
27
+ /** The JSON body of `POST /email/<id>` (`sendEmailMessage`). */
28
+ export interface SendEmailPayload {
29
+ to: string[];
30
+ /** Display names, paired with `to`. */
31
+ to_alias?: string[];
32
+ from?: string;
33
+ from_alias?: string;
34
+ reply_to?: string;
35
+ reply_to_alias?: string;
36
+ subject: string;
37
+ body_parts?: NotificationBodyPart[];
38
+ }
39
+ /** The JSON body of `POST /company/<id>/notification`. */
40
+ export interface CreateNotificationPayload {
41
+ notification: {
42
+ subject: string;
43
+ body: string;
44
+ body_parts?: NotificationBodyPart[];
45
+ };
46
+ /** User ids to notify besides the event's job subscribers. */
47
+ users?: string[];
48
+ /** Sending mailbox; omitted sends no email. */
49
+ email?: string;
50
+ event?: string;
51
+ /** Save the image parts as the event's photos. */
52
+ image_upload_mode?: boolean;
53
+ is_offer?: boolean;
54
+ /** In cents. */
55
+ amount?: number;
56
+ }
18
57
  /** A notification sent within a company (`GET /notification/<id>`). */
19
58
  export interface CompanyNotification {
20
59
  id: string;