@go-avro/avro-js 1.6.6-rc2 → 1.6.6-rc20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/chat.d.ts +25 -0
  2. package/dist/chat.js +47 -0
  3. package/dist/client/QueryClient.d.ts +125 -28
  4. package/dist/client/QueryClient.js +107 -60
  5. package/dist/client/cache.d.ts +4 -0
  6. package/dist/client/cache.js +19 -0
  7. package/dist/client/core/uploads.js +226 -0
  8. package/dist/client/hooks/avro.js +13 -0
  9. package/dist/client/hooks/bills.js +43 -16
  10. package/dist/client/hooks/catalog_items.js +16 -4
  11. package/dist/client/hooks/chats.js +26 -0
  12. package/dist/client/hooks/devices.js +17 -3
  13. package/dist/client/hooks/messages.js +54 -1
  14. package/dist/client/hooks/routes.js +4 -1
  15. package/dist/client/hooks/teams.js +8 -2
  16. package/dist/client/hooks/{proposal_terms.js → terms.js} +14 -14
  17. package/dist/client/hooks/users.js +13 -0
  18. package/dist/client/realtime.d.ts +26 -3
  19. package/dist/client/realtime.js +93 -16
  20. package/dist/client/requests.d.ts +39 -6
  21. package/dist/index.d.ts +4 -1
  22. package/dist/index.js +3 -1
  23. package/dist/types/api/AuditLog.d.ts +1 -1
  24. package/dist/types/api/Avro.d.ts +66 -15
  25. package/dist/types/api/CatalogItem.d.ts +3 -1
  26. package/dist/types/api/Company.d.ts +2 -2
  27. package/dist/types/api/Job.js +11 -2
  28. package/dist/types/api/MemberState.d.ts +3 -0
  29. package/dist/types/api/Notification.d.ts +39 -0
  30. package/dist/types/api/Proposal.d.ts +2 -2
  31. package/dist/types/api/Task.d.ts +8 -0
  32. package/dist/types/api/Task.js +30 -3
  33. package/dist/types/api/{ProposalTerms.d.ts → Terms.d.ts} +3 -3
  34. package/dist/types/api/Terms.js +1 -0
  35. package/dist/types/api.d.ts +1 -1
  36. package/dist/types/api.js +1 -1
  37. package/dist/types/client.d.ts +125 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/package.json +1 -1
  41. /package/dist/client/{hooks/proposal_terms.d.ts → core/uploads.d.ts} +0 -0
  42. /package/dist/{types/api/ProposalTerms.js → client/hooks/terms.d.ts} +0 -0
