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

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]);
@@ -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),
@@ -2,15 +2,18 @@
2
2
  * Request bodies and endpoint-specific responses of the REST API, matching
3
3
  * the backend's pydantic schemas (`avro/views/<domain>/schemas.py`).
4
4
  */
5
- import type { CatalogIndustry, CatalogPriceFormat, EventUpdatePayload, PaymentType, TaskStatus, User } from '../types/api.js';
5
+ import type { CatalogIndustry, CatalogPriceFormat, EventUpdatePayload, LineItemStatus, NotificationLevel, PaymentType, Permission, TaskStatus } from '../types/api.js';
6
6
  /** Body of `POST /company/<id>/skill` (backend `CreateSkill`). */
7
7
  export interface SkillCreatePayload {
8
8
  /** 1–255 characters. */
9
9
  name: string;
10
- /** At most 1023 characters. */
11
- description?: string | null;
10
+ /** At most 1023 characters; defaults to `''`. */
11
+ description?: string;
12
12
  }
13
- /** Body of `PUT /skill/<id>` (backend `UpdateSkill`); omitted fields are unchanged. */
13
+ /**
14
+ * Body of `PUT /skill/<id>` (backend `UpdateSkill`); omitted fields are
15
+ * unchanged and `description: ''` clears the description.
16
+ */
14
17
  export type SkillUpdatePayload = Partial<SkillCreatePayload>;
15
18
  /** `status` filter of `POST /company/<id>/payouts` (backend `PayoutsListBody`). */
16
19
  export type PayoutStatusFilter = 'paid' | 'pending' | 'in_transit' | 'canceled' | 'failed';
@@ -31,14 +34,90 @@ export interface CompanyCreatePayload {
31
34
  name: string;
32
35
  /** Referral code; unknown codes are ignored. */
33
36
  code?: string | null;
34
- /** IANA zone name. */
35
- timezone?: string | null;
36
- overdue_threshold?: number | null;
37
- delay_scalar?: number | null;
37
+ /** IANA zone name; omit for the server's default zone. */
38
+ timezone?: string;
39
+ overdue_threshold?: number;
40
+ /** Rounded to a whole number. */
41
+ delay_scalar?: number;
38
42
  /** Plan GUID to subscribe to. */
39
43
  plan?: string | null;
40
44
  logo?: File | null;
41
45
  }
