@zeniai/client-epic-state 5.2.91 → 5.2.93-betaNB1

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 (52) hide show
  1. package/lib/entity/reconciliationReport/reconciliationReportState.d.ts +3 -2
  2. package/lib/entity/reconciliationReport/reconciliationReportState.js +4 -1
  3. package/lib/entity/snackbar/snackbarTypes.d.ts +1 -1
  4. package/lib/entity/snackbar/snackbarTypes.js +1 -0
  5. package/lib/entity/transaction/stateTypes/paymentType.d.ts +2 -2
  6. package/lib/entity/transaction/stateTypes/paymentType.js +9 -1
  7. package/lib/entity/transaction/stateTypes/printStatus.d.ts +4 -0
  8. package/lib/entity/transaction/stateTypes/printStatus.js +11 -0
  9. package/lib/epic.d.ts +5 -1
  10. package/lib/epic.js +8 -0
  11. package/lib/esm/entity/reconciliationReport/reconciliationReportState.js +4 -1
  12. package/lib/esm/entity/snackbar/snackbarTypes.js +1 -0
  13. package/lib/esm/entity/transaction/stateTypes/paymentType.js +9 -1
  14. package/lib/esm/entity/transaction/stateTypes/printStatus.js +7 -0
  15. package/lib/esm/epic.js +8 -0
  16. package/lib/esm/index.js +4 -2
  17. package/lib/esm/view/invoicing/invoicingOverview/invoicingOverviewPayload.js +3 -0
  18. package/lib/esm/view/transactionDetail/createTransaction/createTransactionLocalDataHelper.js +157 -0
  19. package/lib/esm/view/transactionDetail/createTransaction/createTransactionPayload.js +164 -0
  20. package/lib/esm/view/transactionDetail/createTransaction/createTransactionSelector.js +47 -0
  21. package/lib/esm/view/transactionDetail/createTransaction/createTransactionState.js +11 -0
  22. package/lib/esm/view/transactionDetail/createTransaction/epics/createTransactionAttachmentUploadFailureEpic.js +19 -0
  23. package/lib/esm/view/transactionDetail/createTransaction/epics/createTransactionEpic.js +81 -0
  24. package/lib/esm/view/transactionDetail/createTransaction/epics/fetchVendorRecommendationsForCreateTransactionEpic.js +53 -0
  25. package/lib/esm/view/transactionDetail/createTransaction/epics/initializeCreateTransactionLocalDataEpic.js +10 -0
  26. package/lib/esm/view/transactionDetail/transactionDetailReducer.js +196 -1
  27. package/lib/index.d.ts +6 -2
  28. package/lib/index.js +56 -37
  29. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -1
  30. package/lib/view/invoicing/invoicingOverview/invoicingOverviewPayload.d.ts +7 -0
  31. package/lib/view/invoicing/invoicingOverview/invoicingOverviewPayload.js +3 -0
  32. package/lib/view/invoicing/invoicingOverview/invoicingOverviewState.d.ts +4 -0
  33. package/lib/view/transactionDetail/createTransaction/createTransactionLocalDataHelper.d.ts +56 -0
  34. package/lib/view/transactionDetail/createTransaction/createTransactionLocalDataHelper.js +172 -0
  35. package/lib/view/transactionDetail/createTransaction/createTransactionPayload.d.ts +95 -0
  36. package/lib/view/transactionDetail/createTransaction/createTransactionPayload.js +169 -0
  37. package/lib/view/transactionDetail/createTransaction/createTransactionSelector.d.ts +44 -0
  38. package/lib/view/transactionDetail/createTransaction/createTransactionSelector.js +53 -0
  39. package/lib/view/transactionDetail/createTransaction/createTransactionState.d.ts +82 -0
  40. package/lib/view/transactionDetail/createTransaction/createTransactionState.js +14 -0
  41. package/lib/view/transactionDetail/createTransaction/epics/createTransactionAttachmentUploadFailureEpic.d.ts +10 -0
  42. package/lib/view/transactionDetail/createTransaction/epics/createTransactionAttachmentUploadFailureEpic.js +23 -0
  43. package/lib/view/transactionDetail/createTransaction/epics/createTransactionEpic.d.ts +9 -0
  44. package/lib/view/transactionDetail/createTransaction/epics/createTransactionEpic.js +85 -0
  45. package/lib/view/transactionDetail/createTransaction/epics/fetchVendorRecommendationsForCreateTransactionEpic.d.ts +20 -0
  46. package/lib/view/transactionDetail/createTransaction/epics/fetchVendorRecommendationsForCreateTransactionEpic.js +57 -0
  47. package/lib/view/transactionDetail/createTransaction/epics/initializeCreateTransactionLocalDataEpic.d.ts +12 -0
  48. package/lib/view/transactionDetail/createTransaction/epics/initializeCreateTransactionLocalDataEpic.js +14 -0
  49. package/lib/view/transactionDetail/transactionDetailReducer.d.ts +39 -1
  50. package/lib/view/transactionDetail/transactionDetailReducer.js +198 -2
  51. package/lib/view/transactionDetail/transactionDetailState.d.ts +12 -0
  52. package/package.json +1 -1
