@go-avro/avro-js 0.1.15 → 1.6.1-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/auth/AuthManager.d.ts +32 -0
  2. package/dist/auth/AuthManager.js +138 -43
  3. package/dist/client/QueryClient.d.ts +68 -2
  4. package/dist/client/QueryClient.js +310 -96
  5. package/dist/client/cache.d.ts +24 -0
  6. package/dist/client/cache.js +51 -0
  7. package/dist/client/core/fetch.js +58 -49
  8. package/dist/client/core/policy.d.ts +17 -0
  9. package/dist/client/core/policy.js +35 -0
  10. package/dist/client/core/xhr.js +16 -14
  11. package/dist/client/hooks/bills.js +10 -14
  12. package/dist/client/hooks/catalog_items.js +18 -8
  13. package/dist/client/hooks/chats.js +2 -8
  14. package/dist/client/hooks/companies.js +11 -5
  15. package/dist/client/hooks/events.js +56 -47
  16. package/dist/client/hooks/groups.js +11 -26
  17. package/dist/client/hooks/jobs.js +3 -8
  18. package/dist/client/hooks/labels.js +11 -26
  19. package/dist/client/hooks/messages.js +21 -24
  20. package/dist/client/hooks/months.js +28 -22
  21. package/dist/client/hooks/payouts.js +3 -8
  22. package/dist/client/hooks/prepayments.js +28 -22
  23. package/dist/client/hooks/proposal.js +1 -0
  24. package/dist/client/hooks/routes.js +8 -6
  25. package/dist/client/hooks/sessions.js +21 -31
  26. package/dist/client/hooks/skills.js +6 -4
  27. package/dist/client/hooks/teams.js +6 -4
  28. package/dist/client/hooks/timecards.js +7 -7
  29. package/dist/client/hooks/waivers.js +6 -4
  30. package/dist/client/persist.js +21 -2
  31. package/dist/client/realtime.d.ts +21 -1
  32. package/dist/client/realtime.js +183 -51
  33. package/dist/types/api/Bill.js +2 -1
  34. package/dist/types/api/Company.d.ts +2 -0
  35. package/dist/types/api/Email.d.ts +3 -9
  36. package/dist/types/api/EmailNotification.d.ts +1 -1
  37. package/dist/types/api/Job.js +8 -4
  38. package/dist/types/api/LineItem.d.ts +4 -0
  39. package/dist/types/api/LineItem.js +10 -2
  40. package/dist/types/api/Prepayment.js +2 -1
  41. package/dist/types/api/Route.js +2 -1
  42. package/dist/types/api/RouteJob.js +2 -1
  43. package/dist/types/api/Session.js +2 -1
  44. package/dist/types/api/Task.d.ts +27 -2
  45. package/dist/types/api/Task.js +44 -8
  46. package/dist/types/api/_Event.js +2 -1
  47. package/dist/types/api/assignData.d.ts +9 -0
  48. package/dist/types/api/assignData.js +17 -0
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +7 -2
@@ -1,21 +1,27 @@
1
1
  import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
+ import { restoreNs, snapshotNs, seedDetails, removeOptimisticRow } from '../cache.js';
3
4
  import { keys, matchesList } from '../realtime.js';
4
- import { constructEvent, DelayEvent, Job, LineItemStatus, } from '../../types/api.js';
5
+ import { constructEvent, DelayEvent, Job, LineItemStatus, Task, getTaskOverdueTime, } from '../../types/api.js';
5
6
  const isJobsQuery = (q) => q.queryKey[0] === 'jobs';
6
7
  const isEventsQuery = (q) => q.queryKey[0] === 'events';
7
8
  const isEventsQueryFor = (item) => (q) => q.queryKey[0] === 'events' && matchesList('event', q.queryKey, item) === 'match';
