@go-avro/avro-js 0.0.36 → 0.0.38

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.
Files changed (59) hide show
  1. package/dist/auth/AuthManager.d.ts +2 -2
  2. package/dist/auth/AuthManager.js +37 -32
  3. package/dist/auth/storage.d.ts +1 -1
  4. package/dist/auth/storage.js +6 -6
  5. package/dist/client/AvroQueryClientProvider.js +1 -1
  6. package/dist/client/QueryClient.d.ts +35 -17
  7. package/dist/client/QueryClient.js +486 -384
  8. package/dist/client/core/fetch.js +16 -11
  9. package/dist/client/core/utils.js +5 -5
  10. package/dist/client/core/xhr.js +28 -23
  11. package/dist/client/hooks/analytics.js +14 -14
  12. package/dist/client/hooks/avro.js +2 -2
  13. package/dist/client/hooks/bills.js +66 -30
  14. package/dist/client/hooks/catalog_items.js +57 -22
  15. package/dist/client/hooks/chats.js +4 -4
  16. package/dist/client/hooks/companies.js +96 -39
  17. package/dist/client/hooks/email.js +1 -1
  18. package/dist/client/hooks/events.js +174 -63
  19. package/dist/client/hooks/groups.js +37 -22
  20. package/dist/client/hooks/jobs.js +69 -18
  21. package/dist/client/hooks/labels.js +36 -21
  22. package/dist/client/hooks/messages.js +9 -6
  23. package/dist/client/hooks/months.js +42 -22
  24. package/dist/client/hooks/plans.js +2 -2
  25. package/dist/client/hooks/prepayments.js +42 -22
  26. package/dist/client/hooks/proposal.js +21 -5
  27. package/dist/client/hooks/root.js +4 -4
  28. package/dist/client/hooks/routes.js +77 -32
  29. package/dist/client/hooks/sessions.js +66 -34
  30. package/dist/client/hooks/skills.js +33 -18
  31. package/dist/client/hooks/teams.js +36 -21
  32. package/dist/client/hooks/timecards.js +6 -0
  33. package/dist/client/hooks/users.js +61 -29
  34. package/dist/client/hooks/waivers.js +41 -19
  35. package/dist/index.d.ts +38 -38
  36. package/dist/index.js +37 -37
  37. package/dist/types/api/Bill.d.ts +1 -1
  38. package/dist/types/api/Bill.js +1 -1
  39. package/dist/types/api/Job.d.ts +1 -1
  40. package/dist/types/api/Job.js +14 -14
  41. package/dist/types/api/LineItem.d.ts +3 -3
  42. package/dist/types/api/LineItem.js +5 -2
  43. package/dist/types/api/PaymentType.d.ts +1 -1
  44. package/dist/types/api/Prepayment.d.ts +1 -1
  45. package/dist/types/api/Route.d.ts +3 -3
  46. package/dist/types/api/Route.js +4 -2
  47. package/dist/types/api/RouteJob.d.ts +1 -1
  48. package/dist/types/api/Task.d.ts +2 -2
  49. package/dist/types/api/Task.js +12 -7
  50. package/dist/types/api/Timecard.d.ts +1 -1
  51. package/dist/types/api/TimecardAction.d.ts +1 -1
  52. package/dist/types/api/UserCompanyAssociation.d.ts +2 -2
  53. package/dist/types/api/UserCompanyAssociation.js +1 -1
  54. package/dist/types/api/_Event.d.ts +1 -1
  55. package/dist/types/api/_Event.js +1 -1
  56. package/dist/types/api.d.ts +1 -1
  57. package/dist/types/auth.d.ts +1 -1
  58. package/dist/types/client.d.ts +1 -1
  59. package/package.json +3 -2
@@ -1,11 +1,11 @@
1
- import { AvroQueryClient } from '../../client/QueryClient';
2
- import { StandardError } from '../../types/error';
3
- import { AuthState } from '../../types/auth';
1
+ import { AvroQueryClient } from "../../client/QueryClient";
2
+ import { StandardError } from "../../types/error";
3
+ import { AuthState } from "../../types/auth";
4
4
  AvroQueryClient.prototype._fetch = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
