@go-avro/avro-js 1.7.0 → 1.7.2

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.
@@ -7,6 +7,7 @@ import { CancelToken, ClientId, RetryStrategy, EventPhotoLinks, EventPhotoLinksV
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';
10
+ import type { Account, AccountCreatePayload, AccountUpdatePayload } from '../types/api/Account.js';
10
11
  import { Proposal } from '../types/api/Proposal.js';
11
12
  import { Terms } from '../types/api/Terms.js';
12
13
  import type { EmailSucceededPayload, EmailFailedPayload, EmailType } from '../types/api/EmailNotification.js';
@@ -209,6 +210,35 @@ declare module './QueryClient.js' {
209
210
  query?: string;
210
211
  offset?: number;
211
212
  }, total: number, onProgress?: (fraction: number) => void): UseQueryResult<Label[], StandardError>;
213
+ useGetAccounts(body?: {
214
+ query?: string;
215
+ unknown_ids?: string[];
216
+ }): UseQueryResult<Account[], StandardError>;
217
+ useGetAccount(accountId: string): UseQueryResult<Account, StandardError>;
218
+ useCreateAccount(): ReturnType<typeof useMutation<{
219
+ msg: string;
220
+ id: string;
221
+ }, StandardError, {
222
+ data: AccountCreatePayload;
223
+ }>>;
224
+ useUpdateAccount(): ReturnType<typeof useMutation<{
225
+ msg: string;
226
+ }, StandardError, {
227
+ accountId: string;
228
+ updates: AccountUpdatePayload;
229
+ }>>;
230
+ useDeleteAccount(): ReturnType<typeof useMutation<{
231
+ msg: string;
232
+ }, StandardError, {
233
+ accountId: string;
234
+ }>>;
235
+ /** Fold `sourceIds` into `accountId` and delete them. */
236
+ useMergeAccounts(): ReturnType<typeof useMutation<{
237
+ msg: string;
238
+ }, StandardError, {
239
+ accountId: string;
240
+ sourceIds: string[];
241
+ }>>;
212
242
  useGetWaivers(body: {
213
243
  amt?: number;
214
244
  known_ids?: string[];
@@ -1128,6 +1158,10 @@ export declare class AvroQueryClient {
1128
1158
  sort_by?: 'date' | 'amount' | 'name';
1129
1159
  direction?: 'asc' | 'desc';
1130
1160
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1161
+ fetchAccounts(body?: {
1162
+ query?: string;
1163
+ unknown_ids?: string[];
1164
+ }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<Account[]>;
1131
1165
  fetchWaivers(body?: {
1132
1166
  amt?: number;
1133
1167
  query?: string;
@@ -1197,6 +1197,18 @@ export class AvroQueryClient {
1197
1197
  throw fetchError(err, 'Failed to fetch prepayments');
1198
1198
  });
1199
1199
  }
1200
+ async fetchAccounts(body = {}, cancelToken, headers = {}) {
1201
+ if (!this.companyId || this.companyId.trim() === '') {
1202
+ throw new StandardError(400, 'Company ID is required');
1203
+ }
1204
+ return this._fetch('POST', `/company/${this.companyId}/accounts`, JSON.stringify(body), cancelToken, {
1205
+ ...headers,
1206
+ 'Content-Type': 'application/json',
1207
+ }, true).catch((err) => {
1208
+ console.error('Failed to fetch accounts:', err);
1209
+ throw fetchError(err, 'Failed to fetch accounts');
1210
+ });
1211
+ }
1200
1212
  async fetchWaivers(body = {}, cancelToken, headers = {}) {
1201
1213
  if (!this.companyId || this.companyId.trim() === '') {
1202
1214
  throw new StandardError(400, 'Company ID is required');
@@ -0,0 +1,64 @@
1
+ import { useMutation, useQuery } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../QueryClient.js';
3
+ import { keys } from '../realtime.js';
4
+ AvroQueryClient.prototype.useGetAccounts = function (body = {}) {
5
+ return useQuery({
6
+ queryKey: keys.list('accounts', this.companyId, {
7
+ query: body.query ?? '',
8
+ unknown_ids: body.unknown_ids ?? [],
9
+ }),
10
+ queryFn: () => this.fetchAccounts(body),
11
+ enabled: Boolean(this.companyId),
12
+ });
13
+ };
14
+ AvroQueryClient.prototype.useGetAccount = function (accountId) {
15
+ return useQuery({
16
+ queryKey: keys.detail('accounts', accountId),
17
+ queryFn: () => this.get({ path: `/account/${accountId}` }),
18
+ enabled: Boolean(accountId),
19
+ });
20
+ };
21
+ AvroQueryClient.prototype.useCreateAccount = function () {
22
+ return useMutation({
23
+ mutationFn: ({ data }) => this.post({
24
+ path: `/company/${this.companyId}/account`,
25
+ data: JSON.stringify(data),
26
+ headers: { 'Content-Type': 'application/json' },
27
+ }),
28
+ onSuccess: () => {
29
+ this.syncAfterMutation('account');
30
+ },
31
+ });
32
+ };
33
+ AvroQueryClient.prototype.useUpdateAccount = function () {
34
+ return useMutation({
35
+ mutationFn: ({ accountId, updates, }) => this.put({
36
+ path: `/account/${accountId}`,
37
+ data: JSON.stringify(updates),
38
+ headers: { 'Content-Type': 'application/json' },
39
+ }),
40
+ onSuccess: () => {
41
+ this.syncAfterMutation('account');
42
+ },
43
+ });
44
+ };
45
+ AvroQueryClient.prototype.useDeleteAccount = function () {
46
+ return useMutation({
47
+ mutationFn: ({ accountId }) => this.delete({ path: `/account/${accountId}` }),
48
+ onSuccess: () => {
49
+ this.syncAfterMutation('account');
50
+ },
51
+ });
52
+ };
53
+ AvroQueryClient.prototype.useMergeAccounts = function () {
54
+ return useMutation({
55
+ mutationFn: ({ accountId, sourceIds }) => this.post({
56
+ path: `/account/${accountId}/merge`,
57
+ data: JSON.stringify({ accounts: sourceIds }),
58
+ headers: { 'Content-Type': 'application/json' },
59
+ }),
60
+ onSuccess: () => {
61
+ this.syncAfterMutation('account', 'job', 'bill');
62
+ },
63
+ });
64
+ };
@@ -104,10 +104,10 @@ AvroQueryClient.prototype.useUpdateBill = function () {
104
104
  });
105
105
  },
106
106
  onMutate: async ({ billId, updates: wireUpdates }) => {
107
- // `users`/`line_items` are request-shaped (user ids + amounts,
108
- // bare custom items), not the cached BillUser/LineItem rows; the
109
- // echoed change brings the real ones.
110
- const { users: _users, line_items: _lineItems, ...updates } = wireUpdates;
107
+ // `charges`/`line_items` are request-shaped (user ids + amounts,
108
+ // bare custom items), not cached rows; the echoed change brings
109
+ // the real ones.
110
+ const { charges: _charges, line_items: _lineItems, ...updates } = wireUpdates;
111
111
  await queryClient.cancelQueries({ queryKey: ['bills'] });
112
112
  await queryClient.cancelQueries({ queryKey: ['bills', billId] });
113
113
  const previousBills = snapshotNs(queryClient, 'bills');
@@ -297,6 +297,7 @@ export const REGISTRY = {
297
297
  refreshThrottled: [['analytics', 'sessions']],
298
298
  },
299
299
  checkin: { ns: 'checkins', listMatch: matchCheckins },
300
+ account: { ns: 'accounts', fetchMany: bulk('fetchAccounts'), listMatch: searchAware },
300
301
  waiver: { ns: 'waivers', fetchMany: bulk('fetchWaivers'), listMatch: searchAware },
301
302
  payout: { ns: 'payouts', fetchMany: bulk('fetchPayouts'), listMatch: matchPayouts },
302
303
  timecard: {
@@ -191,15 +191,12 @@ export interface BillLineItemInput {
191
191
  /** Unit price in integer cents (default 0). */
192
192
  cost?: number;
193
193
  }
194
- /** A member recipient on a bill write (backend `BillUserIn`). */
195
- export interface BillUserInput {
196
- /** The member's user GUID. */
194
+ /** An autopay charge to attempt when a bill is created (backend `BillChargeIn`). */
195
+ export interface BillChargeInput {
196
+ /** User GUID; skipped unless they have the billing role on the bill's accounts. */
197
197
  id: string;
198
- /**
199
- * Create only: charge up to this many integer cents (>= 0) to the
200
- * user's autopay method. Fractional values are rejected.
201
- */
202
- amt?: number | null;
198
+ /** Integer cents (>= 0), capped at the bill's outstanding amount. */
199
+ amt: number;
203
200
  }
204
201
  /**
205
202
  * Body of `POST /company/<id>/bill` and `PUT /bill/<id>` (backend
@@ -217,8 +214,10 @@ export interface BillWritePayload {
217
214
  line_items?: BillLineItemInput[];
218
215
  /** Extra recipients as `[name, email]` pairs; replaces them. */
219
216
  manual_emails?: [string, string][];
220
- /** Replaces the member recipients. */
221
- users?: BillUserInput[];
217
+ /** Account GUIDs; replaces the accounts billed. */
218
+ accounts?: string[];
219
+ /** Autopay attempts; honored on creation only. */
220
+ charges?: BillChargeInput[];
222
221
  /** At most 256 characters; null clears it. */
223
222
  name?: string | null;
224
223
  /** Marks every item paid outside Avro. */
package/dist/index.d.ts CHANGED
@@ -41,6 +41,7 @@ import './client/hooks/proposal.js';
41
41
  import './client/hooks/terms.js';
42
42
  import './client/hooks/timecards.js';
43
43
  import './client/hooks/waivers.js';
44
+ import './client/hooks/accounts.js';
44
45
  import './client/hooks/email.js';
45
46
  export { defaultPassOnFeeMethod } from './billing/fees.js';
46
47
  export { REACTION_CODE_POINTS, reactionGlyph, groupReactions, messageTime, isChatUnread, } from './chat.js';
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ import './client/hooks/proposal.js';
37
37
  import './client/hooks/terms.js';
38
38
  import './client/hooks/timecards.js';
39
39
  import './client/hooks/waivers.js';
40
+ import './client/hooks/accounts.js';
40
41
  import './client/hooks/email.js';
41
42
  export { defaultPassOnFeeMethod } from './billing/fees.js';
42
43
  export { REACTION_CODE_POINTS, reactionGlyph, groupReactions, messageTime, isChatUnread, } from './chat.js';
@@ -0,0 +1,61 @@
1
+ import type { UserCompanyAssociation } from './UserCompanyAssociation.js';
2
+ export declare const AccountPermission: {
3
+ readonly BILLING: "billing";
4
+ readonly SERVICE: "service";
5
+ };
6
+ export type AccountPermission = (typeof AccountPermission)[keyof typeof AccountPermission];
7
+ /** A company member on an account, and what they do there. */
8
+ export interface AccountMember {
9
+ id: string;
10
+ account_id: string;
11
+ user_company_id: string;
12
+ permissions: AccountPermission[];
13
+ }
14
+ /** A customer of the company: its people, jobs, and bills. */
15
+ export interface Account {
16
+ id: string;
17
+ company_id: string;
18
+ name: string;
19
+ address: string;
20
+ /** Seconds a bill has until it is due; null means no default terms. */
21
+ net_terms: number | null;
22
+ users: AccountMember[];
23
+ /** Job GUIDs. */
24
+ jobs: string[];
25
+ /** Bill GUIDs. */
26
+ bills: string[];
27
+ time_created: number | null;
28
+ time_updated: number | null;
29
+ }
30
+ /** A member to put on an account. */
31
+ export interface AccountMemberInput {
32
+ /** Member (user-company) GUID. */
33
+ id: string;
34
+ permissions?: AccountPermission[];
35
+ }
36
+ export interface AccountCreatePayload {
37
+ name: string;
38
+ address?: string;
39
+ /** Seconds a bill has until it is due; null removes the terms. */
40
+ net_terms?: number | null;
41
+ users?: AccountMemberInput[];
42
+ /** Job GUIDs. */
43
+ jobs?: string[];
44
+ }
45
+ /** Omitted fields are unchanged; `users` and `jobs` replace the current lists. */
46
+ export type AccountUpdatePayload = Partial<AccountCreatePayload>;
47
+ /** Every account the user is on, optionally only where they hold `role`. */
48
+ export declare function accountsOfUser(accounts: Account[], members: UserCompanyAssociation[], userId: string, role?: AccountPermission): Account[];
49
+ /** One account id per user (their first), without duplicates. */
50
+ export declare function accountIdsForUsers(accounts: Account[], members: UserCompanyAssociation[], userIds: string[], role?: AccountPermission): string[];
51
+ /** Member ids on the given accounts, once each, optionally only those holding `role`. */
52
+ export declare function accountMemberIds(accountIds: string[], accounts: Account[], role?: AccountPermission): string[];
53
+ /** User ids a bill is addressed to: its accounts' billing contacts and anyone who paid. */
54
+ export declare function billRecipientUserIds(bill: {
55
+ accounts: string[];
56
+ payments: {
57
+ user_id: string | null;
58
+ }[];
59
+ }, accounts: Account[], members: UserCompanyAssociation[]): string[];
60
+ /** When a bill issued now is due under the accounts' shortest terms; null if none set any. */
61
+ export declare function netTermsDueDate(accountIds: string[], accounts: Account[]): Date | null;
@@ -0,0 +1,38 @@
1
+ export const AccountPermission = {
2
+ BILLING: 'billing',
3
+ SERVICE: 'service',
4
+ };
5
+ /** Every account the user is on, optionally only where they hold `role`. */
6
+ export function accountsOfUser(accounts, members, userId, role) {
7
+ const member = members.find((candidate) => candidate.user.id === userId);
8
+ if (!member)
9
+ return [];
10
+ return accounts.filter((account) => account.users.some((row) => row.user_company_id === member.id && (!role || row.permissions.includes(role))));
11
+ }
12
+ /** One account id per user (their first), without duplicates. */
13
+ export function accountIdsForUsers(accounts, members, userIds, role) {
14
+ const ids = userIds.flatMap((userId) => accountsOfUser(accounts, members, userId, role)[0]?.id ?? []);
15
+ return [...new Set(ids)];
16
+ }
17
+ /** Member ids on the given accounts, once each, optionally only those holding `role`. */
18
+ export function accountMemberIds(accountIds, accounts, role) {
19
+ const ids = accounts
20
+ .filter((account) => accountIds.includes(account.id))
21
+ .flatMap((account) => account.users)
22
+ .filter((row) => !role || row.permissions.includes(role))
23
+ .map((row) => row.user_company_id);
24
+ return [...new Set(ids)];
25
+ }
26
+ /** User ids a bill is addressed to: its accounts' billing contacts and anyone who paid. */
27
+ export function billRecipientUserIds(bill, accounts, members) {
28
+ const contacts = accountMemberIds(bill.accounts, accounts, AccountPermission.BILLING).flatMap((memberId) => members.find((member) => member.id === memberId)?.user.id ?? []);
29
+ const payers = bill.payments.flatMap((payment) => payment.user_id ?? []);
30
+ return [...new Set([...contacts, ...payers])];
31
+ }
32
+ /** When a bill issued now is due under the accounts' shortest terms; null if none set any. */
33
+ export function netTermsDueDate(accountIds, accounts) {
34
+ const terms = accounts
35
+ .filter((account) => accountIds.includes(account.id) && account.net_terms !== null)
36
+ .map((account) => account.net_terms);
37
+ return terms.length > 0 ? new Date(Date.now() + Math.min(...terms) * 1000) : null;
38
+ }
@@ -1,5 +1,4 @@
1
1
  import { BillPayment } from './BillPayment.js';
2
- import { BillUser } from './BillUser.js';
3
2
  import { CustomLineItem } from './CustomLineItem.js';
4
3
  import { LineItem } from './LineItem.js';
5
4
  import { PaymentType } from './PaymentType.js';
@@ -22,7 +21,8 @@ declare module './Bill.js' {
22
21
  /** Creator's user GUID; the string "None" for automatically created bills. */
23
22
  billed_by: string;
24
23
  manual_emails: string[][];
25
- users: BillUser[];
24
+ /** Accounts the bill was issued to. */
25
+ accounts: string[];
26
26
  status: BillStatus;
27
27
  enabled_payment_methods: PaymentType[];
28
28
  time_created: number | null;
@@ -8,8 +8,8 @@ export interface BillPayment {
8
8
  /** Null for payments recorded outside Stripe. */
9
9
  stripe_pi_id: string | null;
10
10
  payout_id: string | null;
11
- /** Payer's bill-user GUID; the string "None" when there is none. */
12
- bill_user_id: string;
11
+ /** GUID of the user who paid, when known. */
12
+ user_id: string | null;
13
13
  status: 'created' | 'processing' | 'succeeded' | 'failed' | 'canceled' | 'requires_action' | 'in_transit' | 'deposited';
14
14
  type: 'us_bank_account' | 'card';
15
15
  email_paid_by: string;
@@ -2,7 +2,6 @@ import { Task } from './Task.js';
2
2
  import { _Event } from './_Event.js';
3
3
  import type { CheckIn } from '../api.js';
4
4
  import { RouteJob } from './RouteJob.js';
5
- import { Subscription } from './Subscription.js';
6
5
  import { Route } from './Route.js';
7
6
  import type { TaskWritePayload } from '../../client/requests.js';
8
7
  declare module './Job.js' {
@@ -28,7 +27,8 @@ declare module './Job.js' {
28
27
  time_created: number | null;
29
28
  time_updated: number | null;
30
29
  routes: RouteJob[];
31
- subscribers: Subscription[];
30
+ /** Account GUIDs; empty unless the viewer can read subscriptions or is on one. */
31
+ accounts: string[];
32
32
  manual_emails: string[][];
33
33
  last_completed_event: _Event | null;
34
34
  current_event: _Event | null;
@@ -74,8 +74,8 @@ export interface JobUpdate {
74
74
  internal_notes?: string;
75
75
  external_notes?: string;
76
76
  serviced_by?: number;
77
- /** Member (user-company) or user GUIDs; replaces the subscriptions. */
78
- subscribers?: string[];
77
+ /** Account GUIDs; replaces the job's accounts. Customers can only change their own. */
78
+ accounts?: string[];
79
79
  /** Extra notification recipients as `[name, email]` pairs. */
80
80
  manual_emails?: [string, string][];
81
81
  /** Replaces the job's tasks: listed ones are upserted, unlisted deleted. */
@@ -1,6 +1,7 @@
1
1
  import { FrequencyType } from '..';
2
2
  import type { LineItemStatus } from './api/LineItem.js';
3
3
  export * from './api/_Event.js';
4
+ export * from './api/Account.js';
4
5
  export * from './api/AdditionalCharge.js';
5
6
  export * from './api/DelayEvent.js';
6
7
  export * from './api/Device.js';
@@ -43,7 +44,6 @@ export * from './api/RouteJob.js';
43
44
  export * from './api/ServiceMonth.js';
44
45
  export * from './api/Session.js';
45
46
  export * from './api/Skill.js';
46
- export * from './api/Subscription.js';
47
47
  export * from './api/Task.js';
48
48
  export * from './api/Timecard.js';
49
49
  export * from './api/TimecardAction.js';
package/dist/types/api.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './api/_Event.js';
2
+ export * from './api/Account.js';
2
3
  export * from './api/AdditionalCharge.js';
3
4
  export * from './api/DelayEvent.js';
4
5
  export * from './api/Device.js';
@@ -41,7 +42,6 @@ export * from './api/RouteJob.js';
41
42
  export * from './api/ServiceMonth.js';
42
43
  export * from './api/Session.js';
43
44
  export * from './api/Skill.js';
44
- export * from './api/Subscription.js';
45
45
  export * from './api/Task.js';
46
46
  export * from './api/Timecard.js';
47
47
  export * from './api/TimecardAction.js';
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "1.7.0";
1
+ export declare const AVRO_JS_VERSION = "1.7.2";
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.7.0';
3
+ export const AVRO_JS_VERSION = '1.7.2';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,10 +0,0 @@
1
- import type { NotificationLevel } from './UserCompanyAssociation.js';
2
- export interface Subscription {
3
- time_created: number | null;
4
- time_updated: number | null;
5
- /** The subscribed membership; the string "None" for a group subscription. */
6
- user_company_id: string;
7
- job_id: string;
8
- id: string;
9
- notifications: NotificationLevel[];
10
- }