8
9
  AvroQueryClient.prototype.useGetEvents = function (body) {
9
10
  const queryClient = this.getQueryClient();
11
+ // Status buckets default to the backend's (unbilled only) and are
12
+ // always sent, so the key describes exactly what the server returns.
13
+ const unbilled = body.unbilled ?? true;
14
+ const billed = body.billed ?? false;
15
+ const paid = body.paid ?? false;
10
16
  const result = useInfiniteQuery({
11
17
  queryKey: keys.infinite('events', this.companyId, {
12
18
  amt: body.amt ?? 50,
13
19
  known_ids: body.known_ids ?? [],
14
20
  unknown_ids: body.unknown_ids ?? [],
15
21
  query: body.query ?? '',
16
- unbilled: body.unbilled ?? true,
17
- billed: body.billed ?? true,
18
- paid: body.paid ?? true,
22
+ unbilled,
23
+ billed,
24
+ paid,
19
25
  jobId: body.jobId ?? '',
20
26
  sort_by: body.sort_by ?? null,
21
27
  direction: body.direction ?? null,
@@ -28,19 +34,21 @@ AvroQueryClient.prototype.useGetEvents = function (body) {
28
34
  return allPages.flat().length; // next offset
29
35
  },
30
36
  queryFn: ({ pageParam = 0 }) => this.fetchEvents({
31
- ...body,
37
+ amt: body.amt,
38
+ known_ids: body.known_ids,
39
+ unknown_ids: body.unknown_ids,
40
+ query: body.query,
41
+ unbilled,
42
+ billed,
43
+ paid,
32
44
  job_id: body.jobId,
45
+ sort_by: body.sort_by,
46
+ direction: body.direction,
47
+ line_item_types: body.line_item_types,
33
48
  offset: pageParam,
34
- }).then((events) => events.map((event) => constructEvent(event))),
35
- enabled: body.enabled ?? true,
49
+ }).then((events) => seedDetails(queryClient, 'events', events.map((event) => constructEvent(event)))),
50
+ enabled: (body.enabled ?? true) && Boolean(this.companyId),
36
51
  });
37
- if (result.data) {
38
- result.data.pages.forEach((data_page) => {
39
- data_page.forEach((event) => {
40
- queryClient.setQueryData(['events', event.id], event);
41
- });
42
- });
43
- }
44
52
  return result;
45
53
  };
46
54
  AvroQueryClient.prototype.useGetEvent = function (eventId) {
@@ -117,9 +125,12 @@ AvroQueryClient.prototype.useCreateEvent = function () {
117
125
  }
118
126
  return oldData;
119
127
  });
120
- return { previousJob };
128
+ return { previousJob, tempId: optimisticEvent.id };
121
129
  },
122
- onSuccess: () => {
130
+ onSuccess: (_data, _vars, context) => {
131
+ // The echoed change (or the fallback refetch) brings the real row.
132
+ if (context?.tempId)
133
+ removeOptimisticRow(queryClient, 'events', context.tempId);
123
134
  this.syncAfterMutation('event', 'job');
124
135
  },
125
136
  onError: (err, variables, context) => {
@@ -168,13 +179,20 @@ AvroQueryClient.prototype.useCreateDelayEvent = function () {
168
179
  const delayUntil = Math.max(task.delay_until != null && task.delay_until > now
169
180
  ? task.delay_until
170
181
  : 0, now + delayData.delay_seconds);
171
- return {
182
+ if (task.overdue_time == null) {
183
+ return new Task({ ...task, delay_until: delayUntil });
184
+ }
185
+ // `delay` is how far the delay holds the task back,
186
+ // so the snapshot catches up once it lapses.
187
+ const live = getTaskOverdueTime(task, now);
188
+ const held = Math.min(live, now - delayUntil);
189
+ return new Task({
172
190
  ...task,
173
191
  delay_until: delayUntil,
174
- overdue_time: task.overdue_time != null
175
- ? Math.min(task.overdue_time, now - delayUntil)
176
- : task.overdue_time,
177
- };
192
+ delay: live - held,
193
+ overdue_time: held,
194
+ overdue_at: now,
195
+ });
178
196
  }
179
197
  return task;
180
198
  }),
