@go-avro/avro-js 1.6.5 → 1.6.6-rc10

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 (73) hide show
  1. package/dist/client/QueryClient.d.ts +150 -60
  2. package/dist/client/QueryClient.js +175 -27
  3. package/dist/client/core/xhr.js +2 -1
  4. package/dist/client/hooks/audit.js +4 -2
  5. package/dist/client/hooks/avro.js +19 -2
  6. package/dist/client/hooks/bills.d.ts +1 -1
  7. package/dist/client/hooks/bills.js +54 -16
  8. package/dist/client/hooks/catalog_items.js +20 -5
  9. package/dist/client/hooks/chats.js +33 -1
  10. package/dist/client/hooks/companies.js +38 -4
  11. package/dist/client/hooks/events.js +13 -9
  12. package/dist/client/hooks/jobs.js +29 -3
  13. package/dist/client/hooks/messages.js +6 -2
  14. package/dist/client/hooks/plans.js +1 -1
  15. package/dist/client/hooks/routes.js +55 -5
  16. package/dist/client/hooks/sessions.js +39 -11
  17. package/dist/client/hooks/skills.js +1 -1
  18. package/dist/client/hooks/teams.js +5 -2
  19. package/dist/client/hooks/timecards.js +2 -1
  20. package/dist/client/hooks/users.js +21 -3
  21. package/dist/client/realtime.d.ts +13 -0
  22. package/dist/client/realtime.js +41 -8
  23. package/dist/client/requests.d.ts +503 -0
  24. package/dist/client/requests.js +5 -0
  25. package/dist/client/wire.d.ts +7 -0
  26. package/dist/client/wire.js +14 -0
  27. package/dist/index.d.ts +1 -0
  28. package/dist/types/api/AdditionalCharge.d.ts +2 -1
  29. package/dist/types/api/Avro.d.ts +72 -21
  30. package/dist/types/api/Bill.d.ts +7 -5
  31. package/dist/types/api/BillPayment.d.ts +8 -4
  32. package/dist/types/api/BillUser.d.ts +3 -2
  33. package/dist/types/api/CatalogItem.d.ts +11 -6
  34. package/dist/types/api/Chat.d.ts +3 -5
  35. package/dist/types/api/Company.d.ts +41 -15
  36. package/dist/types/api/DelayEvent.d.ts +5 -2
  37. package/dist/types/api/Device.d.ts +5 -4
  38. package/dist/types/api/Email.d.ts +14 -3
  39. package/dist/types/api/Friendship.d.ts +8 -0
  40. package/dist/types/api/Group.d.ts +3 -2
  41. package/dist/types/api/Job.d.ts +55 -5
  42. package/dist/types/api/LineItem.d.ts +3 -2
  43. package/dist/types/api/MemberState.d.ts +2 -1
  44. package/dist/types/api/Message.d.ts +4 -3
  45. package/dist/types/api/Notification.d.ts +26 -0
  46. package/dist/types/api/PaymentMethod.d.ts +7 -2
  47. package/dist/types/api/PaymentOption.d.ts +6 -4
  48. package/dist/types/api/Payout.d.ts +1 -1
  49. package/dist/types/api/Plan.d.ts +5 -4
  50. package/dist/types/api/PlanPayment.d.ts +5 -3
  51. package/dist/types/api/Prepayment.d.ts +2 -1
  52. package/dist/types/api/Proposal.d.ts +1 -1
  53. package/dist/types/api/Reaction.d.ts +3 -3
  54. package/dist/types/api/Refund.d.ts +1 -1
  55. package/dist/types/api/Route.d.ts +11 -10
  56. package/dist/types/api/Route.js +5 -0
  57. package/dist/types/api/RouteJob.d.ts +1 -1
  58. package/dist/types/api/ServiceMonth.d.ts +2 -2
  59. package/dist/types/api/Session.d.ts +5 -2
  60. package/dist/types/api/Skill.d.ts +2 -2
  61. package/dist/types/api/Subscription.d.ts +5 -3
  62. package/dist/types/api/Task.d.ts +10 -9
  63. package/dist/types/api/Task.js +3 -1
  64. package/dist/types/api/TimecardAction.d.ts +2 -2
  65. package/dist/types/api/User.d.ts +11 -9
  66. package/dist/types/api/UserCompanyAssociation.d.ts +7 -1
  67. package/dist/types/api/UserMerge.d.ts +3 -3
  68. package/dist/types/api/_Event.d.ts +20 -4
  69. package/dist/types/api/_Event.js +1 -0
  70. package/dist/types/api.d.ts +156 -39
  71. package/dist/version.d.ts +1 -1
  72. package/dist/version.js +1 -1
  73. package/package.json +1 -1