46
+ /** A Stripe payment method kept on a company (backend `PaymentMethodRef`). */
47
+ export interface CompanyPaymentMethodInput {
48
+ /** Stripe payment method id (`pm_...`). */
49
+ id: string;
50
+ autopay: boolean;
51
+ }
52
+ /**
53
+ * Body of `PUT /company/<id>` (backend `UpdateCompany`); omitted fields are
54
+ * unchanged. `null` unlinks the mailboxes / clears the plan; it is a 400 on
55
+ * every other field (and `''` is a 400 on the id fields).
56
+ */
57
+ export interface CompanyUpdatePayload {
58
+ /** 1–256 characters. */
59
+ name?: string;
60
+ email?: string;
61
+ address?: string;
62
+ /** IANA zone name. */
63
+ timezone?: string;
64
+ delay_scalar?: number;
65
+ overdue_threshold?: number;
66
+ completed_onboarding?: boolean;
67
+ /** Unix seconds the first pay period starts. */
68
+ timecard_base?: number;
69
+ /** Pay period length in seconds; at least one day. */
70
+ timecard_length?: number;
71
+ use_client_side_customer_start_billing?: boolean;
72
+ use_client_side_customer_stop_billing?: boolean;
73
+ use_client_side_employee_start_billing?: boolean;
74
+ use_client_side_employee_stop_billing?: boolean;
75
+ indicator_lifetime?: number;
76
+ /** One of the company's mailboxes; null unsets it. */
77
+ service_email_id?: string | null;
78
+ /** One of the company's mailboxes; null unsets it. */
79
+ billing_email_id?: string | null;
80
+ /** In cents; only applied for root. */
81
+ balance?: number;
82
+ /** Null clears the plan. Ignored while the balance is negative. */
83
+ plan_id?: string | null;
84
+ enabled_payment_methods?: PaymentType[];
85
+ require_team_for_clock_in?: boolean;
86
+ accepts_cash_payments?: boolean;
87
+ default_pass_on_fees?: boolean;
88
+ /** Replaces the company's payment methods (detaching the rest). */
89
+ payment_methods?: CompanyPaymentMethodInput[];
90
+ /** `false` force-releases the scheduling lock; `true` is ignored. */
91
+ schedule_locked?: boolean;
92
+ /** Not read by this endpoint (upload with `POST /company/<id>/logo`). */
93
+ logo?: File | null;
94
+ }
95
+ /** Body of `POST /company/<id>/user/<user_id>` (backend `AddMember`). */
96
+ export interface MemberAddPayload {
97
+ /** `is_root` is dropped. */
98
+ permissions?: Permission[];
99
+ notification_setting?: NotificationLevel[];
100
+ /** A group of the company for the new member to join; null for none. */
101
+ group?: string | null;
102
+ }
103
+ /**
104
+ * Body of `PUT /company/<id>/user/<user_id>` (backend `UpdateMember`);
105
+ * omitted fields are unchanged and nothing is nullable.
106
+ */
107
+ export interface MemberUpdatePayload {
108
+ /** `is_root` is dropped. */
109
+ permissions?: Permission[];
110
+ hourly_rate?: number;
111
+ salary_rate?: number;
112
+ bill_rate?: number;
113
+ pto_rate?: number;
114
+ sick_rate?: number;
115
+ accrued_pto?: number;
116
+ accrued_sick?: number;
117
+ pto_accrual_rate?: number;
118
+ sick_accrual_rate?: number;
119
+ notification_setting?: NotificationLevel[];
120
+ }
42
121
  /**
43
122
  * Body of `POST /user` (backend `CreateUser`). `password` and `last_name`
44
123
  * may be empty; `email` must look like an address; `phone_number` must be a
@@ -59,30 +138,57 @@ export interface UserCreatePayload {
59
138
  /** Company GUID to join as a customer. */
60
139
  company_id?: string | null;
61
140
  invite_token?: string | null;
62
- share_location?: boolean | null;
63
- share_email?: boolean | null;
64
- share_phone?: boolean | null;
65
- share_with_public?: boolean | null;
141
+ share_location?: boolean;
142
+ share_email?: boolean;
143
+ share_phone?: boolean;
144
+ share_with_public?: boolean;
145
+ }
146
+ /** A saved Stripe payment method on a user write (backend `PaymentMethodIn`). */
147
+ export interface UserPaymentMethodInput {
148
+ /** Stripe payment method id (`pm_...`). */
149
+ id: string;
150
+ /** Omitted keeps the current setting (off for a newly saved method). */
151
+ autopay?: boolean;
66
152
  }
67
153
  /**
68
154
  * Body of `PUT /user/<id>` (backend `UpdateUser`): profile fields plus the
69
- * credentials a password/email change needs. `phone_number: ''` leaves the
70
- * number unchanged; a new `password` must be non-empty.
155
+ * credentials a password/email change needs. Omitted fields are unchanged;
156
+ * only `phone_number` is nullable (null removes the number, `''` is a 400).
157
+ * A new `password` must be non-empty.
71
158
  */
72
- export type UserUpdatePayload = Partial<User> & {
159
+ export interface UserUpdatePayload {
160
+ /** 1–150 characters; stored lowercased. */
161
+ username?: string;
162
+ /** At most 100 characters. */
163
+ first_name?: string;
164
+ /** At most 100 characters. */
165
+ last_name?: string;
166
+ /** Changing your own password needs `current_password` (or an Apple re-sign-in). */
73
167
  password?: string;
168
+ /** Changing your own email needs `current_password` (or an Apple re-sign-in). */
169
+ email?: string;
74
170
  current_password?: string;
75
171
  /** A fresh Apple identity token, instead of `current_password`. */
76
172
  apple_token?: string;
173
+ /** The raw nonce `apple_token` was requested with. */
77
174
  apple_nonce?: string;
78
- };
175
+ /** A real number with country code; null removes it. */
176
+ phone_number?: string | null;
177
+ notification_setting?: NotificationLevel[];
178
+ /** Replaces the saved payment methods (`[]` detaches all). */
179
+ payment_methods?: UserPaymentMethodInput[];
180
+ share_location?: boolean;
181
+ share_email?: boolean;
182
+ share_phone?: boolean;
183
+ share_with_public?: boolean;
184
+ }
79
185
  /** A custom line item on a bill write (backend `BillLineItemIn`). */
