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

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 (42) hide show
  1. package/dist/chat.d.ts +25 -0
  2. package/dist/chat.js +47 -0
  3. package/dist/client/QueryClient.d.ts +125 -28
  4. package/dist/client/QueryClient.js +107 -60
  5. package/dist/client/cache.d.ts +4 -0
  6. package/dist/client/cache.js +19 -0
  7. package/dist/client/core/uploads.js +226 -0
  8. package/dist/client/hooks/avro.js +13 -0
  9. package/dist/client/hooks/bills.js +43 -16
  10. package/dist/client/hooks/catalog_items.js +16 -4
  11. package/dist/client/hooks/chats.js +26 -0
  12. package/dist/client/hooks/devices.js +17 -3
  13. package/dist/client/hooks/messages.js +54 -1
  14. package/dist/client/hooks/routes.js +4 -1
  15. package/dist/client/hooks/teams.js +8 -2
  16. package/dist/client/hooks/{proposal_terms.js → terms.js} +14 -14
  17. package/dist/client/hooks/users.js +13 -0
  18. package/dist/client/realtime.d.ts +26 -3
  19. package/dist/client/realtime.js +93 -16
  20. package/dist/client/requests.d.ts +39 -6
  21. package/dist/index.d.ts +4 -1
  22. package/dist/index.js +3 -1
  23. package/dist/types/api/AuditLog.d.ts +1 -1
  24. package/dist/types/api/Avro.d.ts +66 -15
  25. package/dist/types/api/CatalogItem.d.ts +3 -1
  26. package/dist/types/api/Company.d.ts +2 -2
  27. package/dist/types/api/Job.js +11 -2
  28. package/dist/types/api/MemberState.d.ts +3 -0
  29. package/dist/types/api/Notification.d.ts +39 -0
  30. package/dist/types/api/Proposal.d.ts +2 -2
  31. package/dist/types/api/Task.d.ts +8 -0
  32. package/dist/types/api/Task.js +30 -3
  33. package/dist/types/api/{ProposalTerms.d.ts → Terms.d.ts} +3 -3
  34. package/dist/types/api/Terms.js +1 -0
  35. package/dist/types/api.d.ts +1 -1
  36. package/dist/types/api.js +1 -1
  37. package/dist/types/client.d.ts +125 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/package.json +1 -1
  41. /package/dist/client/{hooks/proposal_terms.d.ts → core/uploads.d.ts} +0 -0
  42. /package/dist/{types/api/ProposalTerms.js → client/hooks/terms.d.ts} +0 -0
