@go-avro/avro-js 1.6.6-rc9 → 1.7.1

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 (48) hide show
  1. package/dist/chat.d.ts +25 -0
  2. package/dist/chat.js +47 -0
  3. package/dist/client/QueryClient.d.ts +135 -26
  4. package/dist/client/QueryClient.js +115 -59
  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/accounts.js +52 -0
  9. package/dist/client/hooks/bills.js +19 -17
  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 +4 -1
  16. package/dist/client/hooks/{proposal_terms.js → terms.js} +14 -14
  17. package/dist/client/realtime.d.ts +26 -3
  18. package/dist/client/realtime.js +94 -16
  19. package/dist/client/requests.d.ts +16 -11
  20. package/dist/index.d.ts +5 -1
  21. package/dist/index.js +4 -1
  22. package/dist/types/api/Account.d.ts +61 -0
  23. package/dist/types/api/Account.js +38 -0
  24. package/dist/types/api/AuditLog.d.ts +1 -1
  25. package/dist/types/api/Avro.d.ts +5 -0
  26. package/dist/types/api/Bill.d.ts +2 -2
  27. package/dist/types/api/BillPayment.d.ts +2 -2
  28. package/dist/types/api/CatalogItem.d.ts +3 -1
  29. package/dist/types/api/Company.d.ts +0 -2
  30. package/dist/types/api/Job.d.ts +4 -4
  31. package/dist/types/api/Job.js +11 -2
  32. package/dist/types/api/MemberState.d.ts +3 -0
  33. package/dist/types/api/Notification.d.ts +39 -0
  34. package/dist/types/api/Proposal.d.ts +2 -2
  35. package/dist/types/api/Task.d.ts +16 -0
  36. package/dist/types/api/Task.js +30 -3
  37. package/dist/types/api/{ProposalTerms.d.ts → Terms.d.ts} +3 -3
  38. package/dist/types/api/Terms.js +1 -0
  39. package/dist/types/api.d.ts +2 -2
  40. package/dist/types/api.js +2 -2
  41. package/dist/types/client.d.ts +125 -0
  42. package/dist/version.d.ts +1 -1
  43. package/dist/version.js +1 -1
  44. package/package.json +1 -1
  45. package/dist/types/api/Subscription.d.ts +0 -10
  46. /package/dist/client/{hooks/proposal_terms.d.ts → core/uploads.d.ts} +0 -0
  47. /package/dist/{types/api/ProposalTerms.js → client/hooks/accounts.d.ts} +0 -0
  48. /package/dist/{types/api/Subscription.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
+ };
@@ -0,0 +1,52 @@
1
+ import { useMutation, useQuery } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../QueryClient.js';
3
+ import { keys } from '../realtime.js';
4
+ AvroQueryClient.prototype.useGetAccounts = function (body = {}) {
5
+ return useQuery({
6
+ queryKey: keys.list('accounts', this.companyId, {
7
+ query: body.query ?? '',
8
+ unknown_ids: body.unknown_ids ?? [],
9
+ }),
10
+ queryFn: () => this.fetchAccounts(body),
11
+ enabled: Boolean(this.companyId),
12
+ });
13
+ };
14
+ AvroQueryClient.prototype.useGetAccount = function (accountId) {
15
+ return useQuery({
16
+ queryKey: keys.detail('accounts', accountId),
17
+ queryFn: () => this.get({ path: `/account/${accountId}` }),
18
+ enabled: Boolean(accountId),
19
+ });
20
+ };
21
+ AvroQueryClient.prototype.useCreateAccount = function () {
22
+ return useMutation({
23
+ mutationFn: ({ data }) => this.post({
24
+ path: `/company/${this.companyId}/account`,
25
+ data: JSON.stringify(data),
26
+ headers: { 'Content-Type': 'application/json' },
27
+ }),
28
+ onSuccess: () => {
29
+ this.syncAfterMutation('account');
30
+ },
31
+ });
32
+ };
33
+ AvroQueryClient.prototype.useUpdateAccount = function () {
34
+ return useMutation({
35
+ mutationFn: ({ accountId, updates, }) => this.put({
36
+ path: `/account/${accountId}`,
37
+ data: JSON.stringify(updates),
38
+ headers: { 'Content-Type': 'application/json' },
39
+ }),
40
+ onSuccess: () => {
41
+ this.syncAfterMutation('account');
42
+ },
43
+ });
44
+ };
45
+ AvroQueryClient.prototype.useDeleteAccount = function () {
46
+ return useMutation({
47
+ mutationFn: ({ accountId }) => this.delete({ path: `/account/${accountId}` }),
48
+ onSuccess: () => {
49
+ this.syncAfterMutation('account');
50
+ },
51
+ });
52
+ };
@@ -104,10 +104,10 @@ AvroQueryClient.prototype.useUpdateBill = function () {
104
104
  });
105
105
  },
