@go-avro/avro-js 1.6.5 → 1.6.6-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 (72) hide show
  1. package/dist/client/QueryClient.d.ts +122 -63
  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/chats.js +33 -1
  10. package/dist/client/hooks/companies.js +38 -4
  11. package/dist/client/hooks/events.js +13 -9
  12. package/dist/client/hooks/jobs.js +29 -3
  13. package/dist/client/hooks/messages.js +6 -2
  14. package/dist/client/hooks/plans.js +1 -1
  15. package/dist/client/hooks/routes.js +55 -5
  16. package/dist/client/hooks/sessions.js +39 -11
  17. package/dist/client/hooks/skills.js +1 -1
  18. package/dist/client/hooks/teams.js +1 -1
  19. package/dist/client/hooks/timecards.js +2 -1
  20. package/dist/client/hooks/users.js +8 -3
  21. package/dist/client/realtime.d.ts +6 -0
  22. package/dist/client/realtime.js +16 -5
  23. package/dist/client/requests.d.ts +470 -0
  24. package/dist/client/requests.js +5 -0
  25. package/dist/client/wire.d.ts +7 -0
  26. package/dist/client/wire.js +14 -0
  27. package/dist/index.d.ts +1 -0
  28. package/dist/types/api/AdditionalCharge.d.ts +2 -1
  29. package/dist/types/api/Avro.d.ts +33 -28
  30. package/dist/types/api/Bill.d.ts +7 -5
  31. package/dist/types/api/BillPayment.d.ts +8 -4
  32. package/dist/types/api/BillUser.d.ts +3 -2
  33. package/dist/types/api/CatalogItem.d.ts +9 -6
  34. package/dist/types/api/Chat.d.ts +3 -5
  35. package/dist/types/api/Company.d.ts +39 -13
  36. package/dist/types/api/DelayEvent.d.ts +5 -2
  37. package/dist/types/api/Device.d.ts +5 -4
  38. package/dist/types/api/Email.d.ts +14 -3
  39. package/dist/types/api/Friendship.d.ts +8 -0
  40. package/dist/types/api/Group.d.ts +3 -2
  41. package/dist/types/api/Job.d.ts +55 -5
  42. package/dist/types/api/LineItem.d.ts +3 -2
  43. package/dist/types/api/MemberState.d.ts +2 -1
  44. package/dist/types/api/Message.d.ts +4 -3
  45. package/dist/types/api/Notification.d.ts +26 -0
  46. package/dist/types/api/PaymentMethod.d.ts +7 -2
  47. package/dist/types/api/PaymentOption.d.ts +6 -4
  48. package/dist/types/api/Payout.d.ts +1 -1
  49. package/dist/types/api/Plan.d.ts +5 -4
  50. package/dist/types/api/PlanPayment.d.ts +5 -3
  51. package/dist/types/api/Prepayment.d.ts +2 -1
  52. package/dist/types/api/Reaction.d.ts +3 -3
  53. package/dist/types/api/Refund.d.ts +1 -1
  54. package/dist/types/api/Route.d.ts +11 -10
  55. package/dist/types/api/Route.js +5 -0
  56. package/dist/types/api/RouteJob.d.ts +1 -1
  57. package/dist/types/api/ServiceMonth.d.ts +2 -2
  58. package/dist/types/api/Session.d.ts +5 -2
  59. package/dist/types/api/Skill.d.ts +2 -2
  60. package/dist/types/api/Subscription.d.ts +5 -3
  61. package/dist/types/api/Task.d.ts +10 -9
  62. package/dist/types/api/Task.js +3 -1
  63. package/dist/types/api/TimecardAction.d.ts +2 -2
  64. package/dist/types/api/User.d.ts +11 -9
  65. package/dist/types/api/UserCompanyAssociation.d.ts +7 -1
  66. package/dist/types/api/UserMerge.d.ts +3 -3
  67. package/dist/types/api/_Event.d.ts +20 -4
  68. package/dist/types/api/_Event.js +1 -0
  69. package/dist/types/api.d.ts +156 -39
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/package.json +1 -1
@@ -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
  };
