@go-avro/avro-js 0.0.119 → 0.1.0

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.
@@ -2,402 +2,10 @@ import io from 'socket.io-client';
2
2
  import { useMutation, useQueryClient, } from '@tanstack/react-query';
3
3
  import { v4 as uuidv4 } from 'uuid';
4
4
  import { fetchCensusFeatures } from '../census';
5
- import { Bill, constructEvent, Job, LoginResponse, Route, } from '../types/api';
5
+ import { LoginResponse, } from '../types/api';
6
6
  import { AuthState } from '../types/auth';
7
7
  import { StandardError } from '../types/error';
8
- function isBulkEvent(c) {
9
- return 'invalidateKeys' in c;
10
- }
11
- export function matchesEventsListQuery(queryKey, item) {
12
- if (queryKey.length < 11)
13
- return 'match';
14
- if (!item)
15
- return 'match';
16
- const knownIds = queryKey[3];
17
- const unknownIds = queryKey[4];
18
- const query = queryKey[5];
19
- const includeUnbilled = queryKey[6];
20
- const includeBilled = queryKey[7];
21
- const includePaid = queryKey[8];
22
- const filterJobId = queryKey[9];
23
- // Index 13 was appended after the original 13-element key; older
24
- // keys read undefined here, which means "no type filter".
25
- const lineItemTypes = queryKey[13];
26
- if (knownIds && knownIds.length > 0 && !knownIds.includes(item.id))
27
- return 'nomatch';
28
- if (unknownIds && unknownIds.length > 0 && unknownIds.includes(item.id))
29
- return 'nomatch';
30
- if (filterJobId && item.job_id !== filterJobId)
31
- return 'nomatch';
32
- if (lineItemTypes &&
33
- lineItemTypes.length > 0 &&
34
- item.line_item_type !== undefined &&
35
- !lineItemTypes.includes(item.line_item_type))
36
- return 'nomatch';
37
- const status = item.status;
38
- if (status !== undefined) {
39
- const isPaid = status === 'PAID' || status === 'PREPAID' || status === 'EXTERNALLY_PAID';
40
- const isBilled = status === 'BILLED' || status === 'EXTERNALLY_BILLED';
41
- const isUnbilled = !isPaid && !isBilled;
42
- if (includePaid === false && isPaid)
43
- return 'nomatch';
44
- if (includeBilled === false && isBilled)
45
- return 'nomatch';
46
- if (includeUnbilled === false && isUnbilled)
47
- return 'nomatch';
48
- }
49
- if (query && query.length > 0)
50
- return 'unknown';
51
- return 'match';
52
- }
53
- export function matchesBillsListQuery(queryKey, item) {
54
- if (queryKey.length < 6)
55
- return 'match';
56
- if (!item)
57
- return 'match';
58
- const query = queryKey[2];
59
- const knownIds = queryKey[3];
60
- const unknownIds = queryKey[4];
61
- const paidFilter = queryKey[5];
62
- if (knownIds && knownIds.length > 0 && !knownIds.includes(item.id))
63
- return 'nomatch';
64
- if (unknownIds && unknownIds.length > 0 && unknownIds.includes(item.id))
65
- return 'nomatch';
66
- const status = item.status;
67
- if (paidFilter !== undefined && status !== undefined) {
68
- const isPaid = status === 'PAID' || status === 'MANUALLY_PAID';
69
- if (paidFilter === true && !isPaid)
70
- return 'nomatch';
71
- if (paidFilter === false && isPaid)
72
- return 'nomatch';
73
- }
74
- if (query && query.length > 0)
75
- return 'unknown';
76
- return 'match';
77
- }
78
- export function matchesJobsListQuery(queryKey, item) {
79
- if (queryKey[0] !== 'infinite')
80
- return 'match';
81
- if (queryKey.length < 6)
82
- return 'match';
83
- if (!item)
84
- return 'match';
85
- const query = queryKey[4];
86
- const routeId = queryKey[5];
87
- if (routeId && routeId.length > 0) {
88
- const routes = item.routes ?? [];
89
- if (!routes.some((r) => r?.route_id === routeId))
90
- return 'nomatch';
91
- }
92
- if (query && query.length > 0)
93
- return 'unknown';
94
- return 'match';
95
- }
96
- export function matchesRoutesListQuery(queryKey, _item) {
97
- if (queryKey.length < 5)
98
- return 'match';
99
- const query = queryKey[3];
100
- if (query && query.length > 0)
101
- return 'unknown';
102
- return 'match';
103
- }
104
- /**
105
- * Maps socket event names to cache-update strategies.
106
- *
107
- * *Targeted* events receive `{ id }` from the backend and surgically
108
- * update / insert / remove only the affected cache entries.
109
- *
110
- * *Bulk* events (plural mutations, scheduling, etc.) fall back to
111
- * full query-key invalidation because the backend doesn't emit per-item ids.
112
- */
113
- const SOCKET_EVENT_CONFIG = {
114
- // ── Company ──
115
- create_company: {
116
- entityKey: 'companies',
117
- action: 'create',
118
- fetchPath: (id) => `/company/${id}`,
119
- alsoInvalidate: [['/company/list']],
120
- },
121
- update_company: {
122
- entityKey: 'companies',
123
- action: 'update',
124
- fetchPath: (id) => `/company/${id}`,
125
- alsoInvalidate: [['companies', 'current'], ['/company/list']],
126
- },
127
- delete_company: {
128
- entityKey: 'companies',
129
- action: 'delete',
130
- fetchPath: null,
131
- alsoInvalidate: [['companies', 'current'], ['/company/list']],
132
- },
133
- // ── Users (no single-entity socket events) ──
134
- user_updated: { invalidateKeys: [['users'], ['user']] },
135
- // Membership / permission changes.
136
- update_users: { invalidateKeys: [['users'], ['user']] },
137
- // Presence / location-status flips: only the member list is affected.
138
- update_presence: { invalidateKeys: [['users', 'company']] },
139
- // ── Jobs ──
140
- create_job: {
141
- entityKey: 'jobs',
142
- action: 'create',
143
- fetchPath: (id) => `/job/${id}`,
144
- construct: (d) => new Job(d),
145
- matchesQuery: matchesJobsListQuery,
146
- },
147
- update_job: {
148
- entityKey: 'jobs',
149
- action: 'update',
150
- fetchPath: (id) => `/job/${id}`,
151
- construct: (d) => new Job(d),
152
- matchesQuery: matchesJobsListQuery,
153
- },
154
- delete_job: { entityKey: 'jobs', action: 'delete', fetchPath: null },
155
- update_jobs: { invalidateKeys: [['jobs'], ['infinite', 'jobs']] },
156
- delete_jobs: { invalidateKeys: [['jobs'], ['infinite', 'jobs']] },
157
- // ── Routes ──
158
- // Route membership lives on jobs too (task.route_ids), so every
159
- // route mutation must refresh the jobs caches or unrouted/routed
160
- // state goes stale. The backend names the affected jobs in the
161
- // payload's `job_ids`; only those get refetched and patched.
162
- create_route: {
163
- entityKey: 'routes',
164
- action: 'create',
165
- fetchPath: (id) => `/route/${id}`,
166
- construct: (d) => new Route(d),
167
- matchesQuery: matchesRoutesListQuery,
168
- patchJobsFromPayload: true,
169
- },
170
- update_route: {
171
- entityKey: 'routes',
172
- action: 'update',
173
- fetchPath: (id) => `/route/${id}`,
174
- construct: (d) => new Route(d),
175
- matchesQuery: matchesRoutesListQuery,
176
- patchJobsFromPayload: true,
177
- },
178
- delete_route: {
179
- entityKey: 'routes',
180
- action: 'delete',
181
- fetchPath: null,
182
- patchJobsFromPayload: true,
183
- },
184
- // ── Events (also refetch parent job — overdueness, last_event, etc.) ──
185
- create_event: {
186
- entityKey: 'events',
187
- action: 'create',
188
- fetchPath: (id) => `/event/${id}`,
189
- construct: (d) => constructEvent(d),
190
- matchesQuery: matchesEventsListQuery,
191
- relatedRefetch: [
192
- {
193
- entityKey: 'jobs',
194
- idField: 'job_id',
195
- fetchPath: (id) => `/job/${id}`,
196
- construct: (d) => new Job(d),
197
- matchesQuery: matchesJobsListQuery,
198
- },
199
- ],
200
- },
201
- update_event: {
202
- entityKey: 'events',
203
- action: 'update',
204
- fetchPath: (id) => `/event/${id}`,
205
- construct: (d) => constructEvent(d),
206
- matchesQuery: matchesEventsListQuery,
207
- relatedRefetch: [
208
- {
209
- entityKey: 'jobs',
210
- idField: 'job_id',
211
- fetchPath: (id) => `/job/${id}`,
212
- construct: (d) => new Job(d),
213
- matchesQuery: matchesJobsListQuery,
214
- },
215
- ],
216
- },
217
- delete_event: {
218
- entityKey: 'events',
219
- action: 'delete',
220
- fetchPath: null,
221
- relatedRefetch: [
222
- {
223
- entityKey: 'jobs',
224
- idField: 'job_id',
225
- fetchPath: (id) => `/job/${id}`,
226
- construct: (d) => new Job(d),
227
- matchesQuery: matchesJobsListQuery,
228
- },
229
- ],
230
- },
231
- update_events: { invalidateKeys: [['events']] },
232
- // ── Teams ──
233
- create_team: { entityKey: 'teams', action: 'create', fetchPath: null },
234
- update_team: { entityKey: 'teams', action: 'update', fetchPath: null },
235
- delete_team: { entityKey: 'teams', action: 'delete', fetchPath: null },
236
- update_teams: { invalidateKeys: [['teams']] },
237
- // ── Bills ──
238
- create_bill: {
239
- entityKey: 'bills',
240
- action: 'create',
241
- fetchPath: (id) => `/bill/${id}`,
242
- construct: (d) => new Bill(d),
243
- matchesQuery: matchesBillsListQuery,
244
- },
245
- delete_bill: { entityKey: 'bills', action: 'delete', fetchPath: null },
246
- update_bills: { invalidateKeys: [['bills']] },
247
- // ── Check-ins (also refresh the job — its payload embeds
248
- // current_checkins for the on-site indicator) ──
249
- create_checkin: {
250
- entityKey: 'checkins',
251
- action: 'create',
252
- fetchPath: null,
253
- alsoInvalidate: [['checkins']],
254
- relatedRefetch: [
255
- {
256
- entityKey: 'jobs',
257
- idField: 'job_id',
258
- fetchPath: (id) => `/job/${id}`,
259
- construct: (d) => new Job(d),
260
- matchesQuery: matchesJobsListQuery,
261
- },
262
- ],
263
- },
264
- update_checkin: {
265
- entityKey: 'checkins',
266
- action: 'update',
267
- fetchPath: null,
268
- alsoInvalidate: [['checkins']],
269
- relatedRefetch: [
270
- {
271
- entityKey: 'jobs',
272
- idField: 'job_id',
273
- fetchPath: (id) => `/job/${id}`,
274
- construct: (d) => new Job(d),
275
- matchesQuery: matchesJobsListQuery,
276
- },
277
- ],
278
- },
279
- // ── Sessions ──
280
- create_session: {
281
- entityKey: 'sessions',
282
- action: 'create',
283
- fetchPath: null,
284
- alsoInvalidate: [['analytics', 'sessions']],
285
- },
286
- update_session: {
287
- entityKey: 'sessions',
288
- action: 'update',
289
- fetchPath: null,
290
- alsoInvalidate: [['analytics', 'sessions']],
291
- },
292
- // ── Catalog Items ──
293
- create_catalog_item: {
294
- entityKey: 'catalog_items',
295
- action: 'create',
296
- fetchPath: (id) => `/catalog_item/${id}`,
297
- },
298
- update_catalog_item: {
299
- entityKey: 'catalog_items',
300
- action: 'update',
301
- fetchPath: (id) => `/catalog_item/${id}`,
302
- },
303
- delete_catalog_item: {
304
- entityKey: 'catalog_items',
305
- action: 'delete',
306
- fetchPath: null,
307
- },
308
- // ── Groups ──
309
- create_group: { entityKey: 'groups', action: 'create', fetchPath: null },
310
- update_group: { entityKey: 'groups', action: 'update', fetchPath: null },
311
- delete_group: { entityKey: 'groups', action: 'delete', fetchPath: null },
312
- // ── Labels ──
313
- create_label: { entityKey: 'labels', action: 'create', fetchPath: null },
314
- update_label: { entityKey: 'labels', action: 'update', fetchPath: null },
315
- delete_label: { entityKey: 'labels', action: 'delete', fetchPath: null },
316
- // ── Skills ──
317
- create_skill: { entityKey: 'skills', action: 'create', fetchPath: null },
318
- update_skill: { entityKey: 'skills', action: 'update', fetchPath: null },
319
- delete_skill: { entityKey: 'skills', action: 'delete', fetchPath: null },
320
- // ── Proposals ──
321
- create_proposal: {
322
- entityKey: 'proposals',
323
- action: 'create',
324
- fetchPath: (id) => `/proposal/${id}`,
325
- },
326
- update_proposal: {
327
- entityKey: 'proposals',
328
- action: 'update',
329
- fetchPath: (id) => `/proposal/${id}`,
330
- },
331
- delete_proposal: {
332
- entityKey: 'proposals',
333
- action: 'delete',
334
- fetchPath: null,
335
- },
336
- // ── Service Months ──
337
- create_month: { entityKey: 'months', action: 'create', fetchPath: null },
338
- update_month: { invalidateKeys: [['months']] },
339
- update_months: { invalidateKeys: [['months']] },
340
- delete_months: { invalidateKeys: [['months']] },
341
- // ── Tasks (nested under jobs — target the parent job) ──
342
- create_task: {
343
- entityKey: 'jobs',
344
- action: 'update',
345
- fetchPath: (id) => `/job/${id}`,
346
- idField: 'job_id',
347
- construct: (d) => new Job(d),
348
- },
349
- update_task: {
350
- entityKey: 'jobs',
351
- action: 'update',
352
- fetchPath: (id) => `/job/${id}`,
353
- idField: 'job_id',
354
- construct: (d) => new Job(d),
355
- },
356
- delete_task: {
357
- entityKey: 'jobs',
358
- action: 'update',
359
- fetchPath: (id) => `/job/${id}`,
360
- idField: 'job_id',
361
- construct: (d) => new Job(d),
362
- },
363
- // ── Scheduling ──
364
- // Handled surgically in setupSocketInvalidation: when the payload
365
- // carries `job_ids`, the affected jobs are bulk-fetched and patched
366
- // in place instead of refetching every jobs query. These keys are
367
- // the fallback for payloads without ids (legacy backends, runs
368
- // where the affected set is unknown).
369
- schedule_complete: {
370
- invalidateKeys: [
371
- ['routes'],
372
- ['jobs'],
373
- ['infinite', 'jobs'],
374
- ['companies'],
375
- ['/company/list'],
376
- ],
377
- },
378
- // Terminal failure of a scheduling run: refetch companies so the
379
- // "scheduling in progress" banner (company.schedule_locked) clears
380
- scheduling_error: {
381
- invalidateKeys: [['companies'], ['/company/list']],
382
- },
383
- // ── Location ──
384
- // Handled surgically in setupSocketInvalidation (patches
385
- // `current_location` / `last_location` in place); these keys are
386
- // only the fallback for malformed payloads.
387
- location_update: { invalidateKeys: [['teams']] },
388
- // ── Prepayments ──
389
- update_prepayments: { invalidateKeys: [['prepayments']] },
390
- // ── Chats ──
391
- new_message: { invalidateKeys: [['chats'], ['messages']] },
392
- };
393
- /**
394
- * Returns true when `query.queryKey` belongs to the given entity,
395
- * including the `['infinite', entityKey, ...]` variant used by jobs.
396
- */
397
- function matchesEntityKey(query, entityKey) {
398
- const k = query.queryKey;
399
- return k[0] === entityKey || (k[0] === 'infinite' && k[1] === entityKey);
400
- }
8
+ import { ChangeApplier, fallbackInvalidate, patchMemberLocation, patchTeamLocation, } from '../client/realtime';
401
9
  export class AvroQueryClient {
402
10
  constructor(config) {
403
11
  this._authState = AuthState.UNKNOWN;
@@ -406,6 +14,8 @@ export class AvroQueryClient {
406
14
  this.authStateListeners = [];
407
15
  this._queryClient = null;
408
16
  this._socketInvalidationCleanup = null;
17
+ this._applier = null;
18
+ this._companyVersions = new Map();
409
19
  this._emailTracking = new Map();
410
20
  this._emailListenersInit = false;
411
21
  this.config = {
@@ -506,214 +116,92 @@ export class AvroQueryClient {
506
116
  off(eventName, callback) {
507
117
  this.socket?.off(eventName, callback);
508
118
  }
509
- /**
510
- * Wire up automatic query invalidation for socket events.
511
- * Called once from AvroQueryClientProvider when the tanstack
512
- * QueryClient is available. Also handles auto-joining the
513
- * company room on connect so consumer apps don't have to.
514
- *
515
- * Targeted events (single-entity CRUD) receive `{ id }` from the
516
- * backend and surgically create / update / remove only the
517
- * affected cache entries. Bulk events fall back to full
518
- * query-key invalidation.
519
- *
520
- * Backward-compatible: if a targeted event arrives without an id
521
- * (old backend), we fall back to full invalidation.
522
- */
119
+ /** Wire the socket to the cache (called once from the provider). */
523
120
  setupSocketInvalidation(queryClient) {
524
121
  if (this._socketInvalidationCleanup)
525
122
  return;
526
123
  this._queryClient = queryClient;
124
+ const applier = new ChangeApplier(this, queryClient);
125
+ this._applier = applier;
527
126
  const handlers = [];
528
- const client = this; // stable reference for async closures
529
- /** Full-invalidate every key that matches the entity (including 'infinite' prefix). */
530
- const invalidateEntity = (entityKey) => {
531
- queryClient.invalidateQueries({
532
- predicate: (q) => matchesEntityKey(q, entityKey),
533
- });
127
+ const on = (event, handler) => {
128
+ this.socket.on(event, handler);
129
+ handlers.push({ event, handler });
534
130
  };
535
- const patchMemberLocation = (data) => {
536
- const userId = data?.user_id;
537
- if (!userId || typeof userId !== 'string' || typeof data?.latitude !== 'number') {
131
+ on('changes', (payload) => {
132
+ if (payload?.company && typeof payload.version === 'number') {
133
+ this._companyVersions.set(payload.company, payload.version);
134
+ }
135
+ applier.apply(payload);
136
+ });
137
+ on('rejoin_company', (data) => {
138
+ if (data?.company_id && data.company_id === this.companyId)
139
+ this.joinCompanyRoom();
140
+ });
141
+ on('update_presence', () => {
142
+ queryClient.invalidateQueries({ queryKey: ['users', 'company'] });
143
+ });
144
+ on('location_update', (data) => {
145
+ if (!data || typeof data.latitude !== 'number') {
146
+ queryClient.invalidateQueries({ queryKey: ['teams'] });
538
147
  queryClient.invalidateQueries({ queryKey: ['users', 'company'] });
539
148
  return;
540
149
  }
541
- const patchMembers = (members) => {
542
- let changed = false;
543
- const next = members.map((u) => {
544
- if (u?.user?.id !== userId)
545
- return u;
546
- changed = true;
547
- return { ...u, last_location: data };
548
- });
549
- return changed ? next : members;
550
- };
551
- queryClient.setQueriesData({ queryKey: ['users', 'company'] }, (old) => Array.isArray(old) ? patchMembers(old) : old);
552
- };
553
- const patchTeamLocation = (data) => {
554
- const teamId = data.team_id;
555
- if (!teamId || typeof teamId !== 'string')
556
- return;
557
- const patchTeams = (teams) => {
558
- let changed = false;
559
- const next = teams.map((t) => {
560
- if (t?.id !== teamId)
561
- return t;
562
- changed = true;
563
- return { ...t, current_location: data };
564
- });
565
- return changed ? next : teams;
566
- };
567
- queryClient.setQueriesData({ queryKey: ['teams'] }, (old) => {
568
- if (Array.isArray(old))
569
- return patchTeams(old);
570
- if (old?.pages) {
571
- return {
572
- ...old,
573
- pages: old.pages.map((page) => Array.isArray(page) ? patchTeams(page) : page),
574
- };
575
- }
576
- if (old?.id === teamId)
577
- return { ...old, current_location: data };
578
- return old;
150
+ patchTeamLocation(queryClient, data);
151
+ patchMemberLocation(queryClient, data);
152
+ });
153
+ // schedule_locked lives in a Redis lock, not a row.
154
+ for (const event of [
155
+ 'schedule_started',
156
+ 'schedule_complete',
157
+ 'scheduling_error',
158
+ 'schedule_adjustments',
159
+ ]) {
160
+ on(event, () => {
161
+ queryClient.invalidateQueries({ queryKey: ['companies'] });
579
162
  });
580
- };
581
- for (const [event, config] of Object.entries(SOCKET_EVENT_CONFIG)) {
582
- if (event === 'location_update' && isBulkEvent(config)) {
583
- const handler = (data) => {
584
- if (!data || typeof data.latitude !== 'number') {
585
- for (const key of config.invalidateKeys) {
586
- queryClient.invalidateQueries({ queryKey: key });
587
- }
588
- }
589
- else {
590
- patchTeamLocation(data);
591
- }
592
- patchMemberLocation(data);
593
- };
594
- this.socket.on(event, handler);
595
- handlers.push({ event, handler });
596
- continue;
597
- }
598
- if (event === 'schedule_complete' && isBulkEvent(config)) {
599
- // Scheduling touches a known set of jobs; refetching every
600
- // jobs query on each run is untenable. When the payload
601
- // names the affected ids, bulk-fetch just those jobs and
602
- // patch them into the cached lists in place.
603
- const handler = async (data) => {
604
- // Always cheap and always stale after a run: the new
605
- // routes and the company's schedule_locked banner.
606
- queryClient.invalidateQueries({ queryKey: ['routes'] });
607
- queryClient.invalidateQueries({ queryKey: ['companies'] });
608
- queryClient.invalidateQueries({ queryKey: ['/company/list'] });
609
- const rawIds = data?.job_ids;
610
- if (!Array.isArray(rawIds)) {
611
- // Legacy backend / unknown affected set
612
- queryClient.invalidateQueries({ queryKey: ['jobs'] });
613
- queryClient.invalidateQueries({ queryKey: ['infinite', 'jobs'] });
614
- return;
615
- }
616
- await client._patchJobsByIds(queryClient, rawIds.filter((x) => typeof x === 'string'));
617
- };
618
- this.socket.on(event, handler);
619
- handlers.push({ event, handler });
620
- continue;
621
- }
622
- if (isBulkEvent(config)) {
623
- // ── Bulk: invalidate all specified keys ──────────────
624
- const handler = () => {
625
- for (const key of config.invalidateKeys) {
626
- queryClient.invalidateQueries({ queryKey: key });
627
- }
628
- };
629
- this.socket.on(event, handler);
630
- handlers.push({ event, handler });
631
- }
632
- else {
633
- // ── Targeted: surgical cache update ──────────────────
634
- const { entityKey, action, fetchPath, idField, alsoInvalidate, relatedRefetch } = config;
635
- const handler = async (data) => {
636
- const id = data?.[idField ?? 'id'];
637
- // Refresh the jobs whose route associations this event
638
- // changed: patch the ids named in the payload, or fall
639
- // back to full jobs invalidation when a legacy backend
640
- // didn't send any.
641
- const syncAffectedJobs = async () => {
642
- if (!config.patchJobsFromPayload)
643
- return;
644
- const rawIds = data?.job_ids;
645
- if (!Array.isArray(rawIds)) {
646
- queryClient.invalidateQueries({ queryKey: ['jobs'] });
647
- queryClient.invalidateQueries({ queryKey: ['infinite', 'jobs'] });
648
- return;
649
- }
650
- await client._patchJobsByIds(queryClient, rawIds.filter((x) => typeof x === 'string'));
651
- };
652
- if (!id || typeof id !== 'string') {
653
- invalidateEntity(entityKey);
654
- alsoInvalidate?.forEach((k) => queryClient.invalidateQueries({ queryKey: k }));
655
- await syncAffectedJobs();
656
- return;
657
- }
658
- let fetchedItem;
659
- // ─── CREATE / UPDATE / DELETE via shared _syncEntity ───
660
- fetchedItem = await client._syncEntity(queryClient, {
661
- action,
662
- entityKey,
663
- id,
664
- fetchPath: fetchPath ? fetchPath(id) : undefined,
665
- construct: config.construct,
666
- matchesQuery: config.matchesQuery,
667
- });
668
- // Invalidate any additional keys (e.g. companies → /company/list)
669
- alsoInvalidate?.forEach((k) => queryClient.invalidateQueries({ queryKey: k }));
670
- await syncAffectedJobs();
671
- if (relatedRefetch) {
672
- for (const related of relatedRefetch) {
673
- const relatedId = data?.[related.idField] ?? fetchedItem?.[related.idField];
674
- if (!relatedId || typeof relatedId !== 'string')
675
- continue;
676
- await client._syncEntity(queryClient, {
677
- action: 'update',
678
- entityKey: related.entityKey,
679
- id: relatedId,
680
- fetchPath: related.fetchPath(relatedId),
681
- construct: related.construct,
682
- matchesQuery: related.matchesQuery,
683
- });
684
- }
685
- }
686
- };
687
- this.socket.on(event, handler);
688
- handlers.push({ event, handler });
689
- }
690
- }
691
- // Auto join/leave company room
692
- const joinCompanyRoom = () => {
693
- if (this.companyId) {
694
- this.socket.emit('join_company', { company_id: this.companyId });
695
- }
696
- else {
697
- console.warn(`[socket-debug] joinCompanyRoom skipped — companyId is undefined`);
698
- }
699
- };
700
- this.socket.on('connect', joinCompanyRoom);
701
- handlers.push({ event: 'connect', handler: joinCompanyRoom });
702
- // If already connected, join immediately
703
- if (this.socket.connected && this.companyId) {
704
- joinCompanyRoom();
705
163
  }
164
+ on('new_message', () => {
165
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
166
+ queryClient.invalidateQueries({ queryKey: ['messages'] });
167
+ });
168
+ on('connect', () => this.joinCompanyRoom());
169
+ if (this.socket.connected && this.companyId)
170
+ this.joinCompanyRoom();
706
171
  this._socketInvalidationCleanup = () => {
707
- for (const { event, handler } of handlers) {
172
+ for (const { event, handler } of handlers)
708
173
  this.socket.off(event, handler);
709
- }
710
- // Leave company room on teardown
174
+ applier.dispose();
175
+ this._applier = null;
711
176
  if (this.socket.connected && this.companyId) {
712
177
  this.socket.emit('leave_company', { company_id: this.companyId });
713
178
  }
714
179
  this._queryClient = null;
715
180
  };
716
181
  }
182
+ /** Join the company room; resync if the ack version moved while away. */
183
+ joinCompanyRoom() {
184
+ const companyId = this.companyId;
185
+ if (!companyId || !this.socket.connected)
186
+ return;
187
+ this.socket.emit('join_company', { company_id: companyId }, (ack) => {
188
+ if (!ack || typeof ack.version !== 'number')
189
+ return;
190
+ const known = this._companyVersions.get(companyId);
191
+ this._companyVersions.set(companyId, ack.version);
192
+ if (known !== undefined && known !== ack.version) {
193
+ this._queryClient?.invalidateQueries();
194
+ }
195
+ });
196
+ }
197
+ /** Fallback for mutations when the socket is down (else the echo syncs). */
198
+ syncAfterMutation(...types) {
199
+ const qc = this._queryClient;
200
+ if (!qc)
201
+ return;
202
+ if (!this.socket.connected)
203
+ fallbackInvalidate(qc, types);
204
+ }
717
205
  /**
718
206
  * Remove all invalidation listeners. Called on provider unmount.
719
207
  */
@@ -907,7 +395,7 @@ export class AvroQueryClient {
907
395
  if (previousId && previousId !== companyId) {
908
396
  this.socket.emit('leave_company', { company_id: previousId });
909
397
  }
910
- this.socket.emit('join_company', { company_id: companyId });
398
+ this.joinCompanyRoom();
911
399
  }
912
400
  return this.config.authManager.setCompanyId(companyId);
913
401
  }
@@ -957,172 +445,6 @@ export class AvroQueryClient {
957
445
  peekQueryClient() {
958
446
  return this._queryClient;
959
447
  }
960
- /**
961
- * Bulk-refresh a known set of jobs after a route/scheduling change:
962
- * one request for exactly those ids (`unknown_ids` = "only these
963
- * ids", serialized server-side with this user's own permissions),
964
- * then patch the fresh items into every cached jobs query in place.
965
- * Route-filtered lists are invalidated instead — membership may have
966
- * changed and an in-place patch can't insert newly-assigned jobs.
967
- * Falls back to full jobs invalidation if the fetch fails.
968
- */
969
- async _patchJobsByIds(queryClient, jobIds) {
970
- if (jobIds.length === 0)
971
- return;
972
- try {
973
- const raw = await this.fetchJobs({
974
- unknown_ids: jobIds,
975
- amt: jobIds.length,
976
- });
977
- const fresh = new Map(raw.filter((d) => d?.id).map((d) => [d.id, new Job(d)]));
978
- const matching = queryClient
979
- .getQueryCache()
980
- .findAll({ predicate: (q) => matchesEntityKey(q, 'jobs') });
981
- for (const query of matching) {
982
- const queryKey = query.queryKey;
983
- // Detail cache: ['jobs', jobId]
984
- if (queryKey.length === 2 && queryKey[0] === 'jobs') {
985
- const detailId = queryKey[1];
986
- if (typeof detailId === 'string' && fresh.has(detailId)) {
987
- queryClient.setQueryData(queryKey, fresh.get(detailId));
988
- }
989
- continue;
990
- }
991
- // Route-filtered lists (only mounted route views hold them)
992
- if (queryKey[0] === 'infinite' &&
993
- typeof queryKey[5] === 'string' &&
994
- queryKey[5].length > 0) {
995
- queryClient.invalidateQueries({ queryKey, exact: true });
996
- continue;
997
- }
998
- queryClient.setQueryData(queryKey, (old) => {
999
- if (!old)
1000
- return old;
1001
- const patchList = (list) => {
1002
- let changed = false;
1003
- const next = list.map((x) => {
1004
- const replacement = x?.id ? fresh.get(x.id) : undefined;
1005
- if (!replacement)
1006
- return x;
1007
- changed = true;
1008
- return replacement;
1009
- });
1010
- return changed ? next : list;
1011
- };
1012
- if (old.pages && Array.isArray(old.pages)) {
1013
- return {
1014
- ...old,
1015
- pages: old.pages.map((p) => Array.isArray(p) ? patchList(p) : p),
1016
- };
1017
- }
1018
- if (Array.isArray(old))
1019
- return patchList(old);
1020
- return old;
1021
- });
1022
- }
1023
- }
1024
- catch {
1025
- queryClient.invalidateQueries({ queryKey: ['jobs'] });
1026
- queryClient.invalidateQueries({ queryKey: ['infinite', 'jobs'] });
1027
- }
1028
- }
1029
- async _syncEntity(queryClient, params) {
1030
- const { action, entityKey, id, fetchPath, construct, matchesQuery } = params;
1031
- const predicate = (q) => matchesEntityKey(q, entityKey);
1032
- const invalidate = () => queryClient.invalidateQueries({ predicate });
1033
- if (action === 'delete') {
1034
- queryClient.removeQueries({ queryKey: [entityKey, id], exact: true });
1035
- queryClient.setQueriesData({ predicate }, (old) => {
1036
- if (!old)
1037
- return old;
1038
- if (old.pages && Array.isArray(old.pages)) {
1039
- return {
1040
- ...old,
1041
- pages: old.pages.map((p) => p.filter((x) => x?.id !== id)),
1042
- };
1043
- }
1044
- if (Array.isArray(old)) {
1045
- return old.filter((x) => x?.id !== id);
1046
- }
1047
- return old;
1048
- });
1049
- return undefined;
1050
- }
1051
- if (!fetchPath) {
1052
- invalidate();
1053
- return undefined;
1054
- }
1055
- try {
1056
- // Direct fetch, not fetchQuery: fetchQuery would return an
1057
- // already-in-flight (older) request for the same entity,
1058
- // losing the newer state when socket events arrive in a
1059
- // burst (e.g. auto-checkout followed by check-in)
1060
- const raw = await this.get({ path: fetchPath });
1061
- const item = construct ? construct(raw) : raw;
1062
- queryClient.setQueryData([entityKey, id], item);
1063
- const matchingQueries = queryClient.getQueryCache().findAll({ predicate });
1064
- for (const query of matchingQueries) {
1065
- const queryKey = query.queryKey;
1066
- if (queryKey.length === 2 && queryKey[0] === entityKey)
1067
- continue;
1068
- const verdict = matchesQuery
1069
- ? matchesQuery(queryKey, item)
1070
- : 'match';
1071
- if (verdict === 'unknown') {
1072
- queryClient.invalidateQueries({ queryKey, exact: true });
1073
- continue;
1074
- }
1075
- if (action === 'create') {
1076
- if (verdict === 'nomatch')
1077
- continue;
1078
- queryClient.setQueryData(queryKey, (old) => {
1079
- if (!old)
1080
- return old;
1081
- if (old.pages && Array.isArray(old.pages)) {
1082
- if (old.pages.some((p) => p.some((x) => x?.id === id)))
1083
- return old;
1084
- return {
1085
- ...old,
1086
- pages: [[item, ...(old.pages[0] || [])], ...old.pages.slice(1)],
1087
- };
1088
- }
1089
- if (Array.isArray(old)) {
1090
- if (old.some((x) => x?.id === id))
1091
- return old;
1092
- return [...old, item];
1093
- }
1094
- return old;
1095
- });
1096
- }
1097
- else {
1098
- queryClient.setQueryData(queryKey, (old) => {
1099
- if (!old)
1100
- return old;
1101
- if (old.pages && Array.isArray(old.pages)) {
1102
- return {
1103
- ...old,
1104
- pages: old.pages.map((page) => verdict === 'match'
1105
- ? page.map((x) => (x?.id === id ? item : x))
1106
- : page.filter((x) => x?.id !== id)),
1107
- };
1108
- }
1109
- if (Array.isArray(old)) {
1110
- return verdict === 'match'
1111
- ? old.map((x) => (x?.id === id ? item : x))
1112
- : old.filter((x) => x?.id !== id);
1113
- }
1114
- return old;
1115
- });
1116
- }
1117
- }
1118
- return item;
1119
- }
1120
- catch (err) {
1121
- console.error(`[socket-debug] _syncEntity fetch FAILED for ${entityKey}/${id}:`, err);
1122
- invalidate();
1123
- return undefined;
1124
- }
1125
- }
1126
448
  /**
1127
449
  * Drop all local auth state without a server round-trip: stored
1128
450
  * tokens, cached company, query cache, socket, and auth state.