106
106
  onMutate: async ({ billId, updates: wireUpdates }) => {
107
- // `users`/`line_items` are request-shaped (user ids + amounts,
108
- // bare custom items), not the cached BillUser/LineItem rows; the
109
- // echoed change brings the real ones.
110
- const { users: _users, line_items: _lineItems, ...updates } = wireUpdates;
107
+ // `charges`/`line_items` are request-shaped (user ids + amounts,
108
+ // bare custom items), not cached rows; the echoed change brings
109
+ // the real ones.
110
+ const { charges: _charges, line_items: _lineItems, ...updates } = wireUpdates;
111
111
  await queryClient.cancelQueries({ queryKey: ['bills'] });
112
112
  await queryClient.cancelQueries({ queryKey: ['bills', billId] });
113
113
  const previousBills = snapshotNs(queryClient, 'bills');
@@ -256,12 +256,11 @@ AvroQueryClient.prototype.useIntuitSyncStatus = function () {
256
256
  }, [this]);
257
257
  return status;
258
258
  };
259
- AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId }) {
260
- return this.get({
261
- path: `/company/${this.companyId}/bill/${billId}/pdf`,
262
- }).then((response) => {
263
- return response;
264
- });
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 });
265
264
  };
266
265
  AvroQueryClient.prototype.useBulkDeleteBills = function () {
267
266
  const queryClient = this.getQueryClient();
@@ -301,12 +300,15 @@ AvroQueryClient.prototype.useBulkEmailBills = function () {
301
300
  // `bill_guid`.
302
301
  });
303
302
  };
304
- AvroQueryClient.prototype.sendBillingEmail = async function ({ subject, billId, recipients, request_id, }) {
305
- return this.post({
306
- path: `/bill/${billId}/email`,
307
- data: JSON.stringify({ recipients, subject, request_id }),
308
- headers: {
309
- 'Content-Type': 'application/json',
310
- },
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`.
311
313
  });
312
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') {
@@ -10,7 +10,10 @@ AvroQueryClient.prototype.useGetTeams = function (body, total, onProgress) {
10
10
  queryKey: keys.list('teams', this.companyId, {
11
11
  amt: body.amt ?? 50,
12
12
  query: body.query ?? '',
13
- 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',
14
17
  }),
15
18
  queryFn: async () => {
16
19
  if (typeof total !== 'number') {
@@ -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));
@@ -42,8 +42,14 @@ export interface EntitySpec {
42
42
  construct?: (raw: any) => any;
43
43
  fetchMany?: (client: AvroQueryClient, ids: string[]) => Promise<any[]>;
44
44
  fetchOne?: (client: AvroQueryClient, id: string) => Promise<any>;
45
- listMatch?: (filters: Filters, item: any, scope: string) => ListMatch;
45
+ listMatch?: (filters: Filters, item: any, scope: string, viewerId?: string) => ListMatch;
46
46
  alsoInvalidate?: readonly (readonly unknown[])[];
47
+ /**
48
+ * Derived queries (aggregates) a change makes stale. Every connected
49
+ * client gets the change, so these refresh at most once per
50
+ * THROTTLED_REFRESH_MS instead of once per change.
51
+ */
52
+ refreshThrottled?: readonly (readonly string[])[];
47
53
  invalidateOnly?: boolean;
48
54
  }
49
55
  export declare function constructJob(raw: any): Job;
@@ -56,7 +62,7 @@ export declare function removeEntity(qc: QueryClient, ns: string, id: string): v
56
62
  * companies keeps both companies' lists cached).
57
63
  */
58
64
  export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any, company?: string | null): void;
59
- export declare function matchesList(type: string, key: readonly unknown[], item: any): ListMatch;
65
+ export declare function matchesList(type: string, key: readonly unknown[], item: any, viewerId?: string): ListMatch;
60
66
  export declare function invalidateType(qc: QueryClient, spec: EntitySpec): void;
61
67
  /**
62
68
  * Refetch every query the server refused with a 403. Called when a
@@ -65,9 +71,12 @@ export declare function invalidateType(qc: QueryClient, spec: EntitySpec): void;
65
71
  * focus, remount, or reload.
66
72
  */
67
73
  export declare function retryDenied(qc: QueryClient): void;
74
+ /** Aggregates (analytics) refresh at most this often per client. */
75
+ export declare const THROTTLED_REFRESH_MS = 60000;
68
76
  export declare class ChangeApplier {
69
77
  private client;
70
78
  private qc;
79
+ private refreshMembers?;
71
80
  private pending;
72
81
  private timer;
73
82
  /**
@@ -81,7 +90,21 @@ export declare class ChangeApplier {
81
90
  /** Company each pending `type:id` change came from (see upsertEntity). */
82
91
  private companyOf;
83
92
  private inflight;
84
- constructor(client: AvroQueryClient, qc: QueryClient);
93
+ /** Last run time and pending trailing timer per throttled key. */
94
+ private lastRefresh;
95
+ private refreshTimers;
96
+ /**
97
+ * @param refreshMembers fetches the named members and patches them
98
+ * into the member lists (the same path presence uses), so a
99
+ * change to one member doesn't re-download every member.
100
+ */
101
+ constructor(client: AvroQueryClient, qc: QueryClient, refreshMembers?: ((userIds: string[]) => void) | undefined);
102
+ /**
103
+ * Refresh `key` now if it hasn't refreshed within the window,
104
+ * otherwise once when the window ends. Leading runs are jittered so
105
+ * clients that all received the same change don't refetch in step.
106
+ */
107
+ private refreshThrottled;
85
108
  private mark;
86
109
  /** Settle a change applied inline: only an in-flight fetch needs the mark. */
87
110
  private markApplied;