@go-avro/avro-js 1.6.4-rc2 → 1.6.4-rc4

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 (70) hide show
  1. package/dist/client/QueryClient.d.ts +105 -65
  2. package/dist/client/QueryClient.js +144 -24
  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/companies.js +20 -4
  10. package/dist/client/hooks/events.js +13 -9
  11. package/dist/client/hooks/jobs.js +29 -3
  12. package/dist/client/hooks/messages.js +6 -2
  13. package/dist/client/hooks/plans.js +1 -1
  14. package/dist/client/hooks/routes.js +55 -5
  15. package/dist/client/hooks/sessions.js +37 -9
  16. package/dist/client/hooks/skills.js +1 -1
  17. package/dist/client/hooks/teams.js +1 -1
  18. package/dist/client/hooks/timecards.js +2 -1
  19. package/dist/client/hooks/users.js +8 -3
  20. package/dist/client/realtime.js +8 -3
  21. package/dist/client/requests.d.ts +470 -0
  22. package/dist/client/requests.js +5 -0
  23. package/dist/client/wire.d.ts +7 -0
  24. package/dist/client/wire.js +14 -0
  25. package/dist/index.d.ts +1 -0
  26. package/dist/types/api/AdditionalCharge.d.ts +2 -1
  27. package/dist/types/api/Avro.d.ts +33 -28
  28. package/dist/types/api/Bill.d.ts +7 -5
  29. package/dist/types/api/BillPayment.d.ts +8 -4
  30. package/dist/types/api/BillUser.d.ts +3 -2
  31. package/dist/types/api/CatalogItem.d.ts +9 -6
  32. package/dist/types/api/Chat.d.ts +3 -5
  33. package/dist/types/api/Company.d.ts +39 -13
  34. package/dist/types/api/DelayEvent.d.ts +5 -2
  35. package/dist/types/api/Device.d.ts +5 -4
  36. package/dist/types/api/Email.d.ts +14 -3
  37. package/dist/types/api/Friendship.d.ts +8 -0
  38. package/dist/types/api/Group.d.ts +3 -2
  39. package/dist/types/api/Job.d.ts +55 -5
  40. package/dist/types/api/LineItem.d.ts +3 -2
  41. package/dist/types/api/MemberState.d.ts +2 -1
  42. package/dist/types/api/Message.d.ts +4 -3
  43. package/dist/types/api/Notification.d.ts +26 -0
  44. package/dist/types/api/PaymentMethod.d.ts +7 -2
  45. package/dist/types/api/PaymentOption.d.ts +6 -4
  46. package/dist/types/api/Payout.d.ts +1 -1
  47. package/dist/types/api/Plan.d.ts +5 -4
  48. package/dist/types/api/PlanPayment.d.ts +5 -3
  49. package/dist/types/api/Prepayment.d.ts +2 -1
  50. package/dist/types/api/Reaction.d.ts +3 -3
  51. package/dist/types/api/Refund.d.ts +1 -1
  52. package/dist/types/api/Route.d.ts +11 -10
  53. package/dist/types/api/Route.js +5 -0
  54. package/dist/types/api/RouteJob.d.ts +1 -1
  55. package/dist/types/api/ServiceMonth.d.ts +2 -2
  56. package/dist/types/api/Session.d.ts +5 -2
  57. package/dist/types/api/Skill.d.ts +2 -2
  58. package/dist/types/api/Subscription.d.ts +5 -3
  59. package/dist/types/api/Task.d.ts +10 -9
  60. package/dist/types/api/Task.js +3 -1
  61. package/dist/types/api/TimecardAction.d.ts +2 -2
  62. package/dist/types/api/User.d.ts +11 -9
  63. package/dist/types/api/UserCompanyAssociation.d.ts +7 -1
  64. package/dist/types/api/UserMerge.d.ts +3 -3
  65. package/dist/types/api/_Event.d.ts +20 -4
  66. package/dist/types/api/_Event.js +1 -0
  67. package/dist/types/api.d.ts +156 -39
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. 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;
@@ -731,6 +739,103 @@ export class AvroQueryClient {
731
739
  },