80
186
  export interface BillLineItemInput {
81
187
  name?: string;
82
188
  description?: string;
83
- /** Quantity; may be fractional (e.g. hours). */
189
+ /** Quantity (default 1); may be fractional (e.g. hours). */
84
190
  amount?: number;
85
- /** Unit price in integer cents. */
191
+ /** Unit price in integer cents (default 0). */
86
192
  cost?: number;
87
193
  }
88
194
  /** A member recipient on a bill write (backend `BillUserIn`). */
@@ -97,29 +203,31 @@ export interface BillUserInput {
97
203
  }
98
204
  /**
99
205
  * Body of `POST /company/<id>/bill` and `PUT /bill/<id>` (backend
100
- * `CreateBill` / `UpdateBill`); omitted or null fields are unchanged.
206
+ * `CreateBill` / `UpdateBill`); omitted fields are unchanged. Only `name`
207
+ * and `due_date` are nullable (null clears them); null elsewhere is a 400.
101
208
  */
102
209
  export interface BillWritePayload {
103
210
  /** Event GUIDs; replaces the bill's events. */
104
- events?: string[] | null;
105
- /** Service month GUIDs. */
106
- months?: string[] | null;
107
- /** Prepayment GUIDs. */
108
- prepayments?: string[] | null;
211
+ events?: string[];
212
+ /** Service month GUIDs; replaces the bill's months. */
213
+ months?: string[];
214
+ /** Prepayment GUIDs; replaces the bill's prepayments. */
215
+ prepayments?: string[];
109
216
  /** Replaces the bill's custom line items. */
110
- line_items?: BillLineItemInput[] | null;
111
- /** Extra recipients as `[name, email]` pairs. */
112
- manual_emails?: [string, string][] | null;
113
- users?: BillUserInput[] | null;
114
- /** At most 256 characters. */
217
+ line_items?: BillLineItemInput[];
218
+ /** Extra recipients as `[name, email]` pairs; replaces them. */
219
+ manual_emails?: [string, string][];
220
+ /** Replaces the member recipients. */
221
+ users?: BillUserInput[];
222
+ /** At most 256 characters; null clears it. */
115
223
  name?: string | null;
116
224
  /** Marks every item paid outside Avro. */
117
- status?: 'MANUALLY_PAID' | null;
118
- /** Unix seconds. */
225
+ status?: 'MANUALLY_PAID';
226
+ /** Unix seconds; null clears it. */
119
227
  due_date?: number | null;
120
228
  /** Empty means the company's defaults. */
121
- enabled_payment_methods?: PaymentType[] | null;
122
- pass_on_fees?: boolean | null;
229
+ enabled_payment_methods?: PaymentType[];
230
+ pass_on_fees?: boolean;
123
231
  }
124
232
  /** Response of `POST /company/<id>/intuit/import` (backend `IntuitImportResult`). */
