@go-avro/avro-js 1.6.6-rc15 → 1.6.6-rc17

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.
@@ -1,9 +1,9 @@
1
1
  import { Socket } from 'socket.io-client';
2
2
  import { InfiniteData, QueryClient, UseInfiniteQueryResult, useMutation, UseQueryResult } from '@tanstack/react-query';
3
3
  import { AuthManager } from '../auth/AuthManager.js';
4
- import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Chat, CheckIn, Company, CompanySummary, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLinkProof, AppleLoginResult, MicrosoftLoginResult, LoginResponse, Message, Permission, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogIndustry, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api.js';
4
+ import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Chat, CheckIn, Company, CompanySummary, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLinkProof, AppleLoginResult, MicrosoftLoginResult, LoginResponse, Message, Permission, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogIndustry, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus, CreateNotificationPayload, NotificationCreated, SendEmailPayload } from '../types/api.js';
5
5
  import { AuthState, Tokens } from '../types/auth.js';
6
- import { CancelToken, ClientId, RetryStrategy } from '../types/client.js';
6
+ import { CancelToken, ClientId, RetryStrategy, EventPhotoLinks, EventPhotoLinksVars, PdfSource, SendBillEmailVars, SendEmailMessageVars, SendNotificationVars, ImageTarget, UploadImage, UploadImagesOptions, UploadImagesResult, UploadImagesVars } from '../types/client.js';
7
7
  import { StandardError } from '../types/error.js';
8
8
  import { CacheData } from '../types/cache.js';
9
9
  import { Waiver } from '../types/api/Waiver.js';
@@ -39,6 +39,46 @@ declare module './QueryClient.js' {
39
39
  _fetch<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number): Promise<T>;
40
40
  getDelay(strategy: RetryStrategy, attempt: number): number;
41
41
  sleep(ms: number): Promise<void>;