732
740
  });
733
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
+ }
734
839
  setTokens(tokens) {
735
840
  return this.config.authManager.setTokens(tokens);
736
841
  }
@@ -898,7 +1003,7 @@ export class AvroQueryClient {
898
1003
  if (!companyIdToUse || companyIdToUse.trim() === '') {
899
1004
  throw new StandardError(400, 'Company ID is required');
900
1005
  }
901
- 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, {
902
1007
  ...headers,
903
1008
  'Content-Type': 'application/json',
904
1009
  }, true)
@@ -993,7 +1098,16 @@ export class AvroQueryClient {
993
1098
  if (!chatId || chatId.trim() === '') {
994
1099
  throw new StandardError(400, 'Chat ID is required');
995
1100
  }
996
- 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, {
997
1111
  ...headers,
998
1112
  'Content-Type': 'application/json',
999
1113
  }, true)
@@ -1050,7 +1164,7 @@ export class AvroQueryClient {
1050
1164
  if (!this.companyId || this.companyId.trim() === '') {
1051
1165
  throw new StandardError(400, 'Company ID is required');
1052
1166
  }
1053
- 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, {
1054
1168
  ...headers,
1055
1169
  'Content-Type': 'application/json',
1056
1170
  }, true)
@@ -1069,6 +1183,9 @@ export class AvroQueryClient {
1069
1183
  if (!this.companyId || this.companyId.trim() === '') {
1070
1184
  throw new StandardError(400, 'Company ID is required');
1071
1185
  }
1186
+ // `amt` must be >= 1 here (omit it for every row).
1187
+ if (body.amt !== undefined && body.amt < 1)
1188
+ return Promise.resolve([]);
1072
1189
  return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
1073
1190
  ...headers,
1074
1191
  'Content-Type': 'application/json',
@@ -1107,7 +1224,10 @@ export class AvroQueryClient {
1107
1224
  if (!this.companyId || this.companyId.trim() === '') {
1108
1225
  throw new StandardError(400, 'Company ID is required');
1109
1226
  }
1110
- 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, {
1111
1231
  ...headers,
1112
1232
  'Content-Type': 'application/json',
1113
1233
  }, true)
@@ -1228,7 +1348,7 @@ export class AvroQueryClient {
1228
1348
  throw new StandardError(400, 'Company ID is required');
1229
1349
  }
1230
1350
  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, {
1351
+ return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify(withoutEmpty({ ...body, amt: amount }, 'user_id')), cancelToken, {
1232
1352
  ...headers,
1233
1353
  'Content-Type': 'application/json',
1234
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],
@@ -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
  }
@@ -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
@@ -3,6 +3,7 @@ import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { seedDetails } from '../cache.js';
4
4
  import { keys, constructJob } from '../realtime.js';
5
5
  import { Job } from '../../types/api.js';
6
+ import { withoutEmpty } from '../wire.js';
6
7
  AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
7
8
  const client = queryClient ?? this.peekQueryClient();
8
9
  if (!client) {
@@ -10,6 +11,31 @@ AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
10
11
  }
11
12
  return client.getQueryData(keys.list('jobs', this.companyId)) ?? [];
12
13
  };
14
+ /**
15
+ * Shape a job write for the wire. `UpdateJob`/`ManagedJob` type the job,
16
+ * task, prepayment, owner and catalog item ids as UUIDs, so a blank (`''`)
17
+ * id would be a 400: it is omitted (for `id`s that means "new row"; for
18
+ * `owner_id` / `catalog_item_id` it means "unchanged" — send `null` to
19
+ * clear them). Everything else, explicit nulls included, is sent as given:
20
+ * a null is an intentional clear.
21
+ */
22
+ function toJobWire(job) {
23
+ const wire = withoutEmpty(job, 'id', 'owner_id');
24
+ if (!wire.tasks)
25
+ return wire;
26
+ return {
27
+ ...wire,
28
+ tasks: wire.tasks.map((task) => {
29
+ const wireTask = withoutEmpty(task, 'id', 'catalog_item_id');
30
+ return wireTask.prepayments
31
+ ? {
32
+ ...wireTask,
33
+ prepayments: wireTask.prepayments.map((p) => withoutEmpty(p, 'id')),
34
+ }
35
+ : wireTask;
36
+ }),
37
+ };
38
+ }
13
39
  const JOBS_SYNC_CHUNK = 50;