@@ -0,0 +1,164 @@
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 { getVendorByQboId, 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
+ const vendorQboId = toQboLineVendorId(state, line.vendorQboId);
40
+ if (vendorQboId != null) {
41
+ lineDetail.vendor = { qbo_id: vendorQboId };
42
+ }
43
+ }
44
+ return {
45
+ // The backend rejects a bool here, so this is always coerced to a number.
46
+ amount: line.amount?.amount ?? 0,
47
+ line_description: line.lineDescription,
48
+ line_detail_type: transactionType === 'journal_entry'
49
+ ? 'journal_entry_line_detail'
50
+ : 'account_based_expense_line_detail',
51
+ line_detail: lineDetail,
52
+ };
53
+ };
54
+ /**
55
+ * Thrown when a picked id has no QBO id to send. Sending the Zeni id instead would reach QBO as
56
+ * an unknown reference and come back as an opaque error, so the create is stopped here and the
57
+ * epic shows this message instead.
58
+ */
59
+ export class UnresolvedCreateTransactionIdError extends Error {
60
+ }
61
+ /**
62
+ * Resolves a transfer account (the Zeni account id from the transfer pools) to its QBO id. The
63
+ * header and line account dropdowns already hold the QBO id, so they are sent as-is.
64
+ */
65
+ const toQboTransferAccountId = (state, accountId) => {
66
+ if (accountId == null) {
67
+ return undefined;
68
+ }
69
+ const qboId = getAccountBaseForTransferAccounts(state.accountState, accountId)?.qboId;
70
+ if (qboId == null || qboId === '') {
71
+ throw new UnresolvedCreateTransactionIdError('The selected transfer account could not be found in QuickBooks.');
72
+ }
73
+ return qboId;
74
+ };
75
+ /** Resolves a Zeni class id (`class_<uuid>`) to the QBO id `line_detail.class.qbo_id` expects. */
76
+ const toQboClassId = (state, classId) => {
77
+ if (classId == null) {
78
+ return undefined;
79
+ }
80
+ const qboId = getClassById(state.classState, {
81
+ classId,
82
+ reportId: 'class_list',
83
+ })?.qboId;
84
+ if (qboId == null || qboId === '') {
85
+ throw new UnresolvedCreateTransactionIdError('The selected class could not be found in QuickBooks.');
86
+ }
87
+ return qboId;
88
+ };
89
+ /** A vendor not yet synced to QBO carries `qboId === name`, which QBO would reject. */
90
+ const toSyncedVendorQboId = (vendor) => {
91
+ if (vendor == null || vendor.qboId === '' || vendor.qboId === vendor.name) {
92
+ throw new UnresolvedCreateTransactionIdError('The selected vendor is not synced to QuickBooks yet.');
93
+ }
94
+ return vendor.qboId;
95
+ };
96
+ /** Resolves a Zeni vendor id to its QBO id -- `vendor_id` on the wire is a QBO id. */
97
+ const toQboVendorId = (state, vendorId) => vendorId == null
98
+ ? undefined
99
+ : toSyncedVendorQboId(getVendorByVendorId(state.vendorState, vendorId));
100
+ /** A journal entry line holds the QBO id already, so it is only checked against the store. */
101
+ const toQboLineVendorId = (state, vendorQboId) => vendorQboId == null
102
+ ? undefined
103
+ : toSyncedVendorQboId(getVendorByQboId(state.vendorState, vendorQboId));
104
+ /**
105
+ * Builds the request body for one transaction type. One branch per type rather than a shared
106
+ * body with optional keys, because the types genuinely diverge -- transfer carries no lines at
107
+ * all, and journal_entry carries no header account.
108
+ *
109
+ * Throws UnresolvedCreateTransactionIdError when a picked vendor (header or journal entry line),
110
+ * class or transfer account has no QBO id.
111
+ */
112
+ export const prepareCreateTransactionPayload = (state, localData) => {
113
+ const { transactionType } = localData;
114
+ const base = {
115
+ transaction_type: transactionType,
116
+ transaction_date: localData.transactionDate?.format(DEFAULT_DATE_FORMAT) ?? '',
117
+ transaction_memo: localData.transactionMemo,
118
+ };
119
+ if (transactionType === 'transfer') {
120
+ return {
121
+ ...base,
122
+ from_account_id: toQboTransferAccountId(state, localData.fromAccountId),
123
+ to_account_id: toQboTransferAccountId(state, localData.toAccountId),
124
+ total_amount: localData.totalAmount?.amount ?? 0,
125
+ };
126
+ }
127
+ const lines = localData.lines.map((line) => toLinePayload(state, line, transactionType));
128
+ if (transactionType === 'journal_entry') {
129
+ return {
130
+ ...base,
131
+ document_id: localData.documentId,
132
+ lines,
133
+ };
134
+ }
135
+ const purchaseBase = {
136
+ ...base,
137
+ payment_type: localData.paymentType,
138
+ qbo_account_id: localData.qboAccountId,
139
+ vendor_id: toQboVendorId(state, localData.vendorId),
140
+ lines,
141
+ };
142
+ if (transactionType === 'check') {
143
+ return {
144
+ ...purchaseBase,
145
+ document_number: localData.documentNumber,
146
+ print_status: localData.printStatus,
147
+ remit_to_address: toRemitToAddressPayload(localData.remitToAddress),
148
+ };
149
+ }
150
+ if (transactionType === 'credit_card_credit') {
151
+ // credit_card_credit is not in the backend's SUPPORTED_TRANSACTION_WRITE_TYPES. QBO models
152
+ // it as a Purchase with Credit: true and qbo_purchase.py already honours is_credit for
153
+ // card payment types, so this sends `expense` + is_credit rather than a type the validator
154
+ // rejects outright. Confirm with backend before enabling the menu item. The seed sets
155
+ // payment_type to credit_card, since qbo_purchase.py raises on is_credit without a card type.
156
+ return {
157
+ ...purchaseBase,
158
+ transaction_type: 'expense',
159
+ is_credit: true,
160
+ document_number: localData.documentNumber,
161
+ };
162
+ }
163
+ return purchaseBase;
164
+ };
@@ -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,19 @@
1
+ import { filter, map } from 'rxjs/operators';
2
+ import { openSnackbar } from '../../../../entity/snackbar/snackbarReducer';
3
+ import { createTransactionAttachmentUploadFailure } from '../../transactionDetailReducer';
4
+ /**
5
+ * Attachments upload from the page after the create succeeds, so a failure is reported back here
6
+ * rather than by createTransactionEpic.
7
+ */
8
+ export const createTransactionAttachmentUploadFailureEpic = (actions$) => actions$.pipe(filter(createTransactionAttachmentUploadFailure.match), filter((action) => action.payload.failedAttachmentFileNames.length > 0), map((action) => openSnackbar({
9
+ messageSection: 'missing_receipts_attachment',
10
+ messageText: 'failed',
11
+ type: 'error',
12
+ showStatusIcon: true,
13
+ variables: [
14
+ {
15
+ variableName: '__message__',
16
+ variableValue: ` - ${action.payload.failedAttachmentFileNames.join(', ')},`,
17
+ },
18
+ ],
19
+ })));
@@ -0,0 +1,81 @@
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
+ // No reset here: it would clear createdTransactionId in the same tick, before the
51
+ // screen renders it to upload pending attachments and navigate. The screen resets
52
+ // the working copy on unmount instead.
53
+ // Before the local-data init: it seeds the detail entry that init writes into.
54
+ createTransactionSuccessOrFailure('Completed', newTransactionId),
55
+ initializeTransactionDetailLocalData({
56
+ transactionId: newTransactionId,
57
+ vendorId: created.vendor_id ?? undefined,
58
+ }),
59
+ openSnackbar({
60
+ messageSection: 'create_transaction',
61
+ messageText: 'success',
62
+ type: 'success',
63
+ }),
64
+ ]);
65
+ }), catchError((error) => {
66
+ const message = error instanceof UnresolvedCreateTransactionIdError
67
+ ? error.message
68
+ : JSON.stringify(error);
69
+ return from([
70
+ createTransactionSuccessOrFailure('Error', undefined, createZeniAPIStatus('Unexpected Error', `Create Transaction REST API call errored out ${message}`)),
71
+ openSnackbar({
72
+ messageSection: 'create_transaction',
73
+ messageText: 'failed',
74
+ type: 'error',
75
+ variables: [
76
+ { variableName: '_api-error_', variableValue: message },
77
+ ],
78
+ }),
79
+ ]);
80
+ }));
81
+ }));
@@ -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,10 @@
1
+ import { filter, map } from 'rxjs/operators';
2
+ import { initializeCreateTransactionLocalData, resetCreateTransactionLocalData, } from '../../transactionDetailReducer';
3
+ /**
4
+ * Seeds the working copy when the Create form opens: today's date, the default line set for the
5
+ * type, and the payment_type the backend insists on.
6
+ *
7
+ * The seed replaces the whole working copy rather than merging into it, so a second initialize
8
+ * for the same type can't leave the previous draft's vendor, memo or account behind.
9
+ */
10
+ export const initializeCreateTransactionLocalDataEpic = (actions$) => actions$.pipe(filter(initializeCreateTransactionLocalData.match), map((action) => resetCreateTransactionLocalData(action.payload.transactionType)));
@@ -2,6 +2,7 @@ import { createSlice } from '@reduxjs/toolkit';
2
2
  import recordGet from 'lodash/get';