@@ -0,0 +1,226 @@
1
+ import { useMutation } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../QueryClient.js';
3
+ import { cancelledError, isCancelledError } from './policy.js';
4
+ import { StandardError } from '../../types/error.js';
5
+ /** Photos allocated per request; keeps the presigned batch small. */
6
+ const ALLOCATE_BATCH = 20;
7
+ /** A slow phone gets this long per photo before the try is abandoned. */
8
+ const S3_TIMEOUT_MS = 45000;
9
+ const DEFAULT_ATTEMPTS = 2;
10
+ /** POST one file straight to S3 with its presigned form fields. */
11
+ function postToS3(slot, image, onProgress, cancelToken) {
12
+ return new Promise((resolve, reject) => {
13
+ if (cancelToken?.isCancelled()) {
14
+ reject(cancelledError());
15
+ return;
16
+ }
17
+ const form = new FormData();
18
+ Object.entries(slot.fields ?? {}).forEach(([k, v]) => form.append(k, v));
19
+ // The file must be the last field of a presigned POST.
20
+ if (typeof Blob !== 'undefined' && image.file instanceof Blob) {
21
+ form.append('file', image.file, image.name ?? slot.name);
22
+ }
23
+ else {
24
+ // React Native's FormData takes a `{ uri, name, type }` reference.
25
+ form.append('file', image.file);
26
+ }
27
+ const xhr = new XMLHttpRequest();
28
+ xhr.open('POST', slot.url, true);
29
+ xhr.timeout = S3_TIMEOUT_MS;
30
+ xhr.upload.onprogress = (event) => {
31
+ if (event.lengthComputable && event.total > 0)
32
+ onProgress(event.loaded / event.total);
33
+ };
34
+ xhr.onload = () => {
35
+ if (xhr.status >= 200 && xhr.status < 300)
36
+ resolve();
37
+ else
38
+ reject(new StandardError(xhr.status, xhr.responseText || 'Upload to S3 failed'));
39
+ };
40
+ // Cancelling stops the transfer itself, not just the next one.
41
+ const watch = cancelToken
42
+ ? setInterval(() => {
43
+ if (!cancelToken.isCancelled())
44
+ return;
45
+ xhr.abort();
46
+ reject(cancelledError());
47
+ }, 250)
48
+ : undefined;
49
+ xhr.onloadend = () => clearInterval(watch);
50
+ xhr.onerror = () => reject(new StandardError(0, 'Network Error'));
51
+ xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
52
+ xhr.send(form);
53
+ });
54
+ }
55
+ AvroQueryClient.prototype._uploadImages = async function (base, images, options = {}) {
56
+ const { onProgress, onAttempt, attempts = DEFAULT_ATTEMPTS, cancelToken } = options;
57
+ const names = images.map(() => null);
58
+ const failed = [];
59
+ const total = images.length;
60
+ let done = 0;
61
+ const report = (current) => onProgress?.(done + current, total);
62
+ // Set once a photo exhausts its tries: the connection can't carry a
63
+ // photo right now, so the rest fail fast instead of each waiting out
64
+ // its own timeouts (they're reported retryable for a later resend).
65
+ let stalled = null;
66
+ const skip = (index, upload) => failed.push({ image: images[index], msg: stalled ?? '', retryable: true, upload });
67
+ for (let start = 0; start < images.length; start += ALLOCATE_BATCH) {
68
+ const batch = images.slice(start, start + ALLOCATE_BATCH);
69
+ if (stalled) {
70
+ batch.forEach((image, i) => skip(start + i, image.upload));
71
+ continue;
72
+ }
73
+ const { uploads } = await this.post({
74
+ path: `${base}/uploads`,
75
+ data: JSON.stringify({
76
+ images: batch.map((image) => ({
77
+ ...(image.upload ? { name: image.upload } : {}),
78
+ content_type: image.type,
79
+ size: image.size,
80
+ })),
81
+ }),
82
+ headers: { 'Content-Type': 'application/json' },
83
+ // A lost response only leaves an unconfirmed pending upload.
84
+ idempotent: true,
85
+ cancelToken,
86
+ });
87
+ const toConfirm = [];
88
+ for (let i = 0; i < uploads.length; i++) {
89
+ const slot = uploads[i];
90
+ const index = start + i;
91
+ if (slot.uploaded) {
92
+ names[index] = slot.name;
93
+ done++;
94
+ report(0);
95
+ continue;
96
+ }
97
+ if (stalled) {
98
+ skip(index, slot.name);
99
+ continue;
100
+ }
101
+ for (let attempt = 1;; attempt++) {
102
+ const startedAt = Date.now();
103
+ onAttempt?.({
104
+ startedAt,
105
+ giveUpAt: startedAt + (attempts - attempt + 1) * S3_TIMEOUT_MS,
106
+ });
107
+ try {
108
+ await postToS3(slot, images[index], report, cancelToken);
109
+ toConfirm.push({ index, slot });
110
+ break;
111
+ }
112
+ catch (error) {
113
+ if (isCancelledError(error))
114
+ throw error;
115
+ // S3 rejecting a transfer (timeout, expired policy, cut
116
+ // connection) never means the photo is bad: the server
117
+ // judges the bytes on confirm. So it's always worth
118
+ // sending again.
119
+ if (attempt >= attempts) {
120
+ stalled = error instanceof Error ? error.message : String(error);
121
+ skip(index, slot.name);
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ done++;
127
+ report(0);
128
+ }
129
+ if (toConfirm.length === 0)
130
+ continue;
131
+ let confirmed;
132
+ try {
133
+ confirmed = await this.post({
134
+ path: `${base}/confirm`,
135
+ data: JSON.stringify({ names: toConfirm.map(({ slot }) => slot.name) }),
136
+ headers: { 'Content-Type': 'application/json' },
137
+ idempotent: true,
138
+ cancelToken,
139
+ });
140
+ }
141
+ catch (error) {
142
+ if (isCancelledError(error))
143
+ throw error;
144
+ // The confirm may have landed: report the names so a retry
145
+ // resends these photos under them instead of storing new copies.
146
+ const msg = error instanceof Error ? error.message : String(error);
147
+ for (const { index, slot } of toConfirm) {
148
+ failed.push({ image: images[index], msg, retryable: true, upload: slot.name });
149
+ }
150
+ continue;
151
+ }
152
+ const stored = new Set(confirmed.names);
153
+ const reasons = new Map(confirmed.failed.map((f) => [f.name, f.msg]));
154
+ for (const { index, slot } of toConfirm) {
155
+ if (stored.has(slot.name)) {
156
+ names[index] = slot.name;
157
+ }
158
+ else {
159
+ const msg = reasons.get(slot.name) ?? 'Upload not confirmed';
160
+ failed.push({
161
+ image: images[index],
162
+ msg,
163
+ retryable: msg === 'Not uploaded',
164
+ upload: slot.name,
165
+ });
166
+ }
167
+ }
168
+ }
169
+ return { names, failed };
170
+ };
171
+ AvroQueryClient.prototype.uploadImages = function (target, images, options) {
172
+ const base = 'eventId' in target ? `/event/${target.eventId}/image` : `/task/${target.taskId}/image`;
173
+ return this._uploadImages(base, images, options);
174
+ };
175
+ /**
176
+ * The server sends only once per key however often the request repeats.
177
+ * Not retried here: a caller keeps the key and resends later (an outbox).
178
+ */
179
+ const idempotency = (key) => (key ? { headers: { 'Idempotency-Key': key } } : {});
180
+ AvroQueryClient.prototype.sendNotification = function (body, options = {}) {
181
+ const form = new FormData();
182
+ form.append('data', JSON.stringify(body));
183
+ return this.post({
184
+ path: `/company/${options.companyId ?? this.companyId}/notification`,
185
+ data: form,
186
+ ...idempotency(options.idempotencyKey),
187
+ });
188
+ };
189
+ AvroQueryClient.prototype.sendEmailMessage = function (emailId, body, options = {}) {
190
+ const form = new FormData();
191
+ form.append('data', JSON.stringify(body));
192
+ if (options.requestId)
193
+ form.append('request_id', options.requestId);
194
+ if (options.proposalId)
195
+ form.append('proposal_id', options.proposalId);
196
+ return this.post({
197
+ path: `/email/${emailId}`,
198
+ data: form,
199
+ ...idempotency(options.idempotencyKey),
200
+ });
201
+ };
202
+ AvroQueryClient.prototype.useUploadImages = function () {
203
+ return useMutation({
204
+ mutationFn: ({ target, images, options }) => this.uploadImages(target, images, options),
205
+ // Task photos are embedded in their job.
206
+ onSettled: (_data, _err, { target }) => this.syncAfterMutation('eventId' in target ? 'event' : 'job'),
207
+ });
208
+ };
209
+ AvroQueryClient.prototype.useSendNotification = function () {
210
+ return useMutation({
211
+ mutationFn: ({ body, companyId, idempotencyKey }) => this.sendNotification(body, { companyId, idempotencyKey }),
212
+ });
213
+ };
214
+ AvroQueryClient.prototype.useSendEmailMessage = function () {
215
+ return useMutation({
216
+ mutationFn: ({ emailId, body, requestId, proposalId, idempotencyKey, }) => this.sendEmailMessage(emailId, body, { requestId, proposalId, idempotencyKey }),
217
+ });
218
+ };
219
+ AvroQueryClient.prototype.getEventPhotoLinks = function ({ eventId, count }) {
220
+ return this.get({ path: `/event/${eventId}/photo-links?count=${count}` });
221
+ };
222
+ AvroQueryClient.prototype.useEventPhotoLinks = function () {
223
+ return useMutation({
224
+ mutationFn: (vars) => this.getEventPhotoLinks(vars),
225
+ });
226
+ };
@@ -45,3 +45,16 @@ AvroQueryClient.prototype.useClearErrorLog = function () {
45
45
  },
46
46
  });
47
47
  };