@@ -204,9 +222,11 @@ AvroQueryClient.prototype.useCreateDelayEvent = function () {
204
222
  }
205
223
  return oldData;
206
224
  });
207
- return { previousJob };
225
+ return { previousJob, tempId: optimisticEvent.id };
208
226
  },
209
- onSuccess: () => {
227
+ onSuccess: (_data, _vars, context) => {
228
+ if (context?.tempId)
229
+ removeOptimisticRow(queryClient, 'events', context.tempId);
210
230
  this.syncAfterMutation('event', 'job');
211
231
  },
212
232
  onError: (_err, _variables, context) => {
@@ -270,24 +290,20 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
270
290
  last_completed_event: isEnding && mergedEvent ? mergedEvent : previousJob.last_completed_event,
271
291
  tasks: previousJob.tasks.map((task) => {
272
292
  if (updates.tasks?.includes(task.id ?? '')) {
273
- return {
293
+ return new Task({
274
294
  ...task,
275
295
  current_event: isEnding
276
296
  ? null
277
- : previousEvent
278
- ? { ...previousEvent, ...updates }
279
- : task.current_event,
297
+ : (mergedEvent ?? task.current_event),
280
298
  last_completed_event: isEnding
281
- ? previousEvent
282
- ? { ...previousEvent, ...updates }
283
- : task.last_completed_event
299
+ ? (mergedEvent ?? task.last_completed_event)
284
300
  : task.last_completed_event,
285
301
  // Next due a period out, or when an active
286
302
  // delay ends if that's later.
287
303
  overdue_time: isEnding
288
304
  ? -Math.max(task.frequency ?? 0, (task.delay_until ?? 0) - Date.now() / 1000)
289
305
  : task.overdue_time,
290
- };
306
+ });
291
307
  }
292
308
  return task;
293
309
  }),
@@ -302,16 +318,16 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
302
318
  return old;
303
319
  });
304
320
  }
305
- queryClient.setQueryData(['events', eventId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
321
+ queryClient.setQueryData(['events', eventId], (oldData) => oldData ? constructEvent({ ...oldData, ...updates }) : undefined);
306
322
  queryClient.setQueriesData({ queryKey: ['events'] }, (oldData) => {
307
323
  if (!oldData)
308
324
  return oldData;
309
325
  if (oldData.pages) {
310
- const updatedPages = oldData.pages.map((page) => page.map((event) => event.id === eventId ? { ...event, ...updates } : event));
326
+ const updatedPages = oldData.pages.map((page) => page.map((event) => event.id === eventId ? constructEvent({ ...event, ...updates }) : event));
311
327
  return { ...oldData, pages: updatedPages };
312
328
  }
313
329
  if (Array.isArray(oldData)) {
314
- return oldData.map((event) => event.id === eventId ? { ...event, ...updates } : event);
330
+ return oldData.map((event) => event.id === eventId ? constructEvent({ ...event, ...updates }) : event);
315
331
  }
316
332
  return oldData;
317
333
  });
@@ -358,8 +374,7 @@ AvroQueryClient.prototype.useUpdateEvents = function () {
358
374
  await queryClient.cancelQueries({ queryKey: ['events'] });
359
375
  await queryClient.cancelQueries({ queryKey: ['events'] });
360
376
  const billable = events.filter((event) => event.line_item_type !== 'DELAY');
361
- const previousEvents = queryClient.getQueryData(['events']);
362
- const previousEventObjs = billable.map((event) => queryClient.getQueryData(['events', event.id]));
377
+ const previousEvents = snapshotNs(queryClient, 'events');
363
378
  const eventIds = billable.map((event) => event.id);
364
379
  // Optimistically update individual event cache
365
380
  eventIds.forEach((eventId, idx) => {
@@ -404,20 +419,14 @@ AvroQueryClient.prototype.useUpdateEvents = function () {
404
419
  }
405
420
  return oldData;
406
421
  });
407
- return { previousEvents, previousEventObjs };
422
+ return { previousEvents };
408
423
  },
409
424
  onSuccess: () => {
410
425
  this.syncAfterMutation('event');
411
426
  },
412
427
  onError: (err, variables, context) => {
413
- if (context?.previousEvents) {
414
- queryClient.setQueryData(['events'], context.previousEvents);
415
- }
416
- if (context?.previousEventObjs) {
417
- context.previousEventObjs.forEach((eventObj) => {
418
- queryClient.setQueryData(['events', eventObj.id], eventObj);
419
- });
420
- }
428
+ // The namespace snapshot covers lists and details.
429
+ restoreNs(queryClient, context?.previousEvents);
421
430
  },
422
431
  });