14
40
  const JOBS_SYNC_CONCURRENCY = 3;
15
41
  async function runLimited(items, limit, worker) {
@@ -108,7 +134,7 @@ AvroQueryClient.prototype.useCreateJob = function () {
108
134
  mutationFn: ({ jobData }) => {
109
135
  return this.post({
110
136
  path: `/company/${this.companyId}/job`,
111
- data: JSON.stringify(jobData),
137
+ data: JSON.stringify(toJobWire(jobData)),
112
138
  headers: { 'Content-Type': 'application/json' },
113
139
  });
114
140
  },
@@ -123,7 +149,7 @@ AvroQueryClient.prototype.useManageJobs = function () {
123
149
  mutationFn: ({ jobs }) => {
124
150
  return this.post({
125
151
  path: `/company/${this.companyId}/jobs/manage`,
126
- data: JSON.stringify({ jobs }),
152
+ data: JSON.stringify({ jobs: jobs.map(toJobWire) }),
127
153
  headers: { 'Content-Type': 'application/json' },
128
154
  });
129
155
  },
@@ -138,7 +164,7 @@ AvroQueryClient.prototype.useUpdateJob = function () {
138
164
  mutationFn: ({ jobId, updates }) => {
139
165
  return this.put({
140
166
  path: `/job/${jobId}`,
141
- data: JSON.stringify(updates),
167
+ data: JSON.stringify(toJobWire(updates)),
142
168
  headers: { 'Content-Type': 'application/json' },
143
169
  });
144
170
  },
@@ -4,21 +4,25 @@ import { seedDetails } from '../cache.js';
4
4
  import { keys } from '../realtime.js';
5
5
  AvroQueryClient.prototype.useGetMessages = function (chatId, body) {
6
6
  const queryClient = this.getQueryClient();
7
+ // The backend pages messages 1..100 at a time (default 10); send the
8
+ // page size explicitly so `getNextPageParam` compares against it.
9
+ const amt = Math.min(Math.max(body.amt ?? 50, 1), 100);
7
10
  const result = useInfiniteQuery({
8
11
  queryKey: keys.infinite('messages', chatId, {
9
- amt: body.amt ?? 50,
12
+ amt,
10
13
  known_ids: body.known_ids ?? [],
11
14
  unknown_ids: body.unknown_ids ?? [],
12
15
  query: body.query ?? '',
13
16
  }),
14
17
  initialPageParam: 0,
15
18
  getNextPageParam: (lastPage, allPages) => {
16
- if (lastPage.length < (body.amt ?? 50))
19
+ if (lastPage.length < amt)
17
20
  return undefined;
18
21
  return allPages.flat().length; // next offset
19
22
  },
20
23
  queryFn: ({ pageParam = 0 }) => this.fetchMessages(chatId, {
21
24
  ...body,
25
+ amt,
22
26
  offset: pageParam,
23
27
  }).then((messages) => seedDetails(queryClient, 'message', messages)),
24
28
  enabled: Boolean(chatId),
@@ -3,6 +3,6 @@ import { AvroQueryClient } from '../QueryClient.js';
3
3
  AvroQueryClient.prototype.useGetPlans = function (code) {
4
4
  return useQuery({
5
5
  queryKey: ['plans', code],
6
- queryFn: async () => this.get({ path: `/plans${code ? `?code=${code}` : ''}` }),
6
+ queryFn: async () => this.get({ path: `/plans${code ? `?code=${encodeURIComponent(code)}` : ''}` }),
7
7
  });
8
8
  };