package/dist/chat.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { Chat } from './types/api/Chat.js';
2
+ import { Reaction } from './types/api/Reaction.js';
3
+ /** The quick-pick reactions, as Unicode code points: 👍 ❤️ 😂 😮 😢 🙏. */
4
+ export declare const REACTION_CODE_POINTS: readonly [128077, 10084, 128514, 128558, 128546, 128591];
5
+ /**
6
+ * Render a reaction's code point. Older symbols (❤, ☺) default to text
7
+ * presentation, so they get the emoji variation selector.
8
+ */
9
+ export declare function reactionGlyph(codePoint: number): string;
10
+ export interface ReactionGroup {
11
+ reaction: number;
12
+ count: number;
13
+ /** Ids of the users who reacted, in reaction order. */
14
+ userIds: string[];
15
+ mine: boolean;
16
+ }
17
+ /** Group a message's reactions by emoji, in first-reacted order. */
18
+ export declare function groupReactions(reactions: Reaction[], selfId?: string): ReactionGroup[];
19
+ /** When a message was sent, preferring the server's clock. */
20
+ export declare function messageTime(message: {
21
+ time_created: number | null;
22
+ time_sent: number;
23
+ }): number;
24
+ /** Whether `chat` has a message from someone else the caller hasn't read. */
25
+ export declare function isChatUnread(chat: Chat, selfId?: string): boolean;
package/dist/chat.js ADDED
@@ -0,0 +1,47 @@
1
+ /** The quick-pick reactions, as Unicode code points: 👍 ❤️ 😂 😮 😢 🙏. */
2
+ export const REACTION_CODE_POINTS = [0x1f44d, 0x2764, 0x1f602, 0x1f62e, 0x1f622, 0x1f64f];
3
+ /**
4
+ * Render a reaction's code point. Older symbols (❤, ☺) default to text
5
+ * presentation, so they get the emoji variation selector.
6
+ */
7
+ export function reactionGlyph(codePoint) {
8
+ try {
9
+ const glyph = String.fromCodePoint(codePoint);
10
+ return codePoint < 0x1f000 ? `${glyph}️` : glyph;
11
+ }
12
+ catch {
13
+ return '';
14
+ }
15
+ }
16
+ /** Group a message's reactions by emoji, in first-reacted order. */
17
+ export function groupReactions(reactions, selfId) {
18
+ const groups = new Map();
19
+ for (const r of reactions ?? []) {
20
+ let group = groups.get(r.reaction);
21
+ if (!group) {
22
+ group = { reaction: r.reaction, count: 0, userIds: [], mine: false };
23
+ groups.set(r.reaction, group);
24
+ }
25
+ if (group.userIds.includes(r.sender_id))
26
+ continue;
27
+ group.userIds.push(r.sender_id);
28
+ group.count += 1;
29
+ if (r.sender_id === selfId)
30
+ group.mine = true;
31
+ }
32
+ return [...groups.values()];
33
+ }
34
+ /** When a message was sent, preferring the server's clock. */
35
+ export function messageTime(message) {
36
+ return message.time_created ?? (message.time_sent > 0 ? message.time_sent : 0);
37
+ }
38
+ /** Whether `chat` has a message from someone else the caller hasn't read. */
39
+ export function isChatUnread(chat, selfId) {
40
+ const last = chat.last_message;
41
+ if (!last || !selfId || last.sender_id === selfId)
42
+ return false;
43
+ const me = chat.user_state.find((m) => m.id === selfId);
44
+ if (!me)
45
+ return false;
46
+ return me.last_message_read_at == null || me.last_message_read_at < messageTime(last);
47
+ }
@@ -1,18 +1,19 @@
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, MemberState, Permission, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogIndustry, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus, CreateNotificationPayload, NotificationCreated, SendEmailPayload } from '../types/api.js';
5
5
  import { AuthState, Tokens } from '../types/auth.js';
6
- import { CancelToken, ClientId, RetryStrategy } from '../types/client.js';
6
+ import { CancelToken, ClientId, RetryStrategy, EventPhotoLinks, EventPhotoLinksVars, PdfSource, SendBillEmailVars, SendEmailMessageVars, SendNotificationVars, ImageTarget, UploadImage, UploadImagesOptions, UploadImagesResult, UploadImagesVars } from '../types/client.js';
7
7
  import { StandardError } from '../types/error.js';
8
8
  import { CacheData } from '../types/cache.js';
9
9
  import { Waiver } from '../types/api/Waiver.js';
10
10
  import { Proposal } from '../types/api/Proposal.js';
