@go-avro/avro-js 1.6.5 → 1.6.6-rc10

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 (73) hide show
  1. package/dist/client/QueryClient.d.ts +150 -60
  2. package/dist/client/QueryClient.js +175 -27
  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 +19 -2
  6. package/dist/client/hooks/bills.d.ts +1 -1
  7. package/dist/client/hooks/bills.js +54 -16
  8. package/dist/client/hooks/catalog_items.js +20 -5
  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 +5 -2
  19. package/dist/client/hooks/timecards.js +2 -1
  20. package/dist/client/hooks/users.js +21 -3
  21. package/dist/client/realtime.d.ts +13 -0
  22. package/dist/client/realtime.js +41 -8
  23. package/dist/client/requests.d.ts +503 -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 +72 -21
  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 +11 -6
  34. package/dist/types/api/Chat.d.ts +3 -5
  35. package/dist/types/api/Company.d.ts +41 -15
  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/Proposal.d.ts +1 -1
  53. package/dist/types/api/Reaction.d.ts +3 -3
  54. package/dist/types/api/Refund.d.ts +1 -1
  55. package/dist/types/api/Route.d.ts +11 -10
  56. package/dist/types/api/Route.js +5 -0
  57. package/dist/types/api/RouteJob.d.ts +1 -1
  58. package/dist/types/api/ServiceMonth.d.ts +2 -2
  59. package/dist/types/api/Session.d.ts +5 -2
  60. package/dist/types/api/Skill.d.ts +2 -2
  61. package/dist/types/api/Subscription.d.ts +5 -3
  62. package/dist/types/api/Task.d.ts +10 -9
  63. package/dist/types/api/Task.js +3 -1
  64. package/dist/types/api/TimecardAction.d.ts +2 -2
  65. package/dist/types/api/User.d.ts +11 -9
  66. package/dist/types/api/UserCompanyAssociation.d.ts +7 -1
  67. package/dist/types/api/UserMerge.d.ts +3 -3
  68. package/dist/types/api/_Event.d.ts +20 -4
  69. package/dist/types/api/_Event.js +1 -0
  70. package/dist/types/api.d.ts +156 -39
  71. package/dist/version.d.ts +1 -1
  72. package/dist/version.js +1 -1
  73. package/package.json +1 -1
@@ -2,6 +2,20 @@ import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { StandardError } from '../../types/error.js';
4
4
  import { AuthState } from '../../types/auth.js';
