@go-avro/avro-js 1.6.4-rc3 → 1.6.4-rc5

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.
@@ -1,7 +1,7 @@
1
1
  import { Socket } from 'socket.io-client';
2
2
  import { InfiniteData, QueryClient, UseInfiniteQueryResult, useMutation, UseQueryResult } from '@tanstack/react-query';
3
3
  import { AuthManager } from '../auth/AuthManager.js';
4
- import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Break, Chat, CheckIn, Company, CompanySummary, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLinkProof, AppleLoginResult, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api.js';
4
+ import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Chat, CheckIn, Company, CompanySummary, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLinkProof, AppleLoginResult, MicrosoftLoginResult, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api.js';
5
5
  import { AuthState, Tokens } from '../types/auth.js';
6
6
  import { CancelToken, ClientId, RetryStrategy } from '../types/client.js';
7
7
  import { StandardError } from '../types/error.js';
@@ -11,7 +11,7 @@ import { Proposal } from '../types/api/Proposal.js';
11
11
  import { ProposalTerms } from '../types/api/ProposalTerms.js';
12
12
  import type { EmailSucceededPayload, EmailFailedPayload, EmailType } from '../types/api/EmailNotification.js';
13
13
  import type { BulkDeleteBillsResponse, BulkEmailBillsResponse } from './hooks/bills.js';
14
- import type { BillWritePayload, CatalogItemCreatePayload, CatalogItemUpdatePayload, CompanyCreatePayload, EventCreatePayload, IntuitImportResult, PayoutStatusFilter, ProposalReviewPayload, ProposalWritePayload, SkillCreatePayload, SkillUpdatePayload, UserCreatePayload, UserUpdatePayload } from './requests.js';
14
+ import type { BillWritePayload, BreakWritePayload, CatalogItemCreatePayload, CatalogItemUpdatePayload, CompanyCreatePayload, CompanyUpdatePayload, EventCreatePayload, IntuitImportResult, MemberAddPayload, MemberUpdatePayload, PayoutStatusFilter, ProposalReviewPayload, ProposalWritePayload, SessionCreatePayload, SessionUpdatePayload, SkillCreatePayload, SkillUpdatePayload, TeamWritePayload, UserCreatePayload, UserUpdatePayload } from './requests.js';
15
15
  import { type QueryPersistOptions } from './persist.js';
