@zeniai/client-epic-state 5.2.83 → 5.2.85-beta0KB

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 (69) hide show
  1. package/lib/entity/snackbar/snackbarTypes.d.ts +1 -1
  2. package/lib/entity/snackbar/snackbarTypes.js +1 -0
  3. package/lib/entity/transaction/stateTypes/paymentType.d.ts +2 -2
  4. package/lib/entity/transaction/stateTypes/paymentType.js +9 -1
  5. package/lib/entity/transaction/stateTypes/printStatus.d.ts +4 -0
  6. package/lib/entity/transaction/stateTypes/printStatus.js +11 -0
  7. package/lib/epic.d.ts +4 -1
  8. package/lib/epic.js +6 -0
  9. package/lib/esm/entity/snackbar/snackbarTypes.js +1 -0
  10. package/lib/esm/entity/transaction/stateTypes/paymentType.js +9 -1
  11. package/lib/esm/entity/transaction/stateTypes/printStatus.js +7 -0
  12. package/lib/esm/epic.js +6 -0
  13. package/lib/esm/index.js +5 -2
  14. package/lib/esm/view/invoicing/createInvoice/epics/fetchCreateInvoiceFormPageEpic.js +19 -5
  15. package/lib/esm/view/invoicing/editInvoicingSubscriptionDetailView/editInvoicingSubscriptionDetailViewPayload.js +7 -4
  16. package/lib/esm/view/invoicing/editInvoicingSubscriptionDetailView/editInvoicingSubscriptionDetailViewSelector.js +3 -1
  17. package/lib/esm/view/invoicing/editInvoicingSubscriptionDetailView/fetchInvoicingSubscriptionDetailPageEpic.js +7 -4
  18. package/lib/esm/view/invoicing/editInvoicingSubscriptionDetailView/fetchInvoicingSubscriptionFormPageEpic.js +1 -0
  19. package/lib/esm/view/invoicing/editInvoicingSubscriptionDetailView/invoicingSubscriptionFormConfig.js +2 -0
  20. package/lib/esm/view/invoicing/editInvoicingSubscriptionDetailView/saveInvoicingSubscriptionEpic.js +6 -2
  21. package/lib/esm/view/invoicing/invoicingCatalogListView/epics/fetchInvoicingCatalogPlanListEpic.js +14 -3
  22. package/lib/esm/view/invoicing/invoicingCatalogListView/epics/fetchInvoicingCatalogProductListEpic.js +14 -3
  23. package/lib/esm/view/invoicing/invoicingCatalogListView/invoicingCatalogListViewReducer.js +2 -0
  24. package/lib/esm/view/invoicing/invoicingListTabCache.js +8 -0
  25. package/lib/esm/view/transactionDetail/createTransaction/createTransactionLocalDataHelper.js +145 -0
  26. package/lib/esm/view/transactionDetail/createTransaction/createTransactionPayload.js +162 -0
  27. package/lib/esm/view/transactionDetail/createTransaction/createTransactionSelector.js +47 -0
  28. package/lib/esm/view/transactionDetail/createTransaction/createTransactionState.js +11 -0
  29. package/lib/esm/view/transactionDetail/createTransaction/epics/createTransactionEpic.js +80 -0
  30. package/lib/esm/view/transactionDetail/createTransaction/epics/fetchVendorRecommendationsForCreateTransactionEpic.js +53 -0
  31. package/lib/esm/view/transactionDetail/createTransaction/epics/initializeCreateTransactionLocalDataEpic.js +14 -0
  32. package/lib/esm/view/transactionDetail/transactionDetailReducer.js +176 -1
  33. package/lib/index.d.ts +6 -2
  34. package/lib/index.js +57 -37
  35. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -1
  36. package/lib/view/invoicing/createInvoice/epics/fetchCreateInvoiceFormPageEpic.js +18 -4
  37. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/editInvoicingSubscriptionDetailViewPayload.d.ts +1 -1
  38. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/editInvoicingSubscriptionDetailViewPayload.js +7 -4
  39. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/editInvoicingSubscriptionDetailViewSelector.d.ts +2 -0
  40. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/editInvoicingSubscriptionDetailViewSelector.js +2 -0
  41. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/fetchInvoicingSubscriptionDetailPageEpic.js +6 -3
  42. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/fetchInvoicingSubscriptionFormPageEpic.js +1 -0
  43. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/invoicingSubscriptionFormConfig.d.ts +2 -0
  44. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/invoicingSubscriptionFormConfig.js +4 -1
  45. package/lib/view/invoicing/editInvoicingSubscriptionDetailView/saveInvoicingSubscriptionEpic.js +5 -1
  46. package/lib/view/invoicing/invoicingCatalogListView/epics/fetchInvoicingCatalogPlanListEpic.js +14 -3
  47. package/lib/view/invoicing/invoicingCatalogListView/epics/fetchInvoicingCatalogProductListEpic.js +14 -3
  48. package/lib/view/invoicing/invoicingCatalogListView/invoicingCatalogListViewReducer.d.ts +6 -0
  49. package/lib/view/invoicing/invoicingCatalogListView/invoicingCatalogListViewReducer.js +2 -0
  50. package/lib/view/invoicing/invoicingListTabCache.d.ts +11 -1
  51. package/lib/view/invoicing/invoicingListTabCache.js +10 -1
  52. package/lib/view/transactionDetail/createTransaction/createTransactionLocalDataHelper.d.ts +52 -0
  53. package/lib/view/transactionDetail/createTransaction/createTransactionLocalDataHelper.js +160 -0
  54. package/lib/view/transactionDetail/createTransaction/createTransactionPayload.d.ts +95 -0
  55. package/lib/view/transactionDetail/createTransaction/createTransactionPayload.js +167 -0
  56. package/lib/view/transactionDetail/createTransaction/createTransactionSelector.d.ts +44 -0
  57. package/lib/view/transactionDetail/createTransaction/createTransactionSelector.js +53 -0
  58. package/lib/view/transactionDetail/createTransaction/createTransactionState.d.ts +82 -0
  59. package/lib/view/transactionDetail/createTransaction/createTransactionState.js +14 -0
  60. package/lib/view/transactionDetail/createTransaction/epics/createTransactionEpic.d.ts +9 -0
  61. package/lib/view/transactionDetail/createTransaction/epics/createTransactionEpic.js +84 -0
  62. package/lib/view/transactionDetail/createTransaction/epics/fetchVendorRecommendationsForCreateTransactionEpic.d.ts +20 -0
  63. package/lib/view/transactionDetail/createTransaction/epics/fetchVendorRecommendationsForCreateTransactionEpic.js +57 -0
  64. package/lib/view/transactionDetail/createTransaction/epics/initializeCreateTransactionLocalDataEpic.d.ts +12 -0
  65. package/lib/view/transactionDetail/createTransaction/epics/initializeCreateTransactionLocalDataEpic.js +18 -0
  66. package/lib/view/transactionDetail/transactionDetailReducer.d.ts +37 -1
  67. package/lib/view/transactionDetail/transactionDetailReducer.js +178 -2
  68. package/lib/view/transactionDetail/transactionDetailState.d.ts +12 -0
  69. package/package.json +1 -1