42
+ _uploadImages(base: string, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
43
+ /**
44
+ * Upload photos to an event or task straight to S3: allocate
45
+ * presigned URLs, upload each file (retrying network failures), then
46
+ * confirm. Resend a failed photo with the `upload` name its failure
47
+ * reported: one the server already stored is skipped, never stored
48
+ * twice. Components use `useUploadImages`.
49
+ */
50
+ uploadImages(target: ImageTarget, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
51
+ /**
52
+ * Send a notification (in the current company unless `companyId` is
53
+ * given). Show photos by embedding `useEventPhotoLinks` URLs.
54
+ */
55
+ sendNotification(body: CreateNotificationPayload, options?: {
56
+ companyId?: string;
57
+ }): Promise<NotificationCreated>;
58
+ /**
59
+ * Send an email from a mailbox (show photos by embedding
60
+ * `useEventPhotoLinks` URLs); `requestId` is echoed in the
61
+ * `email_succeeded`/`email_failed` events.
62
+ */
63
+ sendEmailMessage(emailId: string, body: SendEmailPayload, options?: {
64
+ requestId?: string;
65
+ proposalId?: string;
66
+ }): Promise<void>;
67
+ /** `uploadImages` as a mutation; refreshes the event or job when done. */
68
+ useUploadImages(): ReturnType<typeof useMutation<UploadImagesResult, StandardError, UploadImagesVars>>;
69
+ /** `sendNotification` as a mutation. */
70
+ useSendNotification(): ReturnType<typeof useMutation<NotificationCreated, StandardError, SendNotificationVars>>;
71
+ /** Email a bill's invoice (PDF rendered server-side) as a mutation. */
72
+ useSendBillEmail(): ReturnType<typeof useMutation<{
73
+ msg: string;
74
+ }, StandardError, SendBillEmailVars>>;
75
+ /**
76
+ * Fetch permanent, signed links to an event's photos to embed in an
77
+ * email (`<img>` per position plus a "View photos" page).
78
+ */
79
+ useEventPhotoLinks(): ReturnType<typeof useMutation<EventPhotoLinks, StandardError, EventPhotoLinksVars>>;
80
+ /** `sendEmailMessage` as a mutation. */
81
+ useSendEmailMessage(): ReturnType<typeof useMutation<void, StandardError, SendEmailMessageVars>>;
42
82
  useGetRoot(): UseQueryResult<ApiInfo, StandardError>;
43
83
  useJobAudit(jobId: string, params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
44
84
  useCompanyAudit(params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
@@ -180,18 +220,11 @@ declare module './QueryClient.js' {
180
220
  }, total: number, onProgress?: (fraction: number) => void): UseQueryResult<Group[], StandardError>;
181
221
  useGetPlans(code: string): UseQueryResult<Plan[], StandardError>;
182
222
  useGetCompanies(options?: {}): UseQueryResult<CompanySummary[], StandardError>;
183
- generatePDFFromBackend({ billId }: {
184
- billId: string;
185
- }): Promise<Blob>;
186
- sendBillingEmail(options: {
187
- billId: string;
188
- subject?: string;
189
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
190
- recipients?: [string, string][];
191
- request_id?: string;
192
- }): Promise<{
193
- msg: string;
194
- }>;
223
+ /**
224
+ * Render a PDF on the server: a bill's invoice, or the hours report
225
+ * of the pay period containing `timecardsPeriodStart` (Unix time).
226
+ */
227
+ generatePDFFromBackend(source: PdfSource): Promise<Blob>;
195
228
  useGetProposal(proposal_id: string): UseQueryResult<Proposal, StandardError>;
196
229
  useGetTerms(): UseQueryResult<Terms[], StandardError>;
197
230
  useCreateTerms(): ReturnType<typeof useMutation<{
@@ -1200,12 +1233,4 @@ export declare class AvroQueryClient {
1200
1233
  }, cancelToken?: CancelToken, headers?: Record<string, string>, companyId?: string | undefined): Promise<any>;
1201
1234
  private _initEmailListeners;
1202
1235
  trackEmail(options?: TrackEmailOptions): string;
1203
- sendEmail(emailId: string, formData: FormData, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<void>;
1204
- sendBillEmail(billId: string, body?: {
1205
- subject?: string;
1206
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
1207
- recipients?: [string, string][];
1208
- base_url?: string;
1209
- request_id?: string;
1210
- }): Promise<void>;
1211
1236
  }
@@ -1475,28 +1475,4 @@ export class AvroQueryClient {
1475
1475
  });
1476
1476
  return requestId;
1477
1477
  }
1478
- sendEmail(emailId, formData, progressUpdateCallback) {
1479
- try {
1480
- return this.post({
1481
- path: `/email/${emailId}`,
1482
- data: formData,
1483
- progressUpdateCallback,
1484
- });
1485
- }
1486
- catch (error) {
1487
- throw new StandardError(500, `Failed to send email: ${error}`);
1488
- }
1489
- }
1490
- sendBillEmail(billId, body = {}) {
1491
- try {
1492
- return this.post({
1493
- path: `/bill/${billId}/email`,
1494
- data: JSON.stringify(body),
1495
- headers: { 'Content-Type': 'application/json' },
1496
- });
1497
- }
1498
- catch (error) {
1499
- throw new StandardError(500, `Failed to send bill email: ${error}`);
1500
- }
1501
- }
1502
1478
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,213 @@
1
+ import { useMutation } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../QueryClient.js';
3
+ import { cancelledError, isCancelledError } from './policy.js';
4
+ import { StandardError } from '../../types/error.js';
5
+ /** Photos allocated per request; keeps the presigned batch small. */
6
+ const ALLOCATE_BATCH = 20;
7
+ /** A slow phone gets this long per photo before the try is abandoned. */
8
+ const S3_TIMEOUT_MS = 45000;
9
+ const DEFAULT_ATTEMPTS = 2;
10
+ /** POST one file straight to S3 with its presigned form fields. */
11
+ function postToS3(slot, image, onProgress, cancelToken) {
12
+ return new Promise((resolve, reject) => {
13
+ if (cancelToken?.isCancelled()) {
14
+ reject(cancelledError());
15
+ return;
16
+ }
17
+ const form = new FormData();
18
+ Object.entries(slot.fields ?? {}).forEach(([k, v]) => form.append(k, v));
19
+ // The file must be the last field of a presigned POST.
20
+ if (typeof Blob !== 'undefined' && image.file instanceof Blob) {
21
+ form.append('file', image.file, image.name ?? slot.name);
22
+ }
23
+ else {
24
+ // React Native's FormData takes a `{ uri, name, type }` reference.
25
+ form.append('file', image.file);
26
+ }
27
+ const xhr = new XMLHttpRequest();
28
+ xhr.open('POST', slot.url, true);
29
+ xhr.timeout = S3_TIMEOUT_MS;
30
+ xhr.upload.onprogress = (event) => {
31
+ if (event.lengthComputable && event.total > 0)
32
+ onProgress(event.loaded / event.total);
33
+ };
34
+ xhr.onload = () => {
35
+ if (xhr.status >= 200 && xhr.status < 300)
36
+ resolve();
37
+ else
38
+ reject(new StandardError(xhr.status, xhr.responseText || 'Upload to S3 failed'));
39
+ };
40
+ // Cancelling stops the transfer itself, not just the next one.
41
+ const watch = cancelToken
42
+ ? setInterval(() => {
43
+ if (!cancelToken.isCancelled())
44
+ return;
45
+ xhr.abort();
46
+ reject(cancelledError());
47
+ }, 250)
48
+ : undefined;
49
+ xhr.onloadend = () => clearInterval(watch);
50
+ xhr.onerror = () => reject(new StandardError(0, 'Network Error'));
51
+ xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
52
+ xhr.send(form);
53
+ });
54
+ }
55
+ AvroQueryClient.prototype._uploadImages = async function (base, images, options = {}) {
56
+ const { onProgress, onAttempt, attempts = DEFAULT_ATTEMPTS, cancelToken } = options;
57
+ const names = images.map(() => null);
58
+ const failed = [];
59
+ const total = images.length;
60
+ let done = 0;
61
+ const report = (current) => onProgress?.(done + current, total);
62
+ // Set once a photo exhausts its tries: the connection can't carry a
63
+ // photo right now, so the rest fail fast instead of each waiting out
64
+ // its own timeouts (they're reported retryable for a later resend).
65
+ let stalled = null;
66
+ const skip = (index, upload) => failed.push({ image: images[index], msg: stalled ?? '', retryable: true, upload });
67
+ for (let start = 0; start < images.length; start += ALLOCATE_BATCH) {
68
+ const batch = images.slice(start, start + ALLOCATE_BATCH);
69
+ if (stalled) {
70
+ batch.forEach((image, i) => skip(start + i, image.upload));
71
+ continue;
72
+ }
73
+ const { uploads } = await this.post({
74
+ path: `${base}/uploads`,
75
+ data: JSON.stringify({
76
+ images: batch.map((image) => ({
77
+ ...(image.upload ? { name: image.upload } : {}),
78
+ content_type: image.type,
79
+ size: image.size,
80
+ })),
81
+ }),
82
+ headers: { 'Content-Type': 'application/json' },
83
+ // A lost response only leaves an unconfirmed pending upload.
84
+ idempotent: true,
85
+ cancelToken,
86
+ });
87
+ const toConfirm = [];
88
+ for (let i = 0; i < uploads.length; i++) {
89
+ const slot = uploads[i];
90
+ const index = start + i;
91
+ if (slot.uploaded) {
92
+ names[index] = slot.name;
93
+ done++;
94
+ report(0);
95
+ continue;
96
+ }
97
+ if (stalled) {
98
+ skip(index, slot.name);
99
+ continue;
100
+ }
101
+ for (let attempt = 1;; attempt++) {
102
+ const startedAt = Date.now();
103
+ onAttempt?.({
104
+ startedAt,
105
+ giveUpAt: startedAt + (attempts - attempt + 1) * S3_TIMEOUT_MS,
106
+ });
107
+ try {
108
+ await postToS3(slot, images[index], report, cancelToken);
109
+ toConfirm.push({ index, slot });
110
+ break;
111
+ }
112
+ catch (error) {
113
+ if (isCancelledError(error))
114
+ throw error;
115
+ // S3 rejecting a transfer (timeout, expired policy, cut
116
+ // connection) never means the photo is bad: the server
117
+ // judges the bytes on confirm. So it's always worth
118
+ // sending again.
119
+ if (attempt >= attempts) {
120
+ stalled = error instanceof Error ? error.message : String(error);
121
+ skip(index, slot.name);
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ done++;
127
+ report(0);
128
+ }
129
+ if (toConfirm.length === 0)
130
+ continue;
131
+ let confirmed;
132
+ try {
133
+ confirmed = await this.post({
134
+ path: `${base}/confirm`,
135
+ data: JSON.stringify({ names: toConfirm.map(({ slot }) => slot.name) }),
136
+ headers: { 'Content-Type': 'application/json' },
137
+ idempotent: true,
138
+ cancelToken,
139
+ });
140
+ }
141
+ catch (error) {
142
+ if (isCancelledError(error))
143
+ throw error;
144
+ // The confirm may have landed: report the names so a retry
145
+ // resends these photos under them instead of storing new copies.
146
+ const msg = error instanceof Error ? error.message : String(error);
147
+ for (const { index, slot } of toConfirm) {
148
+ failed.push({ image: images[index], msg, retryable: true, upload: slot.name });
149
+ }
150
+ continue;
151
+ }
152
+ const stored = new Set(confirmed.names);
153
+ const reasons = new Map(confirmed.failed.map((f) => [f.name, f.msg]));
154
+ for (const { index, slot } of toConfirm) {
155
+ if (stored.has(slot.name)) {
156
+ names[index] = slot.name;
157
+ }
158
+ else {
159
+ const msg = reasons.get(slot.name) ?? 'Upload not confirmed';
160
+ failed.push({
161
+ image: images[index],
162
+ msg,
163
+ retryable: msg === 'Not uploaded',
164
+ upload: slot.name,
165
+ });
166
+ }
167
+ }
168
+ }
169
+ return { names, failed };
170
+ };
171
+ AvroQueryClient.prototype.uploadImages = function (target, images, options) {
172
+ const base = 'eventId' in target ? `/event/${target.eventId}/image` : `/task/${target.taskId}/image`;
173
+ return this._uploadImages(base, images, options);
174
+ };
175
+ AvroQueryClient.prototype.sendNotification = function (body, options = {}) {
176
+ const form = new FormData();
177
+ form.append('data', JSON.stringify(body));
178
+ return this.post({
179
+ path: `/company/${options.companyId ?? this.companyId}/notification`,
180
+ data: form,
181
+ });
182
+ };
183
+ AvroQueryClient.prototype.sendEmailMessage = function (emailId, body, options = {}) {
184
+ const form = new FormData();
185
+ form.append('data', JSON.stringify(body));
186
+ if (options.requestId)
187
+ form.append('request_id', options.requestId);
188
+ if (options.proposalId)
189
+ form.append('proposal_id', options.proposalId);
190
+ return this.post({ path: `/email/${emailId}`, data: form });
191
+ };
192
+ AvroQueryClient.prototype.useUploadImages = function () {
193
+ return useMutation({
194
+ mutationFn: ({ target, images, options }) => this.uploadImages(target, images, options),
195
+ // Task photos are embedded in their job.
196
+ onSettled: (_data, _err, { target }) => this.syncAfterMutation('eventId' in target ? 'event' : 'job'),
197
+ });
198
+ };
199
+ AvroQueryClient.prototype.useSendNotification = function () {
200
+ return useMutation({
201
+ mutationFn: ({ body, companyId }) => this.sendNotification(body, { companyId }),
202
+ });
203
+ };
204
+ AvroQueryClient.prototype.useSendEmailMessage = function () {
205
+ return useMutation({
206
+ mutationFn: ({ emailId, body, requestId, proposalId }) => this.sendEmailMessage(emailId, body, { requestId, proposalId }),
207
+ });
208
+ };
209
+ AvroQueryClient.prototype.useEventPhotoLinks = function () {
210
+ return useMutation({
211
+ mutationFn: ({ eventId, count }) => this.get({ path: `/event/${eventId}/photo-links?count=${count}` }),
212
+ });
213
+ };
@@ -256,12 +256,11 @@ AvroQueryClient.prototype.useIntuitSyncStatus = function () {
256
256
  }, [this]);
257
257
  return status;
258
258
  };
259
- AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId }) {
260
- return this.get({
261
- path: `/company/${this.companyId}/bill/${billId}/pdf`,
262
- }).then((response) => {
263
- return response;
264
- });
259
+ AvroQueryClient.prototype.generatePDFFromBackend = function (source) {
260
+ const path = 'billId' in source
261
+ ? `/company/${this.companyId}/bill/${source.billId}/pdf`
262
+ : `/company/${this.companyId}/timecards/pdf?period_start=${source.timecardsPeriodStart}`;
263
+ return this.get({ path });
265
264
  };
266
265
  AvroQueryClient.prototype.useBulkDeleteBills = function () {
267
266
  const queryClient = this.getQueryClient();
@@ -301,12 +300,15 @@ AvroQueryClient.prototype.useBulkEmailBills = function () {
301
300
  // `bill_guid`.
302
301
  });
303
302
  };