5
5
  const checkCancelled = () => {
6
6
  try {
7
7
  if (cancelToken?.isCancelled()) {
8
- throw new StandardError(0, 'Request cancelled');
8
+ throw new StandardError(0, "Request cancelled");
9
9
  }
10
10
  }
11
11
  catch (error) {
@@ -14,7 +14,9 @@ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelTok
14
14
  };
15
15
  try {
16
16
  checkCancelled();
17
- const token = this.getAuthState() === AuthState.AUTHENTICATED ? await this.config.authManager.accessToken() : undefined;
17
+ const token = this.getAuthState() === AuthState.AUTHENTICATED
18
+ ? await this.config.authManager.accessToken()
19
+ : undefined;
18
20
  checkCancelled();
19
21
  const url = this.config.baseUrl + path;
20
22
  const requestHeaders = {
@@ -28,9 +30,9 @@ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelTok
28
30
  };
29
31
  const response = await fetch(url, options);
30
32
  if (response.ok) {
31
- const contentType = response.headers.get('content-type') ?? '';
32
- if (contentType.includes('application/pdf') ||
33
- contentType.includes('application/octet-stream')) {
33
+ const contentType = response.headers.get("content-type") ?? "";
34
+ if (contentType.includes("application/pdf") ||
35
+ contentType.includes("application/octet-stream")) {
34
36
  return response.blob();
35
37
  }
36
38
  const text = await response.text();
@@ -39,7 +41,10 @@ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelTok
39
41
  }
40
42
  return JSON.parse(text);
41
43
  }
42
- if (response.status === 401 && this.config.authManager.refreshTokens && retryCount === 0 && this.getAuthState() === AuthState.AUTHENTICATED) {
44
+ if (response.status === 401 &&
45
+ this.config.authManager.refreshTokens &&
46
+ retryCount === 0 &&
47
+ this.getAuthState() === AuthState.AUTHENTICATED) {
43
48
  await this.config.authManager.refreshTokens();
44
49
  return this._fetch(method, path, body, cancelToken, headers, isIdempotent, 1);
45
50
  }
@@ -54,7 +59,7 @@ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelTok
54
59
  errorMessage = parsedError.message ?? parsedError.msg ?? errorMessage;
55
60
  }
56
61
  catch (e) {
57
- console.error('Ignoring:', e);
62
+ console.error("Ignoring:", e);
58
63
  }
59
64
  throw new StandardError(response.status, errorMessage);
60
65
  }
@@ -63,7 +68,7 @@ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelTok
63
68
  throw error;
64
69
  }
65
70
  const message = error instanceof Error ? error.message : String(error);
66
- console.error('Fetch error:', message);
71
+ console.error("Fetch error:", message);
67
72
  throw new StandardError(0, `Request failed: ${message}`);
68
73
  }
69
74
  };
