@go-avro/avro-js 1.6.4 → 1.6.6-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 (72) hide show
  1. package/dist/client/QueryClient.d.ts +123 -67
  2. package/dist/client/QueryClient.js +149 -28
  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 +6 -2
  6. package/dist/client/hooks/bills.d.ts +1 -1
  7. package/dist/client/hooks/bills.js +26 -13
  8. package/dist/client/hooks/catalog_items.js +4 -1
  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 +1 -1
  19. package/dist/client/hooks/timecards.js +2 -1
  20. package/dist/client/hooks/users.js +8 -3
  21. package/dist/client/realtime.d.ts +6 -0
  22. package/dist/client/realtime.js +16 -5
  23. package/dist/client/requests.d.ts +470 -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 +33 -28
  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 +9 -6
  34. package/dist/types/api/Chat.d.ts +3 -5
  35. package/dist/types/api/Company.d.ts +39 -13
  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/Reaction.d.ts +3 -3
  53. package/dist/types/api/Refund.d.ts +1 -1
  54. package/dist/types/api/Route.d.ts +11 -10
  55. package/dist/types/api/Route.js +5 -0
  56. package/dist/types/api/RouteJob.d.ts +1 -1
  57. package/dist/types/api/ServiceMonth.d.ts +2 -2
  58. package/dist/types/api/Session.d.ts +5 -2
  59. package/dist/types/api/Skill.d.ts +2 -2
  60. package/dist/types/api/Subscription.d.ts +5 -3
  61. package/dist/types/api/Task.d.ts +10 -9
  62. package/dist/types/api/Task.js +3 -1
  63. package/dist/types/api/TimecardAction.d.ts +2 -2
  64. package/dist/types/api/User.d.ts +11 -9
  65. package/dist/types/api/UserCompanyAssociation.d.ts +7 -1
  66. package/dist/types/api/UserMerge.d.ts +3 -3
  67. package/dist/types/api/_Event.d.ts +20 -4
  68. package/dist/types/api/_Event.js +1 -0
  69. package/dist/types/api.d.ts +170 -40
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/package.json +1 -1
@@ -6,6 +6,7 @@ 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 { withoutEmpty } from './wire.js';
9
10
  import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, } 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. */
@@ -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;
@@ -353,21 +358,24 @@ export class AvroQueryClient {
353
358
  this._presencePending.clear();
354
359
  if (!this.companyId || userIds.length === 0)
355
360
  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);
361
+ // `ListCompanyUsers.user_ids` holds at most 1000 ids.
362
+ for (let i = 0; i < userIds.length; i += 1000) {
363
+ this.post({
364
+ path: `/company/${this.companyId}/users`,
365
+ data: JSON.stringify({ user_ids: userIds.slice(i, i + 1000) }),
366
+ headers: { 'Content-Type': 'application/json' },
367
+ idempotent: true,
368
+ })
369
+ .then((members) => {
370
+ if (!Array.isArray(members)) {
371
+ markMembersStale();
372
+ return;
373
+ }
374
+ for (const member of members)
375
+ patchMember(queryClient, member);
376
+ })
377
+ .catch(markMembersStale);
378
+ }
371
379
  }, PRESENCE_COALESCE_MS);
372
380
  });
373
381
  on('location_update', (data) => {
@@ -483,8 +491,8 @@ export class AvroQueryClient {
483
491
  // Reporting must never become a second failure.
484
492
  }
485
493
  }
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);
494
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, refreshOnUnauthorized, }) {
495
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback, refreshOnUnauthorized ?? true);
488
496
  }