@@ -23,19 +23,30 @@ const buildProductQuery = (filters, cursor, sort) => {
23
23
  return params;
24
24
  };
25
25
  export const fetchInvoicingCatalogProductListEpic = (actions$, _state$, zeniAPI) => actions$.pipe(filter(fetchInvoicingCatalogProductList.match), switchMap((action) => {
26
- const { filters, cursor, keepExistingListItems, sort } = action.payload;
26
+ const { filters, cursor, fetchAll, keepExistingListItems, sort } = action.payload;
27
27
  const apiUrl = withQuery(`${zeniAPI.apiEndPoints.invoicingMicroServiceBaseUrl}/1.0/catalog/plans`, buildProductQuery(filters, cursor, sort));
28
28
  return zeniAPI.getJSON(apiUrl).pipe(switchMap((response) => {
29
29
  if (isSuccessResponse(response)) {
30
30
  const items = response.data?.items ?? [];
31
- return [
31
+ const nextCursor = response.data?.next_cursor ?? null;
32
+ const pageActions = [
32
33
  updateInvoicingCatalogItems(items, 'merge'),
33
34
  updateInvoicingCatalogProductList({
34
35
  ids: items.map((item) => item.id),
35
- nextCursor: response.data?.next_cursor ?? null,
36
+ nextCursor,
36
37
  keepExistingListItems,
37
38
  }),
38
39
  ];
40
+ if (fetchAll && nextCursor != null && nextCursor !== cursor) {
41
+ pageActions.push(fetchInvoicingCatalogProductList({
42
+ cursor: nextCursor,
43
+ fetchAll,
44
+ filters,
45
+ keepExistingListItems: true,
46
+ sort,
47
+ }));
48
+ }
49
+ return pageActions;
39
50
  }
40
51
  return of(updateInvoicingCatalogProductListFailure(response.status));
41
52
  }), catchError((error) => of(updateInvoicingCatalogProductListFailure(createZeniAPIStatus('Unexpected Error', 'Fetch catalog product list REST API call errored out ' +
@@ -36,6 +36,7 @@ const invoicingCatalogListView = createSlice({
36
36
  payload: {
37
37
  filters: payload.filters ?? {},
38
38
  cursor: payload.cursor,
39
+ fetchAll: payload.fetchAll ?? false,
39
40
  keepExistingListItems: payload.keepExistingListItems ?? false,
40
41
  sort: payload.sort,
41
42
  },
@@ -70,6 +71,7 @@ const invoicingCatalogListView = createSlice({
70
71
  payload: {
71
72
  filters: payload.filters ?? {},
72
73
  cursor: payload.cursor,
74
+ fetchAll: payload.fetchAll ?? false,
73
75
  keepExistingListItems: payload.keepExistingListItems ?? false,
74
76
  sort: payload.sort,
75
77
  },
@@ -33,6 +33,14 @@ export const isSameInvoicingListQuery = (a, b) => {
33
33
  a.sort?.field === b.sort?.field &&
34
34
  a.sort?.dir === b.sort?.dir);
35
35
  };
36
+ /**
37
+ * For a picker that searches client-side: reuse only a complete list fetched
38
+ * with the picker's own query, else load every page of it.
39
+ */
40
+ export const shouldFetchFullInvoicingList = (list, pickerFilters, cacheOverride) => cacheOverride ||
41
+ list.fetchState !== 'Completed' ||
42
+ list.nextCursor != null ||
43
+ !isSameInvoicingListQuery({ filters: list.filters, sort: list.sort }, { filters: pickerFilters });
36
44
  /**
37
45
  * Fetch a tab that is empty or failed; top up one that holds less than a page
38
46
  * while the server says there is more; leave a full or complete one cached.
@@ -0,0 +1,145 @@
1
+ import { dateNow } from '../../../zeniDayJS';
2
+ import { ALL_CREATABLE_TRANSACTION_TYPES, } from './createTransactionState';
3
+ /**
4
+ * Monotonic counter for line row keys. These never leave the client -- the payload builder
5
+ * drops them -- so a counter is enough, and it keeps reducer tests deterministic in a way
6
+ * randomUUID would not.
7
+ */
8
+ let lineIdCounter = 0;
9
+ export const nextCreateTransactionLineId = () => `create-transaction-line-${lineIdCounter++}`;
10
+ /** Test-only: makes line ids predictable from the start of each case. */
11
+ export const resetCreateTransactionLineIdCounter = () => {
12
+ lineIdCounter = 0;
13
+ };
14
+ export const createEmptyCreateTransactionLine = (postingType) => ({
15
+ id: nextCreateTransactionLineId(),
16
+ postingType,
17
+ });
18
+ /**
19
+ * The lines a freshly-opened form starts with. A journal entry is invalid with fewer than one
20
+ * debit and one credit, so it opens with both rather than making the user add the second row.
21
+ * Transfer has no lines at all.
22
+ */
23
+ export const getDefaultCreateTransactionLines = (transactionType) => {
24
+ if (transactionType === 'transfer') {
25
+ return [];
26
+ }
27
+ if (transactionType === 'journal_entry') {
28
+ return [
29
+ createEmptyCreateTransactionLine('debit'),
30
+ createEmptyCreateTransactionLine('credit'),
31
+ ];
32
+ }
33
+ return [createEmptyCreateTransactionLine()];
34
+ };
35
+ /**
36
+ * A blank working copy for one type. Note this does NOT seed the date -- the reducer's initial
37
+ * state has to stay a pure constant so `clearAll` restores something stable. The date is seeded
38
+ * by initializeCreateTransactionLocalDataEpic, which runs when the form opens.
39
+ */
40
+ export const getEmptyCreateTransactionLocalData = (transactionType) => ({
41
+ lines: [],
42
+ transactionType,
43
+ });
44
+ export const getInitialCreateTransactionLocalDataByType = () => ALL_CREATABLE_TRANSACTION_TYPES.reduce((acc, transactionType) => {
45
+ acc[transactionType] =
46
+ getEmptyCreateTransactionLocalData(transactionType);
47
+ return acc;
48
+ }, {});
49
+ /**
50
+ * The payment_type the backend insists on for some types: a check needs `check`, and a
51
+ * credit_card_credit (sent as expense + is_credit) needs a card type -- qbo_purchase.py raises
52
+ * without them.
53
+ */
54
+ const SEEDED_PAYMENT_TYPE = {
55
+ check: 'check',
56
+ credit_card_credit: 'credit_card',
57
+ };
58
+ /**
59
+ * What the form opens with: a blank copy plus today's date, the default line set, and the
60
+ * payment_type the backend insists on for the type.
61
+ */
62
+ export const getSeededCreateTransactionLocalData = (transactionType) => ({
63
+ ...getEmptyCreateTransactionLocalData(transactionType),
64
+ lines: getDefaultCreateTransactionLines(transactionType),
65
+ paymentType: SEEDED_PAYMENT_TYPE[transactionType],
66
+ transactionDate: dateNow(),
67
+ });
68
+ /**
69
+ * Merges a partial edit into the working copy. Lines are replaced wholesale when present --
70
+ * a partial line array would silently truncate the form.
71
+ */
72
+ export const mergeCreateTransactionLocalData = (current, update) => ({
73
+ ...current,
74
+ ...update,
75
+ lines: update.lines ?? current.lines,
76
+ // The type is keyed by the slice, never edited through a merge.
77
+ transactionType: current.transactionType,
78
+ });
79
+ export const updateCreateTransactionLine = (lines, lineId, update) => lines.map((line) => line.id === lineId ? { ...line, ...update, id: line.id } : line);
80
+ /**
81
+ * Recommendation -> RecommendationWithCOT. Chain-of-thought and recommendation feedback both
82
+ * need an existing transaction, so cot/reasoning are empty here by design; the dropdown only
83
+ * needs the entities to build its "Recommended" group.
84
+ */
85
+ export const toRecommendationsWithCOT = (recommendations) => recommendations.map((recommendation) => ({
86
+ account: recommendation.account != null
87
+ ? { ...recommendation.account, cot: [], reasoning: '' }
88
+ : undefined,
89
+ class: recommendation.class != null
90
+ ? { ...recommendation.class, cot: [], reasoning: '' }
91
+ : undefined,
92
+ vendor: recommendation.vendor != null
93
+ ? { ...recommendation.vendor, cot: [], reasoning: '' }
94
+ : undefined,
95
+ }));
96
+ /**
97
+ * Applies a vendor's recommendations to one line: always refreshes the dropdown's "Recommended"
98
+ * group, but only prefills account/class when the field is still empty. Callers switching
99
+ * vendors clear the previous prefill first, so "empty" includes what the last vendor filled. Anything the user
100
+ * picked wins -- this follows the transaction-categorization helper, which prefills, rather
101
+ * than the detail-page helper, which only suggests.
102
+ */
103
+ export const applyRecommendationsToCreateTransactionLine = (line, recommendations, isAccountingClassesEnabled) => {
104
+ const top = recommendations[0];
105
+ const updated = {
106
+ ...line,
107
+ recommendationsWithCOT: toRecommendationsWithCOT(recommendations),
108
+ };
109
+ if (line.accountQboId == null && top?.account?.qboId != null) {
110
+ updated.accountQboId = top.account.qboId;
111
+ updated.accountName = top.account.accountName;
112
+ updated.isAccountPreFilled = true;
113
+ }
114
+ if (isAccountingClassesEnabled &&
115
+ line.classId == null &&
116
+ top?.class?.classId != null) {
117
+ updated.classId = top.class.classId;
118
+ updated.className = top.class.className;
119
+ updated.isClassPreFilled = true;
120
+ }
121
+ return updated;
122
+ };
123
+ /**
124
+ * Undoes a prefill when the vendor is cleared. Only the fields the prefill wrote are removed --
125
+ * the per-field flags are what make the user's own choices distinguishable from ours, which is
126
+ * why they are not a single line-level boolean: a hand-picked account alongside a prefilled
127
+ * class is an ordinary state, and clearing must not take the account with it.
128
+ */
129
+ export const clearRecommendationsFromCreateTransactionLine = (line) => {
130
+ const cleared = {
131
+ ...line,
132
+ recommendationsWithCOT: undefined,
133
+ };
134
+ if (line.isAccountPreFilled === true) {
135
+ cleared.accountQboId = undefined;
136
+ cleared.accountName = undefined;
137
+ cleared.isAccountPreFilled = undefined;
138
+ }
139
+ if (line.isClassPreFilled === true) {
140
+ cleared.classId = undefined;
141
+ cleared.className = undefined;
142
+ cleared.isClassPreFilled = undefined;
143
+ }
144
+ return cleared;
145
+ };
@@ -0,0 +1,162 @@
1
+ import { DEFAULT_DATE_FORMAT } from '../../../commonStateTypes/timePeriod';
2
+ import { getAccountBaseForTransferAccounts } from '../../../entity/account/accountSelector';
3
+ import { getClassById } from '../../../entity/class/classSelector';
4
+ import { toProjectBasePayload, } from '../../../entity/project/projectPayload';
5
+ import { getProjectById } from '../../../entity/project/projectSelector';
6
+ import { getVendorByVendorId } from '../../../entity/vendor/vendorSelector';
7
+ const toRemitToAddressPayload = (address) => {
8
+ if (address == null) {
9
+ return undefined;
10
+ }
11
+ return {
12
+ line1: address.line1,
13
+ city: address.city,
14
+ state: address.state,
15
+ postal_code: address.postalCode,
16
+ country: address.country,
17
+ };
18
+ };
19
+ const toLinePayload = (state, line, transactionType) => {
20
+ const lineDetail = {};
21
+ if (line.accountQboId != null) {
22
+ lineDetail.account = {
23
+ qbo_id: line.accountQboId,
24
+ account_name: line.accountName,
25
+ };
26
+ }
27
+ // An empty object is what the confirmed payloads send when no class is chosen; sending the
28
+ // key with a qbo_id only once one is picked.
29
+ const classQboId = toQboClassId(state, line.classId);
30
+ lineDetail.class = classQboId != null ? { qbo_id: classQboId } : {};
31
+ if (line.projectId != null) {
32
+ lineDetail.project = toProjectBasePayload(getProjectById(state.projectState, line.projectId) ?? {
33
+ projectId: line.projectId,
34
+ projectName: '',
35
+ });
36
+ }
37
+ if (transactionType === 'journal_entry') {
38
+ lineDetail.posting_type = line.postingType;
39
+ if (line.vendorQboId != null) {
40
+ lineDetail.vendor = { qbo_id: line.vendorQboId };
41
+ }
42
+ }
43
+ return {
44
+ // The backend rejects a bool here, so this is always coerced to a number.
45
+ amount: line.amount?.amount ?? 0,
46
+ line_description: line.lineDescription,
47
+ line_detail_type: transactionType === 'journal_entry'
48
+ ? 'journal_entry_line_detail'
49
+ : 'account_based_expense_line_detail',
50
+ line_detail: lineDetail,
51
+ };
52
+ };
53
+ /**
54
+ * Thrown when a picked id has no QBO id to send. Sending the Zeni id instead would reach QBO as
55
+ * an unknown reference and come back as an opaque error, so the create is stopped here and the
56
+ * epic shows this message instead.
57
+ */
58
+ export class UnresolvedCreateTransactionIdError extends Error {
59
+ }
60
+ /**
61
+ * Resolves a transfer account (the Zeni account id from the transfer pools) to its QBO id. The
62
+ * header and line account dropdowns already hold the QBO id, so they are sent as-is.
63
+ */
64
+ const toQboTransferAccountId = (state, accountId) => {
65
+ if (accountId == null) {
66
+ return undefined;
67
+ }
68
+ const qboId = getAccountBaseForTransferAccounts(state.accountState, accountId)?.qboId;
69
+ if (qboId == null || qboId === '') {
70
+ throw new UnresolvedCreateTransactionIdError('The selected transfer account could not be found in QuickBooks.');
71
+ }
72
+ return qboId;
73
+ };
74
+ /** Resolves a Zeni class id (`class_<uuid>`) to the QBO id `line_detail.class.qbo_id` expects. */
75
+ const toQboClassId = (state, classId) => {
76
+ if (classId == null) {
77
+ return undefined;
78
+ }
79
+ const qboId = getClassById(state.classState, {
80
+ classId,
81
+ reportId: 'class_list',
82
+ })?.qboId;
83
+ if (qboId == null || qboId === '') {
84
+ throw new UnresolvedCreateTransactionIdError('The selected class could not be found in QuickBooks.');
85
+ }
86
+ return qboId;
87
+ };
88
+ /**
89
+ * Resolves a Zeni vendor id to its QBO id -- `vendor_id` on the wire is a QBO id. A vendor not
90
+ * yet synced to QBO carries `qboId === name`, which QBO would reject, so it is refused here.
91
+ */
92
+ const toQboVendorId = (state, vendorId) => {
93
+ if (vendorId == null) {
94
+ return undefined;
95
+ }
96
+ const vendor = getVendorByVendorId(state.vendorState, vendorId);
97
+ if (vendor == null || vendor.qboId === '' || vendor.qboId === vendor.name) {
98
+ throw new UnresolvedCreateTransactionIdError('The selected vendor is not synced to QuickBooks yet.');
99
+ }
100
+ return vendor.qboId;
101
+ };
102
+ /**
103
+ * Builds the request body for one transaction type. One branch per type rather than a shared
104
+ * body with optional keys, because the types genuinely diverge -- transfer carries no lines at
105
+ * all, and journal_entry carries no header account.
106
+ *
107
+ * Throws UnresolvedCreateTransactionIdError when a picked vendor, class or transfer account has
108
+ * no QBO id.
109
+ */
110
+ export const prepareCreateTransactionPayload = (state, localData) => {
111
+ const { transactionType } = localData;
112
+ const base = {
113
+ transaction_type: transactionType,
114
+ transaction_date: localData.transactionDate?.format(DEFAULT_DATE_FORMAT) ?? '',
115
+ transaction_memo: localData.transactionMemo,
116
+ };
117
+ if (transactionType === 'transfer') {
118
+ return {
119
+ ...base,
120
+ from_account_id: toQboTransferAccountId(state, localData.fromAccountId),
121
+ to_account_id: toQboTransferAccountId(state, localData.toAccountId),
122
+ total_amount: localData.totalAmount?.amount ?? 0,
123
+ };
124
+ }
125
+ const lines = localData.lines.map((line) => toLinePayload(state, line, transactionType));
126
+ if (transactionType === 'journal_entry') {
127
+ return {
128
+ ...base,
129
+ document_id: localData.documentId,
130
+ lines,
131
+ };
132
+ }
133
+ const purchaseBase = {
134
+ ...base,
135
+ payment_type: localData.paymentType,
136
+ qbo_account_id: localData.qboAccountId,
137
+ vendor_id: toQboVendorId(state, localData.vendorId),
138
+ lines,
139
+ };
140
+ if (transactionType === 'check') {
141
+ return {
142
+ ...purchaseBase,
143
+ document_number: localData.documentNumber,
144
+ print_status: localData.printStatus,
145
+ remit_to_address: toRemitToAddressPayload(localData.remitToAddress),
146
+ };
147
+ }
148
+ if (transactionType === 'credit_card_credit') {
149
+ // credit_card_credit is not in the backend's SUPPORTED_TRANSACTION_WRITE_TYPES. QBO models
150
+ // it as a Purchase with Credit: true and qbo_purchase.py already honours is_credit for
151
+ // card payment types, so this sends `expense` + is_credit rather than a type the validator
152
+ // rejects outright. Confirm with backend before enabling the menu item. The seed sets
153
+ // payment_type to credit_card, since qbo_purchase.py raises on is_credit without a card type.
154
+ return {
155
+ ...purchaseBase,
156
+ transaction_type: 'expense',
157
+ is_credit: true,
158
+ document_number: localData.documentNumber,
159
+ };
160
+ }
161
+ return purchaseBase;
162
+ };
@@ -0,0 +1,47 @@
1
+ import { createSelector } from '@reduxjs/toolkit';
2
+ import { getNestedAccountListHierarchy } from '../../accountList/accountListSelector';
3
+ import { getNestedClassListHierarchy } from '../../classList/classListSelector';
4
+ import { getResolvedTransferAccounts } from '../../createTransferEntry/createTransferEntrySelector';
5
+ import { getRecommendationsForEntity } from '../../recommendation/recommendationSelector';
6
+ export const getCreateTransactionLocalData = (state, transactionType) => state.transactionDetailState.createTransactionsState.newTransactionState[transactionType];
7
+ export const getCreateTransactionStatus = (state) => state.transactionDetailState.createTransactionsState.createStatus;
8
+ /**
9
+ * The vendor recommendations backing the category/class dropdowns on the create page.
10
+ *
11
+ * No new state field is needed for this: getRecommendationsForEntity already returns
12
+ * fetchState alongside recommendations, so composing it here is enough for the page to show a
13
+ * line skeleton and hold Save while a fetch is in flight.
14
+ */
15
+ export const getCreateTransactionVendorRecommendations = (state, vendorQboId) => {
16
+ if (vendorQboId == null || vendorQboId === '') {
17
+ return { fetchState: 'Not-Started' };
18
+ }
19
+ const view = getRecommendationsForEntity(state, vendorQboId, 'vendor');
20
+ return {
21
+ fetchState: view.fetchState,
22
+ recommendations: view.recommendations,
23
+ };
24
+ };
25
+ /**
26
+ * Memoized: app-ui reads this straight from useSelector, and the vendor list and hierarchies are
27
+ * rebuilt on every call, so an unmemoized version re-renders the page on every store action.
28
+ */
29
+ export const getCreateTransactionView = createSelector([
30
+ (state) => state.transactionDetailState.createTransactionsState,
31
+ (state) => state.vendorState.vendorByID,
32
+ (state) => state.accountListState,
33
+ (state) => state.classListState,
34
+ (state) => getResolvedTransferAccounts(state).transferAccountsList,
35
+ (_state, transactionType) => transactionType,
36
+ ], (createTransactionsState, vendorByID, accountListState, classListState, transferAccountsList, transactionType) => ({
37
+ transactionType,
38
+ localData: createTransactionsState.newTransactionState[transactionType],
39
+ createStatus: createTransactionsState.createStatus,
40
+ createdTransactionId: createTransactionsState.createdTransactionId,
41
+ vendorList: Object.values(vendorByID),
42
+ accountListNestedAccountHierarchy: getNestedAccountListHierarchy(accountListState, 'accountList'),
43
+ classListNestedAccountHierarchy: getNestedClassListHierarchy(classListState),
44
+ transferAccountsList: transactionType === 'transfer' ? transferAccountsList : [],
45
+ fetchState: createTransactionsState.createStatus.fetchState,
46
+ error: createTransactionsState.createStatus.error,
47
+ }));
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The transaction types the Create Transaction flow can originate. A narrow subset of
3
+ * TransactionType -- everything else is read-only and arrives via sync.
4
+ */
5
+ export const ALL_CREATABLE_TRANSACTION_TYPES = [
6
+ 'expense',
7
+ 'check',
8
+ 'credit_card_credit',
9
+ 'transfer',
10
+ 'journal_entry',
11
+ ];
@@ -0,0 +1,80 @@
1
+ import { defer, from } from 'rxjs';
2
+ import { catchError, exhaustMap, filter, mergeMap } from 'rxjs/operators';
3
+ import { openSnackbar } from '../../../../entity/snackbar/snackbarReducer';
4
+ import { toTransactionID } from '../../../../entity/transaction/payloadTypes/transactionIDPayload';
5
+ import { updateTransaction } from '../../../../entity/transaction/transactionReducer';
6
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
7
+ import { createTransaction, createTransactionSuccessOrFailure, initializeTransactionDetailLocalData, } from '../../transactionDetailReducer';
8
+ import { getTransactionDetailKey } from '../../transactionDetailState';
9
+ import { UnresolvedCreateTransactionIdError, prepareCreateTransactionPayload, } from '../createTransactionPayload';
10
+ export const createTransactionEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(createTransaction.match),
11
+ // exhaustMap, not mergeMap: a second submit while one is in flight is dropped here rather
12
+ // than relying only on the disabled Save button, so it cannot create a duplicate in QBO.
13
+ exhaustMap((action) => {
14
+ const { transactionType } = action.payload;
15
+ const state = state$.value;
16
+ const localData = state.transactionDetailState.createTransactionsState
17
+ .newTransactionState[transactionType];
18
+ // Deferred so a payload that cannot be built (an id with no QBO id) lands in catchError
19
+ // below as a failure, instead of throwing out of the epic.
20
+ return defer(() => zeniAPI.postAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/transactions/manage`, prepareCreateTransactionPayload(state, localData))).pipe(mergeMap((response) => {
21
+ const created = isSuccessResponse(response)
22
+ ? response.data?.transactions[0]
23
+ : undefined;
24
+ if (created == null) {
25
+ const status = isSuccessResponse(response)
26
+ ? createZeniAPIStatus('Unexpected Error', 'Transaction was created but returned no details.')
27
+ : response.status;
28
+ return from([
29
+ createTransactionSuccessOrFailure('Error', undefined, status),
30
+ openSnackbar({
31
+ messageSection: 'create_transaction',
32
+ messageText: 'failed',
33
+ type: 'error',
34
+ // This variable is how the server's own message reaches the user. Per-type
35
+ // required fields live in the QBO entity classes, so a rejection comes back as a
36
+ // QBO error with no field name -- the message text is the only useful content.
37
+ variables: [
38
+ { variableName: '_api-error_', variableValue: status.message },
39
+ ],
40
+ }),
41
+ ]);
42
+ }
43
+ const newTransactionId = toTransactionID(created);
44
+ // The write is QBO-only: transaction_write_handler.py touches no local storage, and
45
+ // Zeni's mirror is populated by the delta sync that runs afterwards. Refetching here
46
+ // would come back without the new row, so the 200 body is inserted optimistically
47
+ // instead -- the same approach createTransferEntryEpic takes.
48
+ return from([
49
+ updateTransaction(getTransactionDetailKey(newTransactionId), created),
50
+ initializeTransactionDetailLocalData({
51
+ transactionId: newTransactionId,
52
+ vendorId: created.vendor_id ?? undefined,
53
+ }),
54
+ // No reset here: it would clear createdTransactionId in the same tick, before the
55
+ // screen renders it to upload pending attachments and navigate. The screen resets
56
+ // the working copy on unmount instead.
57
+ createTransactionSuccessOrFailure('Completed', newTransactionId),
58
+ openSnackbar({
59
+ messageSection: 'create_transaction',
60
+ messageText: 'success',
61
+ type: 'success',
62
+ }),
63
+ ]);
64
+ }), catchError((error) => {
65
+ const message = error instanceof UnresolvedCreateTransactionIdError
66
+ ? error.message
67
+ : JSON.stringify(error);
68
+ return from([
69
+ createTransactionSuccessOrFailure('Error', undefined, createZeniAPIStatus('Unexpected Error', `Create Transaction REST API call errored out ${message}`)),
70
+ openSnackbar({
71
+ messageSection: 'create_transaction',
72
+ messageText: 'failed',
73
+ type: 'error',
74
+ variables: [
75
+ { variableName: '_api-error_', variableValue: message },
76
+ ],
77
+ }),
78
+ ]);
79
+ }));
80
+ }));
@@ -0,0 +1,53 @@
1
+ import { concat, from, of } from 'rxjs';
2
+ import { filter, mergeMap, switchMap, take } from 'rxjs/operators';
3
+ import { getIsAccountingClassesEnabled } from '../../../../entity/tenant/tenantSelector';
4
+ import { fetchRecommendationByEntityId, fetchRecommendationByEntityName, indicateReadyToInitializeRecommendation, } from '../../../recommendation/recommendationReducer';
5
+ import { getRecommendationsForEntity } from '../../../recommendation/recommendationSelector';
6
+ import { clearRecommendationsForCreateTransactionLines, fetchVendorRecommendationsForCreateTransaction, setRecommendationsForCreateTransactionLines, } from '../../transactionDetailReducer';
7
+ /**
8
+ * The entity-level recommendation fetch, keyed by whatever identifier the endpoint can resolve.
9
+ *
10
+ * A vendor that has not synced to QBO carries `qboId === name`; the id endpoint has nothing to
11
+ * look up in that case, so the by-name variant is used instead.
12
+ */
13
+ const toEntityIdOrName = (entity) => entity.qboId && entity.qboId !== entity.name ? entity.qboId : entity.name;
14
+ const isUnsyncedVendor = (entity) => !entity.qboId || entity.qboId === entity.name;
15
+ /**
16
+ * On vendor select, populates the category/class dropdowns from that vendor's recommendations.
17
+ *
18
+ * Deliberately NOT the detail page's fetchEntityRecommendationsForLineUpdate: that one sends
19
+ * transaction_id / line_ids and writes into transactionDetailById[key], which no-ops when the
20
+ * entry does not exist. A transaction being created has neither.
21
+ *
22
+ * Two differences from the reimbursement epic this is modelled on:
23
+ * 1. the wait filters on the matching entityIdOrName before take(1), so an unrelated
24
+ * recommendation landing first cannot satisfy this request, and
25
+ * 2. switchMap, so changing the vendor again cancels the earlier wait rather than letting a
26
+ * stale result overwrite the newer vendor's prefill.
27
+ */
28
+ export const fetchVendorRecommendationsForCreateTransactionEpic = (actions$, state$) => actions$.pipe(filter(fetchVendorRecommendationsForCreateTransaction.match), switchMap((action) => {
29
+ const { transactionType, entity, lineIds } = action.payload;
30
+ if (entity == null) {
31
+ return of(clearRecommendationsForCreateTransactionLines(transactionType, lineIds));
32
+ }
33
+ const entityIdOrName = toEntityIdOrName(entity);
34
+ const state = state$.value;
35
+ const isAccountingClassesEnabled = getIsAccountingClassesEnabled(state);
36
+ const cached = getRecommendationsForEntity(state, entityIdOrName, 'vendor');
37
+ // Cache hit: apply straight away, no request and no wait.
38
+ if (cached.fetchState === 'Completed') {
39
+ return of(setRecommendationsForCreateTransactionLines(transactionType, lineIds, cached.recommendations ?? [], isAccountingClassesEnabled));
40
+ }
41
+ const waitThenApply = actions$.pipe(filter(indicateReadyToInitializeRecommendation.match), filter((ready) => ready.payload.entityType === 'vendor' &&
42
+ ready.payload.entityIdOrName === entityIdOrName), take(1), // don't listen forever! IMPORTANT!
43
+ mergeMap(() => from([
44
+ setRecommendationsForCreateTransactionLines(transactionType, lineIds, getRecommendationsForEntity(state$.value, entityIdOrName, 'vendor').recommendations ?? [], getIsAccountingClassesEnabled(state$.value)),
45
+ ])));
46
+ // A fetch already in flight needs no second request, only the wait.
47
+ if (cached.fetchState === 'In-Progress') {
48
+ return waitThenApply;
49
+ }
50
+ return concat(of((isUnsyncedVendor(entity)
51
+ ? fetchRecommendationByEntityName(entityIdOrName, 'vendor')
52
+ : fetchRecommendationByEntityId(entityIdOrName, 'vendor'))), waitThenApply);
53
+ }));
@@ -0,0 +1,14 @@
1
+ import { filter, map } from 'rxjs/operators';
2
+ import { initializeCreateTransactionLocalData, updateCreateTransactionLocalData, } from '../../transactionDetailReducer';
3
+ import { getSeededCreateTransactionLocalData } from '../createTransactionLocalDataHelper';
4
+ /**
5
+ * Seeds the working copy when the Create form opens: today's date, the default line set for the
6
+ * type, and a check's mandatory payment_type.
7
+ *
8
+ * Mirrors the `else` branch of initializeScheduleDetailLocalDataEpic -- a create has no
9
+ * existing entity to read from, so there is nothing to merge, only defaults to apply.
10
+ */
11
+ export const initializeCreateTransactionLocalDataEpic = (actions$) => actions$.pipe(filter(initializeCreateTransactionLocalData.match), map((action) => {
12
+ const { transactionType } = action.payload;
13
+ return updateCreateTransactionLocalData(transactionType, getSeededCreateTransactionLocalData(transactionType));
14
+ }));