@@ -1,14 +1,14 @@
1
- import { AvroQueryClient } from '../../client/QueryClient';
1
+ import { AvroQueryClient } from "../../client/QueryClient";
2
2
  AvroQueryClient.prototype.getDelay = function (strategy, attempt) {
3
- if (typeof strategy === 'function') {
3
+ if (typeof strategy === "function") {
4
4
  return strategy(attempt);
5
5
  }
6
- else if (strategy === 'fixed') {
6
+ else if (strategy === "fixed") {
7
7
  return 1000;
8
8
  }
9
- else if (strategy === 'exponential') {
9
+ else if (strategy === "exponential") {
10
10
  return Math.pow(2, attempt) * 100;
11
11
  }
12
12
  throw new Error(`Invalid retry strategy: ${strategy}`);
13
13
  };
14
- AvroQueryClient.prototype.sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
14
+ AvroQueryClient.prototype.sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -1,30 +1,32 @@
1
- import { AvroQueryClient } from '../../client/QueryClient';
2
- import { StandardError } from '../../types/error';
3
- import { AuthState } from '../../types/auth';
1
+ import { AvroQueryClient } from "../../client/QueryClient";
2
+ import { StandardError } from "../../types/error";
3
+ import { AuthState } from "../../types/auth";
4
4
  AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0, progressUpdateCallback) {
5
5
  const checkCancelled = () => {
6
6
  if (cancelToken?.isCancelled()) {
7
- throw new StandardError(0, 'Request cancelled');
7
+ throw new StandardError(0, "Request cancelled");
8
8
  }
9
9
  };
10
10
  for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
11
11
  try {
12
12
  checkCancelled();
13
- const token = this.getAuthState() === AuthState.AUTHENTICATED ? await this.config.authManager.accessToken() : undefined;
13
+ const token = this.getAuthState() === AuthState.AUTHENTICATED
14
+ ? await this.config.authManager.accessToken()
15
+ : undefined;
14
16
  checkCancelled();
15
17
  const result = await new Promise((resolve, reject) => {
16
18
  const xhr = new XMLHttpRequest();
17
19
  const url = this.config.baseUrl + path;
18
20
  xhr.open(method, url, true);
19
21
  if (token)
20
- xhr.setRequestHeader('Authorization', `Bearer ${token}`);
22
+ xhr.setRequestHeader("Authorization", `Bearer ${token}`);
21
23
  Object.entries(headers).forEach(([key, value]) => xhr.setRequestHeader(key, value));
22
24
  xhr.onload = () => {
23
25
  if (xhr.status >= 200 && xhr.status < 300) {
24
26
  try {
25
- const contentType = xhr.getResponseHeader('content-type') || '';
26
- if (contentType.includes('application/pdf') ||
27
- contentType.includes('application/octet-stream')) {
27
+ const contentType = xhr.getResponseHeader("content-type") || "";
28
+ if (contentType.includes("application/pdf") ||
29
+ contentType.includes("application/octet-stream")) {
28
30
  resolve(new Blob([xhr.response], { type: contentType }));
29
31
  return;
30
32
  }
@@ -45,15 +47,15 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
45
47
  msg = parsed.message ?? parsed.msg ?? msg;
46
48
  }
47
49
  catch (e) {
48
- console.error('Ignoring:', e);
50
+ console.error("Ignoring:", e);
49
51
  }
50
52
  reject(new StandardError(xhr.status, msg));
51
53
  }
52
54
  };
53
- xhr.onerror = () => reject(new StandardError(0, 'Network Error'));
55
+ xhr.onerror = () => reject(new StandardError(0, "Network Error"));
54
56
  if (this.config.timeout) {
55
57
  xhr.timeout = this.config.timeout;
56
- xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
58
+ xhr.ontimeout = () => reject(new StandardError(0, "Request timed out"));
57
59
  }
58
60
  if (progressUpdateCallback && xhr.upload) {
59
61
  xhr.upload.onprogress = (event) => {
@@ -63,34 +65,37 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
63
65
  };
64
66
  }
65
67
  // Set responseType to 'blob' if expecting binary
66
- const contentType = headers['Content-Type'] || '';
67
- if (contentType.includes('application/pdf') ||
68
- contentType.includes('application/octet-stream')) {
69
- xhr.responseType = 'blob';
68
+ const contentType = headers["Content-Type"] || "";
69
+ if (contentType.includes("application/pdf") ||
70
+ contentType.includes("application/octet-stream")) {
71
+ xhr.responseType = "blob";
70
72
  }
71
73
  xhr.send(body);
72
74
  });
73
75
  return result;
74
76
  }
75
77
  catch (error) {
76
- console.error('xhr error:', error);
78
+ console.error("xhr error:", error);
77
79
  if (!(error instanceof StandardError)) {
78
80
  const message = error instanceof Error ? error.message : String(error);
79
- console.error('Non-StandardError caught:', message);
81
+ console.error("Non-StandardError caught:", message);
80
82
  throw new StandardError(0, `An unexpected error occurred: ${message}`);
81
83
  }
82
- if (error.status === 401 && this.config.authManager.refreshTokens && attempt === 0 && this.getAuthState() === AuthState.AUTHENTICATED) {
83
- console.log('Attempting to refresh tokens due to 401 response');
84
+ if (error.status === 401 &&
85
+ this.config.authManager.refreshTokens &&
86
+ attempt === 0 &&
87
+ this.getAuthState() === AuthState.AUTHENTICATED) {
88
+ console.log("Attempting to refresh tokens due to 401 response");
84
89
  try {
85
90
  await this.config.authManager.refreshTokens();
86
91
  continue;
87
92
  }
88
93
  catch (refreshError) {
89
- throw new StandardError(401, 'Unauthorized (refresh failed)');
94
+ throw new StandardError(401, "Unauthorized (refresh failed)");
90
95
  }
91
96
  }
92
97
  if (error.status === 401 || attempt >= this.config.maxRetries) {
93
- console.error('Not retrying request, throwing error.');
98
+ console.error("Not retrying request, throwing error.");
94
99
  throw error;
95
100
  }
96
101
  const delay = this.getDelay(this.config.retryStrategy, attempt);
@@ -98,5 +103,5 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
98
103
  await this.sleep(delay);
99
104
  }
100
105
  }
101
- throw new StandardError(0, 'Request failed after maximum retries.');
106
+ throw new StandardError(0, "Request failed after maximum retries.");
102
107
  };
@@ -2,47 +2,47 @@ import { useQuery } from "@tanstack/react-query";
2
2
  import { AvroQueryClient } from "../../client/QueryClient";
3
3
  AvroQueryClient.prototype.useGetAnalytics = function () {
4
4
  return useQuery({
5
- queryKey: ['analytics'],
5
+ queryKey: ["analytics"],
6
6
  queryFn: () => this.post({
7
- path: '/avro/analytics',
7
+ path: "/avro/analytics",
8
8
  }),
9
9
  enabled: true,
10
10
  });
11
11
  };
12
- AvroQueryClient.prototype.useFinanceAnalytics = function ({ periods, cumulative }) {
12
+ AvroQueryClient.prototype.useFinanceAnalytics = function ({ periods, cumulative, }) {
13
13
  return useQuery({
14
- queryKey: ['analytics', 'finance', this.companyId, periods, cumulative],
14
+ queryKey: ["analytics", "finance", this.companyId, periods, cumulative],
15
15
  queryFn: () => this.post({
16
16
  path: `/company/${this.companyId}/analytics/finance`,
17
17
  data: JSON.stringify({ periods, cumulative }),
18
18
  headers: {
19
- 'Content-Type': 'application/json',
20
- }
19
+ "Content-Type": "application/json",
20
+ },
21
21
  }),
22
22
  });
23
23
  };
24
- AvroQueryClient.prototype.useEventAnalytics = function ({ periods }) {
24
+ AvroQueryClient.prototype.useEventAnalytics = function ({ periods, }) {
25
25
  return useQuery({
26
- queryKey: ['analytics', 'events', this.companyId, periods],
26
+ queryKey: ["analytics", "events", this.companyId, periods],
27
27
  queryFn: () => this.post({
28
28
  path: `/company/${this.companyId}/analytics/events`,
29
29
  data: JSON.stringify({ periods }),
30
30
  headers: {
31
- 'Content-Type': 'application/json',
32
- }
31
+ "Content-Type": "application/json",
32
+ },
33
33
  }),
34
34
  enabled: Boolean(this.companyId),
35
35
  });
36
36
  };
37
- AvroQueryClient.prototype.useRevenueAnalytics = function ({ periods }) {
37
+ AvroQueryClient.prototype.useRevenueAnalytics = function ({ periods, }) {
38
38
  return useQuery({
39
- queryKey: ['analytics', 'revenue', this.companyId, periods],
39
+ queryKey: ["analytics", "revenue", this.companyId, periods],
40
40
  queryFn: () => this.post({
41
41
  path: `/company/${this.companyId}/analytics/revenue`,
42
42
  data: JSON.stringify({ periods }),
43
43
  headers: {
44
- 'Content-Type': 'application/json',
45
- }
44
+ "Content-Type": "application/json",
45
+ },
46
46
  }),
47
47
  enabled: Boolean(this.companyId),
48
48
  });
@@ -2,8 +2,8 @@ import { useQuery } from "@tanstack/react-query";
2
2
  import { AvroQueryClient } from "../../client/QueryClient";
3
3
  AvroQueryClient.prototype.useGetAvro = function () {
4
4
  return useQuery({
5
- queryKey: ['avro'],
6
- queryFn: () => this.get({ path: '/avro' }),
5
+ queryKey: ["avro"],
6
+ queryFn: () => this.get({ path: "/avro" }),
7
7
  enabled: true,
8
8
  });
9
9
  };
@@ -1,10 +1,10 @@
1
- import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
- import { AvroQueryClient } from '../../client/QueryClient';
1
+ import { useInfiniteQuery, useQuery, useMutation } from "@tanstack/react-query";
2
+ import { AvroQueryClient } from "../../client/QueryClient";
3
3
  AvroQueryClient.prototype.useGetBills = function (body) {
4
4
  const queryClient = this.getQueryClient();
5
5
  const result = useInfiniteQuery({
6
6
  queryKey: [
7
- 'bills',
7
+ "bills",
8
8
  this.companyId,
9
9
  body.query ?? "",
10
10
  body.known_ids ?? [],
@@ -22,7 +22,7 @@ AvroQueryClient.prototype.useGetBills = function (body) {
22
22
  if (result.data) {
23
23
  result.data.pages.forEach((data_page) => {
24
24
  data_page.forEach((bill) => {
25
- queryClient.setQueryData(['bills', bill.id], bill);
25
+ queryClient.setQueryData(["bills", bill.id], bill);
26
26
  });
27
27
  });
28
28
  }
@@ -30,7 +30,7 @@ AvroQueryClient.prototype.useGetBills = function (body) {
30
30
  };
31
31
  AvroQueryClient.prototype.useGetBill = function (billId) {
32
32
  return useQuery({
33
- queryKey: ['bills', billId],
33
+ queryKey: ["bills", billId],
34
34
  queryFn: () => this.get({ path: `/bill/${billId}` }),
35
35
  enabled: Boolean(billId),
36
36
  });
@@ -53,19 +53,29 @@ AvroQueryClient.prototype.useCreateBill = function () {
53
53
  path: `/company/${this.companyId}/bill`,
54
54
  data: JSON.stringify(body),
55
55
  headers: {
56
- 'Content-Type': 'application/json',
57
- }
56
+ "Content-Type": "application/json",
57
+ },
58
58
  });
59
59
  },
60
60
  onMutate: async () => {
61
- await queryClient.cancelQueries({ queryKey: ['bills', this.companyId] });
62
- const previousBills = queryClient.getQueryData(['bills', this.companyId]);
61
+ await queryClient.cancelQueries({
62
+ queryKey: ["bills", this.companyId],
63
+ });
64
+ const previousBills = queryClient.getQueryData(["bills", this.companyId]);
63
65
  // TODO: Create a fake bill object for optimistic update and update events and months accordingly
64
66
  return { previousBills };
65
67
  },
68
+ onSuccess: async (result) => {
69
+ await this._syncEntity(queryClient, {
70
+ action: "create",
71
+ entityKey: "bills",
72
+ id: result.id,
73
+ fetchPath: `/bill/${result.id}`,
74
+ });
75
+ },
66
76
  onError: (_err, _variables, context) => {
67
77
  if (context?.previousBills) {
68
- queryClient.setQueryData(['bills'], context.previousBills);
78
+ queryClient.setQueryData(["bills"], context.previousBills);
69
79
  }
70
80
  },
71
81
  });
@@ -73,22 +83,22 @@ AvroQueryClient.prototype.useCreateBill = function () {
73
83
  AvroQueryClient.prototype.useUpdateBill = function () {
74
84
  const queryClient = this.getQueryClient();
75
85
  return useMutation({
76
- mutationFn: ({ billId, updates }) => {
86
+ mutationFn: ({ billId, updates, }) => {
77
87
  return this.put({
78
88
  path: `/bill/${billId}`,
79
89
  data: JSON.stringify(updates),
80
90
  headers: {
81
91
  "Content-Type": "application/json",
82
- }
92
+ },
83
93
  });
84
94
  },
85
95
  onMutate: async ({ billId, updates }) => {
86
- await queryClient.cancelQueries({ queryKey: ['bills'] });
87
- await queryClient.cancelQueries({ queryKey: ['bills', billId] });
88
- const previousBills = queryClient.getQueryData(['bills']);
89
- const previousBill = queryClient.getQueryData(['bills', billId]);
90
- queryClient.setQueryData(['bills', billId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
91
- queryClient.setQueriesData({ queryKey: ['bills'] }, (oldData) => {
96
+ await queryClient.cancelQueries({ queryKey: ["bills"] });
97
+ await queryClient.cancelQueries({ queryKey: ["bills", billId] });
98
+ const previousBills = queryClient.getQueryData(["bills"]);
99
+ const previousBill = queryClient.getQueryData(["bills", billId]);
100
+ queryClient.setQueryData(["bills", billId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
101
+ queryClient.setQueriesData({ queryKey: ["bills"] }, (oldData) => {
92
102
  if (!oldData)
93
103
  return oldData;
94
104
  if (oldData.pages) {
@@ -104,13 +114,21 @@ AvroQueryClient.prototype.useUpdateBill = function () {
104
114
  });
105
115
  return { previousBills, previousBill };
106
116
  },
117
+ onSuccess: async (_result, { billId }) => {
118
+ await this._syncEntity(queryClient, {
119
+ action: "update",
120
+ entityKey: "bills",
121
+ id: billId,
122
+ fetchPath: `/bill/${billId}`,
123
+ });
124
+ },
107
125
  onError: (err, variables, context) => {
108
126
  const { billId } = variables;
109
127
  if (context?.previousBills) {
110
- queryClient.setQueryData(['bills'], context.previousBills);
128
+ queryClient.setQueryData(["bills"], context.previousBills);
111
129
  }
112
130
  if (context?.previousBill) {
113
- queryClient.setQueryData(['bills', billId], context.previousBill);
131
+ queryClient.setQueryData(["bills", billId], context.previousBill);
114
132
  }
115
133
  },
116
134
  });
@@ -122,14 +140,21 @@ AvroQueryClient.prototype.useDeleteBill = function () {
122
140
  return this.delete({ path: `/bill/${billId}` });
123
141
  },
124
142
  onMutate: async ({ billId }) => {
125
- await queryClient.cancelQueries({ queryKey: ['bills'] });
126
- const previousBills = queryClient.getQueryData(['bills']);
143
+ await queryClient.cancelQueries({ queryKey: ["bills"] });
144
+ const previousBills = queryClient.getQueryData(["bills"]);
127
145
  // TODO: Create a fake bill object for optimistic update and update events and months accordingly
128
146
  return { previousBills };
129
147
  },
148
+ onSuccess: async (_result, { billId }) => {
149
+ await this._syncEntity(queryClient, {
150
+ action: "delete",
151
+ entityKey: "bills",
152
+ id: billId,
153
+ });
154
+ },
130
155
  onError: (_err, _variables, context) => {
131
156
  if (context?.previousBills) {
132
- queryClient.setQueryData(['bills'], context.previousBills);
157
+ queryClient.setQueryData(["bills"], context.previousBills);
133
158
  }
134
159
  },
135
160
  });
@@ -143,14 +168,20 @@ AvroQueryClient.prototype.useSyncBillToIntuit = function () {
143
168
  });
144
169
  },
145
170
  onMutate: async ({ billId }) => {
146
- await queryClient.cancelQueries({ queryKey: ['bills', billId] });
147
- const previousBill = queryClient.getQueryData(['bills', billId]);
171
+ await queryClient.cancelQueries({ queryKey: ["bills", billId] });
172
+ const previousBill = queryClient.getQueryData([
173
+ "bills",
174
+ billId,
175
+ ]);
148
176
  return { previousBill };
149
177
  },
178
+ onSuccess: () => {
179
+ queryClient.invalidateQueries({ queryKey: ["bills"] });
180
+ },
150
181
  onError: (_err, variables, context) => {
151
182
  const { billId } = variables;
152
183
  if (context?.previousBill) {
153
- queryClient.setQueryData(['bills', billId], context.previousBill);
184
+ queryClient.setQueryData(["bills", billId], context.previousBill);
154
185
  }
155
186
  },
156
187
  });
@@ -163,10 +194,15 @@ AvroQueryClient.prototype.useImportBillsFromIntuit = function () {
163
194
  path: `/company/${this.companyId}/intuit/import`,
164
195
  });
165
196
  },
197
+ onSuccess: () => {
198
+ queryClient.invalidateQueries({ queryKey: ["bills"] });
199
+ },
166
200
  });
167
201
  };
168
- AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId }) {
169
- return this.get({ path: `/company/${this.companyId}/bill/${billId}/pdf` }).then((response) => {
202
+ AvroQueryClient.prototype.generatePDFFromBackend = function ({ billId, }) {
203
+ return this.get({
204
+ path: `/company/${this.companyId}/bill/${billId}/pdf`,
205
+ }).then((response) => {
170
206
  return response;
171
207
  });
172
208
  };
@@ -175,7 +211,7 @@ AvroQueryClient.prototype.sendBillingEmail = async function ({ subject, billId,
175
211
  path: `/bill/${billId}/email`,
176
212
  data: JSON.stringify({ recipients, subject, request_id }),
177
213
  headers: {
178
- "Content-Type": "application/json"
179
- }
214
+ "Content-Type": "application/json",
215
+ },
180
216
  });
181
217
  };
@@ -1,5 +1,5 @@
1
- import { useQuery, useMutation } from '@tanstack/react-query';
2
- import { AvroQueryClient } from '../../client/QueryClient';
1
+ import { useQuery, useMutation } from "@tanstack/react-query";
2
+ import { AvroQueryClient } from "../../client/QueryClient";
3
3
  AvroQueryClient.prototype.useCreateCatalogItem = function () {
4
4
  const queryClient = this.getQueryClient();
5
5
  return useMutation({
@@ -8,18 +8,31 @@ AvroQueryClient.prototype.useCreateCatalogItem = function () {
8
8
  path: `/company/${this.companyId}/catalog_item`,
9
9
  data: JSON.stringify(data),
10
10
  headers: {
11
- 'Content-Type': 'application/json'
12
- }
11
+ "Content-Type": "application/json",
12
+ },
13
13
  });
14
14
  },
15
15
  onMutate: async () => {
16
- await queryClient.cancelQueries({ queryKey: ['catalog_items', this.companyId] });
17
- const previousItems = queryClient.getQueryData(['catalog_items', this.companyId]);
16
+ await queryClient.cancelQueries({
17
+ queryKey: ["catalog_items", this.companyId],
18
+ });
19
+ const previousItems = queryClient.getQueryData([
20
+ "catalog_items",
21
+ this.companyId,
22
+ ]);
18
23
  return { previousItems };
19
24
  },
25
+ onSuccess: async (result) => {
26
+ await this._syncEntity(queryClient, {
27
+ action: "create",
28
+ entityKey: "catalog_items",
29
+ id: result.id,
30
+ fetchPath: `/catalog_item/${result.id}`,
31
+ });
32
+ },
20
33
  onError: (_err, _variables, context) => {
21
34
  if (context?.previousItems) {
22
- queryClient.setQueryData(['catalog_items', this.companyId], context.previousItems);
35
+ queryClient.setQueryData(["catalog_items", this.companyId], context.previousItems);
23
36
  }
24
37
  },
25
38
  });
@@ -27,22 +40,27 @@ AvroQueryClient.prototype.useCreateCatalogItem = function () {
27
40
  AvroQueryClient.prototype.useUpdateCatalogItem = function () {
28
41
  const queryClient = this.getQueryClient();
29
42
  return useMutation({
30
- mutationFn: ({ catalogItemId, data }) => {
43
+ mutationFn: ({ catalogItemId, data, }) => {
31
44
  return this.put({
32
45
  path: `/catalog_item/${catalogItemId}`,
33
46
  data: JSON.stringify(data),
34
47
  headers: {
35
48
  "Content-Type": "application/json",
36
- }
49
+ },
37
50
  });
38
51
  },
39
52
  onMutate: async ({ catalogItemId, data }) => {
40
- await queryClient.cancelQueries({ queryKey: ['catalog_items'] });
41
- await queryClient.cancelQueries({ queryKey: ['catalog_items', catalogItemId] });
42
- const previousItems = queryClient.getQueryData(['catalog_items']);
43
- const previousItem = queryClient.getQueryData(['catalog_items', catalogItemId]);
44
- queryClient.setQueryData(['catalog_items', catalogItemId], (oldData) => oldData ? { ...oldData, ...data } : undefined);
45
- queryClient.setQueriesData({ queryKey: ['catalog_items'] }, (oldData) => {
53
+ await queryClient.cancelQueries({ queryKey: ["catalog_items"] });
54
+ await queryClient.cancelQueries({
55
+ queryKey: ["catalog_items", catalogItemId],
56
+ });
57
+ const previousItems = queryClient.getQueryData(["catalog_items"]);
58
+ const previousItem = queryClient.getQueryData([
59
+ "catalog_items",
60
+ catalogItemId,
61
+ ]);
62
+ queryClient.setQueryData(["catalog_items", catalogItemId], (oldData) => oldData ? { ...oldData, ...data } : undefined);
63
+ queryClient.setQueriesData({ queryKey: ["catalog_items"] }, (oldData) => {
46
64
  if (!oldData)
47
65
  return oldData;
48
66
  if (oldData.pages) {
@@ -58,20 +76,28 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
58
76
  });
59
77
  return { previousItems, previousItem };
60
78
  },
79
+ onSuccess: async (_result, { catalogItemId }) => {
80
+ await this._syncEntity(queryClient, {
81
+ action: "update",
82
+ entityKey: "catalog_items",
83
+ id: catalogItemId,
84
+ fetchPath: `/catalog_item/${catalogItemId}`,
85
+ });
86
+ },
61
87
  onError: (err, variables, context) => {
62
88
  const { catalogItemId } = variables;
63
89
  if (context?.previousItems) {
64
- queryClient.setQueryData(['catalog_items'], context.previousItems);
90
+ queryClient.setQueryData(["catalog_items"], context.previousItems);
65
91
  }
66
92
  if (context?.previousItem) {
67
- queryClient.setQueryData(['catalog_items', catalogItemId], context.previousItem);
93
+ queryClient.setQueryData(["catalog_items", catalogItemId], context.previousItem);
68
94
  }
69
95
  },
70
96
  });
71
97
  };
72
98
  AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
73
99
  return useQuery({
74
- queryKey: ['catalog_items', catalogItemId],
100
+ queryKey: ["catalog_items", catalogItemId],
75
101
  queryFn: () => this.get({ path: `/catalog_item/${catalogItemId}` }),
76
102
  enabled: Boolean(catalogItemId),
77
103
  });
@@ -80,16 +106,25 @@ AvroQueryClient.prototype.useDeleteCatalogItem = function () {
80
106
  const queryClient = this.getQueryClient();
81
107
  return useMutation({
82
108
  mutationFn: async ({ catalogItemId }) => {
83
- return this.delete({ path: `/catalog_item/${catalogItemId}` });
109
+ return this.delete({
110
+ path: `/catalog_item/${catalogItemId}`,
111
+ });
84
112
  },
85
113
  onMutate: async ({ catalogItemId }) => {
86
- await queryClient.cancelQueries({ queryKey: ['catalog_items'] });
87
- const previousItems = queryClient.getQueryData(['catalog_items']);
114
+ await queryClient.cancelQueries({ queryKey: ["catalog_items"] });
115
+ const previousItems = queryClient.getQueryData(["catalog_items"]);
88
116
  return { previousItems };
89
117
  },
118
+ onSuccess: async (_result, { catalogItemId }) => {
119
+ await this._syncEntity(queryClient, {
120
+ action: "delete",
121
+ entityKey: "catalog_items",
122
+ id: catalogItemId,
123
+ });
124
+ },
90
125
  onError: (_err, _variables, context) => {
91
126
  if (context?.previousItems) {
92
- queryClient.setQueryData(['catalog_items'], context.previousItems);
127
+ queryClient.setQueryData(["catalog_items"], context.previousItems);
93
128
  }
94
129
  },
95
130
  });
@@ -4,12 +4,12 @@ AvroQueryClient.prototype.useGetChats = function (body) {
4
4
  const queryClient = this.getQueryClient();
5
5
  const result = useInfiniteQuery({
6
6
  queryKey: [
7
- 'chats',
7
+ "chats",
8
8
  this.companyId,
9
9
  body.amt ?? 50,
10
10
  body.known_ids ?? [],
11
11
  body.unknown_ids ?? [],
12
- body.query ?? '',
12
+ body.query ?? "",
13
13
  ],
14
14
  initialPageParam: 0,
15
15
  getNextPageParam: (lastPage, allPages) => {
@@ -22,7 +22,7 @@ AvroQueryClient.prototype.useGetChats = function (body) {
22
22
  if (result.data) {
23
23
  result.data.pages.forEach((data_page) => {
24
24
  data_page.forEach((chat) => {
25
- queryClient.setQueryData(['chats', chat.id], chat);
25
+ queryClient.setQueryData(["chats", chat.id], chat);
26
26
  });
27
27
  });
28
28
  }
@@ -30,7 +30,7 @@ AvroQueryClient.prototype.useGetChats = function (body) {
30
30
  };
31
31
  AvroQueryClient.prototype.useGetChat = function (chatId) {
32
32
  return useQuery({
33
- queryKey: ['chats', chatId],
33
+ queryKey: ["chats", chatId],
34
34
  queryFn: () => this.get({ path: `/chat/${chatId}` }),
35
35
  enabled: Boolean(chatId),
36
36
  });