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

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 +122 -63
  2. package/dist/client/QueryClient.js +151 -26
  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 +13 -0
  22. package/dist/client/realtime.js +30 -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 +156 -39
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. 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) => {
@@ -483,8 +496,8 @@ export class AvroQueryClient {
483
496
  // Reporting must never become a second failure.
484
497
  }
485
498
  }
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);
499
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, refreshOnUnauthorized, }) {
500
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback, refreshOnUnauthorized ?? true);
488
501
  }
489
502
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
490
503
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -581,7 +594,7 @@ export class AvroQueryClient {
581
594
  const queryClient = this.getQueryClient();
582
595
  return useMutation({
583
596
  mutationFn: async ({ token, cancelToken, }) => {
584
- const resp = await this._xhr('POST', `/google/authorize?token=${token}`, {}, cancelToken, { 'Content-Type': 'application/json' });
597
+ const resp = await this._xhr('POST', `/google/authorize?token=${encodeURIComponent(token)}`, {}, cancelToken, { 'Content-Type': 'application/json' });
585
598
  if (!resp || !('access_token' in resp)) {
586
599
  if (resp.msg === 'TOTP required') {
587
600
  return LoginResponse.NEEDS_TOTP;
@@ -731,6 +744,103 @@ export class AvroQueryClient {
731
744
  },
732
745
  });
733
746
  }
747
+ /**
748
+ * Sign in with a Microsoft authorization code (`code` + the `uri` it was
749
+ * issued for). With no account for the identity yet this resolves
750
+ * `NEEDS_ACCOUNT` (rather than failing) carrying the handle for
751
+ * `useMicrosoftLink`. A 401 means the matching account is linked to
752
+ * another Microsoft identity.
753
+ */
754
+ useMicrosoftLogin() {
755
+ const queryClient = this.getQueryClient();
756
+ return useMutation({
757
+ mutationFn: async ({ code, uri, cancelToken, }) => {
758
+ let resp;
759
+ try {
760
+ resp = await this.post({
761
+ path: `/microsoft/authorize?code=${encodeURIComponent(code)}&uri=${encodeURIComponent(uri)}`,
762
+ cancelToken,
763
+ headers: { 'Content-Type': 'application/json' },
764
+ });
765
+ }
766
+ catch (err) {
767
+ const body = err instanceof StandardError ? err.body : undefined;
768
+ if (err instanceof StandardError &&
769
+ err.status === 404 &&
770
+ body &&
771
+ typeof body.microsoft_token === 'string') {
772
+ const notFound = body;
773
+ return {
774
+ status: 'NEEDS_ACCOUNT',
775
+ microsoft_token: notFound.microsoft_token,
776
+ email: notFound.email ?? null,
777
+ first_name: notFound.first_name ?? '',
778
+ last_name: notFound.last_name ?? '',
779
+ };
780
+ }
781
+ throw err;
782
+ }
783
+ if (!resp || !('access_token' in resp)) {
784
+ throw new StandardError(401, 'Invalid Microsoft login response');
785
+ }
786
+ await this.loginSuccess({
787
+ access_token: resp.access_token,
788
+ refresh_token: resp.refresh_token,
789
+ });
790
+ return { status: LoginResponse.SUCCESS };
791
+ },
792
+ onSettled: () => {
793
+ queryClient.invalidateQueries();
794
+ },
795
+ onError: (err) => {
796
+ console.error('Microsoft Login failed:', err);
797
+ },
798
+ });
799
+ }
800
+ /**
801
+ * Finish a `NEEDS_ACCOUNT` Microsoft sign-in with its `microsoft_token`
802
+ * once the account exists, then sign in with the returned tokens.
803
+ *
804
+ * When the 404 carried an `email`, the handle signs in to the account
805
+ * with that address and no session is needed. When `email` was null,
806
+ * the identity is linked to the account this client is signed in to:
807
+ * sign in to the new account first (e.g. `loginSuccess` with the tokens
808
+ * `POST /user` returned, or a code login when it answered
809
+ * `TOTP required`); the request carries the current session's token.
810
+ * 401s: `Sign in to link this Microsoft account` (no session; the
811
+ * handle stays valid for a retry within 10 min), `This Microsoft
812
+ * account is linked to another account`, `This account is linked to
813
+ * another Microsoft account`. 400: the handle is invalid or expired.
814
+ */
815
+ useMicrosoftLink() {
816
+ const queryClient = this.getQueryClient();
817
+ return useMutation({
818
+ mutationFn: async ({ microsoftToken, cancelToken, }) => {
819
+ const resp = await this.post({
820
+ path: `/microsoft/authorize?token=${encodeURIComponent(microsoftToken)}`,
821
+ cancelToken,
822
+ headers: { 'Content-Type': 'application/json' },
823
+ // The handle is one-time: a refresh-and-replay after a
824
+ // "linked elsewhere" 401 would only get "expired".
825
+ refreshOnUnauthorized: false,
826
+ });
827
+ if (!resp || !('access_token' in resp)) {
828
+ throw new StandardError(401, 'Invalid Microsoft login response');
829
+ }
830
+ await this.loginSuccess({
831
+ access_token: resp.access_token,
832
+ refresh_token: resp.refresh_token,
833
+ });
834
+ return LoginResponse.SUCCESS;
835
+ },
836
+ onSettled: () => {
837
+ queryClient.invalidateQueries();
838
+ },
839
+ onError: (err) => {
840
+ console.error('Microsoft link failed:', err);
841
+ },
842
+ });
843
+ }
734
844
  setTokens(tokens) {
735
845
  return this.config.authManager.setTokens(tokens);
736
846
  }
@@ -898,7 +1008,7 @@ export class AvroQueryClient {
898
1008
  if (!companyIdToUse || companyIdToUse.trim() === '') {
899
1009
  throw new StandardError(400, 'Company ID is required');
900
1010
  }
901
- return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(body), cancelToken, {
1011
+ return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(withoutEmpty(body, 'route_id')), cancelToken, {
902
1012
  ...headers,
903
1013
  'Content-Type': 'application/json',
904
1014
  }, true)
@@ -993,7 +1103,16 @@ export class AvroQueryClient {
993
1103
  if (!chatId || chatId.trim() === '') {
994
1104
  throw new StandardError(400, 'Chat ID is required');
995
1105
  }
996
- return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
1106
+ // `ListMessages`: the keyword field is `keyword`, and `amt` must be 1..100.
1107
+ const { query, amt, ...rest } = body;
1108
+ if (amt !== undefined && amt < 1)
1109
+ return Promise.resolve([]);
1110
+ const wire = {
1111
+ ...rest,
1112
+ ...(amt !== undefined && { amt: Math.min(Math.floor(amt), MAX_MESSAGES_PER_PAGE) }),
1113
+ ...(query && { keyword: query }),
1114
+ };
1115
+ return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(wire), cancelToken, {
997
1116
  ...headers,
998
1117
  'Content-Type': 'application/json',
999
1118
  }, true)
@@ -1050,7 +1169,7 @@ export class AvroQueryClient {
1050
1169
  if (!this.companyId || this.companyId.trim() === '') {
1051
1170
  throw new StandardError(400, 'Company ID is required');
1052
1171
  }
1053
- return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
1172
+ return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(withoutEmpty(body, 'job_id', 'task_id')), cancelToken, {
1054
1173
  ...headers,
1055
1174
  'Content-Type': 'application/json',
1056
1175
  }, true)
@@ -1069,6 +1188,9 @@ export class AvroQueryClient {
1069
1188
  if (!this.companyId || this.companyId.trim() === '') {
1070
1189
  throw new StandardError(400, 'Company ID is required');
1071
1190
  }
1191
+ // `amt` must be >= 1 here (omit it for every row).
1192
+ if (body.amt !== undefined && body.amt < 1)
1193
+ return Promise.resolve([]);
1072
1194
  return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
1073
1195
  ...headers,
1074
1196
  'Content-Type': 'application/json',
@@ -1107,7 +1229,10 @@ export class AvroQueryClient {
1107
1229
  if (!this.companyId || this.companyId.trim() === '') {
1108
1230
  throw new StandardError(400, 'Company ID is required');
1109
1231
  }
1110
- return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(body), cancelToken, {
1232
+ // `amt` must be >= 1 here (omit it for every row).
1233
+ if (body.amt !== undefined && body.amt < 1)
1234
+ return Promise.resolve([]);
1235
+ return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(withoutEmpty(body, 'status')), cancelToken, {
1111
1236
  ...headers,
1112
1237
  'Content-Type': 'application/json',
1113
1238
  }, true)
@@ -1228,7 +1353,7 @@ export class AvroQueryClient {
1228
1353
  throw new StandardError(400, 'Company ID is required');
1229
1354
  }
1230
1355
  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, {
1356
+ return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify(withoutEmpty({ ...body, amt: amount }, 'user_id')), cancelToken, {
1232
1357
  ...headers,
1233
1358
  'Content-Type': 'application/json',
1234
1359
  }, 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