@@ -2,18 +2,66 @@ 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 { Route } from '../../types/api.js';
5
+ import { Route, RouteJob, } from '../../types/api.js';
6
+ const stopTaskId = (task) => (typeof task === 'string' ? task : task.id);
6
7
  const dedupeJobTasks = (payload) => payload.jobs
7
8
  ? {
8
9
  ...payload,
9
10
  jobs: payload.jobs.map((job) => job.tasks
10
11
  ? {
11
12
  ...job,
12
- tasks: job.tasks.filter((task, index, all) => all.findIndex((t) => t.id === task.id) === index),
13
+ tasks: job.tasks.filter((task, index, all) => all.findIndex((t) => stopTaskId(t) === stopTaskId(task)) ===
14
+ index),
13
15
  }
14
16
  : job),
15
17
  }
16
18
  : payload;
19
+ /** The cached-`Route` view of a write: stops become `RouteJob` rows. */
20
+ const toCachedRoute = (routeId, { optimize: _optimize, jobs, ...rest }) => ({
21
+ ...rest,
22
+ ...(jobs && {
23
+ jobs: jobs.map((stop, order) => new RouteJob({
24
+ job_id: stop.job_id,
25
+ route_id: routeId,
26
+ order,
27
+ scheduled_arrival_time: stop.scheduled_arrival_time ?? -1,
28
+ estimated_arrival_time: stop.estimated_arrival_time ?? -1,
29
+ tasks: (stop.tasks ?? []).map((task) => typeof task === 'string'
30
+ ? { id: task, depends_on: [] }
31
+ : { id: task.id, depends_on: task.depends_on ?? [] }),
32
+ })),
33
+ }),
34
+ });
35
+ /**
36
+ * Drop `''` task ids from a schedule request: `ScheduleRoutes` types every
37
+ * task id as a UUID, so one blank id (e.g. an unsaved task) would 400 the
38
+ * whole request instead of being skipped.
39
+ */
40
+ const withoutBlankTaskIds = (schedule) => {
41
+ const ids = (list) => list?.filter((id) => id !== '');
42
+ return {
43
+ ...schedule,
44
+ ...(schedule.whitelist && { whitelist: ids(schedule.whitelist) }),
45
+ ...(schedule.blacklist && { blacklist: ids(schedule.blacklist) }),
46
+ ...(schedule.tasks && {
47
+ tasks: schedule.tasks
48
+ .filter((entry) => (typeof entry === 'string' ? entry : entry.task) !== '')
49
+ .map((entry) => typeof entry === 'string'
50
+ ? entry
51
+ : { ...entry, depends_on: ids(entry.depends_on) }),
52
+ }),
53
+ ...(schedule.schedules && {
54
+ schedules: schedule.schedules.map((team) => team.schedule
55
+ ? {
56
+ ...team,
57
+ schedule: team.schedule.map((stop) => stop.type === 'job'
58
+ ? { ...stop, task_ids: ids(stop.task_ids) ?? [] }
59
+ : stop),
60
+ }
61
+ : team),
62
+ }),
63
+ };
64
+ };
17
65
  AvroQueryClient.prototype.useGetRoutes = function (body, total, onProgress) {
18
66
  return useQuery({
19
67
  queryKey: keys.list('routes', this.companyId, {
@@ -67,7 +115,8 @@ AvroQueryClient.prototype.useCreateRoute = function () {
67
115
  headers: { 'Content-Type': 'application/json' },
68
116
  });
69
117
  },
70
- onMutate: async ({ routeData: { optimize: _optimize, ...routeData } }) => {
118
+ onMutate: async ({ routeData: wireRouteData }) => {
119
+ const routeData = toCachedRoute('temp-id', wireRouteData);
71
120
  await queryClient.cancelQueries({ queryKey: ['routes'] });
72
121
  const previousRoutes = snapshotNs(queryClient, 'routes');
73
122
  queryClient.setQueriesData({ queryKey: ['routes'] }, (oldData) => {
@@ -128,7 +177,7 @@ AvroQueryClient.prototype.useScheduleRoutes = function () {
128
177
  mutationFn: async ({ schedule }) => {
129
178
  return this.post({
130
179
  path: `/company/${this.companyId}/schedule`,
131
- data: JSON.stringify(schedule),
180
+ data: JSON.stringify(withoutBlankTaskIds(schedule)),
132
181
  headers: { 'Content-Type': 'application/json' },
133
182
  });
134
183
  },
@@ -150,7 +199,8 @@ AvroQueryClient.prototype.useUpdateRoute = function () {
150
199
  headers: { 'Content-Type': 'application/json' },
151
200
  });
152
201
  },
153
- onMutate: async ({ routeId, updates: { optimize: _optimize, ...updates } }) => {
202
+ onMutate: async ({ routeId, updates: wireUpdates }) => {
203
+ const updates = toCachedRoute(routeId, wireUpdates);
154
204
  await queryClient.cancelQueries({ queryKey: ['routes', routeId] });
155
205
  await queryClient.cancelQueries({ queryKey: ['routes'] });
156
206
  const previousRoute = queryClient.getQueryData(['routes', routeId]);
@@ -1,8 +1,9 @@
1
1
  import { useMutation, useQuery, useInfiniteQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
- import { keys, isListKey } from '../realtime.js';
3
+ import { keys, isListKey, VIEWER_SCOPE } from '../realtime.js';
4
4
  import { removeOptimisticRow, seedDetails } from '../cache.js';
5
5
  import { Session } from '../../types/api.js';
6
+ import { withoutEmpty } from '../wire.js';
6
7
  const NS = 'sessions';
7
8
  function listFilters(body) {
8
9
  return {
@@ -56,7 +57,7 @@ AvroQueryClient.prototype.useGetSessions = function (body = {}) {
56
57
  AvroQueryClient.prototype.useGetUserSessions = function () {
57
58
  const queryClient = this.getQueryClient();
58
59
  const result = useQuery({
59
- queryKey: keys.list(NS, 'mine', { active: true }),
60
+ queryKey: keys.list(NS, VIEWER_SCOPE, { active: true }),
60
61
  queryFn: () => this.get({ path: '/session' }).then((sessions) => seedDetails(queryClient, NS, (Array.isArray(sessions) ? sessions : []).map((s) => new Session(s)))),
61
62
  enabled: Boolean(this.companyId),
62
63
  });
@@ -89,13 +90,36 @@ AvroQueryClient.prototype.useGetActiveCompanySessions = function (params = {}) {
89
90
  // Optimistic patch on every cached sessions list; the echoed `changes`
90
91
  // batch settles the cache when the socket is up, else syncAfterMutation
91
92
  // falls back to a refetch.
93
+ /**
94
+ * Session id fields the backend types as UUIDs (`StartSession` /
95
+ * `UpdateSession`); `''` is omitted rather than sent.
96
+ */
97
+ const SESSION_ID_FIELDS = ['team_id', 'route_id', 'current_route_id', 'user_id'];
98
+ /**
99
+ * The cached-`Session` view of a write: `time_ended: true` means "now",
100
+ * and `route_id` / `current_route_id` are the same column.
101
+ */
102
+ function toCachedSession({ user_id, time_ended, team_id, route_id, current_route_id, ...rest }) {
103
+ // `''` ids are omitted on the wire (unchanged), so they change nothing here.
104
+ const route = route_id !== undefined ? route_id : current_route_id;
105
+ return {
106
+ ...rest,
107
+ ...(user_id && { user_id }),
108
+ ...(time_ended !== undefined && {
109
+ time_ended: time_ended === true ? Math.floor(Date.now() / 1000) : time_ended,
110
+ }),
111
+ ...(team_id !== undefined && team_id !== '' && { team_id }),
112
+ ...(route !== undefined && route !== '' && { route_id: route, current_route_id: route }),
113
+ };
114
+ }
92
115
  AvroQueryClient.prototype.useCreateUserSession = function () {
93
116
  const queryClient = this.getQueryClient();
94
117
  return useMutation({
95
118
  mutationFn: ({ sessionData }) => {
119
+ // `id` is null only when an already-open session closed mid-request.
96
120
  return this.post({
97
121
  path: `/company/${this.companyId}/session`,
98
- data: JSON.stringify(sessionData),
122
+ data: JSON.stringify(withoutEmpty(sessionData, ...SESSION_ID_FIELDS)),
99
123
  headers: { 'Content-Type': 'application/json' },
100
124
  });
101
125
  },
@@ -103,7 +127,7 @@ AvroQueryClient.prototype.useCreateUserSession = function () {
103
127
  await queryClient.cancelQueries({ queryKey: [NS] });
104
128
  const previous = snapshotSessionLists(queryClient);
105
129
  const optimistic = new Session({
106
- ...sessionData,
130
+ ...toCachedSession(sessionData),
107
131
  id: `optimistic-${Math.random().toString(36).slice(2, 11)}`,
108
132
  company_id: this.companyId,
109
133
  });
@@ -164,10 +188,10 @@ AvroQueryClient.prototype.useCreateSessionBreak = function () {
164
188
  AvroQueryClient.prototype.useUpdateUserSession = function () {
165
189
  const queryClient = this.getQueryClient();
166
190
  return useMutation({
167
- mutationFn: ({ sessionId, updates }) => {
191
+ mutationFn: ({ sessionId, updates, }) => {
168
192
  return this.put({
169
193
  path: `/session/${sessionId}`,
170
- data: JSON.stringify(updates),
194
+ data: JSON.stringify(withoutEmpty(updates, ...SESSION_ID_FIELDS)),
171
195
  headers: { 'Content-Type': 'application/json' },
172
196
  });
173
197
  },
@@ -175,8 +199,10 @@ AvroQueryClient.prototype.useUpdateUserSession = function () {
175
199
  await queryClient.cancelQueries({ queryKey: [NS] });
176
200
  const previous = snapshotSessionLists(queryClient);
177
201
  const previousDetail = queryClient.getQueryData(keys.detail(NS, sessionId));
178
- patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
179
- queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...updates }) : old);
202
+ patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId
203
+ ? new Session({ ...session, ...toCachedSession(updates) })
204
+ : session));
205
+ queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...toCachedSession(updates) }) : old);
180
206
  return { previous, previousDetail };
181
207
  },
182
208
  onError: (_err, { sessionId }, context) => {
@@ -225,7 +251,7 @@ AvroQueryClient.prototype.useUpdateCompanySession = function () {
225
251
  mutationFn: ({ sessionId, updates, companyId, }) => {
226
252
  return this.put({
227
253
  path: `/company/${companyId ?? this.companyId}/session/${sessionId}`,
228
- data: JSON.stringify(updates),
254
+ data: JSON.stringify(withoutEmpty(updates, ...SESSION_ID_FIELDS)),
229
255
  headers: { 'Content-Type': 'application/json' },
230
256
  });
231
257
  },
@@ -233,8 +259,10 @@ AvroQueryClient.prototype.useUpdateCompanySession = function () {
233
259
  await queryClient.cancelQueries({ queryKey: [NS] });
234
260
  const previous = snapshotSessionLists(queryClient);
235
261
  const previousDetail = queryClient.getQueryData(keys.detail(NS, sessionId));
236
- patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
237
- queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...updates }) : old);
262
+ patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId
263
+ ? new Session({ ...session, ...toCachedSession(updates) })
264
+ : session));
265
+ queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...toCachedSession(updates) }) : old);
238
266
  return { previous, previousDetail };
239
267
  },
240
268
  onError: (_err, { sessionId }, context) => {
@@ -51,7 +51,7 @@ AvroQueryClient.prototype.useGetSkills = function (body, total, onProgress) {
51
51
  AvroQueryClient.prototype.useUpdateSkill = function () {
52
52
  const queryClient = this.getQueryClient();
53
53
  return useMutation({
54
- mutationFn: async ({ skillId, updates }) => {
54
+ mutationFn: async ({ skillId, updates, }) => {
55
55
  return this.put({
56
56
  path: `/skill/${skillId}`,
57
57
  data: JSON.stringify(updates),
@@ -51,7 +51,7 @@ AvroQueryClient.prototype.useCreateTeam = function () {
51
51
  AvroQueryClient.prototype.useUpdateTeam = function () {
52
52
  const queryClient = this.getQueryClient();
53
53
  return useMutation({
54
- mutationFn: async ({ teamId, teamData }) => {
54
+ mutationFn: async ({ teamId, teamData, }) => {
55
55
  return this.put({
56
56
  path: `/team/${teamId}`,
57
57
  data: JSON.stringify(teamData),
@@ -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 { withoutEmpty } from '../wire.js';
4
5
  AvroQueryClient.prototype.useGetCompanyTimecards = function (params = {}) {
5
6
  const companyId = params.companyId ?? this.companyId;
6
7
  return useQuery({
@@ -48,7 +49,7 @@ AvroQueryClient.prototype.useCreateTimecard = function () {
48
49
  const targetCompanyId = companyId ?? this.companyId;
49
50
  return this.post({
50
51
  path: `/company/${targetCompanyId}/timecard`,
51
- data: JSON.stringify(data),
52
+ data: JSON.stringify(withoutEmpty(data, 'user_company_id')),
52
53
  headers: { 'Content-Type': 'application/json' },
53
54
  });
54
55
  },
@@ -108,7 +108,11 @@ AvroQueryClient.prototype.useUpdateUser = function (userId) {
108
108
  headers: { 'Content-Type': 'application/json' },
109
109
  });
110
110
  },
111
- onMutate: async (data) => {
111
+ onMutate: async (wireData) => {
112
+ // Credentials and the payment-method refs are request-only;
113
+ // keep them out of the cache (the echoed change brings the
114
+ // real payment methods).
115
+ const { password: _password, current_password: _currentPassword, apple_token: _appleToken, apple_nonce: _appleNonce, payment_methods: _paymentMethods, ...data } = wireData;
112
116
  await queryClient.cancelQueries({ queryKey: ['user'] });
113
117
  await queryClient.cancelQueries({ queryKey: ['users', userId] });
114
118
  const previousSelf = queryClient.getQueryData(['user']);
@@ -144,7 +148,7 @@ AvroQueryClient.prototype.useUpdateUser = function (userId) {
144
148
  AvroQueryClient.prototype.useUpdateUserCompany = function () {
145
149
  const queryClient = this.getQueryClient();
146
150
  return useMutation({
147
- mutationFn: async ({ user_id, data, }) => {
151
+ mutationFn: async ({ user_id, data }) => {
148
152
  return this.put({
149
153
  path: `/company/${this.companyId}/user/${user_id}`,
150
154
  data: JSON.stringify(data),
@@ -213,7 +217,8 @@ AvroQueryClient.prototype.useGetCompanyUsers = function (body = {}) {
213
217
  queryKey: ['users', 'company', this.companyId, body.query ?? '', body.user_ids ?? null],
214
218
  queryFn: () => this.post({
215
219
  path: `/company/${this.companyId}/users`,
216
- data: JSON.stringify(body),
220
+ // `enabled` is a hook option, not a `ListCompanyUsers` field.
221
+ data: JSON.stringify({ query: body.query, user_ids: body.user_ids }),
217
222
  headers: { 'Content-Type': 'application/json' },
218
223
  }),
219
224
  enabled: Boolean(this.companyId) && (body.enabled ?? true),
@@ -16,6 +16,12 @@ export declare const keys: {
16
16
  export declare function isListKey(key: readonly unknown[]): boolean;
17
17
  export declare function isDetailKey(key: readonly unknown[]): boolean;
18
18
  export declare function listFilters(key: readonly unknown[]): Filters;
19
+ /**
20
+ * List scope for viewer-scoped lists (e.g. the caller's own open sessions
21
+ * across companies). Not a company id: change batches for any company may
22
+ * touch it, so they're never skipped by the company check.
23
+ */
24
+ export declare const VIEWER_SCOPE = "mine";
19
25
  export declare function listScope(key: readonly unknown[]): string;
20
26
  export type ChangeOp = 'create' | 'update' | 'delete' | 'invalidate';
21
27
  export interface ChangeEntry {
@@ -20,6 +20,12 @@ export function listFilters(key) {
20
20
  const f = key[3];
21
21
  return f && typeof f === 'object' ? f : {};
22
22
  }
23
+ /**
24
+ * List scope for viewer-scoped lists (e.g. the caller's own open sessions
25
+ * across companies). Not a company id: change batches for any company may
26
+ * touch it, so they're never skipped by the company check.
27
+ */
28
+ export const VIEWER_SCOPE = 'mine';
23
29
  export function listScope(key) {
24
30
  return typeof key[2] === 'string' ? key[2] : '';
25
31
  }
@@ -45,13 +51,13 @@ export function constructJob(raw) {
45
51
  const job = new Job(raw);
46
52
  job.current_event = job.tasks.reduce((latest, task) => {
47
53
  return task.current_event &&
48
- (!latest || task.current_event.time_started > latest.time_started)
54
+ (!latest || (task.current_event.time_started ?? 0) > (latest.time_started ?? 0))
49
55
  ? task.current_event
50
56
  : latest;
51
57
  }, job.current_event);
52
58
  job.last_completed_event = job.tasks.reduce((latest, task) => {
53
59
  return task.last_completed_event &&
54
- (!latest || task.last_completed_event.time_started > latest.time_started)
60
+ (!latest || (task.last_completed_event.time_started ?? 0) > (latest.time_started ?? 0))
55
61
  ? task.last_completed_event
56
62
  : latest;
57
63
  }, job.last_completed_event);
@@ -126,7 +132,7 @@ function matchBills(filters, item) {
126
132
  }
127
133
  function matchSessions(filters, item, scope) {
128
134
  // "mine" comes from GET /session (viewer-scoped): can't tell ownership here.
129
- if (scope === 'mine')
135
+ if (scope === VIEWER_SCOPE)
130
136
  return 'unknown';
131
137
  // `unknown_ids` on the sessions endpoint means "fetch exactly these".
132
138
  const wanted = filters.unknown_ids;
@@ -176,7 +182,12 @@ function matchPayouts(filters, item) {
176
182
  return 'unknown';
177
183
  return searchAware(filters);
178
184
  }
179
- const bulk = (method, extra = {}) => (client, ids) => client[method]({ ...extra, unknown_ids: ids, amt: ids.length });
185
+ const bulk = (method, extra = {}) => (client, ids) =>
186
+ // List endpoints reject `amt: 0` (payouts/months require amt >= 1),
187
+ // and an empty `unknown_ids` would mean "no id filter" anyway.
188
+ ids.length === 0
189
+ ? Promise.resolve([])
190
+ : client[method]({ ...extra, unknown_ids: ids, amt: ids.length });
180
191
  /** Line-item list endpoints default to unbilled-only: ask for every bucket. */
181
192
  const ALL_LINE_ITEM_STATUSES = { unbilled: true, billed: true, paid: true };
182
193
  /** Single-entity GET (404/403 is treated as gone by the applier). */
@@ -328,7 +339,7 @@ export function upsertEntity(qc, spec, item, company) {
328
339
  for (const query of lists) {
329
340
  const key = query.queryKey;
330
341
  const scope = listScope(key);
331
- if (company && scope && scope !== company)
342
+ if (company && scope && scope !== company && scope !== VIEWER_SCOPE)
332
343
  continue;
333
344
  const verdict = spec.listMatch
334
345
  ? spec.listMatch(listFilters(key), item, listScope(key))