3
3
  import { toEntityType, } from '../../entity/genericEntity/entity';
4
4
  import { clearAll } from '../../rootActions';
5
+ import { applyRecommendationsToCreateTransactionLine, clearRecommendationsFromCreateTransactionLine, getInitialCreateTransactionLocalDataByType, getSeededCreateTransactionLocalData, mergeCreateTransactionLocalData, nextCreateTransactionLineId, updateCreateTransactionLine, } from './createTransaction/createTransactionLocalDataHelper';
5
6
  import { removeEntityRecommendationForLineIdInLocalData, setEntityRecommendationForLineIdInLocalData, toSetAllLineItemsLocalDataIsUpdateAllChecked, toSetAllLineItemsToCategoryClass, toSetAllLineItemsToVendor, toUpdateLineItemsOriginalCategoryClass, toUpdateLineItemsToOriginalVendor, } from './transactionDetailLocalDataHelper';
6
7
  import { getTransactionDetailKey, initialSupportedTransactionDetail, } from './transactionDetailState';
7
8
  export const initialState = {
@@ -10,6 +11,10 @@ export const initialState = {
10
11
  fetchState: 'Not-Started',
11
12
  attachmentDataByID: {},
12
13
  },
14
+ createTransactionsState: {
15
+ createStatus: { fetchState: 'Not-Started' },
16
+ newTransactionState: getInitialCreateTransactionLocalDataByType(),
17
+ },
13
18
  };
