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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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, 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';
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, Permission, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogIndustry, 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, BreakWritePayload, CatalogItemCreatePayload, CatalogItemUpdatePayload, CompanyCreatePayload, CompanyUpdatePayload, EventCreatePayload, IntuitImportResult, MemberAddPayload, MemberUpdatePayload, PayoutStatusFilter, ProposalReviewPayload, ProposalWritePayload, SessionCreatePayload, SessionUpdatePayload, SkillCreatePayload, SkillUpdatePayload, TeamWritePayload, UserCreatePayload, UserUpdatePayload } from './requests.js';
14
+ import type { BillWritePayload, BreakWritePayload, CatalogItemCreatePayload, CatalogItemUpdatePayload, CompanyCreatePayload, CompanyUpdatePayload, EventCreatePayload, IntuitSyncStatus, 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;
@@ -252,6 +252,12 @@ declare module './QueryClient.js' {
252
252
  useGetRoute(routeId: string): UseQueryResult<Route, StandardError>;
253
253
  useGetChat(chatId: string): UseQueryResult<Chat, StandardError>;
254
254
  useGetCatalogItem(catalogItemId: string): UseQueryResult<CatalogItem, StandardError>;
255
+ useGetCatalogItems(body?: {
256
+ query?: string;
257
+ industry?: CatalogIndustry;
258
+ archived?: boolean;
259
+ companyId?: string;
260
+ }): UseQueryResult<CatalogItem[], StandardError>;
255
261
  useGetUserSessions(): UseQueryResult<Session[], StandardError>;
256
262
  useGetCompanySessionsByIds(sessionIds: string[], params?: {
257
263
  companyId?: string;
@@ -280,6 +286,15 @@ declare module './QueryClient.js' {
280
286
  msg: string;
281
287
  cleared: number;
282
288
  }, StandardError, void>>;
289
+ /**
290
+ * Root only: run scheduled jobs now (all of them when called with no
291
+ * ids). The scheduler starts them within a few seconds; watch their
292
+ * status in `useGetPerformanceMetrics`.
293
+ */
294
+ useRunSchedulerJobs(): ReturnType<typeof useMutation<{
295
+ msg: string;
296
+ jobs: string[];
297
+ }, StandardError, string[] | void>>;
283
298
  useSearchUsers(searchUsername: string): UseQueryResult<User[], StandardError>;
284
299
  useMergeUsersPreview(keepId: string, duplicateId: string): UseQueryResult<UserMergeSummary, StandardError>;
285
300
  useMergeUsers(): ReturnType<typeof useMutation<UserMergeSummary, StandardError, {
@@ -477,7 +492,11 @@ declare module './QueryClient.js' {
477
492
  id: string | null;
478
493
  job_id: string | null;
479
494
  }>;
480
- useImportBillsFromIntuit(): ReturnType<typeof useMutation<IntuitImportResult, StandardError, void>>;
495
+ useImportBillsFromIntuit(): ReturnType<typeof useMutation<{
496
+ msg: string;
497
+ }, StandardError, void>>;
498
+ /** The company's QuickBooks sync as its socket events report it. */
499
+ useIntuitSyncStatus(): IntuitSyncStatus;
481
500
  useSyncBillToIntuit(): ReturnType<typeof useMutation<{
482
501
  msg: string;
483
502
  }, StandardError, {
@@ -605,6 +624,8 @@ declare module './QueryClient.js' {
605
624
  user_ids?: string[];
606
625
  enabled?: boolean;
607
626
  }): UseQueryResult<UserCompanyAssociation[], StandardError>;
627
+ /** Whether the viewer's membership grants `permission`; undefined until known. */
628
+ useHasPermission(permission: Permission): boolean | undefined;
608
629
  useReportDevice(): ReturnType<typeof useMutation<Device, StandardError, DeviceInfo & {
609
630
  location_status?: LocationServicesStatus;
610
631
  }>>;
@@ -1141,6 +1162,16 @@ export declare class AvroQueryClient {
1141
1162
  query?: string;
1142
1163
  offset?: number;
1143
1164
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1165
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1166
+ fetchCatalogItems(body?: {
1167
+ amt?: number;
1168
+ unknown_ids?: string[];
1169
+ query?: string;
1170
+ offset?: number;
1171
+ industry?: CatalogIndustry;
1172
+ /** Only archived (`true`) or active (`false`) items; both if unset. */
1173
+ archived?: boolean;
1174
+ }, companyId?: string | undefined, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<CatalogItem[]>;
1144
1175
  fetchSkills(body?: {
1145
1176
  amt?: number;
1146
1177
  known_ids?: string[];
@@ -7,7 +7,7 @@ import { LoginResponse, } from '../types/api.js';
7
7
  import { AuthState } from '../types/auth.js';
8
8
  import { StandardError } from '../types/error.js';
9
9
  import { withoutEmpty } from './wire.js';
10
- import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, } from './realtime.js';
10
+ import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, retryDenied, } from './realtime.js';
11
11
  import { QueryPersister } from './persist.js';
12
12
  /** Keep the original status (401/403/404/0…) when surfacing a list-fetch failure. */
13
13
  function fetchError(err, context) {
@@ -319,9 +319,14 @@ export class AvroQueryClient {
319
319
  }
320
320
  applier.apply(payload);
321
321
  });
322
+ // Sent to each member whose access changed (a grant, a group
323
+ // join/leave, or an edit to one of their groups): rejoin, and
324
+ // retry whatever the old permissions were refused.
322
325
  on('rejoin_company', (data) => {
323
- if (data?.company_id && data.company_id === this.companyId)
326
+ if (data?.company_id && data.company_id === this.companyId) {
324
327
  this.joinCompanyRoom();
328
+ retryDenied(queryClient);
329
+ }
325
330
  });
326
331
  // Sent before a chat room is closed after a membership change;
327
332
  // the server re-checks membership, so removed members stay out.
@@ -391,12 +396,15 @@ export class AvroQueryClient {
391
396
  patchTeamLocation(queryClient, data);
392
397
  patchMemberLocation(queryClient, data);
393
398
  });
394
- // schedule_locked lives in a Redis lock, not a row.
399
+ // schedule_locked and intuit_sync_locked live in Redis locks, not rows.
395
400
  for (const event of [
396
401
  'schedule_started',
397
402
  'schedule_complete',
398
403
  'scheduling_error',
399
404
  'schedule_adjustments',
405
+ 'intuit_sync_started',
406
+ 'intuit_sync_complete',
407
+ 'intuit_sync_error',
400
408
  ]) {
401
409
  on(event, () => {
402
410
  queryClient.invalidateQueries({ queryKey: ['companies'] });
@@ -1324,6 +1332,26 @@ export class AvroQueryClient {
1324
1332
  throw fetchError(err, 'Failed to fetch groups');
1325
1333
  });
1326
1334
  }
1335
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1336
+ fetchCatalogItems(body = {}, companyId = this.companyId, cancelToken, headers = {}) {
1337
+ if (!companyId || companyId.trim() === '') {
1338
+ throw new StandardError(400, 'Company ID is required');
1339
+ }
1340
+ return this._fetch('POST', `/company/${companyId}/catalog_items`, JSON.stringify(body), cancelToken, {
1341
+ ...headers,
1342
+ 'Content-Type': 'application/json',
1343
+ }, true)
1344
+ .then((response) => {
1345
+ if (!response || !Array.isArray(response)) {
1346
+ throw new StandardError(400, 'Invalid catalog items response');
1347
+ }
1348
+ return response;
1349
+ })
1350
+ .catch((err) => {
1351
+ console.error('Failed to fetch catalog items:', err);
1352
+ throw fetchError(err, 'Failed to fetch catalog items');
1353
+ });
1354
+ }
1327
1355
  fetchSkills(body = {}, cancelToken, headers = {}) {
1328
1356
  if (!this.companyId || this.companyId.trim() === '') {
1329
1357
  throw new StandardError(400, 'Company ID is required');
@@ -45,3 +45,16 @@ AvroQueryClient.prototype.useClearErrorLog = function () {
45
45
  },
46
46
  });
47
47
  };
48
+ AvroQueryClient.prototype.useRunSchedulerJobs = function () {
49
+ const queryClient = this.getQueryClient();
50
+ return useMutation({
51
+ mutationFn: (jobIds) => this.post({
52
+ path: '/avro/scheduler/run',
53
+ data: JSON.stringify(jobIds ? { job_ids: jobIds } : {}),
54
+ headers: { 'Content-Type': 'application/json' },
55
+ }),
56
+ onSuccess: () => {
57
+ queryClient.invalidateQueries({ queryKey: ['avro', 'performance'] });
58
+ },
59
+ });
60
+ };
@@ -1,4 +1,5 @@
1
1
  import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
+ import { useEffect, useState } from 'react';
2
3
  import { AvroQueryClient } from '../QueryClient.js';
3
4
  import { seedDetails } from '../cache.js';
4
5
  import { restoreNs, snapshotNs } from '../cache.js';
@@ -221,16 +222,40 @@ AvroQueryClient.prototype.useSyncBillToIntuit = function () {
221
222
  AvroQueryClient.prototype.useImportBillsFromIntuit = function () {
222
223
  const queryClient = this.getQueryClient();
223
224
  return useMutation({
225
+ // Starts the sync (202); follow it with useIntuitSyncStatus.
224
226
  mutationFn: async () => {
225
227
  return this.post({
226
228
  path: `/company/${this.companyId}/intuit/import`,
227
229
  });
228
230
  },
229
- onSuccess: () => {
230
- this.syncAfterMutation('bill');
231
- },
232
231
  });
233
232
  };
233
+ /**
234
+ * The company's QuickBooks sync, followed over the socket: `running` (with the
235
+ * latest progress) from `intuit_sync_started` on, then `complete` with the
236
+ * counts or `error`. Every staff member sees a run, whoever started it; the
237
+ * bills it changes arrive through the changes stream.
238
+ */
239
+ AvroQueryClient.prototype.useIntuitSyncStatus = function () {
240
+ const [status, setStatus] = useState({ state: 'idle' });
241
+ useEffect(() => {
242
+ const started = () => setStatus({ state: 'running' });
243
+ const progress = (data) => setStatus({ state: 'running', progress: data });
244
+ const complete = (data) => setStatus({ state: 'complete', result: data });
245
+ const failed = (data) => setStatus({ state: 'error', message: data?.msg ?? 'QuickBooks sync failed' });
246
+ this.on('intuit_sync_started', started);
247
+ this.on('intuit_sync_progress', progress);
248
+ this.on('intuit_sync_complete', complete);
249
+ this.on('intuit_sync_error', failed);
250
+ return () => {
251
+ this.off('intuit_sync_started', started);
252
+ this.off('intuit_sync_progress', progress);
253
+ this.off('intuit_sync_complete', complete);
254
+ this.off('intuit_sync_error', failed);
255
+ };
256
+ }, [this]);
257
+ return status;
258
+ };
234
259
  AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId }) {
235
260
  return this.get({
236
261
  path: `/company/${this.companyId}/bill/${billId}/pdf`,
@@ -1,6 +1,7 @@
1
1
  import { useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs } from '../cache.js';
4
+ import { keys } from '../realtime.js';
4
5
  import { StandardError } from '../../types/error.js';
5
6
  AvroQueryClient.prototype.useCreateCatalogItem = function () {
6
7
  const queryClient = this.getQueryClient();
@@ -87,11 +88,11 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
87
88
  AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
88
89
  return useQuery({
89
90
  queryKey: ['catalog_items', catalogItemId],
90
- // There is no `GET /catalog_item/<id>`: catalog items are embedded
91
- // in the company payload.
92
91
  queryFn: async () => {
93
- const company = await this.get({ path: `/company/${this.companyId}` });
94
- const item = company?.catalog_items?.find((ci) => ci.id === catalogItemId);
92
+ const [item] = await this.fetchCatalogItems({
93
+ unknown_ids: [catalogItemId],
94
+ amt: 1,
95
+ });
95
96
  if (!item)
96
97
  throw new StandardError(404, 'Catalog item not found');
97
98
  return item;
@@ -99,6 +100,17 @@ AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
99
100
  enabled: Boolean(catalogItemId) && Boolean(this.companyId),
100
101
  });
101
102
  };
103
+ AvroQueryClient.prototype.useGetCatalogItems = function (body = {}) {
104
+ const { companyId: bodyCompanyId, ...filters } = body;
105
+ const companyId = bodyCompanyId ?? this.companyId;
106
+ return useQuery({
107
+ // `industry` / `archived` stay absent when unset so list patching
108
+ // reads them as "no filter".
109
+ queryKey: keys.list('catalog_items', companyId, { query: '', ...filters }),
110
+ queryFn: () => this.fetchCatalogItems(filters, companyId),
111
+ enabled: Boolean(companyId),
112
+ });
113
+ };
102
114
  AvroQueryClient.prototype.useDeleteCatalogItem = function () {
103
115
  const queryClient = this.getQueryClient();
104
116
  return useMutation({
@@ -2,7 +2,10 @@ import { useMutation, useQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs } from '../cache.js';
4
4
  import { keys } from '../realtime.js';
5
+ import { Permission } from '../../types/api.js';
5
6
  AvroQueryClient.prototype.useGetTeams = function (body, total, onProgress) {
7
+ // Customers and roles without team read get a 403; don't ask.
8
+ const canReadTeams = this.useHasPermission(Permission.CAN_READ_TEAMS);
6
9
  return useQuery({
7
10
  queryKey: keys.list('teams', this.companyId, {
8
11
  amt: body.amt ?? 50,
@@ -30,7 +33,7 @@ AvroQueryClient.prototype.useGetTeams = function (body, total, onProgress) {
30
33
  const teams = pages.flat();
31
34
  return teams;
32
35
  },
33
- enabled: Boolean(this.companyId),
36
+ enabled: Boolean(this.companyId) && canReadTeams !== false,
34
37
  });
35
38
  };
36
39
  AvroQueryClient.prototype.useCreateTeam = function () {
@@ -228,3 +228,16 @@ AvroQueryClient.prototype.useGetCompanyUsers = function (body = {}) {
228
228
  staleTime: 30000,
229
229
  });
230
230
  };
231
+ /**
232
+ * Whether the signed-in user's membership in the current company grants
233
+ * `permission`, directly or through a group: the check the backend makes
234
+ * before answering. `undefined` until the membership has loaded, so callers
235
+ * choose how to treat "not known yet"; gate a query with `!== false` to only
236
+ * skip it once the permission is known to be missing.
237
+ */
238
+ AvroQueryClient.prototype.useHasPermission = function (permission) {
239
+ const { data: self } = this.useGetSelf();
240
+ const { data: members } = this.useGetCompanyUsers();
241
+ const me = members?.find((member) => member.user?.id === self?.id);
242
+ return me ? (me.effective_permissions ?? []).includes(permission) : undefined;
243
+ };
@@ -58,6 +58,13 @@ export declare function removeEntity(qc: QueryClient, ns: string, id: string): v
58
58
  export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any, company?: string | null): void;
59
59
  export declare function matchesList(type: string, key: readonly unknown[], item: any): ListMatch;
60
60
  export declare function invalidateType(qc: QueryClient, spec: EntitySpec): void;
61
+ /**
62
+ * Refetch every query the server refused with a 403. Called when a
63
+ * membership changes: the viewer may have just been granted the
64
+ * permission, and nothing else would retry a denied list until the next
65
+ * focus, remount, or reload.
66
+ */
67
+ export declare function retryDenied(qc: QueryClient): void;
61
68
  export declare class ChangeApplier {
62
69
  private client;
63
70
  private qc;
@@ -72,6 +72,15 @@ function matchJobs(filters, item) {
72
72
  }
73
73
  return searchAware(filters);
74
74
  }
75
+ function matchCatalogItems(filters, item) {
76
+ if (typeof filters.industry === 'string' && filters.industry !== item.industry) {
77
+ return 'nomatch';
78
+ }
79
+ if (typeof filters.archived === 'boolean' && filters.archived !== item.archived) {
80
+ return 'nomatch';
81
+ }
82
+ return searchAware(filters);
83
+ }
75
84
  function isPaidStatus(status) {
76
85
  return status === 'PAID' || status === 'PREPAID' || status === 'EXTERNALLY_PAID';
77
86
  }
@@ -233,11 +242,10 @@ export const REGISTRY = {
233
242
  listMatch: searchAware,
234
243
  alsoInvalidate: COMPANY_EMBEDS,
235
244
  },
236
- // No single-item GET exists: catalog items only live on the company.
237
245
  catalog_item: {
238
246
  ns: 'catalog_items',
239
- invalidateOnly: true,
240
- alsoInvalidate: COMPANY_EMBEDS,
247
+ fetchMany: bulk('fetchCatalogItems'),
248
+ listMatch: matchCatalogItems,
241
249
  },
242
250
  proposal: {
243
251
  ns: 'proposals',
@@ -373,6 +381,18 @@ export function invalidateType(qc, spec) {
373
381
  qc.invalidateQueries({ queryKey: [spec.ns] });
374
382
  spec.alsoInvalidate?.forEach((k) => qc.invalidateQueries({ queryKey: [...k] }));
375
383
  }
384
+ /**
385
+ * Refetch every query the server refused with a 403. Called when a
386
+ * membership changes: the viewer may have just been granted the
387
+ * permission, and nothing else would retry a denied list until the next
388
+ * focus, remount, or reload.
389
+ */
390
+ export function retryDenied(qc) {
391
+ qc.invalidateQueries({
392
+ predicate: (q) => q.state.status === 'error' &&
393
+ q.state.error?.status === 403,
394
+ });
395
+ }
376
396
  // ─── Applying batches ───────────────────────────────────────────────
377
397
  const FETCH_COALESCE_MS = 50;
378
398
  const FETCH_CHUNK = 100;
@@ -425,6 +445,8 @@ export class ChangeApplier {
425
445
  continue;
426
446
  if (entry.op === 'invalidate' || spec.invalidateOnly) {
427
447
  invalidateType(this.qc, spec);
448
+ if (entry.type === 'member')
449
+ retryDenied(this.qc);
428
450
  if (spec.ns === 'users' && entry.id) {
429
451
  this.qc.invalidateQueries({ queryKey: keys.detail('users', entry.id) });
430
452
  }
@@ -229,14 +229,41 @@ export interface BillWritePayload {
229
229
  enabled_payment_methods?: PaymentType[];
230
230
  pass_on_fees?: boolean;
231
231
  }
232
- /** Response of `POST /company/<id>/intuit/import` (backend `IntuitImportResult`). */
232
+ /** Counts a finished QuickBooks sync reports (the `intuit_sync_complete` payload). */
233
233
  export interface IntuitImportResult {
234
234
  msg: string;
235
235
  imported: number;
236
236
  skipped: number;
237
237
  payments_imported: number;
238
238
  payments_skipped: number;
239
+ /** Avro bills sent to QuickBooks as new invoices. */
240
+ pushed: number;
241
+ /** Avro payments sent to QuickBooks. */
242
+ payments_pushed: number;
243
+ /** Bills QuickBooks refused; they retry on the next sync. */
244
+ push_failed: number;
239
245
  }
246
+ /** A sync's phases, in order: send to QuickBooks, import invoices, import payments. */
247
+ export type IntuitSyncPhase = 'push' | 'import' | 'payments';
248
+ /** An `intuit_sync_progress` payload: `done` of `total` items in `phase`. */
249
+ export interface IntuitSyncProgress {
250
+ phase: IntuitSyncPhase;
251
+ done: number;
252
+ total: number;
253
+ }
254
+ /** The company's QuickBooks sync as its socket events report it. */
255
+ export type IntuitSyncStatus = {
256
+ state: 'idle';
257
+ } | {
258
+ state: 'running';
259
+ progress?: IntuitSyncProgress;
260
+ } | {
261
+ state: 'complete';
262
+ result: IntuitImportResult;
263
+ } | {
264
+ state: 'error';
265
+ message: string;
266
+ };
240
267
  /**
241
268
  * A payment option on a catalog item write (backend `CreatePaymentOption`).
242
269
  * Prices are integer cents.
@@ -266,6 +293,7 @@ export interface CatalogItemUpdatePayload {
266
293
  industry?: CatalogIndustry | (string & {});
267
294
  /** A `CatalogPriceFormat` name, matched like `industry`. */
268
295
  price_format?: CatalogPriceFormat | (string & {});
296
+ archived?: boolean;
269
297
  /** Integer seconds between services; null clears it. */
270
298
  recommended_frequency?: number | null;
271
299
  /** Unix seconds (>= 0); null clears it. */
@@ -274,6 +302,8 @@ export interface CatalogItemUpdatePayload {
274
302
  recommended_expire_on?: number | null;
275
303
  /** Skill GUIDs; replaces the item's skills. */
276
304
  skills?: string[];
305
+ /** ProposalTerms GUIDs; replaces the item's suggested terms. */
306
+ terms?: string[];
277
307
  /** Replaces the item's payment options. */
278
308
  payment_options?: PaymentOptionInput[];
279
309
  }
@@ -284,7 +314,7 @@ export type CatalogItemCreatePayload = CatalogItemUpdatePayload & {
284
314
  /**
285
315
  * Body of `POST /job/<id>/proposal` and `PUT /proposal/<id>` (backend
286
316
  * `CreateProposal` / `UpdateProposal`); omitted fields are unchanged, and
287
- * null clears `expire_on` / `terms_version_id` / `prepay_due_date`.
317
+ * null clears `expire_on` / `prepay_due_date`.
288
318
  */
289
319
  export interface ProposalWritePayload {
290
320
  /**
@@ -292,8 +322,8 @@ export interface ProposalWritePayload {
292
322
  * null means never.
293
323
  */
294
324
  expire_on?: number | null;
295
- /** Terms version GUID; null detaches. */
296
- terms_version_id?: string | null;
325
+ /** Terms version GUIDs; replaces the attached terms (`[]` detaches all). */
326
+ terms_version_ids?: string[];
297
327
  /** Unix seconds (>= 0); null clears. */
298
328
  prepay_due_date?: number | null;
299
329
  /** Replaces the proposal's tasks (only `id` is read). */
@@ -329,8 +359,11 @@ export interface ProposalReviewTask {
329
359
  /** Body of `POST /proposal/<id>/review` (backend `ReviewProposal`). */
330
360
  export interface ProposalReviewPayload {
331
361
  tasks?: ProposalReviewTask[];
332
- /** Required when the proposal has terms and any task is accepted. */
333
- terms_version_id?: string | null;
362
+ /**
363
+ * The terms version GUIDs agreed to; must be exactly the proposal's when
364
+ * it has terms and any task is accepted.
365
+ */
366
+ terms_version_ids?: string[];
334
367
  pay_in_cash?: boolean;
335
368
  }
336
369
  /**
@@ -88,11 +88,55 @@ export interface PerformanceSample {
88
88
  memory_percent: number;
89
89
  }[];
90
90
  }
91
+ /** A live scheduler process (`avro scheduler-worker`). */
92
+ export interface SchedulerWorker {
93
+ /** `<hostname>:<pid>` of the scheduler process. */
94
+ worker: string;
95
+ /** Unix seconds of the last heartbeat. */
96
+ time: number;
97
+ /** Unix seconds when the process started its scheduler. */
98
+ started_at: number;
99
+ }
100
+ /**
101
+ * Latest run state of a scheduled job. `pending` until its first run since
102
+ * the worker started; `locked` when the last run skipped because another
103
+ * process held the job's Redis lock. A run skipped because the previous one
104
+ * is still going leaves it `running` and sets `last_skipped`.
105
+ */
106
+ export type SchedulerJobStatus = 'pending' | 'running' | 'ok' | 'error' | 'missed' | 'locked';
107
+ /** A scheduled job and its latest run (times are Unix seconds). */
108
+ export interface SchedulerJob {
109
+ /** The job's function name, e.g. `update_routes`. */
110
+ id: string;
111
+ /** E.g. `cron[hour='1', minute='0', second='0']`. */
112
+ trigger: string | null;
113
+ status: SchedulerJobStatus | null;
114
+ next_run_time: number | null;
115
+ last_started: number | null;
116
+ last_finished: number | null;
117
+ last_success: number | null;
118
+ last_skipped: number | null;
119
+ /** Last run skipped because another process held the job's lock. */
120
+ last_locked: number | null;
121
+ /** The Redis lock that was held on the last `locked` run. */
122
+ lock_name: string | null;
123
+ /** Of the last finished run. */
124
+ duration_seconds: number | null;
125
+ last_error: string | null;
126
+ last_error_time: number | null;
127
+ }
128
+ /** Scheduler health: live processes and every job's latest run. */
129
+ export interface PerformanceScheduler {
130
+ /** Empty when no scheduler process is alive. */
131
+ workers: SchedulerWorker[];
132
+ jobs: SchedulerJob[];
133
+ }
91
134
  /** Response of GET /avro/performance (root only). */
92
135
  export interface PerformanceMetrics {
93
136
  current: {
94
137
  database: PerformanceDatabase;
95
138
  fleet: PerformanceFleet;
139
+ scheduler: PerformanceScheduler;
96
140
  };
97
141
  /** Oldest first. */
98
142
  samples: PerformanceSample[];
@@ -108,11 +152,15 @@ export interface ClientErrorReport {
108
152
  route?: string;
109
153
  extra?: Record<string, unknown>;
110
154
  }
111
- /** One entry in the admin error log (backend errors and client crashes). */
155
+ /**
156
+ * One entry in the admin error log (backend errors, client crashes and
157
+ * scheduler job failures). Scheduler entries carry no request context:
158
+ * `endpoint` is the job id and the request fields are absent.
159
+ */
112
160
  export interface ErrorLogEntry {
113
161
  id: string;
114
162
  time: number;
115
- source: 'backend' | 'app' | 'web';
163
+ source: 'backend' | 'app' | 'web' | 'scheduler';
116
164
  /** HTTP status; absent from client reports. */
117
165
  status?: number | null;
118
166
  message: string | null;
@@ -123,22 +171,20 @@ export interface ErrorLogEntry {
123
171
  app_version?: string | null;
124
172
  update_id?: string | null;
125
173
  route?: string | null;
126
- method: string;
127
- path: string;
128
- endpoint: string | null;
129
- client_id: string | null;
130
- client_version: string | null;
131
- js_version: string | null;
132
- user_agent: string | null;
133
- remote_addr: string | null;
134
- forwarded_for: string | null;
135
- source_ip: string | null;
136
- /** A string when the stored value was too long and was truncated to its JSON text. */
137
- user: {
174
+ method?: string | null;
175
+ path?: string | null;
176
+ endpoint?: string | null;
177
+ client_id?: string | null;
178
+ client_version?: string | null;
179
+ js_version?: string | null;
180
+ user_agent?: string | null;
181
+ remote_addr?: string | null;
182
+ forwarded_for?: string | null;
183
+ source_ip?: string | null;
184
+ user?: {
138
185
  id: string;
139
186
  username: string;
140
187
  is_paying?: boolean | null;
141
188
  } | string | null;
142
- /** A string when the stored value was too long and was truncated to its JSON text. */
143
189
  extra?: Record<string, unknown> | string | null;
144
190
  }
@@ -8,12 +8,14 @@ export interface CatalogItem {
8
8
  description: string;
9
9
  industry: CatalogIndustry;
10
10
  price_format: CatalogPriceFormat;
11
+ /** Hidden from new proposals and the public catalog; kept for tasks. */
12
+ archived: boolean;
11
13
  payment_options: PaymentOption[];
12
14
  recommended_frequency: number | null;
13
15
  recommended_activate_on: number | null;
14
16
  recommended_expire_on: number | null;
15
17
  time_created: number | null;
16
18
  time_updated: number | null;
17
- /** Skill GUIDs. */
18
19
  skills: string[];
20
+ terms: string[];
19
21
  }
@@ -6,7 +6,6 @@ import { PaymentType } from './PaymentType.js';
6
6
  import { Plan } from './Plan.js';
7
7
  import { PlanPayment } from './PlanPayment.js';
8
8
  import { Skill } from './Skill.js';
9
- import { CatalogItem } from './CatalogItem.js';
10
9
  export interface Company {
11
10
  id: string;
12
11
  name: string;
@@ -14,7 +13,6 @@ export interface Company {
14
13
  address: string;
15
14
  emails: Email[];
16
15
  skills: Skill[];
17
- catalog_items: CatalogItem[];
18
16
  time_created: number | null;
19
17
  time_updated: number | null;
20
18
  /** Null without `can_read_company`. */
@@ -44,6 +42,8 @@ export interface Company {
44
42
  num_routes: number;
45
43
  schedule_locked: boolean;
46
44
  schedule_locked_since: number | null;
45
+ /** A QuickBooks sync is running; another can't start until it ends. */
46
+ intuit_sync_locked: boolean;
47
47
  num_teams: number;
48
48
  num_skills: number;
49
49
  /** Legacy key, always empty. */
@@ -6,7 +6,7 @@ export interface Proposal {
6
6
  job_id: string;
7
7
  expire_on: number | null;
8
8
  expired: boolean;
9
- terms: ProposalTermsVersion | null;
9
+ terms: ProposalTermsVersion[];
10
10
  accepted_at: number | null;
11
11
  tasks: Task[];
12
12
  }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "1.6.6-rc1";
1
+ export declare const AVRO_JS_VERSION = "1.6.6-rc10";
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.6-rc1';
3
+ export const AVRO_JS_VERSION = '1.6.6-rc10';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "1.6.6-rc1",
3
+ "version": "1.6.6-rc10",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",