@@ -6,7 +6,8 @@ import { fetchCensusFeatures } from '../census.js';
6
6
  import { LoginResponse, } from '../types/api.js';
7
7
  import { AuthState } from '../types/auth.js';
8
8
  import { StandardError } from '../types/error.js';
9
- import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, } from './realtime.js';
9
+ import { withoutEmpty } from './wire.js';
10
+ import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, retryDenied, } from './realtime.js';
10
11
  import { QueryPersister } from './persist.js';
11
12
  /** Keep the original status (401/403/404/0…) when surfacing a list-fetch failure. */
12
13
  function fetchError(err, context) {
@@ -40,8 +41,12 @@ function filterLocally(items, body, fields) {
40
41
  /** Translate a legacy camelCase parent filter to the snake_case the backend reads. */
41
42
  function withWireParent(body, legacy, wire) {
42
43
  const { [legacy]: legacyValue, ...rest } = body;
43
- return { ...rest, [wire]: rest[wire] ?? legacyValue ?? undefined };
44
+ // The backend's id filters are UUIDs: '' or null means "no filter",
45
+ // so omit the key rather than send a value it rejects.
46
+ return { ...rest, [wire]: rest[wire] || legacyValue || undefined };
44
47
  }
48
+ /** `ListMessages.amt` upper bound. */
49
+ const MAX_MESSAGES_PER_PAGE = 100;
45
50
  const AUTH_RECHECK_MIN_MS = 2000;
46
51
  const AUTH_RECHECK_MAX_MS = 60000;
47
52
  const SOCKET_AUTH_RETRY_MS = 10000;
@@ -314,9 +319,14 @@ export class AvroQueryClient {
314
319
  }
315
320
  applier.apply(payload);
316
321
  });
322
+ // Sent to each member whose access changed (a grant, a group
323
+ // join/leave, or an edit to one of their groups): rejoin, and
324
+ // retry whatever the old permissions were refused.
317
325
  on('rejoin_company', (data) => {
318
- if (data?.company_id && data.company_id === this.companyId)
326
+ if (data?.company_id && data.company_id === this.companyId) {
319
327
  this.joinCompanyRoom();
328
+ retryDenied(queryClient);
329
+ }
320
330
  });
321
331
  // Sent before a chat room is closed after a membership change;
322
332
  // the server re-checks membership, so removed members stay out.
@@ -353,21 +363,24 @@ export class AvroQueryClient {
353
363
  this._presencePending.clear();
354
364
  if (!this.companyId || userIds.length === 0)
355
365
  return;
356
- this.post({
357
- path: `/company/${this.companyId}/users`,
358
- data: JSON.stringify({ user_ids: userIds }),
359
- headers: { 'Content-Type': 'application/json' },
360
- idempotent: true,
361
- })
362
- .then((members) => {
363
- if (!Array.isArray(members)) {
364
- markMembersStale();
365
- return;
366
- }
367
- for (const member of members)
368
- patchMember(queryClient, member);
369
- })
370
- .catch(markMembersStale);
366
+ // `ListCompanyUsers.user_ids` holds at most 1000 ids.
367
+ for (let i = 0; i < userIds.length; i += 1000) {
368
+ this.post({
369
+ path: `/company/${this.companyId}/users`,
370
+ data: JSON.stringify({ user_ids: userIds.slice(i, i + 1000) }),
371
+ headers: { 'Content-Type': 'application/json' },
372
+ idempotent: true,
373
+ })
374
+ .then((members) => {
375
+ if (!Array.isArray(members)) {
376
+ markMembersStale();
377
+ return;
378
+ }
379
+ for (const member of members)
380
+ patchMember(queryClient, member);
381
+ })
382
+ .catch(markMembersStale);
383
+ }
371
384
  }, PRESENCE_COALESCE_MS);