48
+ AvroQueryClient.prototype.useRunSchedulerJobs = function () {
49
+ const queryClient = this.getQueryClient();
50
+ return useMutation({
51
+ mutationFn: (jobIds) => this.post({
52
+ path: '/avro/scheduler/run',
53
+ data: JSON.stringify(jobIds ? { job_ids: jobIds } : {}),
54
+ headers: { 'Content-Type': 'application/json' },
55
+ }),
56
+ onSuccess: () => {
57
+ queryClient.invalidateQueries({ queryKey: ['avro', 'performance'] });
58
+ },
59
+ });
60
+ };
@@ -1,4 +1,5 @@
1
1
  import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
+ import { useEffect, useState } from 'react';
2
3
  import { AvroQueryClient } from '../QueryClient.js';
3
4
  import { seedDetails } from '../cache.js';
4
5
  import { restoreNs, snapshotNs } from '../cache.js';
@@ -221,22 +222,45 @@ AvroQueryClient.prototype.useSyncBillToIntuit = function () {
221
222
  AvroQueryClient.prototype.useImportBillsFromIntuit = function () {
222
223
  const queryClient = this.getQueryClient();
223
224
  return useMutation({
225
+ // Starts the sync (202); follow it with useIntuitSyncStatus.
224
226
  mutationFn: async () => {
225
227
  return this.post({
226
228
  path: `/company/${this.companyId}/intuit/import`,
227
229
  });
228
230
  },
229
- onSuccess: () => {
230
- this.syncAfterMutation('bill');
231
- },
232
231
  });
233
232
  };
234
- AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId }) {
235
- return this.get({
236
- path: `/company/${this.companyId}/bill/${billId}/pdf`,
237
- }).then((response) => {
238
- return response;
239
- });
233
+ /**
234
+ * The company's QuickBooks sync, followed over the socket: `running` (with the
235
+ * latest progress) from `intuit_sync_started` on, then `complete` with the
236
+ * counts or `error`. Every staff member sees a run, whoever started it; the
237
+ * bills it changes arrive through the changes stream.
238
+ */
239
+ AvroQueryClient.prototype.useIntuitSyncStatus = function () {
240
+ const [status, setStatus] = useState({ state: 'idle' });
241
+ useEffect(() => {
242
+ const started = () => setStatus({ state: 'running' });
243
+ const progress = (data) => setStatus({ state: 'running', progress: data });
244
+ const complete = (data) => setStatus({ state: 'complete', result: data });
245
+ const failed = (data) => setStatus({ state: 'error', message: data?.msg ?? 'QuickBooks sync failed' });
246
+ this.on('intuit_sync_started', started);
247
+ this.on('intuit_sync_progress', progress);
248
+ this.on('intuit_sync_complete', complete);
249
+ this.on('intuit_sync_error', failed);
250
+ return () => {
251
+ this.off('intuit_sync_started', started);
252
+ this.off('intuit_sync_progress', progress);
253
+ this.off('intuit_sync_complete', complete);
254
+ this.off('intuit_sync_error', failed);
255
+ };
256
+ }, [this]);
257
+ return status;
258
+ };
259
+ AvroQueryClient.prototype.generatePDFFromBackend = function (source) {
260
+ const path = 'billId' in source
261
+ ? `/company/${this.companyId}/bill/${source.billId}/pdf`
262
+ : `/company/${this.companyId}/timecards/pdf?period_start=${source.timecardsPeriodStart}`;
263
+ return this.get({ path });
240
264
  };
241
265
  AvroQueryClient.prototype.useBulkDeleteBills = function () {
242
266
  const queryClient = this.getQueryClient();
@@ -276,12 +300,15 @@ AvroQueryClient.prototype.useBulkEmailBills = function () {
276
300
  // `bill_guid`.
277
301
  });
278
302
  };