14
19
  const transactionDetail = createSlice({
15
20
  name: 'transactionDetail',
@@ -829,6 +834,196 @@ const transactionDetail = createSlice({
829
834
  };
830
835
  },
831
836
  },
837
+ // ---------------------------------------------------------------------------------
838
+ // Create Transaction
839
+ //
840
+ // These live on the transactionDetail slice rather than in createTransaction/ because a
841
+ // createSlice owns exactly one state object, and createTransactionsState is nested inside
842
+ // TransactionDetailState. The derivation itself stays in the folder -- each body below
843
+ // delegates to createTransactionLocalDataHelper.ts.
844
+ //
845
+ // They need no clearAll case of their own: the slice already resets to initialState on
846
+ // tenant switch, and createTransactionsState is part of it.
847
+ // ---------------------------------------------------------------------------------
848
+ /** Trigger only -- initializeCreateTransactionLocalDataEpic does the seeding. */
849
+ initializeCreateTransactionLocalData: {
850
+ reducer(
851
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
852
+ _draft,
853
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
854
+ _action) {
855
+ // no-op
856
+ },
857
+ prepare(transactionType) {
858
+ return { payload: { transactionType } };
859
+ },
860
+ },
861
+ updateCreateTransactionLocalData: {
862
+ reducer(draft, action) {
863
+ const { transactionType, localData } = action.payload;
864
+ const current = draft.createTransactionsState.newTransactionState[transactionType];
865
+ draft.createTransactionsState.newTransactionState[transactionType] =
866
+ mergeCreateTransactionLocalData(current, localData);
867
+ },
868
+ prepare(transactionType, localData) {
869
+ return { payload: { transactionType, localData } };
870
+ },
871
+ },
872
+ updateCreateTransactionLineLocalData: {
873
+ reducer(draft, action) {
874
+ const { transactionType, lineId, lineUpdates } = action.payload;
875
+ const current = draft.createTransactionsState.newTransactionState[transactionType];
876
+ current.lines = updateCreateTransactionLine(current.lines, lineId, lineUpdates);
877
+ },
878
+ prepare(transactionType, lineId, lineUpdates) {
879
+ return { payload: { transactionType, lineId, lineUpdates } };
880
+ },
881
+ },
882
+ /**
883
+ * `line` is supplied by the caller rather than built here, so a row added after a vendor is
884
+ * already chosen can arrive pre-populated from the cached recommendations instead of blank.
885
+ */
886
+ addCreateTransactionLine: {
887
+ reducer(draft, action) {
888
+ const { transactionType, line } = action.payload;
889
+ draft.createTransactionsState.newTransactionState[transactionType].lines.push({
890
+ ...line,
891
+ id: nextCreateTransactionLineId(),
892
+ });
893
+ },
894
+ prepare(transactionType, line) {
895
+ return { payload: { transactionType, line } };
896
+ },
897
+ },
898
+ removeCreateTransactionLine: {
899
+ reducer(draft, action) {
900
+ const { transactionType, lineId } = action.payload;
901
+ const current = draft.createTransactionsState.newTransactionState[transactionType];
902
+ current.lines = current.lines.filter((line) => line.id !== lineId);
903
+ },
904
+ prepare(transactionType, lineId) {
905
+ return { payload: { transactionType, lineId } };
906
+ },
907
+ },
908
+ /**
909
+ * Restores the blank working copy AND re-seeds it, so reopening Create starts from a fresh
910
+ * form rather than the previous transaction's values.
911
+ */
912
+ resetCreateTransactionLocalData: {
913
+ reducer(draft, action) {
914
+ const { transactionType } = action.payload;
915
+ draft.createTransactionsState.newTransactionState[transactionType] =
916
+ getSeededCreateTransactionLocalData(transactionType);
917
+ draft.createTransactionsState.createStatus = {
918
+ fetchState: 'Not-Started',
919
+ };
920
+ draft.createTransactionsState.createdTransactionId = undefined;
921
+ },
922
+ prepare(transactionType) {
923
+ return { payload: { transactionType } };
924
+ },
925
+ },
926
+ /** Submit trigger -- createTransactionEpic builds the payload from localData. */
927
+ createTransaction: {
928
+ reducer(draft,
929
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
930
+ _action) {
931
+ draft.createTransactionsState.createStatus = {
932
+ fetchState: 'In-Progress',
933
+ };
934
+ draft.createTransactionsState.createdTransactionId = undefined;
935
+ },
936
+ prepare(transactionType) {
937
+ return { payload: { transactionType } };
938
+ },
939
+ },
940
+ /**
941
+ * Trigger only -- fetchVendorRecommendationsForCreateTransactionEpic does the work.
942
+ * A null entity means the vendor was cleared.
943
+ */
944
+ fetchVendorRecommendationsForCreateTransaction: {
945
+ reducer(
946
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
947
+ _draft,
948
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
949
+ _action) {
950
+ // no-op
951
+ },
952
+ prepare(transactionType, lineIds, entity) {
953
+ return { payload: { transactionType, lineIds, entity } };
954
+ },
955
+ },
956
+ /** Trigger only -- createTransactionAttachmentUploadFailureEpic raises the snackbar. */
957
+ createTransactionAttachmentUploadFailure: {
958
+ reducer(
959
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
960
+ _draft,
961
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
962
+ _action) {
963
+ // no-op
964
+ },
965
+ prepare(failedAttachmentFileNames) {
966
+ return { payload: { failedAttachmentFileNames } };
967
+ },
968
+ },
969
+ /**
970
+ * Writes a vendor's recommendations into the named lines. `lineIds` is explicit rather than
971
+ * "all lines" because a journal entry recommends per line, from that line's own entity.
972
+ */
973
+ setRecommendationsForCreateTransactionLines: {
974
+ reducer(draft, action) {
975
+ const { transactionType, lineIds, recommendations, isAccountingClassesEnabled, } = action.payload;
976
+ const current = draft.createTransactionsState.newTransactionState[transactionType];
977
+ // Clear first: on vendor A -> B, A's prefill is no longer empty, so B's would never
978
+ // replace it. Fields the user picked carry no prefill flag and survive the clear.
979
+ current.lines = current.lines.map((line) => lineIds.includes(line.id)
980
+ ? applyRecommendationsToCreateTransactionLine(clearRecommendationsFromCreateTransactionLine(line), recommendations, isAccountingClassesEnabled)
981
+ : line);
982
+ },
983
+ prepare(transactionType, lineIds, recommendations, isAccountingClassesEnabled) {
984
+ return {
985
+ payload: {
986
+ transactionType,
987
+ lineIds,
988
+ recommendations,
989
+ isAccountingClassesEnabled,
990
+ },
991
+ };
992
+ },
993
+ },
994
+ /** Vendor cleared: drop the dropdown group and undo only what the prefill wrote. */
995
+ clearRecommendationsForCreateTransactionLines: {
996
+ reducer(draft, action) {
997
+ const { transactionType, lineIds } = action.payload;
998
+ const current = draft.createTransactionsState.newTransactionState[transactionType];
999
+ current.lines = current.lines.map((line) => lineIds.includes(line.id)
1000
+ ? clearRecommendationsFromCreateTransactionLine(line)
1001
+ : line);
1002
+ },
1003
+ prepare(transactionType, lineIds) {
1004
+ return { payload: { transactionType, lineIds } };
1005
+ },
1006
+ },
1007
+ createTransactionSuccessOrFailure: {
1008
+ reducer(draft, action) {
1009
+ const { fetchState, error, createdTransactionId } = action.payload;
1010
+ draft.createTransactionsState.createStatus = { fetchState, error };
1011
+ if (createdTransactionId != null) {
1012
+ draft.createTransactionsState.createdTransactionId =
1013
+ createdTransactionId;
1014
+ // The API will not return a QBO-only row until delta sync, so the optimistic insert
1015
+ // is marked fetched: detail local data can be saved and a fetch is a cache hit.
1016
+ draft.transactionDetailById[getTransactionDetailKey(createdTransactionId)] = {
1017
+ ...initialSupportedTransactionDetail,
1018
+ fetchState: 'Completed',
1019
+ transactionId: createdTransactionId,
1020
+ };
1021
+ }
1022
+ },
1023
+ prepare(fetchState, createdTransactionId, error) {
1024
+ return { payload: { fetchState, createdTransactionId, error } };
1025
+ },
1026
+ },
832
1027
  },
