@go-avro/avro-js 1.6.1 → 1.6.3
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.
- package/dist/auth/AuthManager.d.ts +4 -0
- package/dist/auth/AuthManager.js +21 -2
- package/dist/client/QueryClient.d.ts +37 -2
- package/dist/client/QueryClient.js +118 -7
- package/dist/client/hooks/events.js +11 -4
- package/dist/client/realtime.d.ts +9 -1
- package/dist/client/realtime.js +20 -4
- package/dist/types/api/Email.d.ts +3 -9
- package/dist/types/api/EmailNotification.d.ts +1 -1
- package/dist/types/api/Job.js +6 -3
- package/dist/types/api/Task.d.ts +27 -2
- package/dist/types/api/Task.js +42 -7
- package/dist/types/api/User.d.ts +4 -0
- package/dist/types/api.d.ts +12 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -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>;
|
package/dist/auth/AuthManager.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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() {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Socket } from 'socket.io-client';
|
|
2
2
|
import { InfiniteData, QueryClient, UseInfiniteQueryResult, useMutation, UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
import { AuthManager } from '../auth/AuthManager.js';
|
|
4
|
-
import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Break, Chat, CheckIn, Company, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, 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, Break, Chat, CheckIn, Company, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLoginResult, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api.js';
|
|
5
5
|
import { AuthState, Tokens } from '../types/auth.js';
|
|
6
6
|
import { CancelToken, ClientId, RetryStrategy } from '../types/client.js';
|
|
7
7
|
import { StandardError } from '../types/error.js';
|
|
@@ -850,10 +850,45 @@ export declare class AvroQueryClient {
|
|
|
850
850
|
token: string;
|
|
851
851
|
cancelToken?: CancelToken;
|
|
852
852
|
}>>;
|
|
853
|
-
|
|
853
|
+
/**
|
|
854
|
+
* Sign in with an Apple identity token. `nonce` is the raw value whose
|
|
855
|
+
* SHA-256 was passed to Apple; the server checks and spends it. With no
|
|
856
|
+
* account for the Apple ID yet this resolves `NEEDS_ACCOUNT` (rather
|
|
857
|
+
* than failing) carrying the handle for `useAppleRegister`.
|
|
858
|
+
*/
|
|
859
|
+
useAppleLogin(): ReturnType<typeof useMutation<AppleLoginResult, StandardError, {
|
|
854
860
|
token: string;
|
|
861
|
+
nonce: string;
|
|
862
|
+
authorizationCode?: string | null;
|
|
863
|
+
cancelToken?: CancelToken;
|
|
864
|
+
}>>;
|
|
865
|
+
/**
|
|
866
|
+
* Create an account for an Apple ID that `useAppleLogin` found no
|
|
867
|
+
* account for, then sign in. Apple only shares the name on the first
|
|
868
|
+
* authorization, so the caller supplies it (prompting when missing).
|
|
869
|
+
*/
|
|
870
|
+
useAppleRegister(): ReturnType<typeof useMutation<LoginResponse, StandardError, {
|
|
871
|
+
appleToken: string;
|
|
872
|
+
firstName: string;
|
|
873
|
+
lastName?: string;
|
|
874
|
+
username?: string;
|
|
875
|
+
inviteToken?: string;
|
|
876
|
+
authorizationCode?: string | null;
|
|
855
877
|
cancelToken?: CancelToken;
|
|
856
878
|
}>>;
|
|
879
|
+
/** Link an Apple ID to the signed-in account (fresh token + raw nonce). */
|
|
880
|
+
useAppleLink(): ReturnType<typeof useMutation<{
|
|
881
|
+
msg: string;
|
|
882
|
+
}, StandardError, {
|
|
883
|
+
token: string;
|
|
884
|
+
nonce: string;
|
|
885
|
+
authorizationCode?: string | null;
|
|
886
|
+
cancelToken?: CancelToken;
|
|
887
|
+
}>>;
|
|
888
|
+
/** Unlink the account's Apple ID; the server revokes Apple's grant. */
|
|
889
|
+
useAppleUnlink(): ReturnType<typeof useMutation<{
|
|
890
|
+
msg: string;
|
|
891
|
+
}, StandardError, void>>;
|
|
857
892
|
setTokens(tokens: Tokens): Promise<void>;
|
|
858
893
|
setCache(data: Partial<CacheData> | Object): Promise<void>;
|
|
859
894
|
getCache(key?: keyof CacheData | string): Promise<CacheData[keyof CacheData] | Object | string | null>;
|
|
@@ -433,7 +433,17 @@ export class AvroQueryClient {
|
|
|
433
433
|
const known = this._companyVersions.get(companyId);
|
|
434
434
|
this._companyVersions.set(companyId, ack.version);
|
|
435
435
|
this._persister?.setCompanyVersion(companyId, ack.version);
|
|
436
|
-
if (known
|
|
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) {
|
|
437
447
|
this._queryClient?.invalidateQueries();
|
|
438
448
|
}
|
|
439
449
|
});
|
|
@@ -593,22 +603,53 @@ export class AvroQueryClient {
|
|
|
593
603
|
},
|
|
594
604
|
});
|
|
595
605
|
}
|
|
606
|
+
/**
|
|
607
|
+
* Sign in with an Apple identity token. `nonce` is the raw value whose
|
|
608
|
+
* SHA-256 was passed to Apple; the server checks and spends it. With no
|
|
609
|
+
* account for the Apple ID yet this resolves `NEEDS_ACCOUNT` (rather
|
|
610
|
+
* than failing) carrying the handle for `useAppleRegister`.
|
|
611
|
+
*/
|
|
596
612
|
useAppleLogin() {
|
|
597
613
|
const queryClient = this.getQueryClient();
|
|
598
614
|
return useMutation({
|
|
599
|
-
mutationFn: async ({ token, cancelToken, }) => {
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
615
|
+
mutationFn: async ({ token, nonce, authorizationCode, cancelToken, }) => {
|
|
616
|
+
let resp;
|
|
617
|
+
try {
|
|
618
|
+
resp = await this.post({
|
|
619
|
+
path: '/apple/login',
|
|
620
|
+
data: JSON.stringify({
|
|
621
|
+
token,
|
|
622
|
+
nonce,
|
|
623
|
+
authorization_code: authorizationCode ?? undefined,
|
|
624
|
+
}),
|
|
625
|
+
cancelToken,
|
|
626
|
+
headers: { 'Content-Type': 'application/json' },
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
catch (err) {
|
|
630
|
+
const body = err instanceof StandardError ? err.body : undefined;
|
|
631
|
+
if (err instanceof StandardError &&
|
|
632
|
+
err.status === 404 &&
|
|
633
|
+
body &&
|
|
634
|
+
typeof body.apple_token === 'string') {
|
|
635
|
+
const notFound = body;
|
|
636
|
+
return {
|
|
637
|
+
status: 'NEEDS_ACCOUNT',
|
|
638
|
+
apple_token: notFound.apple_token,
|
|
639
|
+
email: notFound.email ?? null,
|
|
640
|
+
is_private_email: Boolean(notFound.is_private_email),
|
|
641
|
+
};
|
|
604
642
|
}
|
|
643
|
+
throw err;
|
|
644
|
+
}
|
|
645
|
+
if (!resp || !('access_token' in resp)) {
|
|
605
646
|
throw new StandardError(401, 'Invalid Apple login response');
|
|
606
647
|
}
|
|
607
648
|
await this.loginSuccess({
|
|
608
649
|
access_token: resp.access_token,
|
|
609
650
|
refresh_token: resp.refresh_token,
|
|
610
651
|
});
|
|
611
|
-
return LoginResponse.SUCCESS;
|
|
652
|
+
return { status: LoginResponse.SUCCESS };
|
|
612
653
|
},
|
|
613
654
|
onSettled: () => {
|
|
614
655
|
queryClient.invalidateQueries();
|
|
@@ -619,6 +660,76 @@ export class AvroQueryClient {
|
|
|
619
660
|
},
|
|
620
661
|
});
|
|
621
662
|
}
|
|
663
|
+
/**
|
|
664
|
+
* Create an account for an Apple ID that `useAppleLogin` found no
|
|
665
|
+
* account for, then sign in. Apple only shares the name on the first
|
|
666
|
+
* authorization, so the caller supplies it (prompting when missing).
|
|
667
|
+
*/
|
|
668
|
+
useAppleRegister() {
|
|
669
|
+
const queryClient = this.getQueryClient();
|
|
670
|
+
return useMutation({
|
|
671
|
+
mutationFn: async ({ appleToken, firstName, lastName, username, inviteToken, authorizationCode, cancelToken, }) => {
|
|
672
|
+
const resp = await this.post({
|
|
673
|
+
path: '/apple/register',
|
|
674
|
+
data: JSON.stringify({
|
|
675
|
+
apple_token: appleToken,
|
|
676
|
+
first_name: firstName,
|
|
677
|
+
last_name: lastName,
|
|
678
|
+
username,
|
|
679
|
+
invite_token: inviteToken,
|
|
680
|
+
authorization_code: authorizationCode ?? undefined,
|
|
681
|
+
}),
|
|
682
|
+
cancelToken,
|
|
683
|
+
headers: { 'Content-Type': 'application/json' },
|
|
684
|
+
});
|
|
685
|
+
if (!resp || !('access_token' in resp)) {
|
|
686
|
+
throw new StandardError(401, 'Invalid Apple sign-up response');
|
|
687
|
+
}
|
|
688
|
+
await this.loginSuccess({
|
|
689
|
+
access_token: resp.access_token,
|
|
690
|
+
refresh_token: resp.refresh_token,
|
|
691
|
+
});
|
|
692
|
+
return LoginResponse.SUCCESS;
|
|
693
|
+
},
|
|
694
|
+
onSettled: () => {
|
|
695
|
+
queryClient.invalidateQueries();
|
|
696
|
+
},
|
|
697
|
+
onError: (err) => {
|
|
698
|
+
console.error('Apple sign-up failed:', err);
|
|
699
|
+
},
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
/** Link an Apple ID to the signed-in account (fresh token + raw nonce). */
|
|
703
|
+
useAppleLink() {
|
|
704
|
+
return useMutation({
|
|
705
|
+
mutationFn: async ({ token, nonce, authorizationCode, cancelToken, }) => {
|
|
706
|
+
return this.post({
|
|
707
|
+
path: '/apple/link',
|
|
708
|
+
data: JSON.stringify({
|
|
709
|
+
token,
|
|
710
|
+
nonce,
|
|
711
|
+
authorization_code: authorizationCode ?? undefined,
|
|
712
|
+
}),
|
|
713
|
+
cancelToken,
|
|
714
|
+
headers: { 'Content-Type': 'application/json' },
|
|
715
|
+
});
|
|
716
|
+
},
|
|
717
|
+
onSettled: () => {
|
|
718
|
+
this.syncAfterMutation('user');
|
|
719
|
+
},
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
/** Unlink the account's Apple ID; the server revokes Apple's grant. */
|
|
723
|
+
useAppleUnlink() {
|
|
724
|
+
return useMutation({
|
|
725
|
+
mutationFn: async () => {
|
|
726
|
+
return this.delete({ path: '/apple/link' });
|
|
727
|
+
},
|
|
728
|
+
onSettled: () => {
|
|
729
|
+
this.syncAfterMutation('user');
|
|
730
|
+
},
|
|
731
|
+
});
|
|
732
|
+
}
|
|
622
733
|
setTokens(tokens) {
|
|
623
734
|
return this.config.authManager.setTokens(tokens);
|
|
624
735
|
}
|
|
@@ -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, Task, } 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,12 +179,19 @@ 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
|
+
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);
|
|
182
189
|
return new Task({
|
|
183
190
|
...task,
|
|
184
191
|
delay_until: delayUntil,
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
192
|
+
delay: live - held,
|
|
193
|
+
overdue_time: held,
|
|
194
|
+
overdue_at: now,
|
|
188
195
|
});
|
|
189
196
|
}
|
|
190
197
|
return task;
|
|
@@ -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
|
-
|
|
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;
|
package/dist/client/realtime.js
CHANGED
|
@@ -311,7 +311,13 @@ export function removeEntity(qc, ns, id) {
|
|
|
311
311
|
qc.removeQueries({ queryKey: keys.detail(ns, id), exact: true });
|
|
312
312
|
qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => (old ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old));
|
|
313
313
|
}
|
|
314
|
-
|
|
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) {
|
|
315
321
|
const id = item?.id;
|
|
316
322
|
if (!id)
|
|
317
323
|
return;
|
|
@@ -321,6 +327,9 @@ export function upsertEntity(qc, spec, item) {
|
|
|
321
327
|
.findAll({ predicate: (q) => q.queryKey[0] === spec.ns && isListKey(q.queryKey) });
|
|
322
328
|
for (const query of lists) {
|
|
323
329
|
const key = query.queryKey;
|
|
330
|
+
const scope = listScope(key);
|
|
331
|
+
if (company && scope && scope !== company)
|
|
332
|
+
continue;
|
|
324
333
|
const verdict = spec.listMatch
|
|
325
334
|
? spec.listMatch(listFilters(key), item, listScope(key))
|
|
326
335
|
: searchAware(listFilters(key));
|
|
@@ -380,6 +389,8 @@ export class ChangeApplier {
|
|
|
380
389
|
*/
|
|
381
390
|
this.seq = 0;
|
|
382
391
|
this.latest = new Map();
|
|
392
|
+
/** Company each pending `type:id` change came from (see upsertEntity). */
|
|
393
|
+
this.companyOf = new Map();
|
|
383
394
|
this.inflight = new Map();
|
|
384
395
|
}
|
|
385
396
|
mark(type, id) {
|
|
@@ -396,6 +407,7 @@ export class ChangeApplier {
|
|
|
396
407
|
}
|
|
397
408
|
apply(payload) {
|
|
398
409
|
const entries = Array.isArray(payload?.changes) ? payload.changes : [];
|
|
410
|
+
const company = payload?.company ?? null;
|
|
399
411
|
for (const entry of entries) {
|
|
400
412
|
const spec = REGISTRY[entry.type];
|
|
401
413
|
if (!spec)
|
|
@@ -417,10 +429,11 @@ export class ChangeApplier {
|
|
|
417
429
|
}
|
|
418
430
|
if (entry.data !== undefined && entry.data !== null) {
|
|
419
431
|
this.markApplied(entry.type, entry.id);
|
|
420
|
-
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);
|
|
421
433
|
spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
|
|
422
434
|
continue;
|
|
423
435
|
}
|
|
436
|
+
this.companyOf.set(`${entry.type}:${entry.id}`, company);
|
|
424
437
|
this.enqueue(entry.type, entry.id);
|
|
425
438
|
}
|
|
426
439
|
}
|
|
@@ -475,8 +488,10 @@ export class ChangeApplier {
|
|
|
475
488
|
return;
|
|
476
489
|
}
|
|
477
490
|
this.inflight.delete(key);
|
|
478
|
-
if (current(id))
|
|
491
|
+
if (current(id)) {
|
|
479
492
|
this.latest.delete(key);
|
|
493
|
+
this.companyOf.delete(key);
|
|
494
|
+
}
|
|
480
495
|
};
|
|
481
496
|
ids.forEach((id) => {
|
|
482
497
|
const key = `${type}:${id}`;
|
|
@@ -528,7 +543,7 @@ export class ChangeApplier {
|
|
|
528
543
|
for (const [id, raw] of found) {
|
|
529
544
|
if (!current(id))
|
|
530
545
|
continue;
|
|
531
|
-
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}`));
|
|
532
547
|
}
|
|
533
548
|
for (const id of gone) {
|
|
534
549
|
if (current(id))
|
|
@@ -551,6 +566,7 @@ export class ChangeApplier {
|
|
|
551
566
|
clearTimeout(this.timer);
|
|
552
567
|
this.timer = null;
|
|
553
568
|
this.pending.clear();
|
|
569
|
+
this.companyOf.clear();
|
|
554
570
|
this.latest.clear();
|
|
555
571
|
this.inflight.clear();
|
|
556
572
|
}
|
|
@@ -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' | '
|
|
11
|
+
type: 'OUTLOOK' | 'GMAIL';
|
|
17
12
|
/**
|
|
18
|
-
* False when
|
|
19
|
-
*
|
|
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' | '
|
|
22
|
+
provider: 'outlook' | 'gmail' | 'unknown';
|
|
23
23
|
}
|
|
24
24
|
export type EmailType = 'bill' | 'proposal' | 'job' | 'generic';
|
|
25
25
|
export interface EmailSucceededPayload {
|
package/dist/types/api/Job.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { assignData } from './assignData.js';
|
|
2
|
-
import { Task, TaskStatus } from './Task.js';
|
|
2
|
+
import { Task, TaskStatus, getTaskOverdueness } from './Task.js';
|
|
3
3
|
import { RouteJob } from './RouteJob.js';
|
|
4
4
|
export class Job {
|
|
5
5
|
constructor(init) {
|
|
@@ -11,11 +11,14 @@ export class Job {
|
|
|
11
11
|
if (activeTasks.length === 0) {
|
|
12
12
|
return 'N/A';
|
|
13
13
|
}
|
|
14
|
+
const now = Date.now() / 1000;
|
|
15
|
+
const live = (t) => getTaskOverdueness(t, now);
|
|
14
16
|
const mostOverdueTask = activeTasks.reduce((mostOverdue, t) => {
|
|
15
|
-
|
|
17
|
+
const overdueness = live(t);
|
|
18
|
+
if (!overdueness || overdueness <= 0) {
|
|
16
19
|
return mostOverdue;
|
|
17
20
|
}
|
|
18
|
-
if (!mostOverdue ||
|
|
21
|
+
if (!mostOverdue || overdueness > (live(mostOverdue) ?? 0)) {
|
|
19
22
|
return t;
|
|
20
23
|
}
|
|
21
24
|
return mostOverdue;
|
package/dist/types/api/Task.d.ts
CHANGED
|
@@ -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
|
-
|
|
92
|
-
|
|
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 {};
|
package/dist/types/api/Task.js
CHANGED
|
@@ -40,6 +40,32 @@ export const UNROUTED_REASON_LABELS = {
|
|
|
40
40
|
* A plain function so it works on spread copies of a Task too.
|
|
41
41
|
*/
|
|
42
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
|
+
};
|
|
43
69
|
export class Task {
|
|
44
70
|
constructor(init) {
|
|
45
71
|
this.getStatusLabel = () => {
|
|
@@ -67,23 +93,28 @@ export class Task {
|
|
|
67
93
|
return null;
|
|
68
94
|
return UNROUTED_REASON_LABELS[this.last_unrouted_reason] ?? this.last_unrouted_reason;
|
|
69
95
|
};
|
|
70
|
-
|
|
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) => {
|
|
71
101
|
return (this.status === TaskStatus.ACTIVE &&
|
|
72
102
|
this.overdue_time !== undefined &&
|
|
73
|
-
this.
|
|
103
|
+
this.getOverdueTime(now) > 0);
|
|
74
104
|
};
|
|
75
|
-
this.getOverdueLabel = () => {
|
|
105
|
+
this.getOverdueLabel = (now) => {
|
|
106
|
+
const overdueTime = this.getOverdueTime(now);
|
|
76
107
|
if (this.overdueness === null || this.status !== TaskStatus.ACTIVE) {
|
|
77
108
|
return this.getStatusLabel();
|
|
78
109
|
}
|
|
79
|
-
else if (
|
|
80
|
-
return `In ${Math.abs(Math.round(
|
|
110
|
+
else if (overdueTime <= 0) {
|
|
111
|
+
return `In ${Math.abs(Math.round(overdueTime / 86400))}d`;
|
|
81
112
|
}
|
|
82
|
-
else if (
|
|
113
|
+
else if (overdueTime < 86400) {
|
|
83
114
|
return '< 1d overdue';
|
|
84
115
|
}
|
|
85
116
|
else {
|
|
86
|
-
return `${Math.floor(
|
|
117
|
+
return `${Math.floor(overdueTime / 86400)}d overdue`;
|
|
87
118
|
}
|
|
88
119
|
};
|
|
89
120
|
/** End (epoch seconds) of this task's delay if it's still in effect. */
|
|
@@ -155,6 +186,10 @@ export class Task {
|
|
|
155
186
|
return (this.last_completed_event?.time_ended ?? 0) >= cutoff;
|
|
156
187
|
};
|
|
157
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;
|
|
158
193
|
if (init?.prepayments) {
|
|
159
194
|
this.prepayments = init.prepayments.map((p) => new Prepayment(p));
|
|
160
195
|
}
|
package/dist/types/api/User.d.ts
CHANGED
package/dist/types/api.d.ts
CHANGED
|
@@ -56,6 +56,18 @@ export declare const LoginResponse: {
|
|
|
56
56
|
readonly NEEDS_TOTP: "NEEDS_TOTP";
|
|
57
57
|
};
|
|
58
58
|
export type LoginResponse = (typeof LoginResponse)[keyof typeof LoginResponse];
|
|
59
|
+
/**
|
|
60
|
+
* Outcome of `useAppleLogin`. With no account for the Apple ID yet,
|
|
61
|
+
* `apple_token` is a one-time handle (10 min) for `useAppleRegister`.
|
|
62
|
+
*/
|
|
63
|
+
export type AppleLoginResult = {
|
|
64
|
+
status: typeof LoginResponse.SUCCESS;
|
|
65
|
+
} | {
|
|
66
|
+
status: 'NEEDS_ACCOUNT';
|
|
67
|
+
apple_token: string;
|
|
68
|
+
email: string | null;
|
|
69
|
+
is_private_email: boolean;
|
|
70
|
+
};
|
|
59
71
|
export interface ApiInfo {
|
|
60
72
|
app_semver: string;
|
|
61
73
|
build_time: string;
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const AVRO_JS_VERSION = "1.6.
|
|
1
|
+
export declare const AVRO_JS_VERSION = "1.6.3";
|
package/dist/version.js
CHANGED