423
432
  };
@@ -433,7 +442,7 @@ AvroQueryClient.prototype.useDeleteEvent = function () {
433
442
  onMutate: async ({ eventId }) => {
434
443
  await queryClient.cancelQueries({ queryKey: ['events'] });
435
444
  await queryClient.cancelQueries({ queryKey: ['events', eventId] });
436
- const previousEvents = queryClient.getQueryData(['events']);
445
+ const previousEvents = snapshotNs(queryClient, 'events');
437
446
  const previousEvent = queryClient.getQueryData(['events', eventId]);
438
447
  queryClient.setQueryData(['events', eventId], undefined);
439
448
  queryClient.setQueriesData({ queryKey: ['events'] }, (oldData) => {
@@ -456,7 +465,7 @@ AvroQueryClient.prototype.useDeleteEvent = function () {
456
465
  onError: (_err, variables, context) => {
457
466
  const { eventId } = variables;
458
467
  if (context?.previousEvents) {
459
- queryClient.setQueryData(['events'], context.previousEvents);
468
+ restoreNs(queryClient, context.previousEvents);
460
469
  }
461
470
  if (context?.previousEvent) {
462
471
  queryClient.setQueryData(['events', eventId], context.previousEvent);
@@ -1,6 +1,7 @@
1
1
  import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { keys } from '../realtime.js';
4
+ import { restoreNs, snapshotNs } from '../cache.js';
4
5
  AvroQueryClient.prototype.useGetGroups = function (body, total, onProgress) {
5
6
  return useQuery({
6
7
  queryKey: keys.list('groups', this.companyId, {
@@ -8,27 +9,15 @@ AvroQueryClient.prototype.useGetGroups = function (body, total, onProgress) {
8
9
  query: body.query ?? '',
9
10
  total: total ?? 'all',
10
11
  }),
12
+ // Embedded in the company payload (no list endpoint): one request
13
+ // returns them all, so `total`/paging is moot.
11
14
  queryFn: async () => {
12
- if (typeof total !== 'number') {
13
- return this.fetchGroups({ ...body, offset: 0 });
14
- }
15
15
  onProgress?.(0);
16
- const pageCount = body.amt ? Math.ceil(total / body.amt) + 1 : 1;
17
- let completed = 0;
18
- const promises = Array.from({ length: pageCount }, (_, i) => this.fetchGroups({
19
- ...body,
20
- offset: i * (body.amt ?? 1),
21
- }));
22
- const trackedPromises = promises.map((promise) => promise.then((result) => {
23
- completed++;
24
- const fraction = completed / pageCount;
25
- onProgress?.(fraction);
26
- return result;
27
- }));
28
- const pages = await Promise.all(trackedPromises);
29
- const groups = pages.flat();
30
- return groups;
16
+ const items = await this.fetchGroups({ query: body.query });
17
+ onProgress?.(1);
18
+ return items;
31
19
  },
20
+ enabled: Boolean(this.companyId),
32
21
  });
33
22
  };
34
23
  AvroQueryClient.prototype.useCreateGroup = function () {
@@ -59,7 +48,7 @@ AvroQueryClient.prototype.useUpdateGroup = function () {
59
48
  onMutate: async ({ groupId, groupData }) => {
60
49
  await queryClient.cancelQueries({ queryKey: ['groups'] });
61
50
  await queryClient.cancelQueries({ queryKey: ['groups', groupId] });
62
- const previousGroups = queryClient.getQueryData(['groups']);
51
+ const previousGroups = snapshotNs(queryClient, 'groups');
63
52
  const previousGroup = queryClient.getQueryData(['groups', groupId]);
64
53
  queryClient.setQueryData(['groups', groupId], (oldData) => {
65
54
  if (!oldData)
@@ -85,9 +74,7 @@ AvroQueryClient.prototype.useUpdateGroup = function () {
85
74
  },
86
75
  onError: (_err, variables, context) => {
87
76
  const { groupId } = variables;
88
- if (context?.previousGroups) {
89
- queryClient.setQueryData(['groups'], context.previousGroups);
90
- }
77
+ restoreNs(queryClient, context?.previousGroups);
91
78
  if (context?.previousGroup) {
92
79
  queryClient.setQueryData(['groups', groupId], context.previousGroup);
93
80
  }
@@ -105,7 +92,7 @@ AvroQueryClient.prototype.useDeleteGroup = function () {
105
92
  onMutate: async ({ groupId }) => {
106
93
  await queryClient.cancelQueries({ queryKey: ['groups'] });
107
94
  await queryClient.cancelQueries({ queryKey: ['groups', groupId] });
108
- const previousGroups = queryClient.getQueryData(['groups']);
95
+ const previousGroups = snapshotNs(queryClient, 'groups');
109
96
  const previousGroup = queryClient.getQueryData(['groups', groupId]);
110
97
  queryClient.setQueryData(['groups', groupId], undefined);
111
98
  queryClient.setQueriesData({ queryKey: ['groups'] }, (oldData) => {
@@ -127,9 +114,7 @@ AvroQueryClient.prototype.useDeleteGroup = function () {
127
114
  },
128
115
  onError: (_err, variables, context) => {
129
116
  const { groupId } = variables;
130
- if (context?.previousGroups) {
131
- queryClient.setQueryData(['groups'], context.previousGroups);
132
- }
117
+ restoreNs(queryClient, context?.previousGroups);
133
118
  if (context?.previousGroup) {
134
119
  queryClient.setQueryData(['groups', groupId], context.previousGroup);
135
120
  }
@@ -1,5 +1,6 @@
1
1
  import { useMutation, useQuery, useInfiniteQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
+ import { seedDetails } from '../cache.js';
3
4
  import { keys, constructJob } from '../realtime.js';
4
5
  import { Job } from '../../types/api.js';
5
6
  AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
@@ -83,16 +84,10 @@ AvroQueryClient.prototype.useGetInfiniteJobs = function (body, onProgress) {
83
84
  ...body,
84
85
  route_id: body.routeId,
85
86
  offset: pageParam,
86
- }).then((jobs) => jobs.map((job) => new Job(job)));
87
+ }).then((jobs) => seedDetails(queryClient, 'jobs', jobs.map((job) => new Job(job))));
87
88
  },
89
+ enabled: Boolean(this.companyId),
88
90
  });
89
- if (result.data) {
90
- result.data.pages.forEach((data_page) => {
91
- data_page.forEach((job) => {
92
- queryClient.setQueryData(['jobs', job.id], job);
93
- });
94
- });
95
- }
96
91
  return result;
97
92
  };
98
93
  AvroQueryClient.prototype.useGetJob = function (jobId) {
@@ -1,6 +1,7 @@
1
1
  import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { keys } from '../realtime.js';
4
+ import { restoreNs, snapshotNs } from '../cache.js';
4
5
  AvroQueryClient.prototype.useGetLabels = function (body, total, onProgress) {
5
6
  return useQuery({
6
7
  queryKey: keys.list('labels', this.companyId, {
@@ -8,27 +9,15 @@ AvroQueryClient.prototype.useGetLabels = function (body, total, onProgress) {
8
9
  query: body.query ?? '',
9
10
  total: total ?? 'all',
10
11
  }),
12
+ // Embedded in the company payload (no list endpoint): one request
13
+ // returns them all, so `total`/paging is moot.
11
14
  queryFn: async () => {
12
- if (typeof total !== 'number') {
13
- return this.fetchLabels({ ...body, offset: 0 });
14
- }
15
15
  onProgress?.(0);
16
- const pageCount = body.amt ? Math.ceil(total / body.amt) + 1 : 1;
17
- let completed = 0;
18
- const promises = Array.from({ length: pageCount }, (_, i) => this.fetchLabels({
19
- ...body,
20
- offset: i * (body.amt ?? 1),
21
- }));
22
- const trackedPromises = promises.map((promise) => promise.then((result) => {
23
- completed++;
24
- const fraction = completed / pageCount;
25
- onProgress?.(fraction);
26
- return result;
27
- }));
28
- const pages = await Promise.all(trackedPromises);
29
- const labels = pages.flat();
30
- return labels;
16
+ const items = await this.fetchLabels({ query: body.query });
17
+ onProgress?.(1);
18
+ return items;
31
19
  },
20
+ enabled: Boolean(this.companyId),
32
21
  });
33
22
  };
34
23
  AvroQueryClient.prototype.useCreateLabel = function () {
@@ -59,7 +48,7 @@ AvroQueryClient.prototype.useUpdateLabel = function () {
59
48
  onMutate: async ({ labelId, labelData }) => {
60
49
  await queryClient.cancelQueries({ queryKey: ['labels'] });
61
50
  await queryClient.cancelQueries({ queryKey: ['labels', labelId] });
62
- const previousLabels = queryClient.getQueryData(['labels']);
51
+ const previousLabels = snapshotNs(queryClient, 'labels');
63
52
  const previousLabel = queryClient.getQueryData(['labels', labelId]);
64
53
  queryClient.setQueryData(['labels', labelId], (oldData) => {
65
54
  if (!oldData)
@@ -85,9 +74,7 @@ AvroQueryClient.prototype.useUpdateLabel = function () {
85
74
  },
86
75
  onError: (_err, variables, context) => {
87
76
  const { labelId } = variables;
88
- if (context?.previousLabels) {
89
- queryClient.setQueryData(['labels'], context.previousLabels);
90
- }
77
+ restoreNs(queryClient, context?.previousLabels);
91
78
  if (context?.previousLabel) {
92
79
  queryClient.setQueryData(['labels', labelId], context.previousLabel);
93
80
  }
@@ -103,7 +90,7 @@ AvroQueryClient.prototype.useDeleteLabel = function () {
103
90
  onMutate: async ({ labelId }) => {
104
91
  await queryClient.cancelQueries({ queryKey: ['labels'] });
105
92
  await queryClient.cancelQueries({ queryKey: ['labels', labelId] });
106
- const previousLabels = queryClient.getQueryData(['labels']);
93
+ const previousLabels = snapshotNs(queryClient, 'labels');
107
94
  const previousLabel = queryClient.getQueryData(['labels', labelId]);
108
95
  queryClient.setQueryData(['labels', labelId], undefined);
109
96
  queryClient.setQueriesData({ queryKey: ['labels'] }, (oldData) => {
@@ -125,9 +112,7 @@ AvroQueryClient.prototype.useDeleteLabel = function () {
125
112
  },
126
113
  onError: (_err, variables, context) => {
127
114
  const { labelId } = variables;
128
- if (context?.previousLabels) {
129
- queryClient.setQueryData(['labels'], context.previousLabels);
130
- }
115
+ restoreNs(queryClient, context?.previousLabels);
131
116
  if (context?.previousLabel) {
132
117
  queryClient.setQueryData(['labels', labelId], context.previousLabel);
133
118
  }
@@ -1,5 +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
4
  import { keys } from '../realtime.js';
4
5
  AvroQueryClient.prototype.useGetMessages = function (chatId, body) {
5
6
  const queryClient = this.getQueryClient();
@@ -19,36 +20,32 @@ AvroQueryClient.prototype.useGetMessages = function (chatId, body) {
19
20
  queryFn: ({ pageParam = 0 }) => this.fetchMessages(chatId, {
20
21
  ...body,
21
22
  offset: pageParam,
22
- }),
23
+ }).then((messages) => seedDetails(queryClient, 'message', messages)),
24
+ enabled: Boolean(chatId),
23
25
  });
24
- if (result.data) {
25
- result.data.pages.forEach((data_page) => {
26
- data_page.forEach((message) => {
27
- queryClient.setQueryData(['message', message.id], message);
28
- });
29
- });
30
- }
31
26
  return result;
32
27
  };
33
28
  AvroQueryClient.prototype.useCreateMessage = function (chatId) {
34
29
  const queryClient = this.getQueryClient();
35
30
  return useMutation({
36
- mutationFn: async ({ content, time_sent, id }) => {
37
- const message = await this.post({
38
- path: `/chat/${chatId}/message`,
39
- data: JSON.stringify({
40
- message: {
41
- content,
42
- time_sent: time_sent ?? Math.floor(Date.now() / 1000),
43
- id,
44
- },
45
- }),
46
- headers: { 'Content-Type': 'application/json' },
47
- });
48
- return message;
49
- },
50
- onSuccess: (message) => {
51
- queryClient.setQueryData(['message', message.id], message);
31
+ // The backend replies `{ msg, id }`, not a full Message, so the
32
+ // reply is never cached as one; the list refetches instead.
33
+ mutationFn: ({ content, time_sent, id }) => this.post({
34
+ path: `/chat/${chatId}/message`,
35
+ data: JSON.stringify({
36
+ message: {
37
+ content,
38
+ time_sent: time_sent ?? Math.floor(Date.now() / 1000),
39
+ id,
40
+ },
41
+ }),
42
+ headers: { 'Content-Type': 'application/json' },
43
+ }),
44
+ onSettled: () => {
45
+ // `new_message` only reaches sockets in the chat room, so the
46
+ // sender can't rely on it to see their own message.
47
+ queryClient.invalidateQueries({ queryKey: ['messages', 'infinite', chatId] });
48
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
52
49
  },
53
50
  });
54
51
  };
@@ -1,18 +1,24 @@
1
1
  import { useInfiniteQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
+ import { restoreNs, seedDetails, snapshotNs } from '../cache.js';
3
4
  import { keys } from '../realtime.js';
4
5
  import { LineItemStatus } from '../../types/api.js';
5
6
  AvroQueryClient.prototype.useGetMonths = function (body) {
6
7
  const queryClient = this.getQueryClient();
8
+ // Status buckets default to the backend's (unbilled only) and are
9
+ // always sent, so the key describes exactly what the server returns.
10
+ const unbilled = body.unbilled ?? true;
11
+ const billed = body.billed ?? false;
12
+ const paid = body.paid ?? false;
7
13
  const result = useInfiniteQuery({
8
14
  queryKey: keys.infinite('months', this.companyId, {
9
15
  amt: body.amt ?? 50,
10
16
  known_ids: body.known_ids ?? [],
11
17
  unknown_ids: body.unknown_ids ?? [],
12
18
  query: body.query ?? '',
13
- unbilled: body.unbilled ?? true,
14
- billed: body.billed ?? true,
15
- paid: body.paid ?? true,
19
+ unbilled,
20
+ billed,
21
+ paid,
16
22
  jobId: body.jobId ?? '',
17
23
  sort_by: body.sort_by ?? null,
18
24
  direction: body.direction ?? null,
@@ -23,16 +29,21 @@ AvroQueryClient.prototype.useGetMonths = function (body) {
23
29
  return undefined;
24
30
  return allPages.flat().length; // next offset
25
31
  },
26
- queryFn: ({ pageParam = 0 }) => this.fetchMonths({ ...body, offset: pageParam }),
27
- enabled: body.enabled ?? true,
32
+ queryFn: ({ pageParam = 0 }) => this.fetchMonths({
33
+ amt: body.amt,
34
+ known_ids: body.known_ids,
35
+ unknown_ids: body.unknown_ids,
36
+ query: body.query,
37
+ unbilled,
38
+ billed,
39
+ paid,
40
+ job_id: body.jobId,
41
+ sort_by: body.sort_by,
42
+ direction: body.direction,
43
+ offset: pageParam,
44
+ }).then((items) => seedDetails(queryClient, 'months', items)),
45
+ enabled: (body.enabled ?? true) && Boolean(this.companyId),
28
46
  });
29
- if (result.data) {
30
- result.data.pages.forEach((data_page) => {
31
- data_page.forEach((month) => {
32
- queryClient.setQueryData(['month', month.id], month);
33
- });
34
- });
35
- }
36
47
  return result;
37
48
  };
38
49
  AvroQueryClient.prototype.useUpdateMonth = function () {
@@ -71,11 +82,10 @@ AvroQueryClient.prototype.useUpdateMonths = function () {
71
82
  onMutate: async ({ months, action }) => {
72
83
  await queryClient.cancelQueries({ queryKey: ['months'] });
73
84
  await queryClient.cancelQueries({ queryKey: ['months'] });
74
- const previousMonths = queryClient.getQueryData(['months']);
75
- const previousMonthObjs = months.map((month) => queryClient.getQueryData(['month', month.id]));
85
+ const previousMonths = snapshotNs(queryClient, 'months');
76
86
  const monthIds = months.map((month) => month.id);
77
87
  monthIds.forEach((monthId, idx) => {
78
- queryClient.setQueryData(['month', monthId], (oldData) => {
88
+ queryClient.setQueryData(['months', monthId], (oldData) => {
79
89
  return oldData
80
90
  ? {
81
91
  ...oldData,
@@ -112,18 +122,14 @@ AvroQueryClient.prototype.useUpdateMonths = function () {
112
122
  }
113
123
  return oldData;
114
124
  });
115
- return { previousMonths, previousMonthObjs };
125
+ return { previousMonths };
116
126
  },
117
127
  onSuccess: () => {
118
128
  queryClient.invalidateQueries({ queryKey: ['months'] });
119
129
  },
120
130
  onError: (err, variables, context) => {
121
- if (context) {
122
- queryClient.setQueryData(['months'], context.previousMonths);
123
- context.previousMonthObjs.forEach((monthObj) => {
124
- queryClient.setQueryData(['month', monthObj.id], monthObj);
125
- });
126
- }
131
+ // The namespace snapshot covers lists and details.
132
+ restoreNs(queryClient, context?.previousMonths);
127
133
  },
128
134
  });
129
135
  };
@@ -1,5 +1,6 @@
1
1
  import { useInfiniteQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
+ import { seedDetails } from '../cache.js';
3
4
  import { keys } from '../realtime.js';
4
5
  AvroQueryClient.prototype.useGetPayouts = function (body) {
5
6
  const queryClient = this.getQueryClient();
@@ -22,14 +23,8 @@ AvroQueryClient.prototype.useGetPayouts = function (body) {
22
23
  return undefined;
23
24
  return allPages.flat().length; // next offset
24
25
  },
25
- queryFn: ({ pageParam = 0 }) => this.fetchPayouts({ ...body, offset: pageParam }),
26
+ queryFn: ({ pageParam = 0 }) => this.fetchPayouts({ ...body, offset: pageParam }).then((payouts) => seedDetails(queryClient, 'payouts', payouts)),
27
+ enabled: Boolean(this.companyId),
26
28
  });
27
- if (result.data) {
28
- result.data.pages.forEach((data_page) => {
29
- data_page.forEach((payout) => {
30
- queryClient.setQueryData(['payouts', payout.id], payout);
31
- });
32
- });
33
- }
34
29
  return result;
35
30
  };