833
1028
  extraReducers: (builder) => {
834
1029
  builder.addCase(clearAll, (draft) => {
@@ -836,7 +1031,7 @@ const transactionDetail = createSlice({
836
1031
  });
837
1032
  },
838
1033
  });
839
- export const { downloadAccountingProviderAttachment, downloadAccountingProviderAttachmentSuccess, downloadAccountingProviderAttachmentFailure, fetchTransactionDetail, updateTransactionDetailFetchState, removeTransactionDetail, uploadMissingAttachmentSuccess, updateTransactionDetail, updateTransactionDetailSaveStatus, clearTransactionDetailSaveStatus, markTransactionAsNotMiscategorized, deleteTransactionAttachment, deleteTransactionAttachmentFailure, deleteTransactionAttachmentSuccess, updateStatusForTransactionNotMiscategorizedUpdate, updateStatusConsolidatedSaveTransactionDetail, updateTransactionStateIfUpdateActionNotAllowed, saveTransactionDetail, initializeTransactionDetailLocalData, saveTransactionDetailLocalData, clearTransactionDetailLocalData, resetLineItemsCategoryClassInLocalData, setAllLineItemsToCategoryClassInLocalData, setAllLineItemsLocalDataIsUpdateAllChecked, setEntityRecommendationForLineIdsForTransactionDetail, markCategoryClassRecommendationsInProgressForTransactionDetail, markCategoryClassRecommendationsCompletedForTransactionDetail, markCategoryClassRecommendationsFailureForTransactionDetail, removeEntityRecommendationForLineIdForTransactionDetail, updateSelectedVendor, updateSelectedCustomer, resetVendor, resetSelectedCustomer, updateLocalDataWithTransactionsUpdateWithVendorCheckbox, updateVendorToAllLineItems, resetAllLineItemsToVendor, updateLatestSelectedEntity, updateVendorBulkRecommendationsFetchStatus, setIsVendorUpdateAllChecked, addSplitLine, deleteSplitLine, toggleSplitEditMode, } = transactionDetail.actions;
1034
+ export const { downloadAccountingProviderAttachment, downloadAccountingProviderAttachmentSuccess, downloadAccountingProviderAttachmentFailure, fetchTransactionDetail, updateTransactionDetailFetchState, removeTransactionDetail, uploadMissingAttachmentSuccess, updateTransactionDetail, updateTransactionDetailSaveStatus, clearTransactionDetailSaveStatus, markTransactionAsNotMiscategorized, deleteTransactionAttachment, deleteTransactionAttachmentFailure, deleteTransactionAttachmentSuccess, updateStatusForTransactionNotMiscategorizedUpdate, updateStatusConsolidatedSaveTransactionDetail, updateTransactionStateIfUpdateActionNotAllowed, saveTransactionDetail, initializeTransactionDetailLocalData, saveTransactionDetailLocalData, clearTransactionDetailLocalData, resetLineItemsCategoryClassInLocalData, setAllLineItemsToCategoryClassInLocalData, setAllLineItemsLocalDataIsUpdateAllChecked, setEntityRecommendationForLineIdsForTransactionDetail, markCategoryClassRecommendationsInProgressForTransactionDetail, markCategoryClassRecommendationsCompletedForTransactionDetail, markCategoryClassRecommendationsFailureForTransactionDetail, removeEntityRecommendationForLineIdForTransactionDetail, updateSelectedVendor, updateSelectedCustomer, resetVendor, resetSelectedCustomer, updateLocalDataWithTransactionsUpdateWithVendorCheckbox, updateVendorToAllLineItems, resetAllLineItemsToVendor, updateLatestSelectedEntity, updateVendorBulkRecommendationsFetchStatus, setIsVendorUpdateAllChecked, addSplitLine, deleteSplitLine, toggleSplitEditMode, initializeCreateTransactionLocalData, updateCreateTransactionLocalData, updateCreateTransactionLineLocalData, addCreateTransactionLine, removeCreateTransactionLine, resetCreateTransactionLocalData, createTransaction, createTransactionSuccessOrFailure, setRecommendationsForCreateTransactionLines, clearRecommendationsForCreateTransactionLines, fetchVendorRecommendationsForCreateTransaction, createTransactionAttachmentUploadFailure, } = transactionDetail.actions;
840
1035
  export default transactionDetail.reducer;
841
1036
  function getUpdatedEntityLocalData(detail, updates, entity, resetRecommendations, type) {
842
1037
  const key = type === 'customer' ? 'customerUpdates' : 'vendorUpdates';