489
497
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
490
498
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -581,7 +589,7 @@ export class AvroQueryClient {
581
589
  const queryClient = this.getQueryClient();
582
590
  return useMutation({
583
591
  mutationFn: async ({ token, cancelToken, }) => {
584
- const resp = await this._xhr('POST', `/google/authorize?token=${token}`, {}, cancelToken, { 'Content-Type': 'application/json' });
592
+ const resp = await this._xhr('POST', `/google/authorize?token=${encodeURIComponent(token)}`, {}, cancelToken, { 'Content-Type': 'application/json' });
585
593
  if (!resp || !('access_token' in resp)) {
586
594
  if (resp.msg === 'TOTP required') {
587
595
  return LoginResponse.NEEDS_TOTP;
@@ -702,13 +710,14 @@ export class AvroQueryClient {
702
710
  /** Link an Apple ID to the signed-in account (fresh token + raw nonce). */
703
711
  useAppleLink() {
704
712
  return useMutation({
705
- mutationFn: async ({ token, nonce, authorizationCode, cancelToken, }) => {
713
+ mutationFn: async ({ cancelToken, ...proof }) => {
706
714
  return this.post({
707
715
  path: '/apple/link',
708
716
  data: JSON.stringify({
709
- token,
710
- nonce,
711
- authorization_code: authorizationCode ?? undefined,
717
+ ...('appleToken' in proof
718
+ ? { apple_token: proof.appleToken }
719
+ : { token: proof.token, nonce: proof.nonce }),
720
+ authorization_code: proof.authorizationCode ?? undefined,
712
721
  }),
713
722
  cancelToken,
714
723
  headers: { 'Content-Type': 'application/json' },
@@ -730,6 +739,103 @@ export class AvroQueryClient {
730
739
  },
731
740
  });
732
741
  }
742
+ /**
743
+ * Sign in with a Microsoft authorization code (`code` + the `uri` it was
744
+ * issued for). With no account for the identity yet this resolves
745
+ * `NEEDS_ACCOUNT` (rather than failing) carrying the handle for
746
+ * `useMicrosoftLink`. A 401 means the matching account is linked to
747
+ * another Microsoft identity.
748
+ */
749
+ useMicrosoftLogin() {
750
+ const queryClient = this.getQueryClient();
751
+ return useMutation({
752
+ mutationFn: async ({ code, uri, cancelToken, }) => {
753
+ let resp;
754
+ try {
755
+ resp = await this.post({
756
+ path: `/microsoft/authorize?code=${encodeURIComponent(code)}&uri=${encodeURIComponent(uri)}`,
757
+ cancelToken,
758
+ headers: { 'Content-Type': 'application/json' },
759
+ });
760
+ }
761
+ catch (err) {
762
+ const body = err instanceof StandardError ? err.body : undefined;
763
+ if (err instanceof StandardError &&
764
+ err.status === 404 &&
765
+ body &&
766
+ typeof body.microsoft_token === 'string') {
767
+ const notFound = body;
768
+ return {
769
+ status: 'NEEDS_ACCOUNT',
770
+ microsoft_token: notFound.microsoft_token,
771
+ email: notFound.email ?? null,
772
+ first_name: notFound.first_name ?? '',
773
+ last_name: notFound.last_name ?? '',
774
+ };
775
+ }
776
+ throw err;
777
+ }
778
+ if (!resp || !('access_token' in resp)) {
779
+ throw new StandardError(401, 'Invalid Microsoft login response');
780
+ }
781
+ await this.loginSuccess({
782
+ access_token: resp.access_token,
783
+ refresh_token: resp.refresh_token,
784
+ });
785
+ return { status: LoginResponse.SUCCESS };
786
+ },
787
+ onSettled: () => {
788
+ queryClient.invalidateQueries();
789
+ },
790
+ onError: (err) => {
791
+ console.error('Microsoft Login failed:', err);
792
+ },
793
+ });
794
+ }
795
+ /**
796
+ * Finish a `NEEDS_ACCOUNT` Microsoft sign-in with its `microsoft_token`
797
+ * once the account exists, then sign in with the returned tokens.
798
+ *
799
+ * When the 404 carried an `email`, the handle signs in to the account
800
+ * with that address and no session is needed. When `email` was null,
801
+ * the identity is linked to the account this client is signed in to:
802
+ * sign in to the new account first (e.g. `loginSuccess` with the tokens
803
+ * `POST /user` returned, or a code login when it answered
804
+ * `TOTP required`); the request carries the current session's token.
805
+ * 401s: `Sign in to link this Microsoft account` (no session; the
806
+ * handle stays valid for a retry within 10 min), `This Microsoft
807
+ * account is linked to another account`, `This account is linked to
808
+ * another Microsoft account`. 400: the handle is invalid or expired.
809
+ */
810
+ useMicrosoftLink() {
811
+ const queryClient = this.getQueryClient();
812
+ return useMutation({
813
+ mutationFn: async ({ microsoftToken, cancelToken, }) => {
814
+ const resp = await this.post({
815
+ path: `/microsoft/authorize?token=${encodeURIComponent(microsoftToken)}`,
816
+ cancelToken,
817
+ headers: { 'Content-Type': 'application/json' },
818
+ // The handle is one-time: a refresh-and-replay after a
819
+ // "linked elsewhere" 401 would only get "expired".
820
+ refreshOnUnauthorized: false,
821
+ });
822
+ if (!resp || !('access_token' in resp)) {
823
+ throw new StandardError(401, 'Invalid Microsoft login response');
824
+ }
825
+ await this.loginSuccess({
826
+ access_token: resp.access_token,
827
+ refresh_token: resp.refresh_token,
828
+ });
829
+ return LoginResponse.SUCCESS;
830
+ },
831
+ onSettled: () => {
832
+ queryClient.invalidateQueries();
833
+ },
834
+ onError: (err) => {
835
+ console.error('Microsoft link failed:', err);
836
+ },
837
+ });
838
+ }
733
839
  setTokens(tokens) {
734
840
  return this.config.authManager.setTokens(tokens);
735
841
  }
@@ -897,7 +1003,7 @@ export class AvroQueryClient {
897
1003
  if (!companyIdToUse || companyIdToUse.trim() === '') {
898
1004
  throw new StandardError(400, 'Company ID is required');
899
1005
  }
900
- return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(body), cancelToken, {
1006
+ return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(withoutEmpty(body, 'route_id')), cancelToken, {
901
1007
  ...headers,
902
1008
  'Content-Type': 'application/json',
903
1009
  }, true)
@@ -992,7 +1098,16 @@ export class AvroQueryClient {
992
1098
  if (!chatId || chatId.trim() === '') {
993
1099
  throw new StandardError(400, 'Chat ID is required');
994
1100
  }
995
- return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
1101
+ // `ListMessages`: the keyword field is `keyword`, and `amt` must be 1..100.
1102
+ const { query, amt, ...rest } = body;
1103
+ if (amt !== undefined && amt < 1)
1104
+ return Promise.resolve([]);
1105
+ const wire = {
1106
+ ...rest,
1107
+ ...(amt !== undefined && { amt: Math.min(Math.floor(amt), MAX_MESSAGES_PER_PAGE) }),
1108
+ ...(query && { keyword: query }),
1109
+ };
1110
+ return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(wire), cancelToken, {
996
1111
  ...headers,
997
1112
  'Content-Type': 'application/json',
998
1113
  }, true)
@@ -1049,7 +1164,7 @@ export class AvroQueryClient {
1049
1164
  if (!this.companyId || this.companyId.trim() === '') {
1050
1165
  throw new StandardError(400, 'Company ID is required');
1051
1166
  }
1052
- return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
1167
+ return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(withoutEmpty(body, 'job_id', 'task_id')), cancelToken, {
1053
1168
  ...headers,
1054
1169
  'Content-Type': 'application/json',
1055
1170
  }, true)
@@ -1068,6 +1183,9 @@ export class AvroQueryClient {
1068
1183
  if (!this.companyId || this.companyId.trim() === '') {
1069
1184
  throw new StandardError(400, 'Company ID is required');
1070
1185
  }
1186
+ // `amt` must be >= 1 here (omit it for every row).
1187
+ if (body.amt !== undefined && body.amt < 1)
1188
+ return Promise.resolve([]);
1071
1189
  return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
1072
1190
  ...headers,
1073
1191
  'Content-Type': 'application/json',
@@ -1106,7 +1224,10 @@ export class AvroQueryClient {
1106
1224
  if (!this.companyId || this.companyId.trim() === '') {
1107
1225
  throw new StandardError(400, 'Company ID is required');
1108
1226
  }
1109
- return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(body), cancelToken, {
1227
+ // `amt` must be >= 1 here (omit it for every row).
1228
+ if (body.amt !== undefined && body.amt < 1)
1229
+ return Promise.resolve([]);
1230
+ return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(withoutEmpty(body, 'status')), cancelToken, {
1110
1231
  ...headers,
1111
1232
  'Content-Type': 'application/json',
1112
1233
  }, true)
@@ -1227,7 +1348,7 @@ export class AvroQueryClient {
1227
1348
  throw new StandardError(400, 'Company ID is required');
1228
1349
  }
1229
1350
  const amount = body.amt ?? Math.max(body.unknown_ids?.length ?? 0, 50);
1230
- return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
1351
+ return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify(withoutEmpty({ ...body, amt: amount }, 'user_id')), cancelToken, {
1231
1352
  ...headers,
1232
1353
  'Content-Type': 'application/json',
1233
1354
  }, 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
  });
@@ -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 {
@@ -4,6 +4,18 @@ import { seedDetails } from '../cache.js';
4
4
  import { restoreNs, snapshotNs } from '../cache.js';
5
5
  import { keys } from '../realtime.js';
6
6
  import { Bill } from '../../types/api.js';
7
+ /**
8
+ * Keep only the `BillLineItemIn` fields, so cached LineItem rows (with
9
+ * `id`, `status`, …) can be passed back as custom items.
10
+ */
11
+ function toBillLineItemInput(item) {
12
+ return {
13
+ name: item.name,
14
+ description: item.description,
15
+ amount: item.amount,
16
+ cost: item.cost,
17
+ };
18
+ }
7
19
  AvroQueryClient.prototype.useGetBills = function (body) {
8
20
  const queryClient = this.getQueryClient();
9
21
  const result = useInfiniteQuery({
@@ -44,17 +56,11 @@ AvroQueryClient.prototype.useCreateBill = function () {
44
56
  const queryClient = this.getQueryClient();
45
57
  return useMutation({
46
58
  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
- };
59
+ // Absent keys take the backend defaults; nulls (name/due_date)
60
+ // are passed through as given.
61
+ const body = data.line_items
62
+ ? { ...data, line_items: data.line_items.map(toBillLineItemInput) }
63
+ : data;
58
64
  return this.post({
59
65
  path: `/company/${this.companyId}/bill`,
60
66
  data: JSON.stringify(body),
@@ -85,15 +91,22 @@ AvroQueryClient.prototype.useUpdateBill = function () {
85
91
  const queryClient = this.getQueryClient();
86
92
  return useMutation({
87
93
  mutationFn: ({ billId, updates }) => {
94
+ const body = updates.line_items
95
+ ? { ...updates, line_items: updates.line_items.map(toBillLineItemInput) }
96
+ : updates;
88
97
  return this.put({
89
98
  path: `/bill/${billId}`,
90
- data: JSON.stringify(updates),
99
+ data: JSON.stringify(body),
91
100
  headers: {
92
101
  'Content-Type': 'application/json',
93
102
  },
94
103
  });
95
104
  },
96
- onMutate: async ({ billId, updates }) => {
105
+ onMutate: async ({ billId, updates: wireUpdates }) => {
106
+ // `users`/`line_items` are request-shaped (user ids + amounts,
107
+ // bare custom items), not the cached BillUser/LineItem rows; the
108
+ // echoed change brings the real ones.
109
+ const { users: _users, line_items: _lineItems, ...updates } = wireUpdates;
97
110
  await queryClient.cancelQueries({ queryKey: ['bills'] });
98
111
  await queryClient.cancelQueries({ queryKey: ['bills', billId] });
99
112
  const previousBills = snapshotNs(queryClient, 'bills');
@@ -43,7 +43,10 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
43
43
  },
44
44
  });
45
45
  },
46
- onMutate: async ({ catalogItemId, data }) => {
46
+ onMutate: async ({ catalogItemId, data: wireData }) => {
47
+ // Enum names and payment options are request-shaped (any case,
48
+ // no ids); only merge the fields stored as sent.
49
+ const { industry: _industry, price_format: _priceFormat, payment_options: _paymentOptions, ...data } = wireData;
47
50
  await queryClient.cancelQueries({ queryKey: ['catalog_items'] });
48
51
  await queryClient.cancelQueries({
49
52
  queryKey: ['catalog_items', catalogItemId],
@@ -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
+ };
@@ -2,6 +2,20 @@ import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { StandardError } from '../../types/error.js';
4
4
  import { AuthState } from '../../types/auth.js';
5
+ /**
6
+ * The cached-`Company` view of an update: the company reports unset
7
+ * mailbox / plan links as `''`, and `payment_methods` / `logo` are
8
+ * request-only shapes the echoed change replaces.
9
+ */
10
+ function toCachedCompany(data) {
11
+ const { payment_methods: _paymentMethods, logo: _logo, service_email_id, billing_email_id, plan_id, ...rest } = data;
12
+ return {
13
+ ...rest,
14
+ ...(service_email_id !== undefined && { service_email_id: service_email_id ?? '' }),
15
+ ...(billing_email_id !== undefined && { billing_email_id: billing_email_id ?? '' }),
16
+ ...(plan_id !== undefined && { plan_id: plan_id ?? '' }),
17
+ };
18
+ }
5
19
  AvroQueryClient.prototype.useGetCompanies = function (options = {}) {
6
20
  return useQuery({
7
21
  queryKey: ['/company/list'],
@@ -68,7 +82,7 @@ AvroQueryClient.prototype.useGetCurrentCompany = function () {
68
82
  AvroQueryClient.prototype.useCreateCompany = function () {
69
83
  const queryClient = this.getQueryClient();
70
84
  return useMutation({
71
- mutationFn: async ({ companyData, }) => {
85
+ mutationFn: async ({ companyData }) => {
72
86
  return this.post({
73
87
  path: `/company`,
74
88
  data: JSON.stringify(companyData),
@@ -97,11 +111,13 @@ AvroQueryClient.prototype.useUpdateCompany = function () {
97
111
  await queryClient.cancelQueries({ queryKey: ['/company/list'] });
98
112
  const previousCompany = queryClient.getQueryData(['companies', companyId]);
99
113
  const previousCompanyList = queryClient.getQueryData(['/company/list']);
100
- queryClient.setQueryData(['companies', companyId], (oldData) => oldData ? { ...oldData, ...companyData } : undefined);
114
+ queryClient.setQueryData(['companies', companyId], (oldData) => oldData ? { ...oldData, ...toCachedCompany(companyData) } : undefined);
101
115
  queryClient.setQueryData(['/company/list'], (oldList) => {
102
116
  if (!oldList)
103
117
  return oldList;
104
- return oldList.map((company) => company?.id === companyId ? { ...company, ...companyData } : company);
118
+ // The list only carries {id, name, plan_id, balance}.
119
+ const { name } = companyData;
120
+ return oldList.map((company) => company?.id === companyId && name ? { ...company, name } : company);
105
121
  });
106
122
  return { previousCompany, previousCompanyList };
107
123
  },
@@ -122,7 +138,7 @@ AvroQueryClient.prototype.useUpdateCompany = function () {
122
138
  AvroQueryClient.prototype.useCreateUserCompany = function () {
123
139
  const queryClient = this.getQueryClient();
124
140
  return useMutation({
125
- mutationFn: async ({ user_id, data, }) => {
141
+ mutationFn: async ({ user_id, data }) => {
126
142
  if (!user_id) {
127
143
  throw new Error('Both userId and companyId are required');
128
144
  }
@@ -151,6 +167,24 @@ AvroQueryClient.prototype.useCreateUserCompany = function () {
151
167
  },
152
168
  });
153
169
  };
170
+ /**
171
+ * Add an existing user to a company (the current one by default), optionally
172
+ * straight into a group such as a user type, in a single request.
173
+ */
174
+ AvroQueryClient.prototype.useAddUserCompany = function () {
175
+ return useMutation({
176
+ mutationFn: async ({ userId, groupId, companyId, }) => {
177
+ return this.post({
178
+ path: `/company/${companyId ?? this.companyId}/user/${userId}`,
179
+ data: JSON.stringify({ user_id: userId, ...(groupId ? { group: groupId } : {}) }),
180
+ headers: { 'Content-Type': 'application/json' },
181
+ });
182
+ },
183
+ onSuccess: () => {
184
+ this.syncAfterMutation('member', 'company', 'group');
185
+ },
186
+ });
187
+ };
154
188
  AvroQueryClient.prototype.useRemoveUserCompany = function () {
155
189
  const queryClient = this.getQueryClient();
156
190
  return useMutation({
@@ -2,6 +2,7 @@ import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs, seedDetails, removeOptimisticRow } from '../cache.js';
4
4
  import { keys, matchesList } from '../realtime.js';
5
+ import { withoutEmpty } from '../wire.js';
5
6
  import { constructEvent, DelayEvent, Job, LineItemStatus, Task, getTaskOverdueTime, } from '../../types/api.js';
6
7
  const isJobsQuery = (q) => q.queryKey[0] === 'jobs';
7
8
  const isEventsQuery = (q) => q.queryKey[0] === 'events';
@@ -64,11 +65,15 @@ AvroQueryClient.prototype.useCreateEvent = function () {
64
65
  mutationFn: ({ eventData }) => {
65
66
  return this.post({
66
67
  path: `/company/${this.companyId}/event`,
67
- data: JSON.stringify(eventData),
68
+ // `team_id` is a UUID: '' (no team picked) is omitted.
69
+ data: JSON.stringify(withoutEmpty(eventData, 'team_id')),
68
70
  headers: { 'Content-Type': 'application/json' },
69
71
  });
70
72
  },
71
- onMutate: async ({ eventData }) => {
73
+ onMutate: async ({ eventData: wireEventData }) => {
74
+ // Wire-shaped participants and charges must not land in the
75
+ // cached _Event's UserEvent / AdditionalCharge rows.
76
+ const { users: _wireUsers, additional_charges: _wireCharges, ...eventData } = wireEventData;
72
77
  await queryClient.cancelQueries({ queryKey: ['events'] });
73
78
  const previousJob = queryClient.getQueryData([
74
79
  'jobs',
@@ -77,7 +82,6 @@ AvroQueryClient.prototype.useCreateEvent = function () {
77
82
  const optimisticEvent = constructEvent({
78
83
  ...eventData,
79
84
  id: Math.random().toString(36).substring(2, 11),
80
- company_id: this.companyId,
81
85
  });
82
86
  if (previousJob) {
83
87
  const updatedJob = new Job({
@@ -159,7 +163,6 @@ AvroQueryClient.prototype.useCreateDelayEvent = function () {
159
163
  const optimisticEvent = new DelayEvent({
160
164
  ...delayData,
161
165
  id: Math.random().toString(36).substring(2, 11),
162
- company_id: this.companyId,
163
166
  time_started: now,
164
167
  time_ended: now,
165
168
  cost: 0,
@@ -244,15 +247,16 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
244
247
  mutationFn: ({ eventId, updates }) => {
245
248
  return this.put({
246
249
  path: `/event/${eventId}`,
247
- data: JSON.stringify(updates),
250
+ data: JSON.stringify(withoutEmpty(updates, 'team_id')),
248
251
  headers: { 'Content-Type': 'application/json' },
249
252
  });
250
253
  },
251
254
  onMutate: async ({ eventId, updates: wireUpdates }) => {
252
- // The wire `users` shape ({user_id, time_*}) must not land in
253
- // cached _Event.users (UserEvent rows) — exclude it from the
254
- // optimistic merge; invalidation on settle refreshes real rows.
255
- const { users: _wireUsers, ...updates } = wireUpdates;
255
+ // The wire `users` ({user_id, time_*}) and `additional_charges`
256
+ // shapes must not land in cached _Event.users / charges rows —
257
+ // exclude them from the optimistic merge; the echoed change
258
+ // refreshes the real rows.
259
+ const { users: _wireUsers, additional_charges: _wireCharges, ...updates } = wireUpdates;
256
260
  await queryClient.cancelQueries({ queryKey: ['events', eventId] });
257
261
  await queryClient.cancelQueries({ queryKey: ['events'] });
258
262
  // Try individual cache first; fall back to scanning all active events queries