279
- AvroQueryClient.prototype.sendBillingEmail = async function ({ subject, billId, recipients, request_id, }) {
280
- return this.post({
281
- path: `/bill/${billId}/email`,
282
- data: JSON.stringify({ recipients, subject, request_id }),
283
- headers: {
284
- 'Content-Type': 'application/json',
285
- },
303
+ AvroQueryClient.prototype.useSendBillEmail = function () {
304
+ return useMutation({
305
+ // The server renders the PDF, totals and each recipient's pay link.
306
+ mutationFn: ({ billId, subject, recipients, request_id }) => this.post({
307
+ path: `/bill/${billId}/email`,
308
+ data: JSON.stringify({ recipients, subject, request_id }),
309
+ headers: { 'Content-Type': 'application/json' },
310
+ }),
311
+ // No cache sync: emailing doesn't change the bill; delivery outcomes
312
+ // arrive as `email_succeeded`/`email_failed` events on `request_id`.
286
313
  });
287
314
  };
@@ -1,6 +1,7 @@
1
1
  import { useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs } from '../cache.js';
4
+ import { keys } from '../realtime.js';
4
5
  import { StandardError } from '../../types/error.js';
5
6
  AvroQueryClient.prototype.useCreateCatalogItem = function () {
6
7
  const queryClient = this.getQueryClient();
@@ -87,11 +88,11 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
87
88
  AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
88
89
  return useQuery({
89
90
  queryKey: ['catalog_items', catalogItemId],
90
- // There is no `GET /catalog_item/<id>`: catalog items are embedded
91
- // in the company payload.
92
91
  queryFn: async () => {
93
- const company = await this.get({ path: `/company/${this.companyId}` });
94
- const item = company?.catalog_items?.find((ci) => ci.id === catalogItemId);
92
+ const [item] = await this.fetchCatalogItems({
93
+ unknown_ids: [catalogItemId],
94
+ amt: 1,
95
+ });
95
96
  if (!item)
96
97
  throw new StandardError(404, 'Catalog item not found');
97
98
  return item;
@@ -99,6 +100,17 @@ AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
99
100
  enabled: Boolean(catalogItemId) && Boolean(this.companyId),
100
101
  });
101
102
  };
103
+ AvroQueryClient.prototype.useGetCatalogItems = function (body = {}) {
104
+ const { companyId: bodyCompanyId, ...filters } = body;
105
+ const companyId = bodyCompanyId ?? this.companyId;
106
+ return useQuery({
107
+ // `industry` / `archived` stay absent when unset so list patching
108
+ // reads them as "no filter".
109
+ queryKey: keys.list('catalog_items', companyId, { query: '', ...filters }),
110
+ queryFn: () => this.fetchCatalogItems(filters, companyId),
111
+ enabled: Boolean(companyId),
112
+ });
113
+ };
102
114
  AvroQueryClient.prototype.useDeleteCatalogItem = function () {
103
115
  const queryClient = this.getQueryClient();
104
116
  return useMutation({
@@ -60,3 +60,29 @@ AvroQueryClient.prototype.useCreateChat = function () {
60
60
  },
61
61
  });
62
62
  };
63
+ AvroQueryClient.prototype.useUpdateChat = function () {
64
+ const queryClient = this.getQueryClient();
65
+ return useMutation({
66
+ mutationFn: ({ chatId, ...data }) => this.put({
67
+ path: `/chat/${chatId}`,
68
+ data: JSON.stringify(data),
69
+ headers: { 'Content-Type': 'application/json' },
70
+ }),
71
+ onSettled: (_data, _err, { chatId }) => {
72
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
73
+ queryClient.invalidateQueries({ queryKey: ['messages', 'infinite', chatId] });
74
+ },
75
+ });
76
+ };
77
+ AvroQueryClient.prototype.useLeaveChat = function () {
78
+ const queryClient = this.getQueryClient();
79
+ return useMutation({
80
+ // The last member to leave deletes the chat.
81
+ mutationFn: ({ chatId }) => this.delete({ path: `/chat/${chatId}` }),
82
+ // Leave the thread's queries to age out: removing them while the
83
+ // thread is still mounted refetches a chat the caller has left.
84
+ onSettled: () => {
85
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
86
+ },
87
+ });
88
+ };
@@ -14,9 +14,23 @@ AvroQueryClient.prototype.useReportDevice = function () {
14
14
  data: JSON.stringify({ ...this.device, ...data }),
15
15
  headers: { 'Content-Type': 'application/json' },
16
16
  }),
17
- onSuccess: () => {
18
- queryClient.invalidateQueries({ queryKey: ['devices'] });
19
- queryClient.invalidateQueries({ queryKey: ['user'] });
17
+ // Reported on every foreground/visibility flip: patch the returned
18
+ // device in rather than refetching the profile and device list.
19
+ onSuccess: (device) => {
20
+ if (!device?.id) {
21
+ queryClient.invalidateQueries({ queryKey: ['devices'] });
22
+ queryClient.invalidateQueries({ queryKey: ['user'] });
23
+ return;
24
+ }
25
+ const upsert = (devices) => {
26
+ if (!Array.isArray(devices))
27
+ return devices;
28
+ return devices.some((d) => d.id === device.id)
29
+ ? devices.map((d) => (d.id === device.id ? device : d))
30
+ : [...devices, device];
31
+ };
32
+ queryClient.setQueryData(['devices'], (old) => upsert(old) ?? old);
33
+ queryClient.setQueryData(['user'], (old) => old && Array.isArray(old.devices) ? { ...old, devices: upsert(old.devices) } : old);
20
34
  },
21
35
  });
22
36
  };
@@ -1,6 +1,6 @@
1
1
  import { useInfiniteQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
- import { seedDetails } from '../cache.js';
3
+ import { replaceRow, restoreNs, seedDetails, snapshotNs } from '../cache.js';
4
4
  import { keys } from '../realtime.js';
5
5
  AvroQueryClient.prototype.useGetMessages = function (chatId, body) {
6
6
  const queryClient = this.getQueryClient();
@@ -53,3 +53,56 @@ AvroQueryClient.prototype.useCreateMessage = function (chatId) {
53
53
  },
54
54
  });
55
55
  };