372
385
  });
373
386
  on('location_update', (data) => {
@@ -383,12 +396,15 @@ export class AvroQueryClient {
383
396
  patchTeamLocation(queryClient, data);
384
397
  patchMemberLocation(queryClient, data);
385
398
  });
386
- // schedule_locked lives in a Redis lock, not a row.
399
+ // schedule_locked and intuit_sync_locked live in Redis locks, not rows.
387
400
  for (const event of [
388
401
  'schedule_started',
389
402
  'schedule_complete',
390
403
  'scheduling_error',
391
404
  'schedule_adjustments',
405
+ 'intuit_sync_started',
406
+ 'intuit_sync_complete',
407
+ 'intuit_sync_error',
392
408
  ]) {
393
409
  on(event, () => {
394
410
  queryClient.invalidateQueries({ queryKey: ['companies'] });
@@ -483,8 +499,8 @@ export class AvroQueryClient {
483
499
  // Reporting must never become a second failure.
484
500
  }
485
501
  }
486
- post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }) {
487
- return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
502
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, refreshOnUnauthorized, }) {
503
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback, refreshOnUnauthorized ?? true);
488
504
  }
489
505
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
490
506
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -581,7 +597,7 @@ export class AvroQueryClient {
581
597
  const queryClient = this.getQueryClient();
582
598
  return useMutation({
583
599
  mutationFn: async ({ token, cancelToken, }) => {
584
- const resp = await this._xhr('POST', `/google/authorize?token=${token}`, {}, cancelToken, { 'Content-Type': 'application/json' });
600
+ const resp = await this._xhr('POST', `/google/authorize?token=${encodeURIComponent(token)}`, {}, cancelToken, { 'Content-Type': 'application/json' });
585
601
  if (!resp || !('access_token' in resp)) {
586
602
  if (resp.msg === 'TOTP required') {
587
603
  return LoginResponse.NEEDS_TOTP;
@@ -731,6 +747,103 @@ export class AvroQueryClient {
731
747
  },
732
748
  });
733
749
  }
750
+ /**
751
+ * Sign in with a Microsoft authorization code (`code` + the `uri` it was
752
+ * issued for). With no account for the identity yet this resolves
753
+ * `NEEDS_ACCOUNT` (rather than failing) carrying the handle for
754
+ * `useMicrosoftLink`. A 401 means the matching account is linked to
755
+ * another Microsoft identity.
756
+ */
757
+ useMicrosoftLogin() {
758
+ const queryClient = this.getQueryClient();
759
+ return useMutation({
760
+ mutationFn: async ({ code, uri, cancelToken, }) => {
761
+ let resp;
762
+ try {
763
+ resp = await this.post({
764
+ path: `/microsoft/authorize?code=${encodeURIComponent(code)}&uri=${encodeURIComponent(uri)}`,
765
+ cancelToken,
766
+ headers: { 'Content-Type': 'application/json' },
767
+ });
768
+ }
769
+ catch (err) {
770
+ const body = err instanceof StandardError ? err.body : undefined;
771
+ if (err instanceof StandardError &&
772
+ err.status === 404 &&
773
+ body &&
774
+ typeof body.microsoft_token === 'string') {
775
+ const notFound = body;
776
+ return {
777
+ status: 'NEEDS_ACCOUNT',
778
+ microsoft_token: notFound.microsoft_token,
779
+ email: notFound.email ?? null,
780
+ first_name: notFound.first_name ?? '',
781
+ last_name: notFound.last_name ?? '',
782
+ };
783
+ }
784
+ throw err;
785
+ }
786
+ if (!resp || !('access_token' in resp)) {
787
+ throw new StandardError(401, 'Invalid Microsoft login response');
788
+ }
789
+ await this.loginSuccess({
790
+ access_token: resp.access_token,
791
+ refresh_token: resp.refresh_token,
792
+ });
793
+ return { status: LoginResponse.SUCCESS };
794
+ },
795
+ onSettled: () => {
796
+ queryClient.invalidateQueries();
797
+ },
798
+ onError: (err) => {
799
+ console.error('Microsoft Login failed:', err);
800
+ },
801
+ });
802
+ }
803
+ /**
804
+ * Finish a `NEEDS_ACCOUNT` Microsoft sign-in with its `microsoft_token`
805
+ * once the account exists, then sign in with the returned tokens.
806
+ *
807
+ * When the 404 carried an `email`, the handle signs in to the account
808
+ * with that address and no session is needed. When `email` was null,
809
+ * the identity is linked to the account this client is signed in to:
810
+ * sign in to the new account first (e.g. `loginSuccess` with the tokens
811
+ * `POST /user` returned, or a code login when it answered
812
+ * `TOTP required`); the request carries the current session's token.
813
+ * 401s: `Sign in to link this Microsoft account` (no session; the
814
+ * handle stays valid for a retry within 10 min), `This Microsoft
815
+ * account is linked to another account`, `This account is linked to
816
+ * another Microsoft account`. 400: the handle is invalid or expired.
817
+ */
818
+ useMicrosoftLink() {
819
+ const queryClient = this.getQueryClient();
820
+ return useMutation({
821
+ mutationFn: async ({ microsoftToken, cancelToken, }) => {
822
+ const resp = await this.post({
823
+ path: `/microsoft/authorize?token=${encodeURIComponent(microsoftToken)}`,
824
+ cancelToken,
825
+ headers: { 'Content-Type': 'application/json' },
826
+ // The handle is one-time: a refresh-and-replay after a
827
+ // "linked elsewhere" 401 would only get "expired".
828
+ refreshOnUnauthorized: false,
829
+ });
830
+ if (!resp || !('access_token' in resp)) {
831
+ throw new StandardError(401, 'Invalid Microsoft login response');
832
+ }
833
+ await this.loginSuccess({
834
+ access_token: resp.access_token,
835
+ refresh_token: resp.refresh_token,
836
+ });
837
+ return LoginResponse.SUCCESS;
838
+ },
839
+ onSettled: () => {
840
+ queryClient.invalidateQueries();
841
+ },
842
+ onError: (err) => {
843
+ console.error('Microsoft link failed:', err);
844
+ },
845
+ });
846
+ }
734
847
  setTokens(tokens) {
735
848
  return this.config.authManager.setTokens(tokens);
736
849
  }
@@ -898,7 +1011,7 @@ export class AvroQueryClient {
898
1011
  if (!companyIdToUse || companyIdToUse.trim() === '') {
899
1012
  throw new StandardError(400, 'Company ID is required');
900
1013
  }
901
- return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(body), cancelToken, {
1014
+ return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(withoutEmpty(body, 'route_id')), cancelToken, {
902
1015
  ...headers,
903
1016
  'Content-Type': 'application/json',
904
1017
  }, true)
@@ -993,7 +1106,16 @@ export class AvroQueryClient {
993
1106
  if (!chatId || chatId.trim() === '') {
994
1107
  throw new StandardError(400, 'Chat ID is required');
995
1108
  }
996
- return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
1109
+ // `ListMessages`: the keyword field is `keyword`, and `amt` must be 1..100.
1110
+ const { query, amt, ...rest } = body;
1111
+ if (amt !== undefined && amt < 1)
1112
+ return Promise.resolve([]);
1113
+ const wire = {
1114
+ ...rest,
1115
+ ...(amt !== undefined && { amt: Math.min(Math.floor(amt), MAX_MESSAGES_PER_PAGE) }),
1116
+ ...(query && { keyword: query }),
1117
+ };
1118
+ return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(wire), cancelToken, {
997
1119
  ...headers,
998
1120
  'Content-Type': 'application/json',
999
1121
  }, true)
@@ -1050,7 +1172,7 @@ export class AvroQueryClient {
1050
1172
  if (!this.companyId || this.companyId.trim() === '') {
1051
1173
  throw new StandardError(400, 'Company ID is required');
1052
1174
  }
1053
- return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
1175
+ return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(withoutEmpty(body, 'job_id', 'task_id')), cancelToken, {
1054
1176
  ...headers,
1055
1177
  'Content-Type': 'application/json',
1056
1178
  }, true)
@@ -1069,6 +1191,9 @@ export class AvroQueryClient {
1069
1191
  if (!this.companyId || this.companyId.trim() === '') {
1070
1192
  throw new StandardError(400, 'Company ID is required');
1071
1193
  }
1194
+ // `amt` must be >= 1 here (omit it for every row).
1195
+ if (body.amt !== undefined && body.amt < 1)
1196
+ return Promise.resolve([]);
1072
1197
  return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
1073
1198
  ...headers,
1074
1199
  'Content-Type': 'application/json',
@@ -1107,7 +1232,10 @@ export class AvroQueryClient {
1107
1232
  if (!this.companyId || this.companyId.trim() === '') {
1108
1233
  throw new StandardError(400, 'Company ID is required');
1109
1234
  }
1110
- return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(body), cancelToken, {
1235
+ // `amt` must be >= 1 here (omit it for every row).
1236
+ if (body.amt !== undefined && body.amt < 1)
1237
+ return Promise.resolve([]);
1238
+ return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(withoutEmpty(body, 'status')), cancelToken, {
1111
1239
  ...headers,
1112
1240
  'Content-Type': 'application/json',
1113
1241
  }, true)
@@ -1204,6 +1332,26 @@ export class AvroQueryClient {
1204
1332
  throw fetchError(err, 'Failed to fetch groups');
1205
1333
  });
1206
1334
  }
1335
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1336
+ fetchCatalogItems(body = {}, companyId = this.companyId, cancelToken, headers = {}) {
1337
+ if (!companyId || companyId.trim() === '') {
1338
+ throw new StandardError(400, 'Company ID is required');
1339
+ }
1340
+ return this._fetch('POST', `/company/${companyId}/catalog_items`, JSON.stringify(body), cancelToken, {
1341
+ ...headers,
1342
+ 'Content-Type': 'application/json',
1343
+ }, true)
1344
+ .then((response) => {
1345
+ if (!response || !Array.isArray(response)) {
1346
+ throw new StandardError(400, 'Invalid catalog items response');
1347
+ }
1348
+ return response;
1349
+ })
1350
+ .catch((err) => {
1351
+ console.error('Failed to fetch catalog items:', err);
1352
+ throw fetchError(err, 'Failed to fetch catalog items');
1353
+ });
1354
+ }
1207
1355
  fetchSkills(body = {}, cancelToken, headers = {}) {
1208
1356
  if (!this.companyId || this.companyId.trim() === '') {
1209
1357
  throw new StandardError(400, 'Company ID is required');
@@ -1228,7 +1376,7 @@ export class AvroQueryClient {
1228
1376
  throw new StandardError(400, 'Company ID is required');
1229
1377
  }
1230
1378
  const amount = body.amt ?? Math.max(body.unknown_ids?.length ?? 0, 50);
1231
- return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
1379
+ return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify(withoutEmpty({ ...body, amt: amount }, 'user_id')), cancelToken, {
1232
1380
  ...headers,
1233
1381
  'Content-Type': 'application/json',
1234
1382
  }, true)
@@ -3,7 +3,7 @@ import { StandardError } from '../../types/error.js';
3
3
  import { AuthState } from '../../types/auth.js';
4
4
  import { AVRO_JS_VERSION } from '../../version.js';
5
5
  import { cancelledError, isCancelledError, refreshFailureError, shouldRetry, } from './policy.js';
6
- AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount, progressUpdateCallback) {
6
+ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount, progressUpdateCallback, refreshOnUnauthorized = true) {
7
7
  const maxRetries = retryCount ?? this.config.maxRetries;
8
8
  const checkCancelled = () => {
9
9
  if (cancelToken?.isCancelled()) {
@@ -101,6 +101,7 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
101
101
  throw new StandardError(0, `An unexpected error occurred: ${message}`);
102
102
  }
103
103
  if (error.status === 401 &&
104
+ refreshOnUnauthorized &&
104
105
  !refreshed &&
105
106
  this.getAuthState() === AuthState.AUTHENTICATED) {
106
107
  refreshed = true;
@@ -8,8 +8,10 @@ const buildQuery = (params) => {
8
8
  search.set('entity_type', params.entityType);
9
9
  if (params?.action)
10
10
  search.set('action', params.action);
11
- if (params?.limit !== undefined)
12
- search.set('limit', String(params.limit));
11
+ // The audit endpoints take an integer `limit` of 1..500.
12
+ if (params?.limit !== undefined) {
13
+ search.set('limit', String(Math.min(Math.max(Math.floor(params.limit), 1), 500)));
14
+ }
13
15
  const encoded = search.toString();
14
16
  return encoded ? `?${encoded}` : '';
15
17
  };
@@ -18,7 +18,8 @@ AvroQueryClient.prototype.useGetErrorLog = function (limit = 200) {
18
18
  queryKey: ['avro', 'errors', limit],
19
19
  queryFn: async () => {
20
20
  const res = await this.get({
21
- path: `/avro/errors?limit=${limit}`,
21
+ // `limit` is an integer of 1..1000.
22
+ path: `/avro/errors?limit=${Math.min(Math.max(Math.floor(limit), 1), 1000)}`,
22
23
  });
23
24
  return res.errors;
24
25
  },
@@ -27,7 +28,10 @@ AvroQueryClient.prototype.useGetErrorLog = function (limit = 200) {
27
28
  AvroQueryClient.prototype.useGetPerformanceMetrics = function ({ limit = 360, refetchInterval, } = {}) {
28
29
  return useQuery({
29
30
  queryKey: ['avro', 'performance', limit],
30
- queryFn: () => this.get({ path: `/avro/performance?limit=${limit}` }),
31
+ // `limit` is an integer of 1..2880.
32
+ queryFn: () => this.get({
33
+ path: `/avro/performance?limit=${Math.min(Math.max(Math.floor(limit), 1), 2880)}`,
34
+ }),
31
35
  staleTime: 0,
32
36
  refetchInterval,
33
37
  });
@@ -41,3 +45,16 @@ AvroQueryClient.prototype.useClearErrorLog = function () {
41
45
  },
42
46
  });
43
47
  };
48
+ AvroQueryClient.prototype.useRunSchedulerJobs = function () {
49
+ const queryClient = this.getQueryClient();
50
+ return useMutation({
51
+ mutationFn: (jobIds) => this.post({
52
+ path: '/avro/scheduler/run',
53
+ data: JSON.stringify(jobIds ? { job_ids: jobIds } : {}),
54
+ headers: { 'Content-Type': 'application/json' },
55
+ }),
56
+ onSuccess: () => {
57
+ queryClient.invalidateQueries({ queryKey: ['avro', 'performance'] });
58
+ },
59
+ });
60
+ };
@@ -10,7 +10,7 @@
10
10
  */
11
11
  export interface BulkBillError {
12
12
  bill_id: string;
13
- invoice_id: number | null;
13
+ invoice_id: number;
14
14
  reason: string;
15
15
  }
16
16
  export interface BulkDeleteBillsResponse {
@@ -1,9 +1,22 @@
1
1
  import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
+ import { useEffect, useState } from 'react';
2
3
  import { AvroQueryClient } from '../QueryClient.js';
3
4
  import { seedDetails } from '../cache.js';
4
5
  import { restoreNs, snapshotNs } from '../cache.js';
5
6
  import { keys } from '../realtime.js';
6
7
  import { Bill } from '../../types/api.js';
8
+ /**
9
+ * Keep only the `BillLineItemIn` fields, so cached LineItem rows (with
10
+ * `id`, `status`, …) can be passed back as custom items.
11
+ */
12
+ function toBillLineItemInput(item) {
13
+ return {
14
+ name: item.name,
15
+ description: item.description,
16
+ amount: item.amount,
17
+ cost: item.cost,
18
+ };
19
+ }
7
20
  AvroQueryClient.prototype.useGetBills = function (body) {
8
21
  const queryClient = this.getQueryClient();
9
22
  const result = useInfiniteQuery({
@@ -44,17 +57,11 @@ AvroQueryClient.prototype.useCreateBill = function () {
44
57
  const queryClient = this.getQueryClient();
45
58
  return useMutation({
46
59
  mutationFn: async ({ data }) => {
47
- const body = {
48
- events: data.events ?? [],
49
- months: data.months ?? [],
50
- line_items: data.line_items ?? [],
51
- manual_emails: data.manual_emails ?? [],
52
- prepayments: data.prepayments ?? [],
53
- enabled_payment_methods: data.enabled_payment_methods ?? [],
54
- pass_on_fees: data.pass_on_fees,
55
- users: data.users,
56
- due_date: data.due_date,
57
- };
60
+ // Absent keys take the backend defaults; nulls (name/due_date)
61
+ // are passed through as given.
62
+ const body = data.line_items
63
+ ? { ...data, line_items: data.line_items.map(toBillLineItemInput) }
64
+ : data;
58
65
  return this.post({
59
66
  path: `/company/${this.companyId}/bill`,
60
67
  data: JSON.stringify(body),
@@ -85,15 +92,22 @@ AvroQueryClient.prototype.useUpdateBill = function () {
85
92
  const queryClient = this.getQueryClient();
86
93
  return useMutation({
87
94
  mutationFn: ({ billId, updates }) => {
95
+ const body = updates.line_items
96
+ ? { ...updates, line_items: updates.line_items.map(toBillLineItemInput) }
97
+ : updates;
88
98
  return this.put({
89
99
  path: `/bill/${billId}`,
90
- data: JSON.stringify(updates),
100
+ data: JSON.stringify(body),
91
101
  headers: {
92
102
  'Content-Type': 'application/json',
93
103
  },
94
104
  });
95
105
  },
96
- onMutate: async ({ billId, updates }) => {
106
+ onMutate: async ({ billId, updates: wireUpdates }) => {
107
+ // `users`/`line_items` are request-shaped (user ids + amounts,
108
+ // bare custom items), not the cached BillUser/LineItem rows; the
109
+ // echoed change brings the real ones.
110
+ const { users: _users, line_items: _lineItems, ...updates } = wireUpdates;
97
111
  await queryClient.cancelQueries({ queryKey: ['bills'] });
98
112
  await queryClient.cancelQueries({ queryKey: ['bills', billId] });
99
113
  const previousBills = snapshotNs(queryClient, 'bills');
@@ -208,16 +222,40 @@ AvroQueryClient.prototype.useSyncBillToIntuit = function () {
208
222
  AvroQueryClient.prototype.useImportBillsFromIntuit = function () {
209
223
  const queryClient = this.getQueryClient();
210
224
  return useMutation({
225
+ // Starts the sync (202); follow it with useIntuitSyncStatus.
211
226
  mutationFn: async () => {
212
227
  return this.post({
213
228
  path: `/company/${this.companyId}/intuit/import`,
214
229
  });
215
230
  },
216
- onSuccess: () => {
217
- this.syncAfterMutation('bill');
218
- },
219
231
  });
220
232
  };
233
+ /**
234
+ * The company's QuickBooks sync, followed over the socket: `running` (with the
235
+ * latest progress) from `intuit_sync_started` on, then `complete` with the
236
+ * counts or `error`. Every staff member sees a run, whoever started it; the
237
+ * bills it changes arrive through the changes stream.
238
+ */
239
+ AvroQueryClient.prototype.useIntuitSyncStatus = function () {
240
+ const [status, setStatus] = useState({ state: 'idle' });
241
+ useEffect(() => {
242
+ const started = () => setStatus({ state: 'running' });
243
+ const progress = (data) => setStatus({ state: 'running', progress: data });
244
+ const complete = (data) => setStatus({ state: 'complete', result: data });
245
+ const failed = (data) => setStatus({ state: 'error', message: data?.msg ?? 'QuickBooks sync failed' });
246
+ this.on('intuit_sync_started', started);
247
+ this.on('intuit_sync_progress', progress);
248
+ this.on('intuit_sync_complete', complete);
249
+ this.on('intuit_sync_error', failed);
250
+ return () => {
251
+ this.off('intuit_sync_started', started);
252
+ this.off('intuit_sync_progress', progress);
253
+ this.off('intuit_sync_complete', complete);
254
+ this.off('intuit_sync_error', failed);
255
+ };
256
+ }, [this]);
257
+ return status;
258
+ };
221
259
  AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId }) {
222
260
  return this.get({
223
261
  path: `/company/${this.companyId}/bill/${billId}/pdf`,
@@ -1,6 +1,7 @@
1
1
  import { useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs } from '../cache.js';
4
+ import { keys } from '../realtime.js';
4
5
  import { StandardError } from '../../types/error.js';
5
6
  AvroQueryClient.prototype.useCreateCatalogItem = function () {
6
7
  const queryClient = this.getQueryClient();
@@ -43,7 +44,10 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
43
44
  },
44
45
  });
45
46
  },
46
- onMutate: async ({ catalogItemId, data }) => {
47
+ onMutate: async ({ catalogItemId, data: wireData }) => {
48
+ // Enum names and payment options are request-shaped (any case,
49
+ // no ids); only merge the fields stored as sent.
50
+ const { industry: _industry, price_format: _priceFormat, payment_options: _paymentOptions, ...data } = wireData;
47
51
  await queryClient.cancelQueries({ queryKey: ['catalog_items'] });
48
52
  await queryClient.cancelQueries({
49
53
  queryKey: ['catalog_items', catalogItemId],
@@ -84,11 +88,11 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
84
88
  AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
85
89
  return useQuery({
86
90
  queryKey: ['catalog_items', catalogItemId],
87
- // There is no `GET /catalog_item/<id>`: catalog items are embedded
88
- // in the company payload.
89
91
  queryFn: async () => {
90
- const company = await this.get({ path: `/company/${this.companyId}` });
91
- const item = company?.catalog_items?.find((ci) => ci.id === catalogItemId);
92
+ const [item] = await this.fetchCatalogItems({
93
+ unknown_ids: [catalogItemId],
94
+ amt: 1,
95
+ });
92
96
  if (!item)
93
97
  throw new StandardError(404, 'Catalog item not found');
94
98
  return item;
@@ -96,6 +100,17 @@ AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
96
100
  enabled: Boolean(catalogItemId) && Boolean(this.companyId),
97
101
  });
98
102
  };
103
+ AvroQueryClient.prototype.useGetCatalogItems = function (body = {}) {
104
+ const { companyId: bodyCompanyId, ...filters } = body;
105
+ const companyId = bodyCompanyId ?? this.companyId;
106
+ return useQuery({
107
+ // `industry` / `archived` stay absent when unset so list patching
108
+ // reads them as "no filter".
109
+ queryKey: keys.list('catalog_items', companyId, { query: '', ...filters }),
110
+ queryFn: () => this.fetchCatalogItems(filters, companyId),
111
+ enabled: Boolean(companyId),
112
+ });
113
+ };
99
114
  AvroQueryClient.prototype.useDeleteCatalogItem = function () {
100
115
  const queryClient = this.getQueryClient();
101
116
  return useMutation({
@@ -1,4 +1,4 @@
1
- import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
1
+ import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { seedDetails } from '../cache.js';
4
4
  import { keys } from '../realtime.js';
@@ -28,3 +28,35 @@ AvroQueryClient.prototype.useGetChat = function (chatId) {
28
28
  enabled: Boolean(chatId),
29
29
  });
30
30
  };
31
+ AvroQueryClient.prototype.useCreateChat = function () {
32
+ const queryClient = this.getQueryClient();
33
+ return useMutation({
34
+ // `users` must include the caller, or the backend adds nobody.
35
+ // A first message is posted once the chat exists.
36
+ mutationFn: async ({ name, users, message }) => {
37
+ const created = await this.post({
38
+ path: '/chat',
39
+ data: JSON.stringify({ name, users }),
40
+ headers: { 'Content-Type': 'application/json' },
41
+ });
42
+ if (message) {
43
+ await this.post({
44
+ path: `/chat/${created.id}/message`,
45
+ data: JSON.stringify({
46
+ message: {
47
+ content: message.content,
48
+ time_sent: message.time_sent ?? Math.floor(Date.now() / 1000),
49
+ },
50
+ }),
51
+ headers: { 'Content-Type': 'application/json' },
52
+ });
53
+ }
54
+ return created;
55
+ },
56
+ onSettled: () => {
57
+ // The chat list comes from the caller's own user record.
58
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
59
+ queryClient.invalidateQueries({ queryKey: ['user'] });
60
+ },
61
+ });
62
+ };