16
16
  export interface TrackEmailOptions {
17
17
  emailType?: EmailType;
@@ -35,7 +35,7 @@ export interface AvroQueryClientConfig {
35
35
  }
36
36
  declare module './QueryClient.js' {
37
37
  interface AvroQueryClient {
38
- _xhr<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<T>;
38
+ _xhr<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number, progressUpdateCallback?: (loaded: number, total: number) => void, refreshOnUnauthorized?: boolean): Promise<T>;
39
39
  _fetch<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number): Promise<T>;
40
40
  getDelay(strategy: RetryStrategy, attempt: number): number;
41
41
  sleep(ms: number): Promise<void>;
@@ -351,7 +351,7 @@ declare module './QueryClient.js' {
351
351
  msg: string;
352
352
  id: string | null;
353
353
  }, StandardError, {
354
- sessionData: Partial<Session>;
354
+ sessionData: SessionCreatePayload;
355
355
  }>>;
356
356
  useCreateTimecard(): ReturnType<typeof useMutation<{
357
357
  msg: string;
@@ -400,7 +400,7 @@ declare module './QueryClient.js' {
400
400
  msg: string;
401
401
  id: string;
402
402
  }, StandardError, {
403
- teamData: Partial<Team> & {
403
+ teamData: TeamWritePayload & {
404
404
  name: string;
405
405
  };
406
406
  }>>;
@@ -421,7 +421,7 @@ declare module './QueryClient.js' {
421
421
  id: string;
422
422
  }, StandardError, {
423
423
  sessionId: string;
424
- breakData: Partial<Break>;
424
+ breakData: BreakWritePayload;
425
425
  }>>;
426
426
  useManageJobs(): ReturnType<typeof useMutation<void, StandardError, {
427
427
  jobs: JobUpdate[];
@@ -482,7 +482,7 @@ declare module './QueryClient.js' {
482
482
  msg: string;
483
483
  }, StandardError, {
484
484
  sessionId: string;
485
- updates: Partial<Session>;
485
+ updates: SessionUpdatePayload;
486
486
  }>>;
487
487
  useUpdateTimecard(): ReturnType<typeof useMutation<{
488
488
  msg: string;
@@ -562,7 +562,7 @@ declare module './QueryClient.js' {
562
562
  msg: string;
563
563
  }, StandardError, {
564
564
  teamId: string;
565
- teamData: Partial<Team>;
565
+ teamData: TeamWritePayload;
566
566
  }>>;
567
567
  useUpdateMonth(): ReturnType<typeof useMutation<{
568
568
  msg: string;
@@ -586,7 +586,7 @@ declare module './QueryClient.js' {
586
586
  msg: string;
587
587
  }, StandardError, {
588
588
  user_id: string;
589
- data: Partial<UserCompanyAssociation>;
589
+ data: MemberUpdatePayload;
590
590
  }>>;
591
591
  useDevices(): UseQueryResult<Device[], StandardError>;
592
592
  useGetCompanyUsers(body?: {
@@ -611,13 +611,13 @@ declare module './QueryClient.js' {
611
611
  msg: string;
612
612
  }, StandardError, {
613
613
  breakId: string;
614
- updates: Partial<Break>;
614
+ updates: BreakWritePayload;
615
615
  }>>;
616
616
  useUpdateCompanySession(): ReturnType<typeof useMutation<{
617
617
  msg: string;
618
618
  }, StandardError, {
619
619
  sessionId: string;
620
- updates: Partial<Session>;
620
+ updates: SessionUpdatePayload;
621
621
  companyId?: string;
622
622
  }>>;
623
623
  useDeleteCompanySession(): ReturnType<typeof useMutation<{
@@ -643,15 +643,13 @@ declare module './QueryClient.js' {
643
643
  msg: string;
644
644
  }, StandardError, {
645
645
  companyId: string;
646
- companyData: Partial<Company | {
647
- logo: File | null;
648
- }>;
646
+ companyData: CompanyUpdatePayload;
649
647
  }>>;
650
648
  useCreateUserCompany(): ReturnType<typeof useMutation<{
651
649
  id: string;
652
650
  }, StandardError, {
653
651
  user_id: string;
654
- data: Partial<UserCompanyAssociation>;
652
+ data: MemberAddPayload;
655
653
  }>>;
656
654
  useAddUserCompany(): ReturnType<typeof useMutation<{
657
655
  msg: string;
@@ -807,7 +805,7 @@ export declare class AvroQueryClient {
807
805
  * Fire-and-forget: never throws, so it is safe inside error handlers.
808
806
  */
809
807
  reportClientError(report: ClientErrorReport): Promise<void>;
810
- post<T>({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }: {
808
+ post<T>({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, refreshOnUnauthorized, }: {
811
809
  path: string;
812
810
  data?: any;
813
811
  cancelToken?: CancelToken;
@@ -820,6 +818,12 @@ export declare class AvroQueryClient {
820
818
  * reached the server is never replayed.
821
819
  */
822
820
  idempotent?: boolean;
821
+ /**
822
+ * Refresh the session and replay once on a 401 (default true).
823
+ * Turn off for requests whose 401 is an answer, not an expired
824
+ * token, and that can't be replayed (one-time handles).
825
+ */
826
+ refreshOnUnauthorized?: boolean;
823
827
  }): Promise<T>;
824
828
  put<T>({ path, data, cancelToken, headers, progressUpdateCallback, }: {
825
829
  path: string;
@@ -900,6 +904,37 @@ export declare class AvroQueryClient {
900
904
  useAppleUnlink(): ReturnType<typeof useMutation<{
901
905
  msg: string;
902
906
  }, StandardError, void>>;
907
+ /**
908
+ * Sign in with a Microsoft authorization code (`code` + the `uri` it was
909
+ * issued for). With no account for the identity yet this resolves
910
+ * `NEEDS_ACCOUNT` (rather than failing) carrying the handle for
911
+ * `useMicrosoftLink`. A 401 means the matching account is linked to
912
+ * another Microsoft identity.
913
+ */
914
+ useMicrosoftLogin(): ReturnType<typeof useMutation<MicrosoftLoginResult, StandardError, {
915
+ code: string;
916
+ uri: string;
917
+ cancelToken?: CancelToken;
918
+ }>>;
919
+ /**
920
+ * Finish a `NEEDS_ACCOUNT` Microsoft sign-in with its `microsoft_token`
921
+ * once the account exists, then sign in with the returned tokens.
922
+ *
923
+ * When the 404 carried an `email`, the handle signs in to the account
924
+ * with that address and no session is needed. When `email` was null,
925
+ * the identity is linked to the account this client is signed in to:
926
+ * sign in to the new account first (e.g. `loginSuccess` with the tokens
927
+ * `POST /user` returned, or a code login when it answered
928
+ * `TOTP required`); the request carries the current session's token.
929
+ * 401s: `Sign in to link this Microsoft account` (no session; the
930
+ * handle stays valid for a retry within 10 min), `This Microsoft
931
+ * account is linked to another account`, `This account is linked to
932
+ * another Microsoft account`. 400: the handle is invalid or expired.
933
+ */
934
+ useMicrosoftLink(): ReturnType<typeof useMutation<LoginResponse, StandardError, {
935
+ microsoftToken: string;
936
+ cancelToken?: CancelToken;
937
+ }>>;
903
938
  setTokens(tokens: Tokens): Promise<void>;
904
939
  setCache(data: Partial<CacheData> | Object): Promise<void>;
905
940
  getCache(key?: keyof CacheData | string): Promise<CacheData[keyof CacheData] | Object | string | null>;
@@ -491,8 +491,8 @@ export class AvroQueryClient {
491
491
  // Reporting must never become a second failure.
492
492
  }
493
493
  }
494
- post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }) {
495
- return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
494
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, refreshOnUnauthorized, }) {
495
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback, refreshOnUnauthorized ?? true);
496
496
  }
497
497
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
498
498
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -739,6 +739,103 @@ export class AvroQueryClient {
739
739
  },
740
740
  });
741
741
  }
742
+ /**
743
+ * Sign in with a Microsoft authorization code (`code` + the `uri` it was
744
+ * issued for). With no account for the identity yet this resolves
745
+ * `NEEDS_ACCOUNT` (rather than failing) carrying the handle for
746
+ * `useMicrosoftLink`. A 401 means the matching account is linked to
747
+ * another Microsoft identity.
748
+ */
749
+ useMicrosoftLogin() {
750
+ const queryClient = this.getQueryClient();
751
+ return useMutation({
752
+ mutationFn: async ({ code, uri, cancelToken, }) => {
753
+ let resp;
754
+ try {
755
+ resp = await this.post({
756
+ path: `/microsoft/authorize?code=${encodeURIComponent(code)}&uri=${encodeURIComponent(uri)}`,
757
+ cancelToken,
758
+ headers: { 'Content-Type': 'application/json' },
759
+ });
760
+ }
761
+ catch (err) {
762
+ const body = err instanceof StandardError ? err.body : undefined;
763
+ if (err instanceof StandardError &&
764
+ err.status === 404 &&
765
+ body &&
766
+ typeof body.microsoft_token === 'string') {
767
+ const notFound = body;
768
+ return {
769
+ status: 'NEEDS_ACCOUNT',
770
+ microsoft_token: notFound.microsoft_token,
771
+ email: notFound.email ?? null,
772
+ first_name: notFound.first_name ?? '',
773
+ last_name: notFound.last_name ?? '',
774
+ };
775
+ }
776
+ throw err;
777
+ }
778
+ if (!resp || !('access_token' in resp)) {
779
+ throw new StandardError(401, 'Invalid Microsoft login response');
780
+ }
781
+ await this.loginSuccess({
782
+ access_token: resp.access_token,
783
+ refresh_token: resp.refresh_token,
784
+ });
785
+ return { status: LoginResponse.SUCCESS };
786
+ },
787
+ onSettled: () => {
788
+ queryClient.invalidateQueries();
789
+ },
790
+ onError: (err) => {
791
+ console.error('Microsoft Login failed:', err);
792
+ },
793
+ });
794
+ }
795
+ /**
796
+ * Finish a `NEEDS_ACCOUNT` Microsoft sign-in with its `microsoft_token`
797
+ * once the account exists, then sign in with the returned tokens.
798
+ *
799
+ * When the 404 carried an `email`, the handle signs in to the account
800
+ * with that address and no session is needed. When `email` was null,
801
+ * the identity is linked to the account this client is signed in to:
802
+ * sign in to the new account first (e.g. `loginSuccess` with the tokens
803
+ * `POST /user` returned, or a code login when it answered
804
+ * `TOTP required`); the request carries the current session's token.
805
+ * 401s: `Sign in to link this Microsoft account` (no session; the
806
+ * handle stays valid for a retry within 10 min), `This Microsoft
807
+ * account is linked to another account`, `This account is linked to
808
+ * another Microsoft account`. 400: the handle is invalid or expired.
809
+ */
810
+ useMicrosoftLink() {
811
+ const queryClient = this.getQueryClient();
812
+ return useMutation({
813
+ mutationFn: async ({ microsoftToken, cancelToken, }) => {
814
+ const resp = await this.post({
815
+ path: `/microsoft/authorize?token=${encodeURIComponent(microsoftToken)}`,
816
+ cancelToken,
817
+ headers: { 'Content-Type': 'application/json' },
818
+ // The handle is one-time: a refresh-and-replay after a
819
+ // "linked elsewhere" 401 would only get "expired".
820
+ refreshOnUnauthorized: false,
821
+ });
822
+ if (!resp || !('access_token' in resp)) {
823
+ throw new StandardError(401, 'Invalid Microsoft login response');
824
+ }
825
+ await this.loginSuccess({
826
+ access_token: resp.access_token,
827
+ refresh_token: resp.refresh_token,
828
+ });
829
+ return LoginResponse.SUCCESS;
830
+ },
831
+ onSettled: () => {
832
+ queryClient.invalidateQueries();
833
+ },
834
+ onError: (err) => {
835
+ console.error('Microsoft link failed:', err);
836
+ },
837
+ });
838
+ }
742
839
  setTokens(tokens) {
743
840
  return this.config.authManager.setTokens(tokens);
744
841
  }
@@ -3,7 +3,7 @@ import { StandardError } from '../../types/error.js';
3
3
  import { AuthState } from '../../types/auth.js';
4
4
  import { AVRO_JS_VERSION } from '../../version.js';
5
5
  import { cancelledError, isCancelledError, refreshFailureError, shouldRetry, } from './policy.js';
6
- AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount, progressUpdateCallback) {
6
+ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount, progressUpdateCallback, refreshOnUnauthorized = true) {
7
7
  const maxRetries = retryCount ?? this.config.maxRetries;
8
8
  const checkCancelled = () => {
9
9
  if (cancelToken?.isCancelled()) {
@@ -101,6 +101,7 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
101
101
  throw new StandardError(0, `An unexpected error occurred: ${message}`);
102
102
  }
103
103
  if (error.status === 401 &&
104
+ refreshOnUnauthorized &&
104
105
  !refreshed &&
105
106
  this.getAuthState() === AuthState.AUTHENTICATED) {
106
107
  refreshed = true;
@@ -56,18 +56,11 @@ AvroQueryClient.prototype.useCreateBill = function () {
56
56
  const queryClient = this.getQueryClient();
57
57
  return useMutation({
58
58
  mutationFn: async ({ data }) => {
59
- const body = {
60
- events: data.events ?? [],
61
- months: data.months ?? [],
62
- line_items: (data.line_items ?? []).map(toBillLineItemInput),
63
- manual_emails: data.manual_emails ?? [],
64
- prepayments: data.prepayments ?? [],
65
- enabled_payment_methods: data.enabled_payment_methods ?? [],
66
- pass_on_fees: data.pass_on_fees,
67
- users: data.users,
68
- due_date: data.due_date,
69
- name: data.name,
70
- };
59
+ // Absent keys take the backend defaults; nulls (name/due_date)
60
+ // are passed through as given.
61
+ const body = data.line_items
62
+ ? { ...data, line_items: data.line_items.map(toBillLineItemInput) }
63
+ : data;
71
64
  return this.post({
72
65
  path: `/company/${this.companyId}/bill`,
73
66
  data: JSON.stringify(body),
@@ -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'],
@@ -97,7 +111,7 @@ 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;
@@ -124,7 +138,7 @@ AvroQueryClient.prototype.useUpdateCompany = function () {
124
138
  AvroQueryClient.prototype.useCreateUserCompany = function () {
125
139
  const queryClient = this.getQueryClient();
126
140
  return useMutation({
127
- mutationFn: async ({ user_id, data, }) => {
141
+ mutationFn: async ({ user_id, data }) => {
128
142
  if (!user_id) {
129
143
  throw new Error('Both userId and companyId are required');
130
144
  }
@@ -71,8 +71,9 @@ AvroQueryClient.prototype.useCreateEvent = function () {
71
71
  });
72
72
  },
73
73
  onMutate: async ({ eventData: wireEventData }) => {
74
- // Wire-shaped participants must not land in cached _Event.users.
75
- const { users: _wireUsers, ...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;
76
77
  await queryClient.cancelQueries({ queryKey: ['events'] });
77
78
  const previousJob = queryClient.getQueryData([
78
79
  'jobs',
@@ -251,10 +252,11 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
251
252
  });
252
253
  },
253
254
  onMutate: async ({ eventId, updates: wireUpdates }) => {
254
- // The wire `users` shape ({user_id, time_*}) must not land in
255
- // cached _Event.users (UserEvent rows) — exclude it from the
256
- // optimistic merge; invalidation on settle refreshes real rows.
257
- 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;
258
260
  await queryClient.cancelQueries({ queryKey: ['events', eventId] });
259
261
  await queryClient.cancelQueries({ queryKey: ['events'] });
260
262
  // Try individual cache first; fall back to scanning all active events queries
@@ -12,9 +12,12 @@ AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
12
12
  return client.getQueryData(keys.list('jobs', this.companyId)) ?? [];
13
13
  };
14
14
  /**
15
- * Omit blank ids from a job write. `UpdateJob`/`ManagedJob` type the job,
16
- * task, prepayment, owner and catalog item ids as UUIDs; a blank id means
17
- * "new row" / "none", which is what omitting it says.
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.
18
21
  */
19
22
  function toJobWire(job) {
20
23
  const wire = withoutEmpty(job, 'id', 'owner_id');
@@ -2,18 +2,36 @@ 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
+ });
17
35
  /**
18
36
  * Drop `''` task ids from a schedule request: `ScheduleRoutes` types every
19
37
  * task id as a UUID, so one blank id (e.g. an unsaved task) would 400 the
@@ -97,7 +115,8 @@ AvroQueryClient.prototype.useCreateRoute = function () {
97
115
  headers: { 'Content-Type': 'application/json' },
98
116
  });
99
117
  },
100
- onMutate: async ({ routeData: { optimize: _optimize, ...routeData } }) => {
118
+ onMutate: async ({ routeData: wireRouteData }) => {
119
+ const routeData = toCachedRoute('temp-id', wireRouteData);
101
120
  await queryClient.cancelQueries({ queryKey: ['routes'] });
102
121
  const previousRoutes = snapshotNs(queryClient, 'routes');
103
122
  queryClient.setQueriesData({ queryKey: ['routes'] }, (oldData) => {
@@ -180,7 +199,8 @@ AvroQueryClient.prototype.useUpdateRoute = function () {
180
199
  headers: { 'Content-Type': 'application/json' },
181
200
  });
182
201
  },
183
- onMutate: async ({ routeId, updates: { optimize: _optimize, ...updates } }) => {
202
+ onMutate: async ({ routeId, updates: wireUpdates }) => {
203
+ const updates = toCachedRoute(routeId, wireUpdates);
184
204
  await queryClient.cancelQueries({ queryKey: ['routes', routeId] });
185
205
  await queryClient.cancelQueries({ queryKey: ['routes'] });
186
206
  const previousRoute = queryClient.getQueryData(['routes', routeId]);
@@ -1,6 +1,6 @@
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
6
  import { withoutEmpty } from '../wire.js';
@@ -57,7 +57,7 @@ AvroQueryClient.prototype.useGetSessions = function (body = {}) {
57
57
  AvroQueryClient.prototype.useGetUserSessions = function () {
58
58
  const queryClient = this.getQueryClient();
59
59
  const result = useQuery({
60
- queryKey: keys.list(NS, 'mine', { active: true }),
60
+ queryKey: keys.list(NS, VIEWER_SCOPE, { active: true }),
61
61
  queryFn: () => this.get({ path: '/session' }).then((sessions) => seedDetails(queryClient, NS, (Array.isArray(sessions) ? sessions : []).map((s) => new Session(s)))),
62
62
  enabled: Boolean(this.companyId),
63
63
  });
@@ -95,6 +95,23 @@ AvroQueryClient.prototype.useGetActiveCompanySessions = function (params = {}) {
95
95
  * `UpdateSession`); `''` is omitted rather than sent.
96
96
  */
97
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
+ }
98
115
  AvroQueryClient.prototype.useCreateUserSession = function () {
99
116
  const queryClient = this.getQueryClient();
100
117
  return useMutation({
@@ -110,7 +127,7 @@ AvroQueryClient.prototype.useCreateUserSession = function () {
110
127
  await queryClient.cancelQueries({ queryKey: [NS] });
111
128
  const previous = snapshotSessionLists(queryClient);
112
129
  const optimistic = new Session({
113
- ...sessionData,
130
+ ...toCachedSession(sessionData),
114
131
  id: `optimistic-${Math.random().toString(36).slice(2, 11)}`,
115
132
  company_id: this.companyId,
116
133
  });
@@ -171,7 +188,7 @@ AvroQueryClient.prototype.useCreateSessionBreak = function () {
171
188
  AvroQueryClient.prototype.useUpdateUserSession = function () {
172
189
  const queryClient = this.getQueryClient();
173
190
  return useMutation({
174
- mutationFn: ({ sessionId, updates }) => {
191
+ mutationFn: ({ sessionId, updates, }) => {
175
192
  return this.put({
176
193
  path: `/session/${sessionId}`,
177
194
  data: JSON.stringify(withoutEmpty(updates, ...SESSION_ID_FIELDS)),
@@ -182,8 +199,10 @@ AvroQueryClient.prototype.useUpdateUserSession = function () {
182
199
  await queryClient.cancelQueries({ queryKey: [NS] });
183
200
  const previous = snapshotSessionLists(queryClient);
184
201
  const previousDetail = queryClient.getQueryData(keys.detail(NS, sessionId));
185
- patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
186
- 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);
187
206
  return { previous, previousDetail };
188
207
  },
189
208
  onError: (_err, { sessionId }, context) => {
@@ -240,8 +259,10 @@ AvroQueryClient.prototype.useUpdateCompanySession = function () {
240
259
  await queryClient.cancelQueries({ queryKey: [NS] });
241
260
  const previous = snapshotSessionLists(queryClient);
242
261
  const previousDetail = queryClient.getQueryData(keys.detail(NS, sessionId));
243
- patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
244
- 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);
245
266
  return { previous, previousDetail };
246
267
  },
247
268
  onError: (_err, { sessionId }, context) => {
@@ -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),
@@ -109,8 +109,10 @@ AvroQueryClient.prototype.useUpdateUser = function (userId) {
109
109
  });
110
110
  },
111
111
  onMutate: async (wireData) => {
112
- // Credentials are request-only; keep them out of the cache.
113
- const { password: _password, current_password: _currentPassword, apple_token: _appleToken, apple_nonce: _appleNonce, ...data } = 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;
114
116
  await queryClient.cancelQueries({ queryKey: ['user'] });
115
117
  await queryClient.cancelQueries({ queryKey: ['users', userId] });
116
118
  const previousSelf = queryClient.getQueryData(['user']);
@@ -146,7 +148,7 @@ AvroQueryClient.prototype.useUpdateUser = function (userId) {
146
148
  AvroQueryClient.prototype.useUpdateUserCompany = function () {
147
149
  const queryClient = this.getQueryClient();
148
150
  return useMutation({
149
- mutationFn: async ({ user_id, data, }) => {
151
+ mutationFn: async ({ user_id, data }) => {
150
152
  return this.put({
151
153
  path: `/company/${this.companyId}/user/${user_id}`,
152
154
  data: JSON.stringify(data),
@@ -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
  }
@@ -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;
@@ -333,7 +339,7 @@ export function upsertEntity(qc, spec, item, company) {
333
339
  for (const query of lists) {
334
340
  const key = query.queryKey;
335
341
  const scope = listScope(key);
336
- if (company && scope && scope !== company)
342
+ if (company && scope && scope !== company && scope !== VIEWER_SCOPE)
337
343
  continue;
338
344
  const verdict = spec.listMatch
339
345
  ? spec.listMatch(listFilters(key), item, listScope(key))