5
+ /**
6
+ * The cached-`Company` view of an update: the company reports unset
7
+ * mailbox / plan links as `''`, and `payment_methods` / `logo` are
8
+ * request-only shapes the echoed change replaces.
9
+ */
10
+ function toCachedCompany(data) {
11
+ const { payment_methods: _paymentMethods, logo: _logo, service_email_id, billing_email_id, plan_id, ...rest } = data;
12
+ return {
13
+ ...rest,
14
+ ...(service_email_id !== undefined && { service_email_id: service_email_id ?? '' }),
15
+ ...(billing_email_id !== undefined && { billing_email_id: billing_email_id ?? '' }),
16
+ ...(plan_id !== undefined && { plan_id: plan_id ?? '' }),
17
+ };
18
+ }
5
19
  AvroQueryClient.prototype.useGetCompanies = function (options = {}) {
6
20
  return useQuery({
7
21
  queryKey: ['/company/list'],
@@ -68,7 +82,7 @@ AvroQueryClient.prototype.useGetCurrentCompany = function () {
68
82
  AvroQueryClient.prototype.useCreateCompany = function () {
69
83
  const queryClient = this.getQueryClient();
70
84
  return useMutation({
71
- mutationFn: async ({ companyData, }) => {
85
+ mutationFn: async ({ companyData }) => {
72
86
  return this.post({
73
87
  path: `/company`,
74
88
  data: JSON.stringify(companyData),
@@ -97,11 +111,13 @@ AvroQueryClient.prototype.useUpdateCompany = function () {
97
111
  await queryClient.cancelQueries({ queryKey: ['/company/list'] });
98
112
  const previousCompany = queryClient.getQueryData(['companies', companyId]);
99
113
  const previousCompanyList = queryClient.getQueryData(['/company/list']);
100
- queryClient.setQueryData(['companies', companyId], (oldData) => oldData ? { ...oldData, ...companyData } : undefined);
114
+ queryClient.setQueryData(['companies', companyId], (oldData) => oldData ? { ...oldData, ...toCachedCompany(companyData) } : undefined);
101
115
  queryClient.setQueryData(['/company/list'], (oldList) => {
102
116
  if (!oldList)
103
117
  return oldList;
104
- return oldList.map((company) => company?.id === companyId ? { ...company, ...companyData } : company);
118
+ // The list only carries {id, name, plan_id, balance}.
119
+ const { name } = companyData;
120
+ return oldList.map((company) => company?.id === companyId && name ? { ...company, name } : company);
105
121
  });
106
122
  return { previousCompany, previousCompanyList };
107
123
  },
@@ -122,7 +138,7 @@ AvroQueryClient.prototype.useUpdateCompany = function () {
122
138
  AvroQueryClient.prototype.useCreateUserCompany = function () {
123
139
  const queryClient = this.getQueryClient();
124
140
  return useMutation({
125
- mutationFn: async ({ user_id, data, }) => {
141
+ mutationFn: async ({ user_id, data }) => {
126
142
  if (!user_id) {
127
143
  throw new Error('Both userId and companyId are required');
128
144
  }
@@ -151,6 +167,24 @@ AvroQueryClient.prototype.useCreateUserCompany = function () {
151
167
  },
152
168
  });
153
169
  };
170
+ /**
171
+ * Add an existing user to a company (the current one by default), optionally
172
+ * straight into a group such as a user type, in a single request.
173
+ */
174
+ AvroQueryClient.prototype.useAddUserCompany = function () {
175
+ return useMutation({
176
+ mutationFn: async ({ userId, groupId, companyId, }) => {
177
+ return this.post({
178
+ path: `/company/${companyId ?? this.companyId}/user/${userId}`,
179
+ data: JSON.stringify({ user_id: userId, ...(groupId ? { group: groupId } : {}) }),
180
+ headers: { 'Content-Type': 'application/json' },
181
+ });
182
+ },
183
+ onSuccess: () => {
184
+ this.syncAfterMutation('member', 'company', 'group');
185
+ },
186
+ });
187
+ };
154
188
  AvroQueryClient.prototype.useRemoveUserCompany = function () {
155
189
  const queryClient = this.getQueryClient();
156
190
  return useMutation({
@@ -2,6 +2,7 @@ import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs, seedDetails, removeOptimisticRow } from '../cache.js';
4
4
  import { keys, matchesList } from '../realtime.js';
5
+ import { withoutEmpty } from '../wire.js';
5
6
  import { constructEvent, DelayEvent, Job, LineItemStatus, Task, getTaskOverdueTime, } from '../../types/api.js';
6
7
  const isJobsQuery = (q) => q.queryKey[0] === 'jobs';
7
8
  const isEventsQuery = (q) => q.queryKey[0] === 'events';
@@ -64,11 +65,15 @@ AvroQueryClient.prototype.useCreateEvent = function () {
64
65
  mutationFn: ({ eventData }) => {
65
66
  return this.post({
66
67
  path: `/company/${this.companyId}/event`,
67
- data: JSON.stringify(eventData),
68
+ // `team_id` is a UUID: '' (no team picked) is omitted.
69
+ data: JSON.stringify(withoutEmpty(eventData, 'team_id')),
68
70
  headers: { 'Content-Type': 'application/json' },
69
71
  });
70
72
  },
71
- onMutate: async ({ eventData }) => {
73
+ onMutate: async ({ eventData: wireEventData }) => {
74
+ // Wire-shaped participants and charges must not land in the
75
+ // cached _Event's UserEvent / AdditionalCharge rows.
76
+ const { users: _wireUsers, additional_charges: _wireCharges, ...eventData } = wireEventData;
72
77
  await queryClient.cancelQueries({ queryKey: ['events'] });
73
78
  const previousJob = queryClient.getQueryData([
74
79
  'jobs',
@@ -77,7 +82,6 @@ AvroQueryClient.prototype.useCreateEvent = function () {
77
82
  const optimisticEvent = constructEvent({
78
83
  ...eventData,
79
84
  id: Math.random().toString(36).substring(2, 11),
80
- company_id: this.companyId,
81
85
  });
82
86
  if (previousJob) {
83
87
  const updatedJob = new Job({
@@ -159,7 +163,6 @@ AvroQueryClient.prototype.useCreateDelayEvent = function () {
159
163
  const optimisticEvent = new DelayEvent({
160
164
  ...delayData,
161
165
  id: Math.random().toString(36).substring(2, 11),
162
- company_id: this.companyId,
163
166
  time_started: now,
164
167
  time_ended: now,
165
168
  cost: 0,
@@ -244,15 +247,16 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
244
247
  mutationFn: ({ eventId, updates }) => {
245
248
  return this.put({
246
249
  path: `/event/${eventId}`,
247
- data: JSON.stringify(updates),
250
+ data: JSON.stringify(withoutEmpty(updates, 'team_id')),
248
251
  headers: { 'Content-Type': 'application/json' },
249
252
  });
250
253
  },
251
254
  onMutate: async ({ eventId, updates: wireUpdates }) => {
252
- // The wire `users` shape ({user_id, time_*}) must not land in
253
- // cached _Event.users (UserEvent rows) — exclude it from the
254
- // optimistic merge; invalidation on settle refreshes real rows.
255
- const { users: _wireUsers, ...updates } = wireUpdates;
255
+ // The wire `users` ({user_id, time_*}) and `additional_charges`
256
+ // shapes must not land in cached _Event.users / charges rows —
257
+ // exclude them from the optimistic merge; the echoed change
258
+ // refreshes the real rows.
259
+ const { users: _wireUsers, additional_charges: _wireCharges, ...updates } = wireUpdates;
256
260
  await queryClient.cancelQueries({ queryKey: ['events', eventId] });
257
261
  await queryClient.cancelQueries({ queryKey: ['events'] });
258
262
  // Try individual cache first; fall back to scanning all active events queries
@@ -3,6 +3,7 @@ import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { seedDetails } from '../cache.js';
4
4
  import { keys, constructJob } from '../realtime.js';
5
5
  import { Job } from '../../types/api.js';
6
+ import { withoutEmpty } from '../wire.js';
6
7
  AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
7
8
  const client = queryClient ?? this.peekQueryClient();
8
9
  if (!client) {
@@ -10,6 +11,31 @@ AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
10
11
  }
11
12
  return client.getQueryData(keys.list('jobs', this.companyId)) ?? [];
12
13
  };
14
+ /**
15
+ * Shape a job write for the wire. `UpdateJob`/`ManagedJob` type the job,
16
+ * task, prepayment, owner and catalog item ids as UUIDs, so a blank (`''`)
17
+ * id would be a 400: it is omitted (for `id`s that means "new row"; for
18
+ * `owner_id` / `catalog_item_id` it means "unchanged" — send `null` to
19
+ * clear them). Everything else, explicit nulls included, is sent as given:
20
+ * a null is an intentional clear.
21
+ */
22
+ function toJobWire(job) {
23
+ const wire = withoutEmpty(job, 'id', 'owner_id');
24
+ if (!wire.tasks)
25
+ return wire;
26
+ return {
27
+ ...wire,
28
+ tasks: wire.tasks.map((task) => {
29
+ const wireTask = withoutEmpty(task, 'id', 'catalog_item_id');
30
+ return wireTask.prepayments
31
+ ? {
32
+ ...wireTask,
33
+ prepayments: wireTask.prepayments.map((p) => withoutEmpty(p, 'id')),
34
+ }
35
+ : wireTask;
36
+ }),
37
+ };
38
+ }
13
39
  const JOBS_SYNC_CHUNK = 50;
14
40
  const JOBS_SYNC_CONCURRENCY = 3;
15
41
  async function runLimited(items, limit, worker) {
@@ -108,7 +134,7 @@ AvroQueryClient.prototype.useCreateJob = function () {
108
134
  mutationFn: ({ jobData }) => {
109
135
  return this.post({
110
136
  path: `/company/${this.companyId}/job`,
111
- data: JSON.stringify(jobData),
137
+ data: JSON.stringify(toJobWire(jobData)),
112
138
  headers: { 'Content-Type': 'application/json' },
113
139
  });
114
140
  },
@@ -123,7 +149,7 @@ AvroQueryClient.prototype.useManageJobs = function () {
123
149
  mutationFn: ({ jobs }) => {
124
150
  return this.post({
125
151
  path: `/company/${this.companyId}/jobs/manage`,
126
- data: JSON.stringify({ jobs }),
152
+ data: JSON.stringify({ jobs: jobs.map(toJobWire) }),
127
153
  headers: { 'Content-Type': 'application/json' },
128
154
  });
129
155
  },
@@ -138,7 +164,7 @@ AvroQueryClient.prototype.useUpdateJob = function () {
138
164
  mutationFn: ({ jobId, updates }) => {
139
165
  return this.put({
140
166
  path: `/job/${jobId}`,
141
- data: JSON.stringify(updates),
167
+ data: JSON.stringify(toJobWire(updates)),
142
168
  headers: { 'Content-Type': 'application/json' },
143
169
  });
144
170
  },
@@ -4,21 +4,25 @@ import { seedDetails } from '../cache.js';
4
4
  import { keys } from '../realtime.js';
5
5
  AvroQueryClient.prototype.useGetMessages = function (chatId, body) {
6
6
  const queryClient = this.getQueryClient();
7
+ // The backend pages messages 1..100 at a time (default 10); send the
8
+ // page size explicitly so `getNextPageParam` compares against it.
9
+ const amt = Math.min(Math.max(body.amt ?? 50, 1), 100);
7
10
  const result = useInfiniteQuery({
8
11
  queryKey: keys.infinite('messages', chatId, {
9
- amt: body.amt ?? 50,
12
+ amt,
10
13
  known_ids: body.known_ids ?? [],
11
14
  unknown_ids: body.unknown_ids ?? [],
12
15
  query: body.query ?? '',
13
16
  }),
14
17
  initialPageParam: 0,
15
18
  getNextPageParam: (lastPage, allPages) => {
16
- if (lastPage.length < (body.amt ?? 50))
19
+ if (lastPage.length < amt)
17
20
  return undefined;
18
21
  return allPages.flat().length; // next offset
19
22
  },
20
23
  queryFn: ({ pageParam = 0 }) => this.fetchMessages(chatId, {
21
24
  ...body,
25
+ amt,
22
26
  offset: pageParam,
23
27
  }).then((messages) => seedDetails(queryClient, 'message', messages)),
24
28
  enabled: Boolean(chatId),
@@ -3,6 +3,6 @@ import { AvroQueryClient } from '../QueryClient.js';
3
3
  AvroQueryClient.prototype.useGetPlans = function (code) {
4
4
  return useQuery({
5
5
  queryKey: ['plans', code],
6
- queryFn: async () => this.get({ path: `/plans${code ? `?code=${code}` : ''}` }),
6
+ queryFn: async () => this.get({ path: `/plans${code ? `?code=${encodeURIComponent(code)}` : ''}` }),
7
7
  });
8
8
  };
@@ -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),
@@ -2,7 +2,10 @@ 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,
@@ -30,7 +33,7 @@ AvroQueryClient.prototype.useGetTeams = function (body, total, onProgress) {
30
33
  const teams = pages.flat();
31
34
  return teams;
32
35
  },
33
- enabled: Boolean(this.companyId),
36
+ enabled: Boolean(this.companyId) && canReadTeams !== false,
34
37
  });
35
38
  };
36
39
  AvroQueryClient.prototype.useCreateTeam = function () {
@@ -51,7 +54,7 @@ AvroQueryClient.prototype.useCreateTeam = function () {
51
54
  AvroQueryClient.prototype.useUpdateTeam = function () {
52
55
  const queryClient = this.getQueryClient();
53
56
  return useMutation({
54
- mutationFn: async ({ teamId, teamData }) => {
57
+ mutationFn: async ({ teamId, teamData, }) => {
55
58
  return this.put({
56
59
  path: `/team/${teamId}`,
57
60
  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),
@@ -223,3 +228,16 @@ AvroQueryClient.prototype.useGetCompanyUsers = function (body = {}) {
223
228
  staleTime: 30000,
224
229
  });
225
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
+ };
@@ -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 {
@@ -52,6 +58,13 @@ export declare function removeEntity(qc: QueryClient, ns: string, id: string): v
52
58
  export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any, company?: string | null): void;
53
59
  export declare function matchesList(type: string, key: readonly unknown[], item: any): ListMatch;
54
60
  export declare function invalidateType(qc: QueryClient, spec: EntitySpec): void;
61
+ /**
62
+ * Refetch every query the server refused with a 403. Called when a
63
+ * membership changes: the viewer may have just been granted the
64
+ * permission, and nothing else would retry a denied list until the next
65
+ * focus, remount, or reload.
66
+ */
67
+ export declare function retryDenied(qc: QueryClient): void;
55
68
  export declare class ChangeApplier {
56
69
  private client;
57
70
  private qc;