@go-avro/avro-js 0.0.90 → 0.0.91

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,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';
4
- import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Break, Chat, CheckIn, Company, EventUpdatePayload, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api';
4
+ import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, 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, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api';
5
5
  import { AuthState, Tokens } from '../types/auth';
6
6
  import { CancelToken, ClientId, RetryStrategy } from '../types/client';
7
7
  import { StandardError } from '../types/error';
@@ -68,6 +68,7 @@ declare module '../client/QueryClient' {
68
68
  sort_by?: 'date' | 'amount' | 'name';
69
69
  direction?: 'asc' | 'desc';
70
70
  enabled?: boolean;
71
+ line_item_types?: LineItemType[];
71
72
  }): UseInfiniteQueryResult<InfiniteData<_Event[], unknown>, StandardError>;
72
73
  useGetSessions(body: {
73
74
  amt?: number;
@@ -283,6 +284,12 @@ declare module '../client/QueryClient' {
283
284
  }, StandardError, {
284
285
  eventData: Partial<_Event>;
285
286
  }>>;
287
+ useCreateDelayEvent(): ReturnType<typeof useMutation<{
288
+ id: string;
289
+ msg: string;
290
+ }, StandardError, {
291
+ delayData: DelayEventCreatePayload;
292
+ }>>;
286
293
  useCreateUserSession(): ReturnType<typeof useMutation<{
287
294
  id: string;
288
295
  }, StandardError, {
@@ -812,6 +819,7 @@ export declare class AvroQueryClient {
812
819
  job_id?: string | null;
813
820
  sort_by?: 'date' | 'amount' | 'name';
814
821
  direction?: 'asc' | 'desc';
822
+ line_item_types?: LineItemType[];
815
823
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
816
824
  fetchMonths(body?: {
817
825
  amt?: number;
@@ -2,7 +2,7 @@ import io from 'socket.io-client';
2
2
  import { useMutation, useQueryClient, } from '@tanstack/react-query';
3
3
  import { v4 as uuidv4 } from 'uuid';
4
4
  import { fetchCensusFeatures } from '../census';
5
- import { _Event, Bill, Job, LoginResponse, Route, } from '../types/api';
5
+ import { Bill, constructEvent, Job, LoginResponse, Route, } from '../types/api';
6
6
  import { AuthState } from '../types/auth';
7
7
  import { StandardError } from '../types/error';
8
8
  function isBulkEvent(c) {
@@ -20,12 +20,20 @@ export function matchesEventsListQuery(queryKey, item) {
20
20
  const includeBilled = queryKey[7];
21
21
  const includePaid = queryKey[8];
22
22
  const filterJobId = queryKey[9];
23
+ // Index 13 was appended after the original 13-element key; older
24
+ // keys read undefined here, which means "no type filter".
25
+ const lineItemTypes = queryKey[13];
23
26
  if (knownIds && knownIds.length > 0 && !knownIds.includes(item.id))
24
27
  return 'nomatch';
25
28
  if (unknownIds && unknownIds.length > 0 && unknownIds.includes(item.id))
26
29
  return 'nomatch';
27
30
  if (filterJobId && item.job_id !== filterJobId)
28
31
  return 'nomatch';
32
+ if (lineItemTypes &&
33
+ lineItemTypes.length > 0 &&
34
+ item.line_item_type !== undefined &&
35
+ !lineItemTypes.includes(item.line_item_type))
36
+ return 'nomatch';
29
37
  const status = item.status;
30
38
  if (status !== undefined) {
31
39
  const isPaid = status === 'PAID' || status === 'PREPAID' || status === 'EXTERNALLY_PAID';
@@ -164,7 +172,7 @@ const SOCKET_EVENT_CONFIG = {
164
172
  entityKey: 'events',
165
173
  action: 'create',
166
174
  fetchPath: (id) => `/event/${id}`,
167
- construct: (d) => new _Event(d),
175
+ construct: (d) => constructEvent(d),
168
176
  matchesQuery: matchesEventsListQuery,
169
177
  relatedRefetch: [
170
178
  {
@@ -180,7 +188,7 @@ const SOCKET_EVENT_CONFIG = {
180
188
  entityKey: 'events',
181
189
  action: 'update',
182
190
  fetchPath: (id) => `/event/${id}`,
183
- construct: (d) => new _Event(d),
191
+ construct: (d) => constructEvent(d),
184
192
  matchesQuery: matchesEventsListQuery,
185
193
  relatedRefetch: [
186
194
  {
@@ -1,6 +1,6 @@
1
1
  import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient, matchesEventsListQuery } from '../../client/QueryClient';
3
- import { _Event, Job, LineItemStatus } from '../../types/api';
3
+ import { constructEvent, DelayEvent, Job, LineItemStatus, } from '../../types/api';
4
4
  const isJobsQuery = (q) => q.queryKey[0] === 'jobs';
5
5
  const isEventsQuery = (q) => q.queryKey[0] === 'events';
6
6
  const isEventsQueryFor = (item) => (q) => q.queryKey[0] === 'events' && matchesEventsListQuery(q.queryKey, item) === 'match';
@@ -21,6 +21,8 @@ AvroQueryClient.prototype.useGetEvents = function (body) {
21
21
  body.enabled ?? true,
22
22
  body.sort_by ?? null,
23
23
  body.direction ?? null,
24
+ // Index 13 — read positionally by matchesEventsListQuery.
25
+ body.line_item_types ?? null,
24
26
  ],
25
27
  initialPageParam: 0,
26
28
  getNextPageParam: (lastPage, allPages) => {
@@ -32,7 +34,7 @@ AvroQueryClient.prototype.useGetEvents = function (body) {
32
34
  ...body,
33
35
  job_id: body.jobId,
34
36
  offset: pageParam,
35
- }).then((events) => events.map((event) => new _Event(event))),
37
+ }).then((events) => events.map((event) => constructEvent(event))),
36
38
  enabled: body.enabled ?? true,
37
39
  });
38
40
  if (result.data) {
@@ -47,7 +49,7 @@ AvroQueryClient.prototype.useGetEvents = function (body) {
47
49
  AvroQueryClient.prototype.useGetEvent = function (eventId) {
48
50
  return useQuery({
49
51
  queryKey: ['events', eventId],
50
- queryFn: () => this.get({ path: `/event/${eventId}` }).then((event) => new _Event(event)),
52
+ queryFn: () => this.get({ path: `/event/${eventId}` }).then((event) => constructEvent(event)),
51
53
  enabled: Boolean(eventId),
52
54
  });
53
55
  };
@@ -67,7 +69,7 @@ AvroQueryClient.prototype.useCreateEvent = function () {
67
69
  'jobs',
68
70
  eventData.job_id,
69
71
  ]);
70
- const optimisticEvent = new _Event({
72
+ const optimisticEvent = constructEvent({
71
73
  ...eventData,
72
74
  id: Math.random().toString(36).substring(2, 11),
73
75
  company_id: this.companyId,
@@ -147,6 +149,103 @@ AvroQueryClient.prototype.useCreateEvent = function () {
147
149
  },
148
150
  });
149
151
  };
152
+ AvroQueryClient.prototype.useCreateDelayEvent = function () {
153
+ const queryClient = this.getQueryClient();
154
+ return useMutation({
155
+ mutationFn: ({ delayData }) => {
156
+ return this.post({
157
+ path: `/job/${delayData.job_id}/delay`,
158
+ data: JSON.stringify(delayData),
159
+ headers: { 'Content-Type': 'application/json' },
160
+ });
161
+ },
162
+ onMutate: async ({ delayData }) => {
163
+ await queryClient.cancelQueries({ queryKey: ['events'] });
164
+ const now = Math.floor(Date.now() / 1000);
165
+ const optimisticEvent = new DelayEvent({
166
+ ...delayData,
167
+ id: Math.random().toString(36).substring(2, 11),
168
+ company_id: this.companyId,
169
+ time_started: now,
170
+ time_ended: now,
171
+ cost: 0,
172
+ amount: 1,
173
+ });
174
+ // The server bumps task.delay atomically with the delay
175
+ // event; mirror that into the cached job.
176
+ const previousJob = queryClient.getQueryData([
177
+ 'jobs',
178
+ delayData.job_id,
179
+ ]);
180
+ if (previousJob) {
181
+ const updatedJob = new Job({
182
+ ...previousJob,
183
+ tasks: previousJob.tasks.map((task) => {
184
+ if (delayData.tasks.includes(task.id ?? '')) {
185
+ return {
186
+ ...task,
187
+ delay: (task.delay ?? 0) + delayData.delay_seconds,
188
+ overdue_time: task.overdue_time != null
189
+ ? task.overdue_time - delayData.delay_seconds
190
+ : task.overdue_time,
191
+ };
192
+ }
193
+ return task;
194
+ }),
195
+ });
196
+ queryClient.setQueriesData({ predicate: isJobsQuery, type: 'active' }, (old) => {
197
+ if (!old)
198
+ return old;
199
+ if (Array.isArray(old))
200
+ return old.map((j) => (j?.id === updatedJob.id ? updatedJob : j));
201
+ if (old?.id === updatedJob.id)
202
+ return updatedJob;
203
+ return old;
204
+ });
205
+ }
206
+ queryClient.setQueriesData({ predicate: isEventsQueryFor(optimisticEvent), type: 'active' }, (oldData) => {
207
+ if (!oldData)
208
+ return oldData;
209
+ if (oldData.pages) {
210
+ const firstPage = oldData.pages[0] || [];
211
+ return {
212
+ ...oldData,
213
+ pages: [[optimisticEvent, ...firstPage], ...oldData.pages.slice(1)],
214
+ };
215
+ }
216
+ if (Array.isArray(oldData)) {
217
+ return [optimisticEvent, ...oldData];
218
+ }
219
+ return oldData;
220
+ });
221
+ return { previousJob };
222
+ },
223
+ onSuccess: async (result, { delayData }) => {
224
+ await this._syncEntity(queryClient, {
225
+ action: 'create',
226
+ entityKey: 'events',
227
+ id: result.id,
228
+ fetchPath: `/event/${result.id}`,
229
+ construct: (d) => constructEvent(d),
230
+ matchesQuery: matchesEventsListQuery,
231
+ });
232
+ await this._syncEntity(queryClient, {
233
+ action: 'update',
234
+ entityKey: 'jobs',
235
+ id: delayData.job_id,
236
+ fetchPath: `/job/${delayData.job_id}`,
237
+ construct: (d) => new Job(d),
238
+ });
239
+ },
240
+ onError: (_err, _variables, context) => {
241
+ if (context?.previousJob) {
242
+ queryClient.setQueryData(['jobs', context.previousJob.id], context.previousJob);
243
+ }
244
+ queryClient.invalidateQueries({ predicate: isJobsQuery });
245
+ queryClient.invalidateQueries({ predicate: isEventsQuery });
246
+ },
247
+ });
248
+ };
150
249
  AvroQueryClient.prototype.useUpdateEvent = function () {
151
250
  const queryClient = this.getQueryClient();
152
251
  return useMutation({
@@ -191,7 +290,7 @@ AvroQueryClient.prototype.useUpdateEvent = function () {
191
290
  if (previousJob) {
192
291
  const isEnding = (updates.time_ended ?? -1) > -1;
193
292
  const mergedEvent = previousEvent
194
- ? new _Event({ ...previousEvent, ...updates })
293
+ ? constructEvent({ ...previousEvent, ...updates })
195
294
  : null;
196
295
  const updatedJob = new Job({
197
296
  ...previousJob,
@@ -278,7 +377,11 @@ AvroQueryClient.prototype.useUpdateEvents = function () {
278
377
  const queryClient = this.getQueryClient();
279
378
  return useMutation({
280
379
  mutationFn: async ({ events, action, }) => {
281
- const eventIds = events.map((event) => event.id);
380
+ // Delays are never billable — the server rejects the whole
381
+ // batch if one slips in, so drop them client-side.
382
+ const eventIds = events
383
+ .filter((event) => event.line_item_type !== 'DELAY')
384
+ .map((event) => event.id);
282
385
  return this.put({
283
386
  path: `/company/${this.companyId}/events`,
284
387
  data: JSON.stringify({
@@ -294,9 +397,10 @@ AvroQueryClient.prototype.useUpdateEvents = function () {
294
397
  onMutate: async ({ events, action }) => {
295
398
  await queryClient.cancelQueries({ queryKey: ['events'] });
296
399
  await queryClient.cancelQueries({ queryKey: ['events'] });
400
+ const billable = events.filter((event) => event.line_item_type !== 'DELAY');
297
401
  const previousEvents = queryClient.getQueryData(['events']);
298
- const previousEventObjs = events.map((event) => queryClient.getQueryData(['events', event.id]));
299
- const eventIds = events.map((event) => event.id);
402
+ const previousEventObjs = billable.map((event) => queryClient.getQueryData(['events', event.id]));
403
+ const eventIds = billable.map((event) => event.id);
300
404
  // Optimistically update individual event cache
301
405
  eventIds.forEach((eventId, idx) => {
302
406
  queryClient.setQueryData(['events', eventId], (oldData) => {
@@ -0,0 +1,25 @@
1
+ import { _Event } from '../../types/api/_Event';
2
+ declare module '../../types/api/DelayEvent' {
3
+ interface DelayEvent extends _Event {
4
+ line_item_type: 'DELAY';
5
+ /** Seconds this delay added to each linked task's delay. */
6
+ delay_seconds: number;
7
+ }
8
+ }
9
+ /**
10
+ * An instantaneous, never-billable record of a schedule delay.
11
+ *
12
+ * Shares the events table/endpoints with service events; the linked
13
+ * tasks are in `tasks`/`task_names`, and `internal_notes`/
14
+ * `external_notes`/`proofs` behave exactly as on a service event.
15
+ */
16
+ export declare class DelayEvent extends _Event {
17
+ constructor(init?: Partial<DelayEvent>);
18
+ }
19
+ /** Service events keep the `_Event` runtime class; alias for clarity. */
20
+ export type ServiceEvent = _Event & {
21
+ line_item_type: 'EVENT';
22
+ };
23
+ export declare const isDelayEvent: (event: _Event | null | undefined) => event is DelayEvent;
24
+ /** Hydrate raw event JSON into the class matching its discriminator. */
25
+ export declare const constructEvent: (data: Partial<_Event>) => _Event;
@@ -0,0 +1,20 @@
1
+ import { _Event } from '../../types/api/_Event';
2
+ /**
3
+ * An instantaneous, never-billable record of a schedule delay.
4
+ *
5
+ * Shares the events table/endpoints with service events; the linked
6
+ * tasks are in `tasks`/`task_names`, and `internal_notes`/
7
+ * `external_notes`/`proofs` behave exactly as on a service event.
8
+ */
9
+ export class DelayEvent extends _Event {
10
+ constructor(init) {
11
+ super(init);
12
+ this.line_item_type = 'DELAY';
13
+ this.delay_seconds = init?.delay_seconds ?? 0;
14
+ }
15
+ }
16
+ export const isDelayEvent = (event) => event?.line_item_type === 'DELAY';
17
+ /** Hydrate raw event JSON into the class matching its discriminator. */
18
+ export const constructEvent = (data) => data?.line_item_type === 'DELAY'
19
+ ? new DelayEvent(data)
20
+ : new _Event(data);
@@ -12,6 +12,7 @@ export declare const LineItemType: {
12
12
  readonly CUSTOM: "CUSTOM";
13
13
  readonly ADDITIONAL_CHARGE: "ADDITIONAL_CHARGE";
14
14
  readonly EVENT: "EVENT";
15
+ readonly DELAY: "DELAY";
15
16
  readonly SERVICE_MONTH: "SERVICE_MONTH";
16
17
  readonly PREPAYMENT: "PREPAYMENT";
17
18
  readonly PROCESSING_FEE: "PROCESSING_FEE";
@@ -11,6 +11,7 @@ export const LineItemType = {
11
11
  CUSTOM: 'CUSTOM',
12
12
  ADDITIONAL_CHARGE: 'ADDITIONAL_CHARGE',
13
13
  EVENT: 'EVENT',
14
+ DELAY: 'DELAY',
14
15
  SERVICE_MONTH: 'SERVICE_MONTH',
15
16
  PREPAYMENT: 'PREPAYMENT',
16
17
  PROCESSING_FEE: 'PROCESSING_FEE',
@@ -4,7 +4,7 @@ import { UserEvent } from '../../types/api/UserEvent';
4
4
  declare module '../../types/api/_Event' {
5
5
  interface _Event extends LineItem {
6
6
  breaks: string[];
7
- line_item_type: 'EVENT';
7
+ line_item_type: 'EVENT' | 'DELAY';
8
8
  job_id: string;
9
9
  job_name: string;
10
10
  job_address: string;
@@ -3,6 +3,7 @@ import { _Event } from '../types/api/_Event';
3
3
  import { Route } from '../types/api/Route';
4
4
  export * from '../types/api/_Event';
5
5
  export * from '../types/api/AdditionalCharge';
6
+ export * from '../types/api/DelayEvent';
6
7
  export * from '../types/api/Address';
7
8
  export * from '../types/api/Avro';
8
9
  export * from '../types/api/Bill';
@@ -212,6 +213,23 @@ export type RouteWritePayload = Partial<Omit<Route, 'is_optimized'>> & {
212
213
  export type EventUpdatePayload = Partial<Omit<_Event, 'users'>> & {
213
214
  users?: EventUserUpdate[];
214
215
  };
216
+ /**
217
+ * Wire payload for logging a delay (POST /job/{job_id}/delay).
218
+ *
219
+ * The backend applies `delay_seconds` to each task in `tasks`
220
+ * atomically with the DelayEvent row — callers must NOT also bump
221
+ * `task.delay` through a job update.
222
+ */
223
+ export interface DelayEventCreatePayload {
224
+ job_id: string;
225
+ /** Task ids (guids) whose schedule this delay pushes back. */
226
+ tasks: string[];
227
+ delay_seconds: number;
228
+ name?: string;
229
+ internal_notes?: string;
230
+ external_notes?: string;
231
+ description?: string;
232
+ }
215
233
  export interface EventInsightData {
216
234
  start: number;
217
235
  end: number;
package/dist/types/api.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from '../types/api/_Event';
2
2
  export * from '../types/api/AdditionalCharge';
3
+ export * from '../types/api/DelayEvent';
3
4
  export * from '../types/api/Address';
4
5
  export * from '../types/api/Avro';
5
6
  export * from '../types/api/Bill';
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "0.0.90";
1
+ export declare const AVRO_JS_VERSION = "0.0.91";
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 = '0.0.90';
3
+ export const AVRO_JS_VERSION = '0.0.91';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.0.90",
3
+ "version": "0.0.91",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",