304
- AvroQueryClient.prototype.sendBillingEmail = async function ({ subject, billId, recipients, request_id, }) {
305
- return this.post({
306
- path: `/bill/${billId}/email`,
307
- data: JSON.stringify({ recipients, subject, request_id }),
308
- headers: {
309
- 'Content-Type': 'application/json',
310
- },
303
+ AvroQueryClient.prototype.useSendBillEmail = function () {
304
+ return useMutation({
305
+ // The server renders the PDF, totals and each recipient's pay link.
306
+ mutationFn: ({ billId, subject, recipients, request_id }) => this.post({
307
+ path: `/bill/${billId}/email`,
308
+ data: JSON.stringify({ recipients, subject, request_id }),
309
+ headers: { 'Content-Type': 'application/json' },
310
+ }),
311
+ // No cache sync: emailing doesn't change the bill; delivery outcomes
312
+ // arrive as `email_succeeded`/`email_failed` events on `request_id`.
311
313
  });
312
314
  };
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export type { KeyValueStore, QueryPersistOptions } from './client/persist.js';
11
11
  import './client/core/xhr.js';
12
12
  import './client/core/fetch.js';
13
13
  import './client/core/utils.js';
14
+ import './client/core/uploads.js';
14
15
  import './client/hooks/address.js';
15
16
  import './client/hooks/root.js';
16
17
  import './client/hooks/jobs.js';
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ export { QueryPersister, IndexedDBStore, MemoryKeyValueStore, defaultKeyValueSto
7
7
  import './client/core/xhr.js';
8
8
  import './client/core/fetch.js';
9
9
  import './client/core/utils.js';
10
+ import './client/core/uploads.js';
10
11
  import './client/hooks/address.js';
11
12
  import './client/hooks/root.js';
12
13
  import './client/hooks/jobs.js';
@@ -15,6 +15,45 @@ export interface NotificationCreated {
15
15
  id: string;
16
16
  email_errors: NotificationEmailError[];
17
17
  }
18
+ /** One part of a notification email (`CreateNotificationPayload`). */
19
+ export interface NotificationBodyPart {
20
+ /** MIME type; `image/*` parts name an uploaded file in `content`. */
21
+ type: string;
22
+ /** The text itself, or the form field name of an uploaded file. */
23
+ content: string;
24
+ /** Inline attachment bytes (base64) instead of an uploaded file. */
25
+ content_b64?: string;
26
+ }
27
+ /** The JSON body of `POST /email/<id>` (`sendEmailMessage`). */
28
+ export interface SendEmailPayload {
29
+ to: string[];
30
+ /** Display names, paired with `to`. */
31
+ to_alias?: string[];
32
+ from?: string;
33
+ from_alias?: string;
34
+ reply_to?: string;
35
+ reply_to_alias?: string;
36
+ subject: string;
37
+ body_parts?: NotificationBodyPart[];
38
+ }
39
+ /** The JSON body of `POST /company/<id>/notification`. */
40
+ export interface CreateNotificationPayload {
41
+ notification: {
42
+ subject: string;
43
+ body: string;
44
+ body_parts?: NotificationBodyPart[];
45
+ };
46
+ /** User ids to notify besides the event's job subscribers. */
47
+ users?: string[];
48
+ /** Sending mailbox; omitted sends no email. */
49
+ email?: string;
50
+ event?: string;
51
+ /** Save the image parts as the event's photos. */
52
+ image_upload_mode?: boolean;
53
+ is_offer?: boolean;
54
+ /** In cents. */
55
+ amount?: number;
56
+ }
18
57
  /** A notification sent within a company (`GET /notification/<id>`). */
19
58
  export interface CompanyNotification {
20
59
  id: string;
@@ -122,8 +122,6 @@ export declare class Task {
122
122
  computeNextTaskState: (isCustomer: boolean, action: "accept" | "modify" | "reject") => TaskStatus;
123
123
  getPrepaidEventsRemaining: () => number;
124
124
  getPrepaidMonthsRemaining: () => number;
125
- /** Local midnight starting the day of the route's current occurrence. */
126
- private routeDayStart;
127
125
  isDone: (route: Route) => boolean;
128
126
  /**
129
127
  * Whether this visit of `route` should do the task: it's active and
@@ -66,6 +66,12 @@ export const getTaskOverdueness = (task, now = Date.now() / 1000) => {
66
66
  }
67
67
  return overdueTime / (86400 * (task.priority ? 1 : 7));
68
68
  };
69
+ /** Local midnight starting the day of the route's current occurrence. */
70
+ function routeDayStart(route) {
71
+ const day = new Date((route.start_time ?? 0) * 1000);
72
+ day.setHours(0, 0, 0, 0);
73
+ return day;
74
+ }
69
75
  export class Task {
70
76
  constructor(init) {
71
77
  this.getStatusLabel = () => {
@@ -173,12 +179,6 @@ export class Task {
173
179
  return acc;
174
180
  }, 0);
175
181
  };
176
- /** Local midnight starting the day of the route's current occurrence. */
177
- this.routeDayStart = (route) => {
178
- const day = new Date((route.start_time ?? 0) * 1000);
179
- day.setHours(0, 0, 0, 0);
180
- return day;
181
- };
182
182
  this.isDone = (route) => {
183
183
  if (!this.status || this.status !== TaskStatus.ACTIVE) {
184
184
  return true;
@@ -188,7 +188,7 @@ export class Task {
188
188
  // an early-started visit that finishes a few minutes before
189
189
  // route.start_time) while still rejecting stale events from previous
190
190
  // occurrences. Applies to both recurring and one-shot tasks.
191
- const cutoff = Math.floor(this.routeDayStart(route).getTime() / 1000);
191
+ const cutoff = Math.floor(routeDayStart(route).getTime() / 1000);
192
192
  return (this.last_completed_event?.time_ended ?? 0) >= cutoff;
193
193
  };
194
194
  /**
@@ -206,7 +206,7 @@ export class Task {
206
206
  const nextDue = this.getNextDue();
207
207
  if (nextDue == null)
208
208
  return true;
209
- const routeDayEnd = this.routeDayStart(route);
209
+ const routeDayEnd = routeDayStart(route);
210
210
  routeDayEnd.setDate(routeDayEnd.getDate() + 1);
211
211
  const nextVisit = route.getNextOccurrence(routeDayEnd);
212
212
  // One-off routes have no next visit: then only the route's day counts.
@@ -1,3 +1,4 @@
1
+ import { CreateNotificationPayload, SendEmailPayload } from './api.js';
1
2
  export type RetryStrategy = 'fixed' | 'exponential' | ((attempt: number) => number);
2
3
  export interface CancelToken {
3
4
  isCancelled(): boolean;
@@ -11,3 +12,119 @@ export declare const ClientId: {
11
12
  readonly DEV_APP: "dev-app";
12
13
  };
13
14
  export type ClientId = (typeof ClientId)[keyof typeof ClientId];
15
+ /**
16
+ * A photo file to upload: a browser `Blob`/`File`, or React Native's
17
+ * `{ uri, name, type }` file reference.
18
+ */
19
+ export type UploadFile = Blob | {
20
+ uri: string;
21
+ name: string;
22
+ type: string;
23
+ };
24
+ /** One photo for `uploadImages` / `useUploadImages`. */
25
+ export interface UploadImage {
26
+ file: UploadFile;
27
+ /** MIME type (`image/jpeg`, `image/png`, …); S3 enforces it. */
28
+ type: string;
29
+ /** Size in bytes; the upload may not exceed it. */
30
+ size: number;
31
+ /** File name sent with the upload (defaults to a `File`'s own name). */
32
+ name?: string;
33
+ /**
34
+ * The name the server gave this photo on an earlier try (from
35
+ * `UploadImageFailure.upload`). Sending it back resends the same photo,
36
+ * so one resent after a lost response, or from an offline queue, is
37
+ * never stored twice.
38
+ */
39
+ upload?: string;
40
+ }
41
+ export interface UploadImagesOptions {
42
+ /** Progress in photos: `sent` of `total`, fractional mid-upload. */
43
+ onProgress?: (sent: number, total: number) => void;
44
+ /** Tries per photo upload to S3 before it counts as failed. */
45
+ attempts?: number;
46
+ /**
47
+ * Each S3 upload try as it starts, with when the whole upload will give
48
+ * up (and report the rest retryable) if the connection stays stalled,
49
+ * e.g. to show a countdown on a slow connection.
50
+ */
51
+ onAttempt?: (attempt: {
52
+ startedAt: number;
53
+ giveUpAt: number;
54
+ }) => void;
55
+ /** Cancelling aborts the upload in flight too (e.g. "Try later"). */
56
+ cancelToken?: CancelToken;
57
+ }
58
+ /** The event or task photos are uploaded to. */
59
+ export type ImageTarget = {
60
+ eventId: string;
61
+ } | {
62
+ taskId: string;
63
+ };
64
+ /** Variables of `useUploadImages`. */
65
+ export interface UploadImagesVars {
66
+ target: ImageTarget;
67
+ images: UploadImage[];
68
+ options?: UploadImagesOptions;
69
+ }
70
+ /** Variables of `useSendNotification`. */
71
+ export interface SendNotificationVars {
72
+ body: CreateNotificationPayload;
73
+ /** Defaults to the current company. */
74
+ companyId?: string;
75
+ }
76
+ /** Variables of `useSendEmailMessage`. */
77
+ export interface SendEmailMessageVars {
78
+ emailId: string;
79
+ body: SendEmailPayload;
80
+ /** Echoed in the `email_succeeded`/`email_failed` events. */
81
+ requestId?: string;
82
+ /** Attach this proposal's PDF (rendered server-side). */
83
+ proposalId?: string;
84
+ }
85
+ /** Variables of `useSendBillEmail`. */
86
+ export interface SendBillEmailVars {
87
+ billId: string;
88
+ /** Defaults to `Invoice (<number>): <company>`. */
89
+ subject?: string;
90
+ /** `[name, email]` pairs; omitted: the bill's own recipients. */
91
+ recipients?: [string, string][];
92
+ request_id?: string;
93
+ }
94
+ /** Permanent, signed links to an event's photos (`useEventPhotoLinks`). */
95
+ export interface EventPhotoLinks {
96
+ /**
97
+ * One URL per photo position, for `<img>` tags in an email. Each
98
+ * redirects to the photo, including photos still uploading when the
99
+ * email is sent (they appear once stored).
100
+ */
101
+ images: string[];
102
+ /** A page showing every photo the event has ("View photos"). */
103
+ page: string;
104
+ }
105
+ /** Variables of `useEventPhotoLinks`. */
106
+ export interface EventPhotoLinksVars {
107
+ eventId: string;
108
+ /** How many photo positions to link (photos taken, stored or queued). */
109
+ count: number;
110
+ }
111
+ /** What `generatePDFFromBackend` renders. */
112
+ export type PdfSource = {
113
+ billId: string;
114
+ } | {
115
+ timecardsPeriodStart: number;
116
+ };
117
+ /** A photo that wasn't stored. */
118
+ export interface UploadImageFailure {
119
+ image: UploadImage;
120
+ msg: string;
121
+ /** Worth sending again later (e.g. it never reached S3). */
122
+ retryable: boolean;
123
+ /** The name the server gave it: keep it as `UploadImage.upload`. */
124
+ upload?: string;
125
+ }
126
+ export interface UploadImagesResult {
127
+ /** Stored name per photo, in order; `null` where it failed. */
128
+ names: (string | null)[];
129
+ failed: UploadImageFailure[];
130
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "1.6.6-rc15";
1
+ export declare const AVRO_JS_VERSION = "1.6.6-rc17";
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.6-rc15';
3
+ export const AVRO_JS_VERSION = '1.6.6-rc17';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "1.6.6-rc15",
3
+ "version": "1.6.6-rc17",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",