125
233
  export interface IntuitImportResult {
@@ -149,25 +257,25 @@ export interface PaymentOptionInput {
149
257
  */
150
258
  export interface CatalogItemUpdatePayload {
151
259
  /** 1–256 characters. */
152
- name?: string | null;
153
- description?: string | null;
260
+ name?: string;
261
+ description?: string;
154
262
  /**
155
263
  * A `CatalogIndustry` name, matched case-insensitively with spaces for
156
264
  * underscores (`'Snow Removal'`).
157
265
  */
158
- industry?: CatalogIndustry | (string & {}) | null;
266
+ industry?: CatalogIndustry | (string & {});
159
267
  /** A `CatalogPriceFormat` name, matched like `industry`. */
160
- price_format?: CatalogPriceFormat | (string & {}) | null;
161
- /** Integer seconds between services. */
268
+ price_format?: CatalogPriceFormat | (string & {});
269
+ /** Integer seconds between services; null clears it. */
162
270
  recommended_frequency?: number | null;
163
- /** Unix seconds (>= 0). */
271
+ /** Unix seconds (>= 0); null clears it. */
164
272
  recommended_activate_on?: number | null;
165
- /** Unix seconds (>= 0). */
273
+ /** Unix seconds (>= 0); null clears it. */
166
274
  recommended_expire_on?: number | null;
167
275
  /** Skill GUIDs; replaces the item's skills. */
168
- skills?: string[] | null;
276
+ skills?: string[];
169
277
  /** Replaces the item's payment options. */
170
- payment_options?: PaymentOptionInput[] | null;
278
+ payment_options?: PaymentOptionInput[];
171
279
  }
172
280
  /** Body of `POST /company/<id>/catalog_item` (backend `CreateCatalogItem`). */
173
281
  export type CatalogItemCreatePayload = CatalogItemUpdatePayload & {
@@ -176,10 +284,13 @@ export type CatalogItemCreatePayload = CatalogItemUpdatePayload & {
176
284
  /**
177
285
  * Body of `POST /job/<id>/proposal` and `PUT /proposal/<id>` (backend
178
286
  * `CreateProposal` / `UpdateProposal`); omitted fields are unchanged, and
179
- * null clears `terms_version_id` / `prepay_due_date`.
287
+ * null clears `expire_on` / `terms_version_id` / `prepay_due_date`.
180
288
  */
181
289
  export interface ProposalWritePayload {
182
- /** Unix seconds (>= 0) after which the customer can no longer review. */
290
+ /**
291
+ * Unix seconds (>= 0) after which the customer can no longer review;
292
+ * null means never.
293
+ */
183
294
  expire_on?: number | null;
184
295
  /** Terms version GUID; null detaches. */
185
296
  terms_version_id?: string | null;
@@ -188,7 +299,7 @@ export interface ProposalWritePayload {
188
299
  /** Replaces the proposal's tasks (only `id` is read). */
189
300
  tasks?: {
190
301
  id: string;
191
- }[] | null;
302
+ }[];
192
303
  }
193
304
  /** A prepayment a customer commits to when accepting a task (backend `AcceptPrepayment`). */
194
305
  export interface ProposalReviewPrepayment {
@@ -200,15 +311,18 @@ export interface ProposalReviewPrepayment {
200
311
  description?: string;
201
312
  name?: string;
202
313
  }
203
- /** The customer's decision on one proposal task (backend `ReviewTask`). */
314
+ /**
315
+ * The customer's decision on one proposal task (backend `ReviewTask`).
316
+ * Omit a choice to not make it; null is a 400.
317
+ */
204
318
  export interface ProposalReviewTask {
205
319
  id: string;
206
- /** `ARCHIVED` rejects the task; anything else accepts it. */
207
- status?: TaskStatus | null;
208
- prepayments?: ProposalReviewPrepayment[] | null;
209
- bill_mode?: 'NONE' | 'MONTH' | 'SERVICE' | null;
320
+ /** `ARCHIVED` rejects the task; anything else (or omitting it) accepts it. */
321
+ status?: TaskStatus;
322
+ prepayments?: ProposalReviewPrepayment[];
323
+ bill_mode?: 'NONE' | 'MONTH' | 'SERVICE';
210
324
  /** Chosen price in integer cents. */
211
- price?: number | null;
325
+ price?: number;
212
326
  /** @deprecated Not read by the backend. */
213
327
  payment_option_id?: string;
214
328
  }
@@ -219,3 +333,138 @@ export interface ProposalReviewPayload {
219
333
  terms_version_id?: string | null;
220
334
  pay_in_cash?: boolean;
221
335
  }
336
+ /**
337
+ * A prepayment on a task write (backend `TaskPrepaymentIn`), matched to an
338
+ * existing one by `id`; omitted fields keep an existing prepayment's values.
339
+ */
340
+ export interface TaskPrepaymentInput {
341
+ /** An existing prepayment of the task; omit to create one. */
342
+ id?: string;
343
+ /** Unit price in integer cents; defaults to 0. */
344
+ cost?: number;
345
+ /** Defaults to 1. */
346
+ amount?: number;
347
+ /** Defaults to `SERVICE`. */
348
+ type?: 'SERVICE' | 'MONTH';
349
+ /** Defaults to `EXTERNALLY_PAID`. */
350
+ status?: LineItemStatus;
351
+ description?: string;
352
+ name?: string;
353
+ }
354
+ /**
355
+ * A task inside a job write (backend `JobTaskIn` / `UpdateTask`), matched
356
+ * to the job's tasks by `id`. Omitted fields are unchanged; null clears
357
+ * `expire_on`, `activate_on`, `bill_day`, `enforce_image_amount` and
358
+ * `catalog_item_id` and is a 400 on every other field.
359
+ */
360
+ export interface TaskWritePayload {
361
+ /** An existing task of the job; omit (or `''`) to create one. */
362
+ id?: string;
363
+ /** Required unless the task already has a name. */
364
+ name?: string;
365
+ /** Replaces the task's prepayments. */
366
+ prepayments?: TaskPrepaymentInput[];
367
+ /** Unix seconds, truncated to UTC midnight; null means never. */
368
+ expire_on?: number | null;
369
+ /** Unix seconds, truncated to UTC midnight; null means right away. */
370
+ activate_on?: number | null;
371
+ /** Day of month to bill; null means the month's last day. */
372
+ bill_day?: number | null;
373
+ services_remaining?: number;
374
+ /** Seconds between services; <= 0 means not recurring. */
375
+ frequency?: number;
376
+ internal_notes?: string;
377
+ external_notes?: string;
378
+ /** Proof images expected per service. */
379
+ image_amt?: number;
380
+ enforce_image_amount?: boolean | null;
381
+ status?: TaskStatus;
382
+ /** Email the other party when `status` moves to a pending state. */
383
+ send_email?: boolean;
384
+ /** With an accepting `status`, settle a cash proposal's unbilled prepayments. */
385
+ cash_received?: boolean;
386
+ /** Service duration in seconds. */
387
+ service?: number;
388
+ autobill?: boolean;
389
+ bill_mode?: 'NONE' | 'MONTH' | 'SERVICE';
390
+ /** Replaces the task's payment options. */
391
+ payment_options?: PaymentOptionInput[];
392
+ /** Price in integer cents; -1 means unset. */
393
+ price?: number;
394
+ priority?: boolean;
395
+ /** Null unlinks the catalog item. */
396
+ catalog_item_id?: string | null;
397
+ /** Skill GUIDs; replaces the task's skills. */
398
+ skills?: string[];
399
+ }
400
+ /**
401
+ * Body of `POST /company/<id>/team` and `PUT /team/<id>` (backend
402
+ * `CreateTeam` / `UpdateTeam`); omitted fields are unchanged. A start or
403
+ * end point is sent whole: both halves as numbers, or both null to clear
404
+ * it (one half alone is a 400). Null is a 400 on every other field.
405
+ */
406
+ export interface TeamWritePayload {
407
+ name?: string;
408
+ description?: string;
409
+ start_latitude?: number | null;
410
+ start_longitude?: number | null;
411
+ start_address?: string;
412
+ end_latitude?: number | null;
413
+ end_longitude?: number | null;
414
+ end_address?: string;
415
+ /** -1 for no limit. */
416
+ max_jobs?: number;
417
+ speed_factor?: number;
418
+ /** Seconds; -1 for no limit. */
419
+ max_travel_time?: number;
420
+ /** Meters; -1 for no limit. */
421
+ max_distance?: number;
422
+ /** Seconds after midnight the shift starts; -1 for none. */
423
+ start_time?: number;
424
+ /** Seconds after midnight the shift ends; -1 for none. */
425
+ end_time?: number;
426
+ fixed_cost?: number;
427
+ hourly_cost?: number;
428
+ km_cost?: number;
429
+ autoconfigure?: boolean;
430
+ /** `#RRGGBB`. */
431
+ color?: string;
432
+ /** Route GUIDs; replaces the team's routes (`[]` clears them). */
433
+ routes?: string[];
434
+ /** User GUIDs; replaces the team's members. */
435
+ users?: string[];
436
+ /** Skill GUIDs; replaces the team's skills. */
437
+ skills?: string[];
438
+ }
439
+ /**
440
+ * Body of `PUT /session/<id>` (backend `UpdateSession`); omitted fields are
441
+ * unchanged. Null clears the team / route, and `time_ended: null` re-opens
442
+ * the session; `time_started` is not nullable.
443
+ */
444
+ export interface SessionUpdatePayload {
445
+ team_id?: string | null;
446
+ route_id?: string | null;
447
+ /** Alias of `route_id`. */
448
+ current_route_id?: string | null;
449
+ /** Unix seconds; restarts the clock. */
450
+ time_started?: number;
451
+ /** Unix seconds, or `true` for now; null re-opens the session. */
452
+ time_ended?: number | true | null;
453
+ }
454
+ /** Body of `POST /company/<id>/session` (backend `StartSession`). */
455
+ export interface SessionCreatePayload extends SessionUpdatePayload {
456
+ /** Member to clock in; defaults to the caller. */
457
+ user_id?: string | null;
458
+ }
459
+ /**
460
+ * Body of `POST /session/<id>/break` and `PUT /break/<id>` (backend
461
+ * `CreateSessionBreak` / `UpdateBreak`); nothing is nullable.
462
+ */
463
+ export interface BreakWritePayload {
464
+ /** Unix seconds. */
465
+ time_started?: number;
466
+ /** Unix seconds. */
467
+ time_ended?: number;
468
+ company_billable?: boolean;
469
+ client_billable?: boolean;
470
+ }
@@ -9,10 +9,11 @@ export type DevicePlatform = (typeof DevicePlatform)[keyof typeof DevicePlatform
9
9
  export interface DeviceInfo {
10
10
  device_key: string;
11
11
  platform: DevicePlatform;
12
- name?: string;
13
- model?: string;
14
- os?: string;
15
- app_version?: string;
12
+ /** Omitted details are unchanged; null clears one. */
13
+ name?: string | null;
14
+ model?: string | null;
15
+ os?: string | null;
16
+ app_version?: string | null;
16
17
  foreground?: boolean;
17
18
  headless?: boolean;
18
19
  }
@@ -4,6 +4,7 @@ import type { CheckIn } from '../api.js';
4
4
  import { RouteJob } from './RouteJob.js';
5
5
  import { Subscription } from './Subscription.js';
6
6
  import { Route } from './Route.js';
7
+ import type { TaskWritePayload } from '../../client/requests.js';
7
8
  declare module './Job.js' {
8
9
  interface Job {
9
10
  address: string;
@@ -53,9 +54,37 @@ export interface TimeWindow {
53
54
  time_created: number | null;
54
55
  time_updated: number | null;
55
56
  }
56
- export type JobUpdate = Partial<Omit<Job, 'subscribers'>> & {
57
+ /**
58
+ * Body of a job write (backend `UpdateJob` / `CreateJob` / `ManagedJob`).
59
+ * Omitted fields are unchanged; `owner_id: null` removes the owner and null
60
+ * on any other field is a 400. `''` clears text, `[]` clears lists. `id`
61
+ * (bulk writes only) and `owner_id` may be `''`, which the SDK omits.
62
+ * Send only the fields that changed, never a cached `Job` back.
63
+ */
64
+ export interface JobUpdate {
65
+ /** Bulk writes (`useManageJobs`): the job to update; omit to create one. */
66
+ id?: string;
67
+ /** Required unless the job already has one. */
68
+ name?: string;
69
+ /** Applied only together with `longitude`; a new job needs both. */
70
+ latitude?: number;
71
+ longitude?: number;
72
+ address?: string;
73
+ description?: string;
74
+ internal_notes?: string;
75
+ external_notes?: string;
76
+ serviced_by?: number;
77
+ /** Member (user-company) or user GUIDs; replaces the subscriptions. */
57
78
  subscribers?: string[];
58
- };
79
+ /** Extra notification recipients as `[name, email]` pairs. */
80
+ manual_emails?: [string, string][];
81
+ /** Replaces the job's tasks: listed ones are upserted, unlisted deleted. */
82
+ tasks?: TaskWritePayload[];
83
+ /** Label GUIDs or names; replaces the job's labels. */
84
+ labels?: string[];
85
+ /** User GUID of the owner (a company member); null removes the owner. */
86
+ owner_id?: string | null;
87
+ }
59
88
  export declare class Job {
60
89
  constructor(init?: Partial<Job>);
61
90
  isOverdue: () => boolean;
@@ -1,6 +1,5 @@
1
1
  import { FrequencyType } from '..';
2
- import { _Event } from './api/_Event.js';
3
- import { Route } from './api/Route.js';
2
+ import type { LineItemStatus } from './api/LineItem.js';
4
3
  export * from './api/_Event.js';
5
4
  export * from './api/AdditionalCharge.js';
6
5
  export * from './api/DelayEvent.js';
@@ -70,6 +69,24 @@ export type AppleLoginResult = {
70
69
  email: string | null;
71
70
  is_private_email: boolean;
72
71
  };
72
+ /**
73
+ * Outcome of `useMicrosoftLogin`. With no account for the Microsoft identity
74
+ * yet this is `NEEDS_ACCOUNT` (the backend's 404 `MicrosoftUserNotFound`):
75
+ * create the account (`POST /user`), then pass `microsoft_token` (a
76
+ * one-time handle, valid 10 min) to `useMicrosoftLink`. `email` is the
77
+ * verified sign-in address, or null when Microsoft gave none (e.g. a
78
+ * phone-number account): then ask the user for an address, and the link
79
+ * call must carry the new account's session.
80
+ */
81
+ export type MicrosoftLoginResult = {
82
+ status: typeof LoginResponse.SUCCESS;
83
+ } | {
84
+ status: 'NEEDS_ACCOUNT';
85
+ microsoft_token: string;
86
+ email: string | null;
87
+ first_name: string;
88
+ last_name: string;
89
+ };
73
90
  /**
74
91
  * Proof of the Apple ID `useAppleLink` attaches: a fresh identity token and
75
92
  * its raw nonce, or the `apple_token` handle from a `NEEDS_ACCOUNT` sign-in.
@@ -119,8 +136,8 @@ export type TeamSchedule = {
119
136
  team_id: string;
120
137
  /** Ordered by start time; defaults to `[]`. */
121
138
  schedule?: ScheduleItem[];
122
- /** 1–255 characters; omit for `Route for <team name>`. */
123
- name?: string | null;
139
+ /** 1–255 characters; omit for `Route for <team name>` (null is a 400). */
140
+ name?: string;
124
141
  /** Defaults to true. */
125
142
  optimize?: boolean;
126
143
  /** Upper-case `FrequencyType`; defaults to `ONCE`. */
@@ -242,24 +259,107 @@ export interface CheckIn {
242
259
  time_created: number | null;
243
260
  time_updated: number | null;
244
261
  }
245
- /** Wire shape for per-participant entries on an event update. */
262
+ /**
263
+ * Wire shape for per-participant entries on an event update. Null
264
+ * `time_started` resets it to the event's start; null `time_ended` clears it.
265
+ */
246
266
  export interface EventUserUpdate {
247
267
  user_id: string;
248
268
  time_started?: number | null;
249
269
  time_ended?: number | null;
250
270
  }
271
+ /** A task done at a route stop, with its in-route dependencies. */
272
+ export interface RouteStopTaskInput {
273
+ id: string;
274
+ /** Tasks that must be done first. */
275
+ depends_on?: string[];
276
+ }
277
+ /** One job stop of a route write (backend `RouteStop`), in route order. */
278
+ export interface RouteStopInput {
279
+ job_id: string;
280
+ /** The stop's tasks, as ids or `{id, depends_on}`; omitted means none. */
281
+ tasks?: (string | RouteStopTaskInput)[];
282
+ /** Pinned arrival (Unix seconds); -1 (the default) means not pinned. */
283
+ scheduled_arrival_time?: number;
284
+ /** Estimated arrival (Unix seconds); -1 (the default) means unknown. */
285
+ estimated_arrival_time?: number;
286
+ }
251
287
  /**
252
- * Route create/update payload. `optimize` explicitly requests an
253
- * optimizer run on this save; `is_optimized` itself is server-owned
254
- * (true only when the current order came from the optimizer).
288
+ * Route create/update payload (backend `CreateRoute` / `UpdateRoute`);
289
+ * omitted fields are unchanged. Null is accepted only for the endpoint
290
+ * coordinates, and only for both halves of an endpoint together (it clears
291
+ * that endpoint); `start_time`/`end_time` are unset with -1. `optimize`
292
+ * explicitly requests an optimizer run on this save; `is_optimized` itself
293
+ * is server-owned (true only when the current order came from the
294
+ * optimizer).
255
295
  */
256
- export type RouteWritePayload = Partial<Omit<Route, 'is_optimized'>> & {
296
+ export interface RouteWritePayload {
297
+ /** 1–255 characters; required on create. */
298
+ name?: string;
299
+ start_latitude?: number | null;
300
+ start_longitude?: number | null;
301
+ end_latitude?: number | null;
302
+ end_longitude?: number | null;
303
+ /** Unix seconds; -1 unsets it. */
304
+ start_time?: number;
305
+ /** Unix seconds; -1 unsets it. */
306
+ end_time?: number;
307
+ frequency?: FrequencyType;
308
+ /** Team GUIDs; replaces the route's teams (`[]` removes them). */
309
+ teams?: string[];
310
+ /** Replaces the route's stops (`[]` removes them). */
311
+ jobs?: RouteStopInput[];
257
312
  optimize?: boolean;
258
- };
259
- /** Event update payload: _Event fields, but users use the wire shape. */
260
- export type EventUpdatePayload = Partial<Omit<_Event, 'users'>> & {
313
+ }
314
+ /** An additional charge on an event write (backend `EventCharge`), upserted by `id`. */
315
+ export interface EventChargeInput {
316
+ /** An existing charge's id; omit (or null) to create a new charge. */
317
+ id?: string | null;
318
+ name?: string;
319
+ description?: string;
320
+ /** Unit price in integer cents. */
321
+ cost?: number;
322
+ /** Quantity (at least 1). */
323
+ amount?: number;
324
+ earned_revenue?: number;
325
+ }
326
+ /**
327
+ * Event create/update payload (backend `UpdateEvent`); omitted fields are
328
+ * unchanged. Only `team_id` is nullable (null clears the team; `''` is
329
+ * omitted by the SDK); null on any other field is a 400 (an ended event
330
+ * can't be re-opened). On a delay only the descriptive fields may be sent.
331
+ */
332
+ export interface EventUpdatePayload {
333
+ /** 1–254 characters. */
334
+ name?: string;
335
+ internal_notes?: string;
336
+ external_notes?: string;
337
+ description?: string;
338
+ /** Names of existing images to copy onto the event. */
339
+ images?: string[];
340
+ team_id?: string | null;
341
+ status?: LineItemStatus;
342
+ /** Alias of `time_started`; wins when both are sent. */
343
+ start?: number;
344
+ /** Restarts the event (at this time when client start times are trusted). */
345
+ time_started?: number;
346
+ /** Alias of `time_ended`; wins when both are sent. */
347
+ end?: number;
348
+ /** Ends the event (at this time when client stop times are trusted). */
349
+ time_ended?: number;
350
+ task_names?: string[];
351
+ /** Task GUIDs; replaces the event's tasks. */
352
+ tasks?: string[];
353
+ /** Unit price in integer cents. */
354
+ cost?: number;
355
+ /** Quantity (at least 1). */
356
+ amount?: number;
357
+ earned_revenue?: number;
358
+ /** Replaces the event's charges (upserting by `id`). */
359
+ additional_charges?: EventChargeInput[];
360
+ /** Replaces the event's participants. */
261
361
  users?: EventUserUpdate[];
262
- };
362
+ }
263
363
  /**
264
364
  * Wire payload for logging a delay (POST /job/{job_id}/delay).
265
365
  *
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "1.6.4-rc3";
1
+ export declare const AVRO_JS_VERSION = "1.6.4-rc4";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // AUTO-GENERATED by scripts/gen-version.js — do not edit by hand.
2
2
  // Regenerated from package.json by the `prebuild` npm hook.
3
- export const AVRO_JS_VERSION = '1.6.4-rc3';
3
+ export const AVRO_JS_VERSION = '1.6.4-rc4';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "1.6.4-rc3",
3
+ "version": "1.6.4-rc4",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",