11
- import { ProposalTerms } from '../types/api/ProposalTerms.js';
11
+ import { Terms } from '../types/api/Terms.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
+ import { type NsSnapshot } from './cache.js';
16
17
  export interface TrackEmailOptions {
17
18
  emailType?: EmailType;
18
19
  requestId?: string;
@@ -39,6 +40,50 @@ declare module './QueryClient.js' {
39
40
  _fetch<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number): Promise<T>;
40
41
  getDelay(strategy: RetryStrategy, attempt: number): number;
41
42
  sleep(ms: number): Promise<void>;
43
+ _uploadImages(base: string, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
44
+ /**
45
+ * Upload photos to an event or task straight to S3: allocate
46
+ * presigned URLs, upload each file (retrying network failures), then
47
+ * confirm. Resend a failed photo with the `upload` name its failure
48
+ * reported: one the server already stored is skipped, never stored
49
+ * twice. Components use `useUploadImages`.
50
+ */
51
+ uploadImages(target: ImageTarget, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
52
+ /**
53
+ * Send a notification (in the current company unless `companyId` is
54
+ * given). Show photos by embedding `useEventPhotoLinks` URLs.
55
+ */
56
+ sendNotification(body: CreateNotificationPayload, options?: {
57
+ companyId?: string;
58
+ idempotencyKey?: string;
59
+ }): Promise<NotificationCreated>;
60
+ /**
61
+ * Send an email from a mailbox (show photos by embedding
62
+ * `useEventPhotoLinks` URLs); `requestId` is echoed in the
63
+ * `email_succeeded`/`email_failed` events.
64
+ */
65
+ sendEmailMessage(emailId: string, body: SendEmailPayload, options?: {
66
+ requestId?: string;
67
+ proposalId?: string;
68
+ idempotencyKey?: string;
69
+ }): Promise<void>;
70
+ /** `uploadImages` as a mutation; refreshes the event or job when done. */
71
+ useUploadImages(): ReturnType<typeof useMutation<UploadImagesResult, StandardError, UploadImagesVars>>;
72
+ /** `sendNotification` as a mutation. */
73
+ useSendNotification(): ReturnType<typeof useMutation<NotificationCreated, StandardError, SendNotificationVars>>;
74
+ /** Email a bill's invoice (PDF rendered server-side) as a mutation. */
75
+ useSendBillEmail(): ReturnType<typeof useMutation<{
76
+ msg: string;
77
+ }, StandardError, SendBillEmailVars>>;
78
+ /** `useEventPhotoLinks` outside React (e.g. an offline outbox). */
79
+ getEventPhotoLinks(vars: EventPhotoLinksVars): Promise<EventPhotoLinks>;
80
+ /**
81
+ * Fetch permanent, signed links to an event's photos to embed in an
82
+ * email (`<img>` per position plus a "View photos" page).
83
+ */
84
+ useEventPhotoLinks(): ReturnType<typeof useMutation<EventPhotoLinks, StandardError, EventPhotoLinksVars>>;
85
+ /** `sendEmailMessage` as a mutation. */
86
+ useSendEmailMessage(): ReturnType<typeof useMutation<void, StandardError, SendEmailMessageVars>>;
42
87
  useGetRoot(): UseQueryResult<ApiInfo, StandardError>;
43
88
  useJobAudit(jobId: string, params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
44
89
  useCompanyAudit(params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
@@ -180,21 +225,14 @@ declare module './QueryClient.js' {
180
225
  }, total: number, onProgress?: (fraction: number) => void): UseQueryResult<Group[], StandardError>;
181
226
  useGetPlans(code: string): UseQueryResult<Plan[], StandardError>;
182
227
  useGetCompanies(options?: {}): UseQueryResult<CompanySummary[], StandardError>;
183
- generatePDFFromBackend({ billId }: {
184
- billId: string;
185
- }): Promise<Blob>;
186
- sendBillingEmail(options: {
187
- billId: string;
188
- subject?: string;
189
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
190
- recipients?: [string, string][];
191
- request_id?: string;
192
- }): Promise<{
193
- msg: string;
194
- }>;
228
+ /**
229
+ * Render a PDF on the server: a bill's invoice, or the hours report
230
+ * of the pay period containing `timecardsPeriodStart` (Unix time).
231
+ */
232
+ generatePDFFromBackend(source: PdfSource): Promise<Blob>;
195
233
  useGetProposal(proposal_id: string): UseQueryResult<Proposal, StandardError>;
196
- useGetProposalTerms(): UseQueryResult<ProposalTerms[], StandardError>;
197
- useCreateProposalTerms(): ReturnType<typeof useMutation<{
234
+ useGetTerms(): UseQueryResult<Terms[], StandardError>;
235
+ useCreateTerms(): ReturnType<typeof useMutation<{
198
236
  msg: string;
199
237
  id: string;
200
238
  }, StandardError, {
@@ -202,7 +240,7 @@ declare module './QueryClient.js' {
202
240
  body: string;
203
241
  archived?: boolean;
204
242
  }>>;
205
- useUpdateProposalTerms(): ReturnType<typeof useMutation<{
243
+ useUpdateTerms(): ReturnType<typeof useMutation<{
206
244
  msg: string;
207
245
  }, StandardError, {
208
246
  termsId: string;
@@ -252,6 +290,12 @@ declare module './QueryClient.js' {
252
290
  useGetRoute(routeId: string): UseQueryResult<Route, StandardError>;
253
291
  useGetChat(chatId: string): UseQueryResult<Chat, StandardError>;
254
292
  useGetCatalogItem(catalogItemId: string): UseQueryResult<CatalogItem, StandardError>;
293
+ useGetCatalogItems(body?: {
294
+ query?: string;
295
+ industry?: CatalogIndustry;
296
+ archived?: boolean;
297
+ companyId?: string;
298
+ }): UseQueryResult<CatalogItem[], StandardError>;
255
299
  useGetUserSessions(): UseQueryResult<Session[], StandardError>;
256
300
  useGetCompanySessionsByIds(sessionIds: string[], params?: {
257
301
  companyId?: string;
@@ -280,6 +324,15 @@ declare module './QueryClient.js' {
280
324
  msg: string;
281
325
  cleared: number;
282
326
  }, StandardError, void>>;
327
+ /**
328
+ * Root only: run scheduled jobs now (all of them when called with no
329
+ * ids). The scheduler starts them within a few seconds; watch their
330
+ * status in `useGetPerformanceMetrics`.
331
+ */
332
+ useRunSchedulerJobs(): ReturnType<typeof useMutation<{
333
+ msg: string;
334
+ jobs: string[];
335
+ }, StandardError, string[] | void>>;
283
336
  useSearchUsers(searchUsername: string): UseQueryResult<User[], StandardError>;
284
337
  useMergeUsersPreview(keepId: string, duplicateId: string): UseQueryResult<UserMergeSummary, StandardError>;
285
338
  useMergeUsers(): ReturnType<typeof useMutation<UserMergeSummary, StandardError, {
@@ -309,6 +362,30 @@ declare module './QueryClient.js' {
309
362
  time_sent?: number;
310
363
  id?: string;
311
364
  }>>;
365
+ useUpdateChat(): ReturnType<typeof useMutation<{
366
+ msg?: string;
367
+ }, StandardError, {
368
+ chatId: string;
369
+ name?: string;
370
+ status?: MemberState['state'];
371
+ users?: string[];
372
+ }>>;
373
+ useLeaveChat(): ReturnType<typeof useMutation<{
374
+ msg?: string;
375
+ }, StandardError, {
376
+ chatId: string;
377
+ }>>;
378
+ useReactToMessage(chatId: string): ReturnType<typeof useMutation<unknown, StandardError, {
379
+ message: Message;
380
+ reaction: number;
381
+ userId: string;
382
+ remove?: boolean;
383
+ }, {
384
+ snapshot: NsSnapshot;
385
+ }>>;
386
+ useMarkChatRead(chatId: string): ReturnType<typeof useMutation<unknown, StandardError, {
387
+ messageId: string;
388
+ }>>;
312
389
  useCreateProposal(): ReturnType<typeof useMutation<{
313
390
  msg: string;
314
391
  id: string;
@@ -477,7 +554,11 @@ declare module './QueryClient.js' {
477
554
  id: string | null;
478
555
  job_id: string | null;
479
556
  }>;
480
- useImportBillsFromIntuit(): ReturnType<typeof useMutation<IntuitImportResult, StandardError, void>>;
557
+ useImportBillsFromIntuit(): ReturnType<typeof useMutation<{
558
+ msg: string;
559
+ }, StandardError, void>>;
560
+ /** The company's QuickBooks sync as its socket events report it. */
561
+ useIntuitSyncStatus(): IntuitSyncStatus;
481
562
  useSyncBillToIntuit(): ReturnType<typeof useMutation<{
482
563
  msg: string;
483
564
  }, StandardError, {
@@ -605,6 +686,8 @@ declare module './QueryClient.js' {
605
686
  user_ids?: string[];
606
687
  enabled?: boolean;
607
688
  }): UseQueryResult<UserCompanyAssociation[], StandardError>;
689
+ /** Whether the viewer's membership grants `permission`; undefined until known. */
690
+ useHasPermission(permission: Permission): boolean | undefined;
608
691
  useReportDevice(): ReturnType<typeof useMutation<Device, StandardError, DeviceInfo & {
609
692
  location_status?: LocationServicesStatus;
610
693
  }>>;
@@ -746,6 +829,7 @@ export declare class AvroQueryClient {
746
829
  private _persister;
747
830
  private _presencePending;
748
831
  private _presenceTimer;
832
+ private _resyncTimer;
749
833
  /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
750
834
  private _joinedChats;
751
835
  private _restored;
@@ -799,6 +883,15 @@ export declare class AvroQueryClient {
799
883
  setupSocketInvalidation(queryClient: QueryClient): void;
800
884
  /** Join the company room; resync if the ack version moved while away. */
801
885
  private joinCompanyRoom;
886
+ /**
887
+ * Mark matching queries stale now; refetch the ones on screen after a
888
+ * random delay. A deploy or restart reconnects every client at once
889
+ * (and resets the version counter), so an immediate refetch of
890
+ * everything sent the whole fleet's load at a just-restarted backend
891
+ * in the same second. Anything mounted meanwhile still refetches,
892
+ * since it is already stale.
893
+ */
894
+ private resync;
802
895
  /** Fallback for mutations when the socket is down (else the echo syncs). */
803
896
  syncAfterMutation(...types: string[]): void;
804
897
  /**
@@ -1012,6 +1105,8 @@ export declare class AvroQueryClient {
1012
1105
  offset?: number;
1013
1106
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1014
1107
  fetchMessages(chatId: string, body?: {
1108
+ /** Marks this message (and the chat) as read by the caller. */
1109
+ last_message_read?: string;
1015
1110
  amt?: number;
1016
1111
  known_ids?: string[];
1017
1112
  unknown_ids?: string[];
@@ -1141,6 +1236,16 @@ export declare class AvroQueryClient {
1141
1236
  query?: string;
1142
1237
  offset?: number;
1143
1238
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1239
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1240
+ fetchCatalogItems(body?: {
1241
+ amt?: number;
1242
+ unknown_ids?: string[];
1243
+ query?: string;
1244
+ offset?: number;
1245
+ industry?: CatalogIndustry;
1246
+ /** Only archived (`true`) or active (`false`) items; both if unset. */
1247
+ archived?: boolean;
1248
+ }, companyId?: string | undefined, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<CatalogItem[]>;
1144
1249
  fetchSkills(body?: {
1145
1250
  amt?: number;
1146
1251
  known_ids?: string[];
@@ -1159,12 +1264,4 @@ export declare class AvroQueryClient {
1159
1264
  }, cancelToken?: CancelToken, headers?: Record<string, string>, companyId?: string | undefined): Promise<any>;
1160
1265
  private _initEmailListeners;
1161
1266
  trackEmail(options?: TrackEmailOptions): string;
1162
- sendEmail(emailId: string, formData: FormData, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<void>;
1163
- sendBillEmail(billId: string, body?: {
1164
- subject?: string;
1165
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
1166
- recipients?: [string, string][];
1167
- base_url?: string;
1168
- request_id?: string;
1169
- }): Promise<void>;
1170
1267
  }
@@ -9,6 +9,7 @@ import { StandardError } from '../types/error.js';
9
9
  import { withoutEmpty } from './wire.js';
10
10
  import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, retryDenied, } from './realtime.js';
11
11
  import { QueryPersister } from './persist.js';
12
+ import { replaceRow } from './cache.js';
12
13
  /** Keep the original status (401/403/404/0…) when surfacing a list-fetch failure. */
13
14
  function fetchError(err, context) {
14
15
  if (err instanceof StandardError)
@@ -50,6 +51,8 @@ const MAX_MESSAGES_PER_PAGE = 100;
50
51
  const AUTH_RECHECK_MIN_MS = 2000;
51
52
  const AUTH_RECHECK_MAX_MS = 60000;
52
53
  const SOCKET_AUTH_RETRY_MS = 10000;
54
+ /** Spread of the refetch after a reconnect finds the company changed. */
55
+ const RESYNC_JITTER_MS = 10000;
53
56
  export class AvroQueryClient {
54
57
  constructor(config) {
55
58
  this._authState = AuthState.UNKNOWN;
@@ -63,6 +66,7 @@ export class AvroQueryClient {
63
66
  this._persister = null;
64
67
  this._presencePending = new Set();
65
68
  this._presenceTimer = null;
69
+ this._resyncTimer = null;
66
70
  /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
67
71
  this._joinedChats = new Set();
68
72
  this._restored = null;
@@ -305,7 +309,47 @@ export class AvroQueryClient {
305
309
  if (this._socketInvalidationCleanup)
306
310
  return;
307
311
  this._queryClient = queryClient;
308
- const applier = new ChangeApplier(this, queryClient);
312
+ // Stale-mark only: an active refetch here turned backend
313
+ // trouble into a full-list refetch storm (every failing
314
+ // presence fetch scheduled a 400KB+ list download). The next
315
+ // mount/focus or realtime change refetches instead.
316
+ const markMembersStale = () => queryClient.invalidateQueries({
317
+ queryKey: ['users', 'company'],
318
+ refetchType: 'none',
319
+ });
320
+ // Fetch just the named members and patch them into every member
321
+ // list; used for presence flips and for `member` changes that
322
+ // name the user.
323
+ const refreshMembers = (userIds) => {
324
+ const companyId = this.companyId;
325
+ if (!companyId || userIds.length === 0)
326
+ return;
327
+ // `ListCompanyUsers.user_ids` holds at most 1000 ids.
328
+ for (let i = 0; i < userIds.length; i += 1000) {
329
+ const wanted = userIds.slice(i, i + 1000);
330
+ this.post({
331
+ path: `/company/${companyId}/users`,
332
+ data: JSON.stringify({ user_ids: wanted }),
333
+ headers: { 'Content-Type': 'application/json' },
334
+ idempotent: true,
335
+ })
336
+ .then((members) => {
337
+ if (!Array.isArray(members)) {
338
+ markMembersStale();
339
+ return;
340
+ }
341
+ for (const member of members)
342
+ patchMember(queryClient, member);
343
+ // A member the server no longer returns left the
344
+ // company; patching can't remove it.
345
+ const got = new Set(members.map((m) => m?.user?.id));
346
+ if (wanted.some((id) => !got.has(id)))
347
+ markMembersStale();
348
+ })
349
+ .catch(markMembersStale);
350
+ }
351
+ };
352
+ const applier = new ChangeApplier(this, queryClient, refreshMembers);
309
353
  this._applier = applier;
310
354
  const handlers = [];
311
355
  const on = (event, handler) => {
@@ -340,14 +384,6 @@ export class AvroQueryClient {
340
384
  // and patch those members instead of re-downloading every
341
385
  // member once per flip on every connected client.
342
386
  const PRESENCE_COALESCE_MS = 500;
343
- // Stale-mark only: an active refetch here turned backend
344
- // trouble into a full-list refetch storm (every failing
345
- // presence fetch scheduled a 400KB+ list download). The next
346
- // mount/focus or realtime change refetches instead.
347
- const markMembersStale = () => queryClient.invalidateQueries({
348
- queryKey: ['users', 'company'],
349
- refetchType: 'none',
350
- });
351
387
  on('update_presence', (data) => {
352
388
  const userId = data?.user_id;
353
389
  if (!userId || !this.companyId) {
@@ -361,26 +397,7 @@ export class AvroQueryClient {
361
397
  this._presenceTimer = null;
362
398
  const userIds = [...this._presencePending];
363
399
  this._presencePending.clear();
364
- if (!this.companyId || userIds.length === 0)
365
- return;
366
- // `ListCompanyUsers.user_ids` holds at most 1000 ids.
367
- for (let i = 0; i < userIds.length; i += 1000) {
368
- this.post({
369
- path: `/company/${this.companyId}/users`,
370
- data: JSON.stringify({ user_ids: userIds.slice(i, i + 1000) }),
371
- headers: { 'Content-Type': 'application/json' },
372
- idempotent: true,
373
- })
374
- .then((members) => {
375
- if (!Array.isArray(members)) {
376
- markMembersStale();
377
- return;
378
- }
379
- for (const member of members)
380
- patchMember(queryClient, member);
381
- })
382
- .catch(markMembersStale);
383
- }
400
+ refreshMembers(userIds);
384
401
  }, PRESENCE_COALESCE_MS);
385
402
  });
386
403
  on('location_update', (data) => {
@@ -396,20 +413,32 @@ export class AvroQueryClient {
396
413
  patchTeamLocation(queryClient, data);
397
414
  patchMemberLocation(queryClient, data);
398
415
  });
399
- // schedule_locked lives in a Redis lock, not a row.
416
+ // schedule_locked and intuit_sync_locked live in Redis locks, not rows.
400
417
  for (const event of [
401
418
  'schedule_started',
402
419
  'schedule_complete',
403
420
  'scheduling_error',
404
421
  'schedule_adjustments',
422
+ 'intuit_sync_started',
423
+ 'intuit_sync_complete',
424
+ 'intuit_sync_error',
405
425
  ]) {
406
426
  on(event, () => {
407
427
  queryClient.invalidateQueries({ queryKey: ['companies'] });
408
428
  });
409
429
  }
410
- on('new_message', () => {
430
+ // Chat events reach every accepted member through their own room,
431
+ // so chat lists stay live without joining each chat's room.
432
+ on('new_message', (data) => {
411
433
  queryClient.invalidateQueries({ queryKey: ['chats'] });
412
- queryClient.invalidateQueries({ queryKey: ['messages'] });
434
+ queryClient.invalidateQueries({
435
+ queryKey: data?.chat_id ? ['messages', 'infinite', data.chat_id] : ['messages'],
436
+ });
437
+ });
438
+ // Carries the whole message (e.g. after a reaction change).
439
+ on('message_updated', (data) => {
440
+ if (data?.id)
441
+ replaceRow(queryClient, 'messages', data);
413
442
  });
414
443
  on('connect', () => {
415
444
  this.joinCompanyRoom();
@@ -427,6 +456,10 @@ export class AvroQueryClient {
427
456
  this._presenceTimer = null;
428
457
  }
429
458
  this._presencePending.clear();
459
+ if (this._resyncTimer) {
460
+ clearTimeout(this._resyncTimer);
461
+ this._resyncTimer = null;
462
+ }
430
463
  applier.dispose();
431
464
  this._applier = null;
432
465
  if (this.socket.connected && this.companyId) {
@@ -452,15 +485,33 @@ export class AvroQueryClient {
452
485
  // were never delivered. Refresh what loaded before now
453
486
  // once; later joins compare versions instead.
454
487
  const joinedAt = Date.now();
455
- this._queryClient?.invalidateQueries({
456
- predicate: (q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt,
457
- });
488
+ this.resync((q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt);
458
489
  }
459
490
  else if (known !== ack.version) {
460
- this._queryClient?.invalidateQueries();
491
+ this.resync(() => true);
461
492
  }
462
493
  });
463
494
  }
495
+ /**
496
+ * Mark matching queries stale now; refetch the ones on screen after a
497
+ * random delay. A deploy or restart reconnects every client at once
498
+ * (and resets the version counter), so an immediate refetch of
499
+ * everything sent the whole fleet's load at a just-restarted backend
500
+ * in the same second. Anything mounted meanwhile still refetches,
501
+ * since it is already stale.
502
+ */
503
+ resync(predicate) {
504
+ const qc = this._queryClient;
505
+ if (!qc)
506
+ return;
507
+ void qc.invalidateQueries({ predicate, refetchType: 'none' });
508
+ if (this._resyncTimer)
509
+ clearTimeout(this._resyncTimer);
510
+ this._resyncTimer = setTimeout(() => {
511
+ this._resyncTimer = null;
512
+ void this._queryClient?.refetchQueries({ predicate, type: 'active', stale: true });
513
+ }, Math.random() * RESYNC_JITTER_MS);
514
+ }
464
515
  /** Fallback for mutations when the socket is down (else the echo syncs). */
465
516
  syncAfterMutation(...types) {
466
517
  const qc = this._queryClient;
@@ -1329,6 +1380,26 @@ export class AvroQueryClient {
1329
1380
  throw fetchError(err, 'Failed to fetch groups');
1330
1381
  });
1331
1382
  }
1383
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1384
+ fetchCatalogItems(body = {}, companyId = this.companyId, cancelToken, headers = {}) {
1385
+ if (!companyId || companyId.trim() === '') {
1386
+ throw new StandardError(400, 'Company ID is required');
1387
+ }
1388
+ return this._fetch('POST', `/company/${companyId}/catalog_items`, JSON.stringify(body), cancelToken, {
1389
+ ...headers,
1390
+ 'Content-Type': 'application/json',
1391
+ }, true)
1392
+ .then((response) => {
1393
+ if (!response || !Array.isArray(response)) {
1394
+ throw new StandardError(400, 'Invalid catalog items response');
1395
+ }
1396
+ return response;
1397
+ })
1398
+ .catch((err) => {
1399
+ console.error('Failed to fetch catalog items:', err);
1400
+ throw fetchError(err, 'Failed to fetch catalog items');
1401
+ });
1402
+ }
1332
1403
  fetchSkills(body = {}, cancelToken, headers = {}) {
1333
1404
  if (!this.companyId || this.companyId.trim() === '') {
1334
1405
  throw new StandardError(400, 'Company ID is required');
@@ -1414,28 +1485,4 @@ export class AvroQueryClient {
1414
1485
  });
1415
1486
  return requestId;
1416
1487
  }
1417
- sendEmail(emailId, formData, progressUpdateCallback) {
1418
- try {
1419
- return this.post({
1420
- path: `/email/${emailId}`,
1421
- data: formData,
1422
- progressUpdateCallback,
1423
- });
1424
- }
1425
- catch (error) {
1426
- throw new StandardError(500, `Failed to send email: ${error}`);
1427
- }
1428
- }
1429
- sendBillEmail(billId, body = {}) {
1430
- try {
1431
- return this.post({
1432
- path: `/bill/${billId}/email`,
1433
- data: JSON.stringify(body),
1434
- headers: { 'Content-Type': 'application/json' },
1435
- });
1436
- }
1437
- catch (error) {
1438
- throw new StandardError(500, `Failed to send bill email: ${error}`);
1439
- }
1440
- }
1441
1488
  }
@@ -22,3 +22,7 @@ export declare function seedDetails<T extends {
22
22
  }>(qc: QueryClient | null, ns: string, items: T[]): T[];
23
23
  /** Remove an optimistic row (by its temporary id) from every list in `ns`. */
24
24
  export declare function removeOptimisticRow(qc: QueryClient, ns: string, tempId: string): void;
25
+ /** Replace a row (matched by id) in every list in `ns` that holds it. */
26
+ export declare function replaceRow<T extends {
27
+ id?: string;
28
+ }>(qc: QueryClient, ns: string, row: T): void;
@@ -49,3 +49,22 @@ export function removeOptimisticRow(qc, ns, tempId) {
49
49
  return old;
50
50
  });
51
51
  }
52
+ /** Replace a row (matched by id) in every list in `ns` that holds it. */
53
+ export function replaceRow(qc, ns, row) {
54
+ if (!row?.id)
55
+ return;
56
+ const swap = (x) => (x?.id === row.id ? row : x);
57
+ qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => {
58
+ if (!old)
59
+ return old;
60
+ if (Array.isArray(old))
61
+ return old.map(swap);
62
+ if (Array.isArray(old.pages)) {
63
+ return {
64
+ ...old,
65
+ pages: old.pages.map((p) => (Array.isArray(p) ? p.map(swap) : p)),
66
+ };
67
+ }
68
+ return old;
69
+ });
70
+ }