@go-avro/avro-js 1.6.0 → 1.6.1-rc1

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.
@@ -11,6 +11,8 @@ export declare class AuthManager {
11
11
  private tokenRefreshedCallbacks;
12
12
  private tokenRefreshFailedCallbacks;
13
13
  private refreshing;
14
+ /** Bumped on every login and logout; see refreshTokens. */
15
+ private generation;
14
16
  constructor({ baseUrl, storage }: {
15
17
  baseUrl: string;
16
18
  storage: Cache | Cache[];
@@ -43,6 +45,8 @@ export declare class AuthManager {
43
45
  * failure notifies `onTokenRefreshFailed` listeners (→ logout).
44
46
  */
45
47
  refreshTokens(): Promise<Tokens>;
48
+ /** Start a new session: in-flight refreshes of the old one are void. */
49
+ private newSession;
46
50
  setTokens(tokens: Tokens): Promise<void>;
47
51
  setCache(data: Partial<CacheData> | Object): Promise<void>;
48
52
  getCache(key?: keyof CacheData | string): Promise<CacheData[keyof CacheData] | Object | string | null>;
@@ -13,6 +13,8 @@ export class AuthManager {
13
13
  this.tokenRefreshedCallbacks = [];
14
14
  this.tokenRefreshFailedCallbacks = [];
15
15
  this.refreshing = null;
16
+ /** Bumped on every login and logout; see refreshTokens. */
17
+ this.generation = 0;
16
18
  this.storages = Array.isArray(storage) ? storage : [storage];
17
19
  if (this.storages.length === 0) {
18
20
  throw new Error('At least one token storage must be provided');
@@ -162,9 +164,16 @@ export class AuthManager {
162
164
  refreshTokens() {
163
165
  if (this.refreshing)
164
166
  return this.refreshing;
167
+ const generation = this.generation;
165
168
  this.refreshing = (async () => {
166
169
  try {
167
170
  const newToken = await this.fetchNewTokens();
171
+ // A logout or a new login while this was in flight: these
172
+ // tokens belong to the old session, so never store them.
173
+ // Not an auth status: that would log out the new session.
174
+ if (generation !== this.generation) {
175
+ throw new StandardError(0, 'Session changed during token refresh');
176
+ }
168
177
  await Promise.all(this.storages.map((s) => s.set(newToken)));
169
178
  this.tokenRefreshedCallbacks.forEach((cb) => {
170
179
  if (newToken?.access_token)
@@ -173,7 +182,8 @@ export class AuthManager {
173
182
  return newToken;
174
183
  }
175
184
  catch (err) {
176
- if (isDefinitiveAuthFailure(err)) {
185
+ // Only the current session's failure means "log out".
186
+ if (isDefinitiveAuthFailure(err) && generation === this.generation) {
177
187
  this.tokenRefreshFailedCallbacks.forEach((cb) => {
178
188
  try {
179
189
  cb();
@@ -186,12 +196,20 @@ export class AuthManager {
186
196
  throw err;
187
197
  }
188
198
  finally {
189
- this.refreshing = null;
199
+ // A newer session may already have its own refresh running.
200
+ if (generation === this.generation)
201
+ this.refreshing = null;
190
202
  }
191
203
  })();
192
204
  return this.refreshing;
193
205
  }
206
+ /** Start a new session: in-flight refreshes of the old one are void. */
207
+ newSession() {
208
+ this.generation++;
209
+ this.refreshing = null;
210
+ }
194
211
  async setTokens(tokens) {
212
+ this.newSession();
195
213
  await Promise.all(this.storages.map((s) => s.set(tokens)));
196
214
  }
197
215
  async setCache(data) {
@@ -209,6 +227,7 @@ export class AuthManager {
209
227
  return null;
210
228
  }
211
229
  async clearCache() {
230
+ this.newSession();
212
231
  await Promise.all(this.storages.map((s) => s.clear()));
213
232
  }
214
233
  async getCompanyId() {
@@ -290,10 +290,12 @@ declare module './QueryClient.js' {
290
290
  pay_in_cash?: boolean;
291
291
  }>>;
292
292
  useCreateMessage(chatId: string): ReturnType<typeof useMutation<{
293
+ msg?: string;
293
294
  id: string;
294
295
  }, StandardError, {
295
296
  content: string;
296
297
  time_sent?: number;
298
+ id?: string;
297
299
  }>>;
298
300
  useCreateProposal(): ReturnType<typeof useMutation<{
299
301
  id: string;
@@ -721,6 +723,8 @@ export declare class AvroQueryClient {
721
723
  private _persister;
722
724
  private _presencePending;
723
725
  private _presenceTimer;
726
+ /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
727
+ private _joinedChats;
724
728
  private _restored;
725
729
  private _emailTracking;
726
730
  private _emailListenersInit;
@@ -759,6 +763,13 @@ export declare class AvroQueryClient {
759
763
  /** Tell the server which install this live socket belongs to. */
760
764
  private registerDevice;
761
765
  emit(eventName: string, data: unknown): void;
766
+ /**
767
+ * Join a chat's socket room so `new_message` and presence events for it
768
+ * arrive. The room is rejoined after reconnects until `leaveChat`.
769
+ */
770
+ joinChat(chatId: string): void;
771
+ /** Leave a chat's socket room joined with `joinChat`. */
772
+ leaveChat(chatId: string): void;
762
773
  on<T>(eventName: string, callback: (data: T) => void): void;
763
774
  off(eventName: string, callback?: Function): void;
764
775
  /** Wire the socket to the cache (called once from the provider). */
@@ -1050,7 +1061,7 @@ export declare class AvroQueryClient {
1050
1061
  unknown_ids?: string[];
1051
1062
  active?: boolean;
1052
1063
  user_id?: string;
1053
- }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1064
+ }, cancelToken?: CancelToken, headers?: Record<string, string>, companyId?: string | undefined): Promise<any>;
1054
1065
  private _initEmailListeners;
1055
1066
  trackEmail(options?: TrackEmailOptions): string;
1056
1067
  sendEmail(emailId: string, formData: FormData, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<void>;
@@ -58,6 +58,8 @@ export class AvroQueryClient {
58
58
  this._persister = null;
59
59
  this._presencePending = new Set();
60
60
  this._presenceTimer = null;
61
+ /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
62
+ this._joinedChats = new Set();
61
63
  this._restored = null;
62
64
  this._emailTracking = new Map();
63
65
  this._emailListenersInit = false;
@@ -268,6 +270,25 @@ export class AvroQueryClient {
268
270
  }
269
271
  this.socket.emit(eventName, data);
270
272
  }
273
+ /**
274
+ * Join a chat's socket room so `new_message` and presence events for it
275
+ * arrive. The room is rejoined after reconnects until `leaveChat`.
276
+ */
277
+ joinChat(chatId) {
278
+ if (!chatId)
279
+ return;
280
+ this._joinedChats.add(chatId);
281
+ if (this.socket?.connected)
282
+ this.socket.emit('join_chat', { chat_id: chatId });
283
+ }
284
+ /** Leave a chat's socket room joined with `joinChat`. */
285
+ leaveChat(chatId) {
286
+ if (!chatId)
287
+ return;
288
+ this._joinedChats.delete(chatId);
289
+ if (this.socket?.connected)
290
+ this.socket.emit('leave_chat', { chat_id: chatId });
291
+ }
271
292
  on(eventName, callback) {
272
293
  this.socket?.on(eventName, callback);
273
294
  }
@@ -297,6 +318,13 @@ export class AvroQueryClient {
297
318
  if (data?.company_id && data.company_id === this.companyId)
298
319
  this.joinCompanyRoom();
299
320
  });
321
+ // Sent before a chat room is closed after a membership change;
322
+ // the server re-checks membership, so removed members stay out.
323
+ on('rejoin_chat', (data) => {
324
+ if (data?.chat_id && this._joinedChats.has(data.chat_id)) {
325
+ this.socket?.emit('join_chat', { chat_id: data.chat_id });
326
+ }
327
+ });
300
328
  // Presence names the member that changed; coalesce a burst of
301
329
  // flips (mobile sockets cycle constantly) into one bulk fetch
302
330
  // and patch those members instead of re-downloading every
@@ -370,7 +398,12 @@ export class AvroQueryClient {
370
398
  queryClient.invalidateQueries({ queryKey: ['chats'] });
371
399
  queryClient.invalidateQueries({ queryKey: ['messages'] });
372
400
  });
373
- on('connect', () => this.joinCompanyRoom());
401
+ on('connect', () => {
402
+ this.joinCompanyRoom();
403
+ for (const chatId of this._joinedChats) {
404
+ this.socket.emit('join_chat', { chat_id: chatId });
405
+ }
406
+ });
374
407
  if (this.socket.connected && this.companyId)
375
408
  this.joinCompanyRoom();
376
409
  this._socketInvalidationCleanup = () => {
@@ -400,7 +433,17 @@ export class AvroQueryClient {
400
433
  const known = this._companyVersions.get(companyId);
401
434
  this._companyVersions.set(companyId, ack.version);
402
435
  this._persister?.setCompanyVersion(companyId, ack.version);
403
- if (known !== undefined && known !== ack.version) {
436
+ if (known === undefined) {
437
+ // First join: nothing to compare with, and changes made
438
+ // between the initial REST loads and joining the room
439
+ // were never delivered. Refresh what loaded before now
440
+ // once; later joins compare versions instead.
441
+ const joinedAt = Date.now();
442
+ this._queryClient?.invalidateQueries({
443
+ predicate: (q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt,
444
+ });
445
+ }
446
+ else if (known !== ack.version) {
404
447
  this._queryClient?.invalidateQueries();
405
448
  }
406
449
  });
@@ -545,12 +588,7 @@ export class AvroQueryClient {
545
588
  }
546
589
  throw new StandardError(401, 'Invalid Google login response');
547
590
  }
548
- this.setAuthState(AuthState.AUTHENTICATED);
549
- this.socket.auth = this.socketAuth(resp.access_token);
550
- if (!this.socket.connected) {
551
- this.ensureSocketConnected();
552
- }
553
- await this.config.authManager.setTokens({
591
+ await this.loginSuccess({
554
592
  access_token: resp.access_token,
555
593
  refresh_token: resp.refresh_token,
556
594
  });
@@ -576,12 +614,7 @@ export class AvroQueryClient {
576
614
  }
577
615
  throw new StandardError(401, 'Invalid Apple login response');
578
616
  }
579
- this.setAuthState(AuthState.AUTHENTICATED);
580
- this.socket.auth = this.socketAuth(resp.access_token);
581
- if (!this.socket.connected) {
582
- this.ensureSocketConnected();
583
- }
584
- await this.config.authManager.setTokens({
617
+ await this.loginSuccess({
585
618
  access_token: resp.access_token,
586
619
  refresh_token: resp.refresh_token,
587
620
  });
@@ -1088,12 +1121,12 @@ export class AvroQueryClient {
1088
1121
  throw fetchError(err, 'Failed to fetch skills');
1089
1122
  });
1090
1123
  }
1091
- fetchSessions(body = {}, cancelToken, headers = {}) {
1092
- if (!this.companyId || this.companyId.trim() === '') {
1124
+ fetchSessions(body = {}, cancelToken, headers = {}, companyId = this.companyId) {
1125
+ if (!companyId || companyId.trim() === '') {
1093
1126
  throw new StandardError(400, 'Company ID is required');
1094
1127
  }
1095
1128
  const amount = body.amt ?? Math.max(body.unknown_ids?.length ?? 0, 50);
1096
- return this._fetch('POST', `/company/${this.companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
1129
+ return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
1097
1130
  ...headers,
1098
1131
  'Content-Type': 'application/json',
1099
1132
  }, true)
@@ -2,7 +2,7 @@ import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs, seedDetails, removeOptimisticRow } from '../cache.js';
4
4
  import { keys, matchesList } from '../realtime.js';
5
- import { constructEvent, DelayEvent, Job, LineItemStatus, } from '../../types/api.js';
5
+ import { constructEvent, DelayEvent, Job, LineItemStatus, Task, getTaskOverdueTime, } from '../../types/api.js';
6
6
  const isJobsQuery = (q) => q.queryKey[0] === 'jobs';
7
7
  const isEventsQuery = (q) => q.queryKey[0] === 'events';
8
8
  const isEventsQueryFor = (item) => (q) => q.queryKey[0] === 'events' && matchesList('event', q.queryKey, item) === 'match';
@@ -179,13 +179,20 @@ AvroQueryClient.prototype.useCreateDelayEvent = function () {
179
179
  const delayUntil = Math.max(task.delay_until != null && task.delay_until > now
180
180
  ? task.delay_until
181
181
  : 0, now + delayData.delay_seconds);
182
- return {
182
+ if (task.overdue_time == null) {
183
+ return new Task({ ...task, delay_until: delayUntil });
184
+ }
185
+ // `delay` is how far the delay holds the task back,
186
+ // so the snapshot catches up once it lapses.
187
+ const live = getTaskOverdueTime(task, now);
188
+ const held = Math.min(live, now - delayUntil);
189
+ return new Task({
183
190
  ...task,
184
191
  delay_until: delayUntil,
185
- overdue_time: task.overdue_time != null
186
- ? Math.min(task.overdue_time, now - delayUntil)
187
- : task.overdue_time,
188
- };
192
+ delay: live - held,
193
+ overdue_time: held,
194
+ overdue_at: now,
195
+ });
189
196
  }
190
197
  return task;
191
198
  }),
@@ -283,24 +290,20 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
283
290
  last_completed_event: isEnding && mergedEvent ? mergedEvent : previousJob.last_completed_event,
284
291
  tasks: previousJob.tasks.map((task) => {
285
292
  if (updates.tasks?.includes(task.id ?? '')) {
286
- return {
293
+ return new Task({
287
294
  ...task,
288
295
  current_event: isEnding
289
296
  ? null
290
- : previousEvent
291
- ? { ...previousEvent, ...updates }
292
- : task.current_event,
297
+ : (mergedEvent ?? task.current_event),
293
298
  last_completed_event: isEnding
294
- ? previousEvent
295
- ? { ...previousEvent, ...updates }
296
- : task.last_completed_event
299
+ ? (mergedEvent ?? task.last_completed_event)
297
300
  : task.last_completed_event,
298
301
  // Next due a period out, or when an active
299
302
  // delay ends if that's later.
300
303
  overdue_time: isEnding
301
304
  ? -Math.max(task.frequency ?? 0, (task.delay_until ?? 0) - Date.now() / 1000)
302
305
  : task.overdue_time,
303
- };
306
+ });
304
307
  }
305
308
  return task;
306
309
  }),
@@ -315,16 +318,16 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
315
318
  return old;
316
319
  });
317
320
  }
318
- queryClient.setQueryData(['events', eventId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
321
+ queryClient.setQueryData(['events', eventId], (oldData) => oldData ? constructEvent({ ...oldData, ...updates }) : undefined);
319
322
  queryClient.setQueriesData({ queryKey: ['events'] }, (oldData) => {
320
323
  if (!oldData)
321
324
  return oldData;
322
325
  if (oldData.pages) {
323
- const updatedPages = oldData.pages.map((page) => page.map((event) => event.id === eventId ? { ...event, ...updates } : event));
326
+ const updatedPages = oldData.pages.map((page) => page.map((event) => event.id === eventId ? constructEvent({ ...event, ...updates }) : event));
324
327
  return { ...oldData, pages: updatedPages };
325
328
  }
326
329
  if (Array.isArray(oldData)) {
327
- return oldData.map((event) => event.id === eventId ? { ...event, ...updates } : event);
330
+ return oldData.map((event) => event.id === eventId ? constructEvent({ ...event, ...updates }) : event);
328
331
  }
329
332
  return oldData;
330
333
  });
@@ -28,22 +28,24 @@ AvroQueryClient.prototype.useGetMessages = function (chatId, body) {
28
28
  AvroQueryClient.prototype.useCreateMessage = function (chatId) {
29
29
  const queryClient = this.getQueryClient();
30
30
  return useMutation({
31
- mutationFn: async ({ content, time_sent, id }) => {
32
- const message = await this.post({
33
- path: `/chat/${chatId}/message`,
34
- data: JSON.stringify({
35
- message: {
36
- content,
37
- time_sent: time_sent ?? Math.floor(Date.now() / 1000),
38
- id,
39
- },
40
- }),
41
- headers: { 'Content-Type': 'application/json' },
42
- });
43
- return message;
44
- },
45
- onSuccess: (message) => {
46
- queryClient.setQueryData(['message', message.id], message);
31
+ // The backend replies `{ msg, id }`, not a full Message, so the
32
+ // reply is never cached as one; the list refetches instead.
33
+ mutationFn: ({ content, time_sent, id }) => this.post({
34
+ path: `/chat/${chatId}/message`,
35
+ data: JSON.stringify({
36
+ message: {
37
+ content,
38
+ time_sent: time_sent ?? Math.floor(Date.now() / 1000),
39
+ id,
40
+ },
41
+ }),
42
+ headers: { 'Content-Type': 'application/json' },
43
+ }),
44
+ onSettled: () => {
45
+ // `new_message` only reaches sockets in the chat room, so the
46
+ // sender can't rely on it to see their own message.
47
+ queryClient.invalidateQueries({ queryKey: ['messages', 'infinite', chatId] });
48
+ queryClient.invalidateQueries({ queryKey: ['chats'] });
47
49
  },
48
50
  });
49
51
  };
@@ -69,7 +69,7 @@ AvroQueryClient.prototype.useGetCompanySessionsByIds = function (sessionIds, par
69
69
  const sortedIds = [...sessionIds].sort();
70
70
  const result = useQuery({
71
71
  queryKey: keys.list(NS, companyId, listFilters({ unknown_ids: sortedIds })),
72
- queryFn: () => this.fetchSessions({ unknown_ids: sortedIds, amt: sortedIds.length }).then((sessions) => seedDetails(queryClient, NS, sessions.map((s) => new Session(s)))),
72
+ queryFn: () => this.fetchSessions({ unknown_ids: sortedIds, amt: sortedIds.length }, undefined, {}, companyId).then((sessions) => seedDetails(queryClient, NS, sessions.map((s) => new Session(s)))),
73
73
  enabled: Boolean(companyId) && sortedIds.length > 0 && (params.enabled ?? true),
74
74
  });
75
75
  return result;
@@ -80,7 +80,7 @@ AvroQueryClient.prototype.useGetActiveCompanySessions = function (params = {}) {
80
80
  const companyId = params.companyId ?? this.companyId;
81
81
  const result = useQuery({
82
82
  queryKey: keys.list(NS, companyId, listFilters({ active: true })),
83
- queryFn: () => this.fetchSessions({ active: true, amt: 500 }).then((sessions) => seedDetails(queryClient, NS, sessions.map((s) => new Session(s)))),
83
+ queryFn: () => this.fetchSessions({ active: true, amt: 500 }, undefined, {}, companyId).then((sessions) => seedDetails(queryClient, NS, sessions.map((s) => new Session(s)))),
84
84
  enabled: Boolean(companyId) && (params.enabled ?? true),
85
85
  });
86
86
  return result;
@@ -174,13 +174,16 @@ AvroQueryClient.prototype.useUpdateUserSession = function () {
174
174
  onMutate: async ({ sessionId, updates, }) => {
175
175
  await queryClient.cancelQueries({ queryKey: [NS] });
176
176
  const previous = snapshotSessionLists(queryClient);
177
+ const previousDetail = queryClient.getQueryData(keys.detail(NS, sessionId));
177
178
  patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
178
179
  queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...updates }) : old);
179
- return { previous };
180
+ return { previous, previousDetail };
180
181
  },
181
- onError: (_err, _vars, context) => {
182
+ onError: (_err, { sessionId }, context) => {
182
183
  if (context?.previous)
183
184
  restoreSessionLists(queryClient, context.previous);
185
+ if (context?.previousDetail)
186
+ queryClient.setQueryData(keys.detail(NS, sessionId), context.previousDetail);
184
187
  },
185
188
  onSettled: () => {
186
189
  this.syncAfterMutation('session', 'timecard');
@@ -229,13 +232,16 @@ AvroQueryClient.prototype.useUpdateCompanySession = function () {
229
232
  onMutate: async ({ sessionId, updates }) => {
230
233
  await queryClient.cancelQueries({ queryKey: [NS] });
231
234
  const previous = snapshotSessionLists(queryClient);
235
+ const previousDetail = queryClient.getQueryData(keys.detail(NS, sessionId));
232
236
  patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
233
237
  queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...updates }) : old);
234
- return { previous };
238
+ return { previous, previousDetail };
235
239
  },
236
- onError: (_err, _vars, context) => {
240
+ onError: (_err, { sessionId }, context) => {
237
241
  if (context?.previous)
238
242
  restoreSessionLists(queryClient, context.previous);
243
+ if (context?.previousDetail)
244
+ queryClient.setQueryData(keys.detail(NS, sessionId), context.previousDetail);
239
245
  },
240
246
  onSettled: () => {
241
247
  this.syncAfterMutation('session', 'timecard');
@@ -43,7 +43,13 @@ export interface EntitySpec {
43
43
  export declare function constructJob(raw: any): Job;
44
44
  export declare const REGISTRY: Record<string, EntitySpec>;
45
45
  export declare function removeEntity(qc: QueryClient, ns: string, id: string): void;
46
- export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any): void;
46
+ /**
47
+ * Write an entity into its detail entry and every list it belongs in.
48
+ * `company` is the company the change came from: list scopes are company
49
+ * ids, so another company's lists are left alone (a member of two
50
+ * companies keeps both companies' lists cached).
51
+ */
52
+ export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any, company?: string | null): void;
47
53
  export declare function matchesList(type: string, key: readonly unknown[], item: any): ListMatch;
48
54
  export declare function invalidateType(qc: QueryClient, spec: EntitySpec): void;
49
55
  export declare class ChangeApplier {
@@ -59,6 +65,8 @@ export declare class ChangeApplier {
59
65
  */
60
66
  private seq;
61
67
  private latest;
68
+ /** Company each pending `type:id` change came from (see upsertEntity). */
69
+ private companyOf;
62
70
  private inflight;
63
71
  constructor(client: AvroQueryClient, qc: QueryClient);
64
72
  private mark;
@@ -152,8 +152,10 @@ function matchTimecards(filters, item) {
152
152
  return 'nomatch';
153
153
  if (filters.status && item.status !== filters.status)
154
154
  return 'nomatch';
155
- if (filters.periodStart && item.period_start !== filters.periodStart)
156
- return 'nomatch';
155
+ // The backend snaps period_start to the enclosing pay period, so the
156
+ // requested instant can't be compared to item.start client-side.
157
+ if (filters.periodStart)
158
+ return 'unknown';
157
159
  return 'match';
158
160
  }
159
161
  function matchPayouts(filters, item) {
@@ -309,7 +311,13 @@ export function removeEntity(qc, ns, id) {
309
311
  qc.removeQueries({ queryKey: keys.detail(ns, id), exact: true });
310
312
  qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => (old ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old));
311
313
  }
312
- export function upsertEntity(qc, spec, item) {
314
+ /**
315
+ * Write an entity into its detail entry and every list it belongs in.
316
+ * `company` is the company the change came from: list scopes are company
317
+ * ids, so another company's lists are left alone (a member of two
318
+ * companies keeps both companies' lists cached).
319
+ */
320
+ export function upsertEntity(qc, spec, item, company) {
313
321
  const id = item?.id;
314
322
  if (!id)
315
323
  return;
@@ -319,6 +327,9 @@ export function upsertEntity(qc, spec, item) {
319
327
  .findAll({ predicate: (q) => q.queryKey[0] === spec.ns && isListKey(q.queryKey) });
320
328
  for (const query of lists) {
321
329
  const key = query.queryKey;
330
+ const scope = listScope(key);
331
+ if (company && scope && scope !== company)
332
+ continue;
322
333
  const verdict = spec.listMatch
323
334
  ? spec.listMatch(listFilters(key), item, listScope(key))
324
335
  : searchAware(listFilters(key));
@@ -378,6 +389,8 @@ export class ChangeApplier {
378
389
  */
379
390
  this.seq = 0;
380
391
  this.latest = new Map();
392
+ /** Company each pending `type:id` change came from (see upsertEntity). */
393
+ this.companyOf = new Map();
381
394
  this.inflight = new Map();
382
395
  }
383
396
  mark(type, id) {
@@ -394,6 +407,7 @@ export class ChangeApplier {
394
407
  }
395
408
  apply(payload) {
396
409
  const entries = Array.isArray(payload?.changes) ? payload.changes : [];
410
+ const company = payload?.company ?? null;
397
411
  for (const entry of entries) {
398
412
  const spec = REGISTRY[entry.type];
399
413
  if (!spec)
@@ -415,10 +429,11 @@ export class ChangeApplier {
415
429
  }
416
430
  if (entry.data !== undefined && entry.data !== null) {
417
431
  this.markApplied(entry.type, entry.id);
418
- upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data);
432
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data, company);
419
433
  spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
420
434
  continue;
421
435
  }
436
+ this.companyOf.set(`${entry.type}:${entry.id}`, company);
422
437
  this.enqueue(entry.type, entry.id);
423
438
  }
424
439
  }
@@ -473,8 +488,10 @@ export class ChangeApplier {
473
488
  return;
474
489
  }
475
490
  this.inflight.delete(key);
476
- if (current(id))
491
+ if (current(id)) {
477
492
  this.latest.delete(key);
493
+ this.companyOf.delete(key);
494
+ }
478
495
  };
479
496
  ids.forEach((id) => {
480
497
  const key = `${type}:${id}`;
@@ -526,7 +543,7 @@ export class ChangeApplier {
526
543
  for (const [id, raw] of found) {
527
544
  if (!current(id))
528
545
  continue;
529
- upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw);
546
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw, this.companyOf.get(`${type}:${id}`));
530
547
  }
531
548
  for (const id of gone) {
532
549
  if (current(id))
@@ -549,6 +566,7 @@ export class ChangeApplier {
549
566
  clearTimeout(this.timer);
550
567
  this.timer = null;
551
568
  this.pending.clear();
569
+ this.companyOf.clear();
552
570
  this.latest.clear();
553
571
  this.inflight.clear();
554
572
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { LineItem } from './LineItem.js';
2
3
  export const BillStatus = {
3
4
  SENT: 'SENT',
@@ -17,7 +18,7 @@ export class Bill {
17
18
  this.customItems = () => (this.line_items ?? []).filter((item) => item.line_item_type === 'CUSTOM' || item.line_item_type === 'PROCESSING_FEE');
18
19
  this.topLevelItems = () => (this.line_items ?? []).filter((item) => !item.parent_id);
19
20
  this.childItems = (parentId) => (this.line_items ?? []).filter((item) => item.parent_id === parentId);
20
- Object.assign(this, init);
21
+ assignData(this, init);
21
22
  if (init?.line_items) {
22
23
  this.line_items = init.line_items.map((item) => new LineItem(item));
23
24
  }
@@ -3,21 +3,15 @@ export interface Email {
3
3
  id: string;
4
4
  company_id: string;
5
5
  name: string;
6
- mail_server: string;
7
- mail_port: number;
8
6
  mail_username: string;
9
- mail_password: string | null;
10
7
  mail_default_sender: string;
11
- mail_use_tls: boolean;
12
- mail_use_ssl: boolean;
13
8
  mail_api_key: string;
14
9
  is_company_wide: boolean;
15
10
  users: User[];
16
- type: 'OUTLOOK' | 'SMTP' | 'GMAIL';
11
+ type: 'OUTLOOK' | 'GMAIL';
17
12
  /**
18
- * False when an OAuth (Outlook/Gmail) account's grant was revoked or
19
- * expired: sends fail until someone signs in again. Always true for
20
- * SMTP accounts.
13
+ * False when the account's grant was revoked or expired: sends fail
14
+ * until someone signs in again.
21
15
  */
22
16
  connected: boolean;
23
17
  }
@@ -19,7 +19,7 @@ export interface EmailError {
19
19
  * raised before any provider could be selected (e.g. missing
20
20
  * billing email, no recipients).
21
21
  */
22
- provider: 'outlook' | 'gmail' | 'smtp' | 'unknown';
22
+ provider: 'outlook' | 'gmail' | 'unknown';
23
23
  }
24
24
  export type EmailType = 'bill' | 'proposal' | 'job' | 'generic';
25
25
  export interface EmailSucceededPayload {
@@ -1,4 +1,5 @@
1
- import { Task, TaskStatus } from './Task.js';
1
+ import { assignData } from './assignData.js';
2
+ import { Task, TaskStatus, getTaskOverdueness } from './Task.js';
2
3
  import { RouteJob } from './RouteJob.js';
3
4
  export class Job {
4
5
  constructor(init) {
@@ -10,11 +11,14 @@ export class Job {
10
11
  if (activeTasks.length === 0) {
11
12
  return 'N/A';
12
13
  }
14
+ const now = Date.now() / 1000;
15
+ const live = (t) => getTaskOverdueness(t, now);
13
16
  const mostOverdueTask = activeTasks.reduce((mostOverdue, t) => {
14
- if (!t.overdueness || t.overdueness <= 0) {
17
+ const overdueness = live(t);
18
+ if (!overdueness || overdueness <= 0) {
15
19
  return mostOverdue;
16
20
  }
17
- if (!mostOverdue || t.overdueness > (mostOverdue.overdueness ?? 0)) {
21
+ if (!mostOverdue || overdueness > (live(mostOverdue) ?? 0)) {
18
22
  return t;
19
23
  }
20
24
  return mostOverdue;
@@ -59,7 +63,7 @@ export class Job {
59
63
  this.isDone = (route) => {
60
64
  return this.portionDone(route) === 1;
61
65
  };
62
- Object.assign(this, init);
66
+ assignData(this, init);
63
67
  if (init?.tasks) {
64
68
  this.tasks = init.tasks.map((t) => new Task(t));
65
69
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  export const LineItemStatus = {
2
3
  CREATED: 'CREATED',
3
4
  PENDING_AUTOBILL: 'PENDING_AUTOBILL',
@@ -37,6 +38,6 @@ export class LineItem {
37
38
  return (this.status === LineItemStatus.PENDING_AUTOBILL ||
38
39
  this.status === LineItemStatus.PROCESSING);
39
40
  };
40
- Object.assign(this, init);
41
+ assignData(this, init);
41
42
  }
42
43
  }
@@ -1,7 +1,8 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { LineItem } from './LineItem.js';
2
3
  export class Prepayment extends LineItem {
3
4
  constructor(init) {
4
5
  super(init);
5
- Object.assign(this, init);
6
+ assignData(this, init);
6
7
  }
7
8
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { RouteJob } from './RouteJob.js';
2
3
  export const FrequencyType = {
3
4
  ONCE: 'ONCE',
@@ -84,7 +85,7 @@ export class Route {
84
85
  }
85
86
  return offset;
86
87
  };
87
- Object.assign(this, init);
88
+ assignData(this, init);
88
89
  if (init?.jobs) {
89
90
  this.jobs = init.jobs.map((j) => new RouteJob(j));
90
91
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  export class RouteJob {
2
3
  constructor(init) {
3
4
  this.getPredictedArrival = () => {
@@ -5,7 +6,7 @@ export class RouteJob {
5
6
  ? this.estimated_arrival_time
6
7
  : this.scheduled_arrival_time;
7
8
  };
8
- Object.assign(this, init);
9
+ assignData(this, init);
9
10
  this.tasks = (init?.tasks ?? []).map((t) => typeof t === 'string'
10
11
  ? { id: t, depends_on: [] }
11
12
  : { ...t, depends_on: t.depends_on ?? [] });
@@ -1,5 +1,6 @@
1
+ import { assignData } from './assignData.js';
1
2
  export class Session {
2
3
  constructor(init) {
3
- Object.assign(this, init);
4
+ assignData(this, init);
4
5
  }
5
6
  }
@@ -45,8 +45,19 @@ declare module './Task.js' {
45
45
  time_updated: number | null;
46
46
  status: TaskStatus;
47
47
  created_by: UserCompanyAssociation | null;
48
+ /**
49
+ * Overdueness as of `overdue_at`. It grows with time while nothing
50
+ * in the database changes, so no realtime event refreshes it:
51
+ * prefer `getOverdueness()`.
52
+ */
48
53
  overdueness: number | null;
54
+ /** Seconds overdue as of `overdue_at`; prefer `getOverdueTime()`. */
49
55
  overdue_time: number;
56
+ /**
57
+ * When (epoch seconds) `overdueness`/`overdue_time` were computed:
58
+ * when the server payload arrived, unless the copy carried one.
59
+ */
60
+ overdue_at: number;
50
61
  last_completed_event: _Event | null;
51
62
  current_event: _Event | null;
52
63
  /**
@@ -84,12 +95,25 @@ declare module './Task.js' {
84
95
  export declare const getTaskDelayUntil: (task: {
85
96
  delay_until?: number | null;
86
97
  }, now?: number) => number | null;
98
+ /**
99
+ * Seconds overdue at `now`, rolled forward from the server's snapshot.
100
+ * Mirrors the backend: the clock only moves the value forward, except that
101
+ * a delay stops counting once it has ended.
102
+ */
103
+ type OverdueSnapshot = Partial<Pick<Task, 'overdueness' | 'overdue_time' | 'overdue_at' | 'delay' | 'delay_until' | 'status' | 'frequency' | 'priority'>>;
104
+ export declare const getTaskOverdueTime: (task: OverdueSnapshot, now?: number) => number;
105
+ /** The backend's overdueness formula, evaluated at `now`. */
106
+ export declare const getTaskOverdueness: (task: OverdueSnapshot, now?: number) => number | null;
87
107
  export declare class Task {
88
108
  constructor(init?: Partial<Task>);
89
109
  getStatusLabel: () => "Active" | "Archived" | "Pending Activation" | "Draft" | "Pending Customer Approval" | "Pending Company Approval" | "Pending Payment";
90
110
  getUnroutedReasonLabel: () => string | null;
91
- isOverdue: () => boolean;
92
- getOverdueLabel: () => string;
111
+ /** Seconds overdue right now (negative: due in that many seconds). */
112
+ getOverdueTime: (now?: number) => number;
113
+ /** Overdueness right now; null when the server reported none. */
114
+ getOverdueness: (now?: number) => number | null;
115
+ isOverdue: (now?: number) => boolean;
116
+ getOverdueLabel: (now?: number) => string;
93
117
  /** End (epoch seconds) of this task's delay if it's still in effect. */
94
118
  getDelayUntil: (now?: number) => number | null;
95
119
  isDelayed: (now?: number) => boolean;
@@ -99,3 +123,4 @@ export declare class Task {
99
123
  getPrepaidMonthsRemaining: () => number;
100
124
  isDone: (route: Route) => boolean;
101
125
  }
126
+ export {};
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { Prepayment } from './Prepayment.js';
2
3
  export const TaskStatus = {
3
4
  PENDING_CUSTOMER: 'PENDING_CUSTOMER',
@@ -39,6 +40,32 @@ export const UNROUTED_REASON_LABELS = {
39
40
  * A plain function so it works on spread copies of a Task too.
40
41
  */
41
42
  export const getTaskDelayUntil = (task, now = Date.now() / 1000) => (task.delay_until != null && task.delay_until > now ? task.delay_until : null);
43
+ export const getTaskOverdueTime = (task, now = Date.now() / 1000) => {
44
+ if (task.overdue_time == null)
45
+ return 0;
46
+ const at = task.overdue_at ?? now;
47
+ let time = task.overdue_time + Math.max(now - at, 0);
48
+ // The snapshot subtracted a delay that has since lapsed.
49
+ if (task.delay_until != null && task.delay_until > at && task.delay_until <= now) {
50
+ time += task.delay ?? 0;
51
+ }
52
+ return time;
53
+ };
54
+ /** The backend's overdueness formula, evaluated at `now`. */
55
+ export const getTaskOverdueness = (task, now = Date.now() / 1000) => {
56
+ if (task.overdueness == null || task.status !== TaskStatus.ACTIVE) {
57
+ return task.overdueness ?? null;
58
+ }
59
+ const overdueTime = getTaskOverdueTime(task, now);
60
+ if (task.frequency && task.frequency > 0) {
61
+ // overdue_time counts from the due date; overdueness from the
62
+ // last service, one period earlier.
63
+ const scalar = task.priority ? 3 : 1;
64
+ const ratio = Math.max((overdueTime + task.frequency) / task.frequency, 0.01);
65
+ return Math.min(ratio * scalar, task.priority ? 10 : 3);
66
+ }
67
+ return overdueTime / (86400 * (task.priority ? 1 : 7));
68
+ };
42
69
  export class Task {
43
70
  constructor(init) {
44
71
  this.getStatusLabel = () => {
@@ -66,23 +93,28 @@ export class Task {
66
93
  return null;
67
94
  return UNROUTED_REASON_LABELS[this.last_unrouted_reason] ?? this.last_unrouted_reason;
68
95
  };
69
- this.isOverdue = () => {
96
+ /** Seconds overdue right now (negative: due in that many seconds). */
97
+ this.getOverdueTime = (now) => getTaskOverdueTime(this, now);
98
+ /** Overdueness right now; null when the server reported none. */
99
+ this.getOverdueness = (now) => getTaskOverdueness(this, now);
100
+ this.isOverdue = (now) => {
70
101
  return (this.status === TaskStatus.ACTIVE &&
71
102
  this.overdue_time !== undefined &&
72
- this.overdue_time > 0);
103
+ this.getOverdueTime(now) > 0);
73
104
  };
74
- this.getOverdueLabel = () => {
105
+ this.getOverdueLabel = (now) => {
106
+ const overdueTime = this.getOverdueTime(now);
75
107
  if (this.overdueness === null || this.status !== TaskStatus.ACTIVE) {
76
108
  return this.getStatusLabel();
77
109
  }
78
- else if (this.overdue_time <= 0) {
79
- return `In ${Math.abs(Math.round(this.overdue_time / 86400))}d`;
110
+ else if (overdueTime <= 0) {
111
+ return `In ${Math.abs(Math.round(overdueTime / 86400))}d`;
80
112
  }
81
- else if (this.overdue_time < 86400) {
113
+ else if (overdueTime < 86400) {
82
114
  return '< 1d overdue';
83
115
  }
84
116
  else {
85
- return `${Math.floor(this.overdue_time / 86400)}d overdue`;
117
+ return `${Math.floor(overdueTime / 86400)}d overdue`;
86
118
  }
87
119
  };
88
120
  /** End (epoch seconds) of this task's delay if it's still in effect. */
@@ -153,7 +185,11 @@ export class Task {
153
185
  const cutoff = Math.floor(routeDay.getTime() / 1000);
154
186
  return (this.last_completed_event?.time_ended ?? 0) >= cutoff;
155
187
  };
156
- Object.assign(this, init);
188
+ assignData(this, init);
189
+ // Payloads from the server carry no timestamp: they were computed
190
+ // just now. Copies keep the one they were made with.
191
+ if (this.overdue_at == null)
192
+ this.overdue_at = Date.now() / 1000;
157
193
  if (init?.prepayments) {
158
194
  this.prepayments = init.prepayments.map((p) => new Prepayment(p));
159
195
  }
@@ -1,3 +1,4 @@
1
+ import { assignData } from './assignData.js';
1
2
  import { LineItem } from './LineItem.js';
2
3
  export class _Event extends LineItem {
3
4
  constructor(init) {
@@ -6,7 +7,7 @@ export class _Event extends LineItem {
6
7
  const additionalChargesCost = this.additional_charges.reduce((acc, charge) => acc + (charge.cost ?? 0) * (charge.amount ?? 0), 0);
7
8
  return this.cost * this.amount + additionalChargesCost;
8
9
  };
9
- Object.assign(this, init);
10
+ assignData(this, init);
10
11
  this.breaks = init?.breaks ?? [];
11
12
  this.images = init?.images ?? [];
12
13
  this.tasks = init?.tasks ?? [];
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Copy an init object's data onto a model instance.
3
+ *
4
+ * Model methods are arrow-function class fields bound to their own
5
+ * instance. Rebuilding a model from a spread of another instance
6
+ * (`new Job({ ...job, ...updates })`) would otherwise copy the old
7
+ * instance's methods, which keep reading the old object.
8
+ */
9
+ export declare function assignData<T extends object>(target: T, init?: Partial<T>): void;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Copy an init object's data onto a model instance.
3
+ *
4
+ * Model methods are arrow-function class fields bound to their own
5
+ * instance. Rebuilding a model from a spread of another instance
6
+ * (`new Job({ ...job, ...updates })`) would otherwise copy the old
7
+ * instance's methods, which keep reading the old object.
8
+ */
9
+ export function assignData(target, init) {
10
+ if (!init)
11
+ return;
12
+ for (const [key, value] of Object.entries(init)) {
13
+ if (typeof value === 'function')
14
+ continue;
15
+ target[key] = value;
16
+ }
17
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "1.6.0";
1
+ export declare const AVRO_JS_VERSION = "1.6.1-rc1";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // AUTO-GENERATED by scripts/gen-version.js — do not edit by hand.
2
2
  // Regenerated from package.json by the `prebuild` npm hook.
3
- export const AVRO_JS_VERSION = '1.6.0';
3
+ export const AVRO_JS_VERSION = '1.6.1-rc1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "1.6.0",
3
+ "version": "1.6.1-rc1",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",