@go-avro/avro-js 1.6.6-rc9 → 1.7.1

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 (48) hide show
  1. package/dist/chat.d.ts +25 -0
  2. package/dist/chat.js +47 -0
  3. package/dist/client/QueryClient.d.ts +135 -26
  4. package/dist/client/QueryClient.js +115 -59
  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/accounts.js +52 -0
  9. package/dist/client/hooks/bills.js +19 -17
  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 +4 -1
  16. package/dist/client/hooks/{proposal_terms.js → terms.js} +14 -14
  17. package/dist/client/realtime.d.ts +26 -3
  18. package/dist/client/realtime.js +94 -16
  19. package/dist/client/requests.d.ts +16 -11
  20. package/dist/index.d.ts +5 -1
  21. package/dist/index.js +4 -1
  22. package/dist/types/api/Account.d.ts +61 -0
  23. package/dist/types/api/Account.js +38 -0
  24. package/dist/types/api/AuditLog.d.ts +1 -1
  25. package/dist/types/api/Avro.d.ts +5 -0
  26. package/dist/types/api/Bill.d.ts +2 -2
  27. package/dist/types/api/BillPayment.d.ts +2 -2
  28. package/dist/types/api/CatalogItem.d.ts +3 -1
  29. package/dist/types/api/Company.d.ts +0 -2
  30. package/dist/types/api/Job.d.ts +4 -4
  31. package/dist/types/api/Job.js +11 -2
  32. package/dist/types/api/MemberState.d.ts +3 -0
  33. package/dist/types/api/Notification.d.ts +39 -0
  34. package/dist/types/api/Proposal.d.ts +2 -2
  35. package/dist/types/api/Task.d.ts +16 -0
  36. package/dist/types/api/Task.js +30 -3
  37. package/dist/types/api/{ProposalTerms.d.ts → Terms.d.ts} +3 -3
  38. package/dist/types/api/Terms.js +1 -0
  39. package/dist/types/api.d.ts +2 -2
  40. package/dist/types/api.js +2 -2
  41. package/dist/types/client.d.ts +125 -0
  42. package/dist/version.d.ts +1 -1
  43. package/dist/version.js +1 -1
  44. package/package.json +1 -1
  45. package/dist/types/api/Subscription.d.ts +0 -10
  46. /package/dist/client/{hooks/proposal_terms.d.ts → core/uploads.d.ts} +0 -0
  47. /package/dist/{types/api/ProposalTerms.js → client/hooks/accounts.d.ts} +0 -0
  48. /package/dist/{types/api/Subscription.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,20 @@
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, Permission, 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
+ import type { Account, AccountCreatePayload, AccountUpdatePayload } from '../types/api/Account.js';
10
11
  import { Proposal } from '../types/api/Proposal.js';
11
- import { ProposalTerms } from '../types/api/ProposalTerms.js';
12
+ import { Terms } from '../types/api/Terms.js';
12
13
  import type { EmailSucceededPayload, EmailFailedPayload, EmailType } from '../types/api/EmailNotification.js';
13
14
  import type { BulkDeleteBillsResponse, BulkEmailBillsResponse } from './hooks/bills.js';
14
15
  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
16
  import { type QueryPersistOptions } from './persist.js';
17
+ import { type NsSnapshot } from './cache.js';
16
18
  export interface TrackEmailOptions {
17
19
  emailType?: EmailType;
18
20
  requestId?: string;
@@ -39,6 +41,50 @@ declare module './QueryClient.js' {
39
41
  _fetch<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number): Promise<T>;
40
42
  getDelay(strategy: RetryStrategy, attempt: number): number;
41
43
  sleep(ms: number): Promise<void>;
44
+ _uploadImages(base: string, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
45
+ /**
46
+ * Upload photos to an event or task straight to S3: allocate
47
+ * presigned URLs, upload each file (retrying network failures), then
48
+ * confirm. Resend a failed photo with the `upload` name its failure
49
+ * reported: one the server already stored is skipped, never stored
50
+ * twice. Components use `useUploadImages`.
51
+ */
52
+ uploadImages(target: ImageTarget, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
53
+ /**
54
+ * Send a notification (in the current company unless `companyId` is
55
+ * given). Show photos by embedding `useEventPhotoLinks` URLs.
56
+ */
57
+ sendNotification(body: CreateNotificationPayload, options?: {
58
+ companyId?: string;
59
+ idempotencyKey?: string;
60
+ }): Promise<NotificationCreated>;
61
+ /**
62
+ * Send an email from a mailbox (show photos by embedding
63
+ * `useEventPhotoLinks` URLs); `requestId` is echoed in the
64
+ * `email_succeeded`/`email_failed` events.
65
+ */
66
+ sendEmailMessage(emailId: string, body: SendEmailPayload, options?: {
67
+ requestId?: string;
68
+ proposalId?: string;
69
+ idempotencyKey?: string;
70
+ }): Promise<void>;
71
+ /** `uploadImages` as a mutation; refreshes the event or job when done. */
72
+ useUploadImages(): ReturnType<typeof useMutation<UploadImagesResult, StandardError, UploadImagesVars>>;
73
+ /** `sendNotification` as a mutation. */
74
+ useSendNotification(): ReturnType<typeof useMutation<NotificationCreated, StandardError, SendNotificationVars>>;
75
+ /** Email a bill's invoice (PDF rendered server-side) as a mutation. */
76
+ useSendBillEmail(): ReturnType<typeof useMutation<{
77
+ msg: string;
78
+ }, StandardError, SendBillEmailVars>>;
79
+ /** `useEventPhotoLinks` outside React (e.g. an offline outbox). */
80
+ getEventPhotoLinks(vars: EventPhotoLinksVars): Promise<EventPhotoLinks>;
81
+ /**
82
+ * Fetch permanent, signed links to an event's photos to embed in an
83
+ * email (`<img>` per position plus a "View photos" page).
84
+ */
85
+ useEventPhotoLinks(): ReturnType<typeof useMutation<EventPhotoLinks, StandardError, EventPhotoLinksVars>>;
86
+ /** `sendEmailMessage` as a mutation. */
87
+ useSendEmailMessage(): ReturnType<typeof useMutation<void, StandardError, SendEmailMessageVars>>;
42
88
  useGetRoot(): UseQueryResult<ApiInfo, StandardError>;
43
89
  useJobAudit(jobId: string, params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
44
90
  useCompanyAudit(params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
@@ -164,6 +210,28 @@ declare module './QueryClient.js' {
164
210
  query?: string;
165
211
  offset?: number;
166
212
  }, total: number, onProgress?: (fraction: number) => void): UseQueryResult<Label[], StandardError>;
213
+ useGetAccounts(body?: {
214
+ query?: string;
215
+ unknown_ids?: string[];
216
+ }): UseQueryResult<Account[], StandardError>;
217
+ useGetAccount(accountId: string): UseQueryResult<Account, StandardError>;
218
+ useCreateAccount(): ReturnType<typeof useMutation<{
219
+ msg: string;
220
+ id: string;
221
+ }, StandardError, {
222
+ data: AccountCreatePayload;
223
+ }>>;
224
+ useUpdateAccount(): ReturnType<typeof useMutation<{
225
+ msg: string;
226
+ }, StandardError, {
227
+ accountId: string;
228
+ updates: AccountUpdatePayload;
229
+ }>>;
230
+ useDeleteAccount(): ReturnType<typeof useMutation<{
231
+ msg: string;
232
+ }, StandardError, {
233
+ accountId: string;
234
+ }>>;
167
235
  useGetWaivers(body: {
168
236
  amt?: number;
169
237
  known_ids?: string[];
@@ -180,21 +248,14 @@ declare module './QueryClient.js' {
180
248
  }, total: number, onProgress?: (fraction: number) => void): UseQueryResult<Group[], StandardError>;
181
249
  useGetPlans(code: string): UseQueryResult<Plan[], StandardError>;
182
250
  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
- }>;
251
+ /**
252
+ * Render a PDF on the server: a bill's invoice, or the hours report
253
+ * of the pay period containing `timecardsPeriodStart` (Unix time).
254
+ */
255
+ generatePDFFromBackend(source: PdfSource): Promise<Blob>;
195
256
  useGetProposal(proposal_id: string): UseQueryResult<Proposal, StandardError>;
196
- useGetProposalTerms(): UseQueryResult<ProposalTerms[], StandardError>;
197
- useCreateProposalTerms(): ReturnType<typeof useMutation<{
257
+ useGetTerms(): UseQueryResult<Terms[], StandardError>;
258
+ useCreateTerms(): ReturnType<typeof useMutation<{
198
259
  msg: string;
199
260
  id: string;
200
261
  }, StandardError, {
@@ -202,7 +263,7 @@ declare module './QueryClient.js' {
202
263
  body: string;
203
264
  archived?: boolean;
204
265
  }>>;
205
- useUpdateProposalTerms(): ReturnType<typeof useMutation<{
266
+ useUpdateTerms(): ReturnType<typeof useMutation<{
206
267
  msg: string;
207
268
  }, StandardError, {
208
269
  termsId: string;
@@ -252,6 +313,12 @@ declare module './QueryClient.js' {
252
313
  useGetRoute(routeId: string): UseQueryResult<Route, StandardError>;
253
314
  useGetChat(chatId: string): UseQueryResult<Chat, StandardError>;
254
315
  useGetCatalogItem(catalogItemId: string): UseQueryResult<CatalogItem, StandardError>;
316
+ useGetCatalogItems(body?: {
317
+ query?: string;
318
+ industry?: CatalogIndustry;
319
+ archived?: boolean;
320
+ companyId?: string;
321
+ }): UseQueryResult<CatalogItem[], StandardError>;
255
322
  useGetUserSessions(): UseQueryResult<Session[], StandardError>;
256
323
  useGetCompanySessionsByIds(sessionIds: string[], params?: {
257
324
  companyId?: string;
@@ -318,6 +385,30 @@ declare module './QueryClient.js' {
318
385
  time_sent?: number;
319
386
  id?: string;
320
387
  }>>;
388
+ useUpdateChat(): ReturnType<typeof useMutation<{
389
+ msg?: string;
390
+ }, StandardError, {
391
+ chatId: string;
392
+ name?: string;
393
+ status?: MemberState['state'];
394
+ users?: string[];
395
+ }>>;
396
+ useLeaveChat(): ReturnType<typeof useMutation<{
397
+ msg?: string;
398
+ }, StandardError, {
399
+ chatId: string;
400
+ }>>;
401
+ useReactToMessage(chatId: string): ReturnType<typeof useMutation<unknown, StandardError, {
402
+ message: Message;
403
+ reaction: number;
404
+ userId: string;
405
+ remove?: boolean;
406
+ }, {
407
+ snapshot: NsSnapshot;
408
+ }>>;
409
+ useMarkChatRead(chatId: string): ReturnType<typeof useMutation<unknown, StandardError, {
410
+ messageId: string;
411
+ }>>;
321
412
  useCreateProposal(): ReturnType<typeof useMutation<{
322
413
  msg: string;
323
414
  id: string;
@@ -761,6 +852,7 @@ export declare class AvroQueryClient {
761
852
  private _persister;
762
853
  private _presencePending;
763
854
  private _presenceTimer;
855
+ private _resyncTimer;
764
856
  /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
765
857
  private _joinedChats;
766
858
  private _restored;
@@ -814,6 +906,15 @@ export declare class AvroQueryClient {
814
906
  setupSocketInvalidation(queryClient: QueryClient): void;
815
907
  /** Join the company room; resync if the ack version moved while away. */
816
908
  private joinCompanyRoom;
909
+ /**
910
+ * Mark matching queries stale now; refetch the ones on screen after a
911
+ * random delay. A deploy or restart reconnects every client at once
912
+ * (and resets the version counter), so an immediate refetch of
913
+ * everything sent the whole fleet's load at a just-restarted backend
914
+ * in the same second. Anything mounted meanwhile still refetches,
915
+ * since it is already stale.
916
+ */
917
+ private resync;
817
918
  /** Fallback for mutations when the socket is down (else the echo syncs). */
818
919
  syncAfterMutation(...types: string[]): void;
819
920
  /**
@@ -1027,6 +1128,8 @@ export declare class AvroQueryClient {
1027
1128
  offset?: number;
1028
1129
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1029
1130
  fetchMessages(chatId: string, body?: {
1131
+ /** Marks this message (and the chat) as read by the caller. */
1132
+ last_message_read?: string;
1030
1133
  amt?: number;
1031
1134
  known_ids?: string[];
1032
1135
  unknown_ids?: string[];
@@ -1048,6 +1151,10 @@ export declare class AvroQueryClient {
1048
1151
  sort_by?: 'date' | 'amount' | 'name';
1049
1152
  direction?: 'asc' | 'desc';
1050
1153
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1154
+ fetchAccounts(body?: {
1155
+ query?: string;
1156
+ unknown_ids?: string[];
1157
+ }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<Account[]>;
1051
1158
  fetchWaivers(body?: {
1052
1159
  amt?: number;
1053
1160
  query?: string;
@@ -1156,6 +1263,16 @@ export declare class AvroQueryClient {
1156
1263
  query?: string;
1157
1264
  offset?: number;
1158
1265
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1266
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1267
+ fetchCatalogItems(body?: {
1268
+ amt?: number;
1269
+ unknown_ids?: string[];
1270
+ query?: string;
1271
+ offset?: number;
1272
+ industry?: CatalogIndustry;
1273
+ /** Only archived (`true`) or active (`false`) items; both if unset. */
1274
+ archived?: boolean;
1275
+ }, companyId?: string | undefined, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<CatalogItem[]>;
1159
1276
  fetchSkills(body?: {
1160
1277
  amt?: number;
1161
1278
  known_ids?: string[];
@@ -1174,12 +1291,4 @@ export declare class AvroQueryClient {
1174
1291
  }, cancelToken?: CancelToken, headers?: Record<string, string>, companyId?: string | undefined): Promise<any>;
1175
1292
  private _initEmailListeners;
1176
1293
  trackEmail(options?: TrackEmailOptions): string;
1177
- sendEmail(emailId: string, formData: FormData, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<void>;
1178
- sendBillEmail(billId: string, body?: {
1179
- subject?: string;
1180
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
1181
- recipients?: [string, string][];
1182
- base_url?: string;
1183
- request_id?: string;
1184
- }): Promise<void>;
1185
1294
  }
@@ -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) => {
@@ -410,9 +427,18 @@ export class AvroQueryClient {
410
427
  queryClient.invalidateQueries({ queryKey: ['companies'] });
411
428
  });
412
429
  }
413
- 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) => {
414
433
  queryClient.invalidateQueries({ queryKey: ['chats'] });
415
- 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);
416
442
  });
417
443
  on('connect', () => {
418
444
  this.joinCompanyRoom();
@@ -430,6 +456,10 @@ export class AvroQueryClient {
430
456
  this._presenceTimer = null;
431
457
  }
432
458
  this._presencePending.clear();
459
+ if (this._resyncTimer) {
460
+ clearTimeout(this._resyncTimer);
461
+ this._resyncTimer = null;
462
+ }
433
463
  applier.dispose();
434
464
  this._applier = null;
435
465
  if (this.socket.connected && this.companyId) {
@@ -455,15 +485,33 @@ export class AvroQueryClient {
455
485
  // were never delivered. Refresh what loaded before now
456
486
  // once; later joins compare versions instead.
457
487
  const joinedAt = Date.now();
458
- this._queryClient?.invalidateQueries({
459
- predicate: (q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt,
460
- });
488
+ this.resync((q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt);
461
489
  }
462
490
  else if (known !== ack.version) {
463
- this._queryClient?.invalidateQueries();
491
+ this.resync(() => true);
464
492
  }
465
493
  });
466
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
+ }
467
515
  /** Fallback for mutations when the socket is down (else the echo syncs). */
468
516
  syncAfterMutation(...types) {
469
517
  const qc = this._queryClient;
@@ -1149,6 +1197,18 @@ export class AvroQueryClient {
1149
1197
  throw fetchError(err, 'Failed to fetch prepayments');
1150
1198
  });
1151
1199
  }
1200
+ async fetchAccounts(body = {}, cancelToken, headers = {}) {
1201
+ if (!this.companyId || this.companyId.trim() === '') {
1202
+ throw new StandardError(400, 'Company ID is required');
1203
+ }
1204
+ return this._fetch('POST', `/company/${this.companyId}/accounts`, JSON.stringify(body), cancelToken, {
1205
+ ...headers,
1206
+ 'Content-Type': 'application/json',
1207
+ }, true).catch((err) => {
1208
+ console.error('Failed to fetch accounts:', err);
1209
+ throw fetchError(err, 'Failed to fetch accounts');
1210
+ });
1211
+ }
1152
1212
  async fetchWaivers(body = {}, cancelToken, headers = {}) {
1153
1213
  if (!this.companyId || this.companyId.trim() === '') {
1154
1214
  throw new StandardError(400, 'Company ID is required');
@@ -1332,6 +1392,26 @@ export class AvroQueryClient {
1332
1392
  throw fetchError(err, 'Failed to fetch groups');
1333
1393
  });
1334
1394
  }
1395
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1396
+ fetchCatalogItems(body = {}, companyId = this.companyId, cancelToken, headers = {}) {
1397
+ if (!companyId || companyId.trim() === '') {
1398
+ throw new StandardError(400, 'Company ID is required');
1399
+ }
1400
+ return this._fetch('POST', `/company/${companyId}/catalog_items`, JSON.stringify(body), cancelToken, {
1401
+ ...headers,
1402
+ 'Content-Type': 'application/json',
1403
+ }, true)
1404
+ .then((response) => {
1405
+ if (!response || !Array.isArray(response)) {
1406
+ throw new StandardError(400, 'Invalid catalog items response');
1407
+ }
1408
+ return response;
1409
+ })
1410
+ .catch((err) => {
1411
+ console.error('Failed to fetch catalog items:', err);
1412
+ throw fetchError(err, 'Failed to fetch catalog items');
1413
+ });
1414
+ }
1335
1415
  fetchSkills(body = {}, cancelToken, headers = {}) {
1336
1416
  if (!this.companyId || this.companyId.trim() === '') {
1337
1417
  throw new StandardError(400, 'Company ID is required');
@@ -1417,28 +1497,4 @@ export class AvroQueryClient {
1417
1497
  });
1418
1498
  return requestId;
1419
1499
  }
1420
- sendEmail(emailId, formData, progressUpdateCallback) {
1421
- try {
1422
- return this.post({
1423
- path: `/email/${emailId}`,
1424
- data: formData,
1425
- progressUpdateCallback,
1426
- });
1427
- }
1428
- catch (error) {
1429
- throw new StandardError(500, `Failed to send email: ${error}`);
1430
- }
1431
- }
1432
- sendBillEmail(billId, body = {}) {
1433
- try {
1434
- return this.post({
1435
- path: `/bill/${billId}/email`,
1436
- data: JSON.stringify(body),
1437
- headers: { 'Content-Type': 'application/json' },
1438
- });
1439
- }
1440
- catch (error) {
1441
- throw new StandardError(500, `Failed to send bill email: ${error}`);
1442
- }
1443
- }
1444
1500
  }
@@ -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
+ }