56
+ AvroQueryClient.prototype.useReactToMessage = function (chatId) {
57
+ const queryClient = this.getQueryClient();
58
+ return useMutation({
59
+ // `reaction` is a Unicode code point. Adding twice, or removing one
60
+ // that isn't there, is a no-op server-side.
61
+ mutationFn: ({ message, reaction, remove }) => remove
62
+ ? this.delete({ path: `/message/${message.id}/react/${reaction}` })
63
+ : this.post({
64
+ path: `/message/${message.id}/react`,
65
+ data: JSON.stringify({ reaction }),
66
+ headers: { 'Content-Type': 'application/json' },
67
+ }),
68
+ onMutate: async ({ message, reaction, userId, remove }) => {
69
+ await queryClient.cancelQueries({ queryKey: ['messages', 'infinite', chatId] });
70
+ const snapshot = snapshotNs(queryClient, 'messages');
71
+ const mine = (r) => r.sender_id === userId && r.reaction === reaction;
72
+ const reactions = remove
73
+ ? message.reactions.filter((r) => !mine(r))
74
+ : message.reactions.some(mine)
75
+ ? message.reactions
76
+ : [
77
+ ...message.reactions,
78
+ {
79
+ id: `optimistic-${reaction}`,
80
+ message_id: message.id,
81
+ sender_id: userId,
82
+ reaction,
83
+ time_created: Math.floor(Date.now() / 1000),
84
+ time_updated: null,
85
+ },
86
+ ];
87
+ replaceRow(queryClient, 'messages', { ...message, reactions });
88
+ return { snapshot };
89
+ },
90
+ onError: (_err, _vars, context) => restoreNs(queryClient, context?.snapshot),
91
+ onSettled: () => {
92
+ // A live socket gets `message_updated` with the real rows.
93
+ if (!this.socket?.connected) {
94
+ queryClient.invalidateQueries({ queryKey: ['messages', 'infinite', chatId] });
95
+ }
96
+ },
97
+ });
98
+ };
99
+ AvroQueryClient.prototype.useMarkChatRead = function (chatId) {
100
+ const queryClient = this.getQueryClient();
101
+ return useMutation({
102
+ // Reading a message page with `last_message_read` records the read.
103
+ mutationFn: ({ messageId }) => this.fetchMessages(chatId, { amt: 1, last_message_read: messageId }),
104
+ onSuccess: () => {
105
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
106
+ },
107
+ });
108
+ };
@@ -67,7 +67,10 @@ AvroQueryClient.prototype.useGetRoutes = function (body, total, onProgress) {
67
67
  queryKey: keys.list('routes', this.companyId, {
68
68
  amt: body.amt ?? 50,
69
69
  query: body.query ?? '',
70
- total: total ?? 'all',
70
+ // Paged vs single fetch only: a count change (a route added or
71
+ // removed) arrives as a realtime change and is patched in, so it
72
+ // mustn't re-page the whole list on every client.
73
+ total: typeof total === 'number' ? 'paged' : 'all',
71
74
  }),
72
75
  queryFn: async () => {
73
76
  if (typeof total !== 'number') {
@@ -2,12 +2,18 @@ import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs } from '../cache.js';
4
4
  import { keys } from '../realtime.js';
5
+ import { Permission } from '../../types/api.js';
5
6
  AvroQueryClient.prototype.useGetTeams = function (body, total, onProgress) {
7
+ // Customers and roles without team read get a 403; don't ask.
8
+ const canReadTeams = this.useHasPermission(Permission.CAN_READ_TEAMS);
6
9
  return useQuery({
7
10
  queryKey: keys.list('teams', this.companyId, {
8
11
  amt: body.amt ?? 50,
9
12
  query: body.query ?? '',
10
- total: total ?? 'all',
13
+ // Paged vs single fetch only: a count change (a team added or
14
+ // removed) arrives as a realtime change and is patched in, so it
15
+ // mustn't re-page the whole list on every client.
16
+ total: typeof total === 'number' ? 'paged' : 'all',
11
17
  }),
12
18
  queryFn: async () => {
13
19
  if (typeof total !== 'number') {
@@ -30,7 +36,7 @@ AvroQueryClient.prototype.useGetTeams = function (body, total, onProgress) {
30
36
  const teams = pages.flat();
31
37
  return teams;
32
38
  },
33
- enabled: Boolean(this.companyId),
39
+ enabled: Boolean(this.companyId) && canReadTeams !== false,
34
40
  });
35
41
  };
36
42
  AvroQueryClient.prototype.useCreateTeam = function () {
@@ -1,20 +1,20 @@
1
1
  import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { keys } from '../realtime.js';
4
- AvroQueryClient.prototype.useGetProposalTerms = function () {
4
+ AvroQueryClient.prototype.useGetTerms = function () {
5
5
  return useQuery({
6
- queryKey: keys.list('proposal_terms', this.companyId),
7
- queryFn: () => this.get({ path: `/company/${this.companyId}/proposal_terms` }),
6
+ queryKey: keys.list('terms', this.companyId),
7
+ queryFn: () => this.get({ path: `/company/${this.companyId}/terms` }),
8
8
  enabled: Boolean(this.companyId),
9
9
  });
10
10
  };
11
- AvroQueryClient.prototype.useCreateProposalTerms = function () {
11
+ AvroQueryClient.prototype.useCreateTerms = function () {
12
12
  const queryClient = this.getQueryClient();
13
- const listKey = keys.list('proposal_terms', this.companyId);
13
+ const listKey = keys.list('terms', this.companyId);
14
14
  return useMutation({
15
15
  mutationFn: async (data) => {
16
16
  return this.post({
17
- path: `/company/${this.companyId}/proposal_terms`,
17
+ path: `/company/${this.companyId}/terms`,
18
18
  data: JSON.stringify(data),
19
19
  headers: { 'Content-Type': 'application/json' },
20
20
  });
@@ -40,26 +40,26 @@ AvroQueryClient.prototype.useCreateProposalTerms = function () {
40
40
  time_created: now,
41
41
  time_updated: now,
42
42
  };
43
- queryClient.setQueryData(listKey, (old) => old ? [...old, optimistic] : old);
43
+ queryClient.setQueryData(listKey, (old) => (old ? [...old, optimistic] : old));
44
44
  return { previous, tempId };
45
45
  },
46
46
  onSuccess: ({ id }, _variables, context) => {
47
47
  queryClient.setQueryData(listKey, (old) => old?.some((t) => t.id === id)
48
48
  ? old.filter((t) => t.id !== context?.tempId)
49
49
  : old?.map((t) => (t.id === context?.tempId ? { ...t, id } : t)));
50
- this.syncAfterMutation('proposal_terms');
50
+ this.syncAfterMutation('terms');
51
51
  },
52
52
  onError: (_err, _variables, context) => {
53
53
  queryClient.setQueryData(listKey, context?.previous);
54
54
  },
55
55
  });
56
56
  };
57
- AvroQueryClient.prototype.useUpdateProposalTerms = function () {
57
+ AvroQueryClient.prototype.useUpdateTerms = function () {
58
58
  const queryClient = this.getQueryClient();
59
59
  return useMutation({
60
60
  mutationFn: async ({ termsId, updates, }) => {
61
61
  return this.put({
62
- path: `/proposal_terms/${termsId}`,
62
+ path: `/terms/${termsId}`,
63
63
  data: JSON.stringify(updates),
64
64
  headers: { 'Content-Type': 'application/json' },
65
65
  });
@@ -78,13 +78,13 @@ AvroQueryClient.prototype.useUpdateProposalTerms = function () {
78
78
  body: body ?? t.current_version.body,
79
79
  },
80
80
  };
81
- await queryClient.cancelQueries({ queryKey: ['proposal_terms'] });
82
- const previous = queryClient.getQueriesData({ queryKey: ['proposal_terms'] });
83
- queryClient.setQueriesData({ queryKey: ['proposal_terms'] }, (old) => (Array.isArray(old) ? old.map(patch) : old && patch(old)));
81
+ await queryClient.cancelQueries({ queryKey: ['terms'] });
82
+ const previous = queryClient.getQueriesData({ queryKey: ['terms'] });
83
+ queryClient.setQueriesData({ queryKey: ['terms'] }, (old) => Array.isArray(old) ? old.map(patch) : old && patch(old));
84
84
  return { previous };
85
85
  },
86
86
  onSuccess: () => {
87
- this.syncAfterMutation('proposal_terms');
87
+ this.syncAfterMutation('terms');
88
88
  },
89
89
  onError: (_err, _variables, context) => {
90
90
  context?.previous.forEach(([key, data]) => queryClient.setQueryData(key, data));
@@ -228,3 +228,16 @@ AvroQueryClient.prototype.useGetCompanyUsers = function (body = {}) {
228
228
  staleTime: 30000,
229
229
  });
230
230
  };
231
+ /**
232
+ * Whether the signed-in user's membership in the current company grants
233
+ * `permission`, directly or through a group: the check the backend makes
234
+ * before answering. `undefined` until the membership has loaded, so callers
235
+ * choose how to treat "not known yet"; gate a query with `!== false` to only
236
+ * skip it once the permission is known to be missing.
237
+ */
238
+ AvroQueryClient.prototype.useHasPermission = function (permission) {
239
+ const { data: self } = this.useGetSelf();
240
+ const { data: members } = this.useGetCompanyUsers();
241
+ const me = members?.find((member) => member.user?.id === self?.id);
242
+ return me ? (me.effective_permissions ?? []).includes(permission) : undefined;
243
+ };