@zeniai/client-epic-state 5.0.55-betaSS2 → 5.0.55-betaVR1

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 (31) hide show
  1. package/lib/esm/index.js +5 -4
  2. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.js +0 -4
  3. package/lib/esm/view/expenseAutomationView/epics/transactionCategorization/fetchTransactionCategorizationEpic.js +1 -9
  4. package/lib/esm/view/expenseAutomationView/reducers/transactionsViewReducer.js +1 -80
  5. package/lib/esm/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +1 -20
  6. package/lib/esm/view/expenseAutomationView/types/missingReceiptsViewState.js +2 -0
  7. package/lib/esm/view/transactionDetail/journalEntryLinesViewModel.js +113 -0
  8. package/lib/esm/view/transactionDetail/journalEntryLinesViewModel.vitest.js +243 -0
  9. package/lib/index.d.ts +6 -4
  10. package/lib/index.js +43 -37
  11. package/lib/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.js +0 -4
  12. package/lib/view/expenseAutomationView/epics/transactionCategorization/fetchTransactionCategorizationEpic.d.ts +2 -2
  13. package/lib/view/expenseAutomationView/epics/transactionCategorization/fetchTransactionCategorizationEpic.js +0 -8
  14. package/lib/view/expenseAutomationView/payload/transactionCategorizationPayload.d.ts +0 -15
  15. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.d.ts +1 -2
  16. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +2 -8
  17. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.js +2 -81
  18. package/lib/view/expenseAutomationView/selectorTypes/missingReceiptsSelectorTypes.d.ts +1 -2
  19. package/lib/view/expenseAutomationView/selectorTypes/transactionsViewSelectorTypes.d.ts +0 -14
  20. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +1 -20
  21. package/lib/view/expenseAutomationView/types/missingReceiptsViewState.d.ts +2 -1
  22. package/lib/view/expenseAutomationView/types/missingReceiptsViewState.js +4 -1
  23. package/lib/view/expenseAutomationView/types/transactionsViewState.d.ts +1 -35
  24. package/lib/view/transactionDetail/journalEntryLinesViewModel.d.ts +73 -0
  25. package/lib/view/transactionDetail/journalEntryLinesViewModel.js +124 -0
  26. package/lib/view/transactionDetail/journalEntryLinesViewModel.vitest.d.ts +1 -0
  27. package/lib/view/transactionDetail/journalEntryLinesViewModel.vitest.js +245 -0
  28. package/package.json +2 -2
  29. package/lib/esm/view/expenseAutomationView/types/completedSubTab.js +0 -9
  30. package/lib/view/expenseAutomationView/types/completedSubTab.d.ts +0 -2
  31. package/lib/view/expenseAutomationView/types/completedSubTab.js +0 -13
package/lib/esm/index.js CHANGED
@@ -167,13 +167,12 @@ import { clearExpenseAutomationFluxAnalysisView, fetchFluxAnalysisView, reviewFl
167
167
  import { clearJeScheduleLocalData as clearExpenseAutomationJEScheduleLocalData, clearExpenseAutomationJESchedulesView, fetchJeSchedulesPage as fetchExpenseAutomationJESchedulesPage, ignoreRecommendedJeSchedule as ignoreExpenseAutomationJESchedule, initializeAccountSettingsView as initializeJeAccountSettingsView, initializeJeScheduleLocalData, removeJeScheduleTransactionKey, retryJeSchedule as retryExpenseAutomationJESchedule, saveAccountSettings as saveJeAccountSettings, saveAccountSettingsLocalData as saveJeAccountSettingsLocalData, updateJESchedulesUIState as updateExpenseAutomationJESchedulesUIState, updateJeScheduleLocalDataById, updateJeScheduleTransactionKeys, } from './view/expenseAutomationView/reducers/jeSchedulesViewReducer';
168
168
  import { acknowledgeBulkUploadConfirmMatchComplete, bulkUploadAutomatchingTimedOut, bulkUploadReceipts, bulkUploadReceiptsFailure, bulkUploadReceiptsSuccess, clearBulkUpload, clearManualSearchResults, clearMissingReceiptsTabNavigation, confirmBulkUploadMatch, confirmBulkUploadMatchFailure, confirmBulkUploadMatchSuccess, fetchBulkUploadBatchDetails, fetchBulkUploadBatchDetailsFailure, fetchBulkUploadBatchDetailsSuccess, fetchBulkUploadBatches, fetchBulkUploadBatchesFailure, fetchBulkUploadBatchesSuccess, fetchCompletedTransactions, fetchCompletedTransactionsFailure, fetchCompletedTransactionsSuccess, fetchMissingReceipts as fetchExpenseAutomationMissingReceipts, fetchMoreBatchDetails, fetchMoreBatchDetailsComplete, fetchMoreBatchDetailsFailure, markMissingReceiptAsDone as markExpenseAutomationMissingReceiptAsDone, pusherBatchStatusUpdate, requestMissingReceiptsTabNavigation, restoreBulkUploadAutomatchingOnMount, restoreBulkUploadMatchingState, searchTransactionsForManualMatch, searchTransactionsForManualMatchFailure, searchTransactionsForManualMatchSuccess, setBulkUploadCompletedSubTab, setBulkUploadResultsTab, setBulkUploadSortConfig, setBulkUploadUploadedFileCount, storeBatchDetails, updateBulkUploadProgress, updateMissingReceiptUploadState as updateExpenseAutomationMissingReceiptUploadState, updateMissingReceiptsUIState as updateExpenseAutomationMissingReceiptsUIState, uploadMissingReceiptSuccess as uploadExpenseAutomationMissingReceiptSuccess, } from './view/expenseAutomationView/reducers/missingReceiptsViewReducer';
169
169
  import { deleteAccountStatement, excludeAccountFromReconciliation, fetchReconciliation as fetchReconciliationView, includeAccountInReconciliation, saveReconciliationDetail as saveExpenseAutomationReconciliationDetail, saveReconciliationReview as saveExpenseAutomationReconciliationReview, setConnectionInProgressForAccount as setConnectionInProgressForAccountReconciliation, setStatementParseInProgress, updateAccountReconciliationLocalData as updateExpenseAutomationAccountReconciliationLocalData, updateSelectedAccountId as updateExpenseAutomationAccountReconciliationSelectedAccountId, updateSelectedTab as updateExpenseAutomationAccountReconciliationSelectedTab, updateReconListScrollPosition as updateExpenseAutomationReconListScrollPosition, updateReviewTabSortState as updateExpenseAutomationReconReviewTabListSortState, updateReviewTabLocalData as updateExpenseAutomationReconReviewTabLocalData, updateReconcileTabListScrollState as updateExpenseAutomationReconcileTabListScrollState, updateReconcileTabListSortState as updateExpenseAutomationReconcileTabListSortState, updateReconcileTabLocalData as updateExpenseAutomationReconcileTabLocalData, updateSelectedDrawerAccountId as updateExpenseAutomationSelectedDrawerAccountId, updateNodeCollapseState, updateStatementUploadChosen, uploadAccountStatement, } from './view/expenseAutomationView/reducers/reconciliationViewReducer';
170
- import { backgroundRefetchReviewTab, clearExpenseAutomationTransactionsView, fetchTransactionCategorization, fetchTransactionCategorizationFailure, fetchTransactionCategorizationView, initializeTransactionCategorizationViewLocalData, markTransactionAsNotMiscategorized, saveTransactionCategorization, saveTransactionCategorizationLocalData, setAllItemsToCategoryClassInLocalDataForCategorization, setEntityRecommendationForLineIdsForCategorization, syncTransactionCategorizationFromDetailSave, updateCurrentSelectedTransactionCategorizationTab, updateTransactionCategorizationCompletedSubTab, updateSelectedCheckboxTransactionIds, updateSelectedCustomerForTransaction, updateSelectedTransactionId, updateSelectedVendorForTransaction, updateTransactionCategorization, updateTransactionCategorizationSaveStatus, updateTransactionCategorizationUIState, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } from './view/expenseAutomationView/reducers/transactionsViewReducer';
170
+ import { backgroundRefetchReviewTab, clearExpenseAutomationTransactionsView, fetchTransactionCategorization, fetchTransactionCategorizationFailure, fetchTransactionCategorizationView, initializeTransactionCategorizationViewLocalData, markTransactionAsNotMiscategorized, saveTransactionCategorization, saveTransactionCategorizationLocalData, setAllItemsToCategoryClassInLocalDataForCategorization, setEntityRecommendationForLineIdsForCategorization, syncTransactionCategorizationFromDetailSave, updateCurrentSelectedTransactionCategorizationTab, updateSelectedCheckboxTransactionIds, updateSelectedCustomerForTransaction, updateSelectedTransactionId, updateSelectedVendorForTransaction, updateTransactionCategorization, updateTransactionCategorizationSaveStatus, updateTransactionCategorizationUIState, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } from './view/expenseAutomationView/reducers/transactionsViewReducer';
171
171
  import { getExpenseAutomationFluxAnalysisView } from './view/expenseAutomationView/selectors/fluxAnalysisViewSelector';
172
172
  import { getExpenseAutomationReconciliationView, isAccountReconReport, } from './view/expenseAutomationView/selectors/reconciliationViewSelector';
173
173
  import { getExpenseAutomationTransactionView } from './view/expenseAutomationView/selectors/transactionCategorizationSelector';
174
174
  import { toJEScheduleMainTab as toExpenseAutomationJEScheduleMainTab, toJEScheduleSortKey as toExpenseAutomationJEScheduleSortKey, } from './view/expenseAutomationView/types/jeSchedulesViewState';
175
- import { BATCH_FILE_STATUSES, isUnmatchedTabFileStatus, toBatchFileStatus, toBatchStatusValue, toBulkUploadPhase, toBulkUploadResultsTab, toBulkUploadSortKey, toMatchSource, toMissingReceiptsTab, } from './view/expenseAutomationView/types/missingReceiptsViewState';
176
- import { toCompletedSubTab, } from './view/expenseAutomationView/types/completedSubTab';
175
+ import { BATCH_FILE_STATUSES, isUnmatchedTabFileStatus, toBatchFileStatus, toBatchStatusValue, toBulkUploadPhase, toBulkUploadResultsTab, toBulkUploadSortKey, toCompletedSubTab, toMatchSource, toMissingReceiptsTab, } from './view/expenseAutomationView/types/missingReceiptsViewState';
177
176
  import { toMissingReceiptsSortKey as toExpenseAutomationMissingReceiptsSortKey, } from './view/expenseAutomationView/types/missingReceiptsViewState';
178
177
  import { toReconciliationTabsType, } from './view/expenseAutomationView/types/reconciliationViewState';
179
178
  import { toTransactionsTabKey as toExpenseAutomationTransactionsTabKey, toTransactionsSortKey, } from './view/expenseAutomationView/types/transactionsViewState';
@@ -379,6 +378,7 @@ import { getAllTopExpenses, getTop6Expenses, getTopExpenses, } from './view/topE
379
378
  import { TOP_EX_TIME_PERIODS, } from './view/topEx/topExState';
380
379
  import { getAccountingProviderAttachment, } from './view/transactionDetail/getAccountingProviderAttachmentSelector';
381
380
  import { getChangedLineItemCountFromLocalData, isAccountUncategorized, } from './view/transactionDetail/transactionDetailLocalDataHelper';
381
+ import { JOURNAL_ENTRY_SORT_KEYS, filterJournalEntryLinesExcludingLinked, journalEntryDefaultSortConfig, journalEntryTotalsByPostingSide, sortJournalEntryLines, sumJournalEntryAmounts, toJournalEntrySortKey, } from './view/transactionDetail/journalEntryLinesViewModel';
382
382
  import { clearTransactionDetailSaveStatus, deleteTransactionAttachment, downloadAccountingProviderAttachment, downloadAccountingProviderAttachmentFailure, downloadAccountingProviderAttachmentSuccess, fetchTransactionDetail, initializeTransactionDetailLocalData, removeEntityRecommendationForLineIdForTransactionDetail, resetAllLineItemsToVendor, resetLineItemsCategoryClassInLocalData, resetSelectedCustomer, resetVendor, saveTransactionDetail, saveTransactionDetailLocalData, setAllLineItemsLocalDataIsUpdateAllChecked, setAllLineItemsToCategoryClassInLocalData, setIsVendorUpdateAllChecked, updateLatestSelectedEntity, updateLocalDataWithTransactionsUpdateWithVendorCheckbox, updateSelectedCustomer, updateSelectedVendor, updateTransactionDetail, updateVendorBulkRecommendationsFetchStatus, updateVendorToAllLineItems, uploadMissingAttachmentSuccess, } from './view/transactionDetail/transactionDetailReducer';
383
383
  import { getInitialUpdatablePeriodsForTransactionRecommendations, getTransactionDetail, getTransactionDetailForTransaction, } from './view/transactionDetail/transactionDetailSelector';
384
384
  import { getThirdPartyIdFromTransactionId, } from './view/transactionDetail/transactionDetailState';
@@ -442,7 +442,7 @@ export { stringToUnion, stringToUnionStrict };
442
442
  export { fetchMonthEndCloseChecks, fetchMonthClosePerformanceTrend, getMonthEndCloseChecksViewByTenantId, ALL_MONTH_END_CLOSE_CHECKS_FREQUENCY, };
443
443
  export {
444
444
  // Bulk Upload Types
445
- BATCH_FILE_STATUSES, isUnmatchedTabFileStatus, toBatchFileStatus, toBatchStatusValue, toBulkUploadPhase, toBulkUploadResultsTab, toBulkUploadSortKey, toCompletedSubTab, toMatchSource, toMissingReceiptsTab, toExpenseAutomationJEScheduleMainTab, toExpenseAutomationJEScheduleSortKey, getExpenseAutomationView, toExpenseAutomationMissingReceiptsSortKey, toExpenseAutomationTransactionsTabKey, toExpenseAutomationViewType, uploadExpenseAutomationMissingReceiptSuccess, markExpenseAutomationMissingReceiptAsDone, fetchAllExpenseAutomationTabs, refreshExpenseAutomationCurrentTab, updateCurrentSelectedTransactionCategorizationTab, updateTransactionCategorizationCompletedSubTab, fetchExpenseAutomationMissingReceipts,
445
+ BATCH_FILE_STATUSES, isUnmatchedTabFileStatus, toBatchFileStatus, toBatchStatusValue, toBulkUploadPhase, toBulkUploadResultsTab, toBulkUploadSortKey, toCompletedSubTab, toMatchSource, toMissingReceiptsTab, toExpenseAutomationJEScheduleMainTab, toExpenseAutomationJEScheduleSortKey, getExpenseAutomationView, toExpenseAutomationMissingReceiptsSortKey, toExpenseAutomationTransactionsTabKey, toExpenseAutomationViewType, uploadExpenseAutomationMissingReceiptSuccess, markExpenseAutomationMissingReceiptAsDone, fetchAllExpenseAutomationTabs, refreshExpenseAutomationCurrentTab, updateCurrentSelectedTransactionCategorizationTab, fetchExpenseAutomationMissingReceipts,
446
446
  // Bulk Upload Actions
447
447
  bulkUploadReceipts, bulkUploadAutomatchingTimedOut, bulkUploadReceiptsSuccess, bulkUploadReceiptsFailure, restoreBulkUploadAutomatchingOnMount, restoreBulkUploadMatchingState, updateBulkUploadProgress, pusherBatchStatusUpdate, requestMissingReceiptsTabNavigation, clearMissingReceiptsTabNavigation, fetchBulkUploadBatchDetails, fetchBulkUploadBatchDetailsSuccess, fetchBulkUploadBatchDetailsFailure, storeBatchDetails, fetchMoreBatchDetails, fetchMoreBatchDetailsComplete, fetchMoreBatchDetailsFailure, fetchBulkUploadBatches, fetchBulkUploadBatchesSuccess, fetchBulkUploadBatchesFailure, confirmBulkUploadMatch, confirmBulkUploadMatchSuccess, confirmBulkUploadMatchFailure, setBulkUploadResultsTab, setBulkUploadCompletedSubTab, setBulkUploadSortConfig, setBulkUploadUploadedFileCount, clearBulkUpload, searchTransactionsForManualMatch, searchTransactionsForManualMatchSuccess, searchTransactionsForManualMatchFailure, clearManualSearchResults, acknowledgeBulkUploadConfirmMatchComplete, fetchCompletedTransactions, fetchCompletedTransactionsSuccess, fetchCompletedTransactionsFailure, fetchFluxAnalysisView, clearExpenseAutomationFluxAnalysisView, updateOperatingExpensesIdsForReview as updateFluxOperatingExpensesIdsForReview, updateSelectedSectionIdsForReview as updateFluxAnalysisSelectedSectionIdsForReview, reviewFluxAnalysisView, updateExpenseAutomationMissingReceiptUploadState, updateExpenseAutomationMissingReceiptsUIState, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, getExpenseAutomationFluxAnalysisView, updateCurrentSelectedView, updateCurrentSelectedPeriod, getExpenseAutomationTransactionView, updateFluxAnalysisViewUIState, updateFluxAnalysisViewPageMetaData, MAX_SELECTION_LIMIT, checkIfAllLineItemsAreCategoryClassFilled, getLineItemsByTransactionIdsFromLocalData, isAnyItemWithUncategorizedExpenseAccount, excludeAccountFromReconciliation, includeAccountInReconciliation, saveExpenseAutomationReconciliationDetail, updateExpenseAutomationReconcileTabListScrollState, updateExpenseAutomationReconReviewTabListSortState, updateExpenseAutomationReconcileTabListSortState, updateExpenseAutomationReconcileTabLocalData, updateExpenseAutomationAccountReconciliationSelectedTab, updateExpenseAutomationAccountReconciliationSelectedAccountId, getExpenseAutomationReconciliationView, fetchReconciliationView, uploadAccountStatementIntoDocumentAI, updateExpenseAutomationReconListScrollPosition, setConnectionInProgressForAccountReconciliation, getAccountReconByAccountIdAndSelectedPeriod, toReconciliationTabsType, isAccountReconReport, updateExpenseAutomationReconReviewTabLocalData, updateExpenseAutomationSelectedDrawerAccountId, saveExpenseAutomationReconciliationReview, updateExpenseAutomationAccountReconciliationLocalData, toReconciliationAccountSource, deleteAccountStatement, uploadAccountStatement, updateNodeCollapseState, updateStatementUploadChosen, isReviewTransactionBankTransferType, isReviewTransactionBillPaymentType, isReviewTransactionCreditCardPaymentType, isReviewTransactionDepositType, isReviewTransactionExpenseType, isReviewTransactionCreditCardCreditType, setStatementParseInProgress, };
448
448
  export { fetchTransactionCategorization, fetchTransactionCategorizationView, updateTransactionCategorizationUIState, updateSelectedCheckboxTransactionIds, setEntityRecommendationForLineIdsForCategorization, initializeTransactionCategorizationViewLocalData, setAllItemsToCategoryClassInLocalDataForCategorization, saveTransactionCategorizationLocalData, fetchTransactionCategorizationFailure, saveTransactionCategorization, updateTransactionCategorization, updateTransactionCategorizationSaveStatus, markTransactionAsNotMiscategorized, updateSelectedVendorForTransaction, updateSelectedCustomerForTransaction, updateSelectedTransactionId, syncTransactionCategorizationFromDetailSave, backgroundRefetchReviewTab, clearExpenseAutomationTransactionsView, toTransactionsSortKey, };
@@ -573,6 +573,7 @@ export { getNextNthWorkingDay, getPreviousNthWorkingDay, isHolidayToday, filterD
573
573
  export { fetchCompanyOnboardingView, fetchQBOConnectionPool, updateQBOConnectionPoolExternalConnection, fetchOnboardingCompletedCompanies, saveOnboardingCustomerCompletedStatus, toProductType, toProductTypeStrict, getOnboardingCockpitView, getNewOnboardingCustomerView, getOnboardingEmailGroup, initializeOnboardingCustomerViewUpdateData, clearOnboardingCustomerViewUpdateData, saveOnboardingCustomerViewUpdateData, updateOnboardingCustomerListUIState, updateCustomerCreationStatus, updateStatusAfterOnboardingCompleted, saveOnboardingCustomerViewUpdates, saveOnboardingCustomerNotes, saveOnboardingCustomerDataInLocalStore, updateOnboardingCustomerDataInLocalStore, resetNewOnboardedCustomerId, sendOnboardingCustomerViewInvite, retryBankAccountConnectionForOnboarding, };
574
574
  export { getTransactionsListByCategoryType, getTransactionListUIStateByCategoryType, };
575
575
  export { getChangedLineItemCountFromLocalData, isAccountUncategorized };
576
+ export { JOURNAL_ENTRY_SORT_KEYS, filterJournalEntryLinesExcludingLinked, journalEntryDefaultSortConfig, journalEntryTotalsByPostingSide, sortJournalEntryLines, sumJournalEntryAmounts, toJournalEntrySortKey, };
576
577
  export { openSnackbar, closeSnackbar, getSnackbar, };
577
578
  export { getSpendManagementEffectiveListPeriod, getSelectedCompanyOfficer, showBillPayPromoPage, showReimbursementPromoPage, getActualPaymentDate, isVerifiedStatusCode, isVerifiedPaymentAccountProviderStatusCode, isBulkProcessing, getBillListUniqueType, getRemiListUniqueType, getBulkOperationSuffix, toAccountsPromoConfig, toSameDayAchDisablementConfig, isPaymentMethodOutsideZeni, isAwaitingMarkAsPaid, checkIfLowBalance, };
578
579
  export { canSendMonthEndEmailReport, shouldEnableCalendarPickerForLastReportSent, };
@@ -46,10 +46,6 @@ export const searchTransactionsForManualMatchEpic = (actions$, state$, zeniAPI)
46
46
  page_token: pageToken ?? null,
47
47
  page_size: manualSearch.pageSize,
48
48
  search_text: query,
49
- // Manual search ignores the Completed sub-tab axis — always span 'all'
50
- // so the receipt-matching UX returns results regardless of where the
51
- // transaction would otherwise be bucketed on the Completed tab.
52
- sub_tab: 'all',
53
49
  };
54
50
  return zeniAPI
55
51
  .getJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/expense-automation/transactions?query=${encodeURIComponent(JSON.stringify(queryParam))}`)
@@ -5,7 +5,7 @@ import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
5
5
  import { updateTransactions } from '../../../../entity/transaction/transactionReducer';
6
6
  import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
7
7
  import { getLineItemsByTransactionsIdsFromResponse } from '../../helpers/transactionCategorizationLocalDataHelper';
8
- import { fetchTransactionCategorization, fetchTransactionCategorizationFailure, fetchTransactionCategorizationSuccess, initializeTransactionCategorizationViewLocalData, resetOtherTabsFetchState, updateParentTotalCountForTab, updateTotalCountForTransactionCategorization, updateTransactionCategorizationUIState, } from '../../reducers/transactionsViewReducer';
8
+ import { fetchTransactionCategorization, fetchTransactionCategorizationFailure, fetchTransactionCategorizationSuccess, initializeTransactionCategorizationViewLocalData, resetOtherTabsFetchState, updateTotalCountForTransactionCategorization, updateTransactionCategorizationUIState, } from '../../reducers/transactionsViewReducer';
9
9
  import { TRANSACTIONS_TABS, toTransactionsSortKey, } from '../../types/transactionsViewState';
10
10
  export const fetchTransactionCategorizationEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(fetchTransactionCategorization.match), switchMap((action) => {
11
11
  const { expenseAutomationViewState: { selectedPeriodByTenantId }, expenseAutomationTransactionsViewState, } = state$.value;
@@ -23,9 +23,6 @@ export const fetchTransactionCategorizationEpic = (actions$, state$, zeniAPI) =>
23
23
  page_token: pageToken,
24
24
  page_size: 25,
25
25
  search_text: uiState.searchString,
26
- sub_tab: selectedTab === 'autoCategorized'
27
- ? expenseAutomationTransactionsViewState.selectedTransactionCategorizationCompletedSubTab
28
- : 'all',
29
26
  };
30
27
  return zeniAPI
31
28
  .getJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/expense-automation/transactions?query=${encodeURIComponent(JSON.stringify(queryParam))}`)
@@ -48,11 +45,6 @@ export const fetchTransactionCategorizationEpic = (actions$, state$, zeniAPI) =>
48
45
  selectedTab,
49
46
  totalCount: response.data.total_count,
50
47
  }));
51
- updateActions.push(updateParentTotalCountForTab({
52
- selectedPeriod,
53
- selectedTab,
54
- parentTotalCount: response.data.parent_tab_total_count,
55
- }));
56
48
  updateActions.push(resetOtherTabsFetchState({
57
49
  refreshViewInBackground,
58
50
  tabs: TRANSACTIONS_TABS.filter((tab) => selectedTab !== tab),
@@ -41,44 +41,12 @@ export const initialTransactionTabViewState = {
41
41
  selectedTransactionLineId: undefined,
42
42
  };
43
43
  export const initialState = {
44
- autoCategorizedSubTabCache: {},
45
- parentTotalCountByTab: {
46
- review: {},
47
- autoCategorized: {},
48
- },
49
44
  selectedTransactionCategorizationTab: 'review',
50
- selectedTransactionCategorizationCompletedSubTab: 'all',
51
45
  transactionCategorizationView: {
52
46
  review: { ...initialTransactionTabViewState },
53
47
  autoCategorized: { ...initialTransactionTabViewState },
54
48
  },
55
49
  };
56
- /**
57
- * Capture the autoCategorized tab's current paginated dataset for a sub-tab.
58
- * The mid-flight `'In-Progress'` state is normalised to `'Completed'` because
59
- * the in-flight request is cancelled by `switchMap` in the fetch epic when the
60
- * sub-tab changes — restoring `'In-Progress'` later would leave the UI stuck
61
- * showing a phantom loading state with no fetch actually running. Length-zero
62
- * datasets degrade to `'Not-Started'` so the next visit triggers a fresh
63
- * fetch from page 1 instead of short-circuiting on stale empty caches.
64
- */
65
- function snapshotAutoCategorizedTab(autoCat) {
66
- const transactionIdsBySelectedPeriod = {
67
- ...autoCat.transactionIdsBySelectedPeriod,
68
- };
69
- const hasAnyLoadedRows = Object.values(transactionIdsBySelectedPeriod).some((ids) => ids.length > 0);
70
- let normalisedFetchState = autoCat.fetchState;
71
- if (normalisedFetchState === 'In-Progress') {
72
- normalisedFetchState = hasAnyLoadedRows ? 'Completed' : 'Not-Started';
73
- }
74
- return {
75
- error: autoCat.error,
76
- fetchState: normalisedFetchState,
77
- pageToken: autoCat.uiState.pageToken,
78
- totalCount: { ...autoCat.uiState.totalCount },
79
- transactionIdsBySelectedPeriod,
80
- };
81
- }
82
50
  const expenseAutomationTransactionsView = createSlice({
83
51
  name: 'expenseAutomationTransactionsView',
84
52
  initialState,
@@ -292,48 +260,6 @@ const expenseAutomationTransactionsView = createSlice({
292
260
  return { payload: { newSelectedTab } };
293
261
  },
294
262
  },
295
- updateTransactionCategorizationCompletedSubTab: {
296
- reducer(draft, action) {
297
- const { newSubTab } = action.payload;
298
- const previousSubTab = draft.selectedTransactionCategorizationCompletedSubTab;
299
- if (previousSubTab === newSubTab) {
300
- return;
301
- }
302
- const autoCat = draft.transactionCategorizationView.autoCategorized;
303
- // Snapshot the outgoing sub-tab so a future revisit can short-circuit
304
- // the fetch epic (mirrors the parent-tab "don't refetch what's
305
- // already cached" behaviour). Period-scoped data is preserved as-is
306
- // because the snapshot itself is keyed only by sub-tab; the active
307
- // tab's per-period maps remain the source of truth while live.
308
- draft.autoCategorizedSubTabCache[previousSubTab] =
309
- snapshotAutoCategorizedTab(autoCat);
310
- const cached = draft.autoCategorizedSubTabCache[newSubTab];
311
- if (cached != null) {
312
- autoCat.uiState.pageToken = cached.pageToken;
313
- autoCat.uiState.totalCount = { ...cached.totalCount };
314
- autoCat.transactionIdsBySelectedPeriod = {
315
- ...cached.transactionIdsBySelectedPeriod,
316
- };
317
- autoCat.fetchState = cached.fetchState;
318
- autoCat.error = cached.error;
319
- }
320
- else {
321
- // Sub-tab has never been visited — clear the active slot so the
322
- // view-epic's `fetchState === 'Not-Started' || transactionIds.length
323
- // === 0` cache check falls through and triggers a fresh page-1
324
- // fetch for the new dataset.
325
- autoCat.uiState.pageToken = null;
326
- autoCat.uiState.totalCount = {};
327
- autoCat.transactionIdsBySelectedPeriod = {};
328
- autoCat.fetchState = 'Not-Started';
329
- autoCat.error = undefined;
330
- }
331
- draft.selectedTransactionCategorizationCompletedSubTab = newSubTab;
332
- },
333
- prepare(newSubTab) {
334
- return { payload: { newSubTab } };
335
- },
336
- },
337
263
  updateTransactionCategorization: {
338
264
  reducer(draft, action) {
339
265
  const selectedTab = action.payload.selectedTab;
@@ -771,10 +697,6 @@ const expenseAutomationTransactionsView = createSlice({
771
697
  const { selectedTab, selectedPeriod, totalCount } = action.payload;
772
698
  draft.transactionCategorizationView[selectedTab].uiState.totalCount[toMonthYearPeriodId(selectedPeriod)] = totalCount;
773
699
  },
774
- updateParentTotalCountForTab(draft, action) {
775
- const { selectedTab, selectedPeriod, parentTotalCount } = action.payload;
776
- draft.parentTotalCountByTab[selectedTab][toMonthYearPeriodId(selectedPeriod)] = parentTotalCount;
777
- },
778
700
  updateSelectedCheckboxTransactionIds(draft, action) {
779
701
  const selectedTab = action.payload.selectedTab;
780
702
  const transactionIds = action.payload.transactionIds;
@@ -785,7 +707,6 @@ const expenseAutomationTransactionsView = createSlice({
785
707
  draft.transactionCategorizationView[selectedTab] = {
786
708
  ...initialTransactionTabViewState,
787
709
  };
788
- draft.parentTotalCountByTab[selectedTab] = {};
789
710
  },
790
711
  clearExpenseAutomationTransactionsView(draft) {
791
712
  Object.assign(draft, initialState);
@@ -882,5 +803,5 @@ const expenseAutomationTransactionsView = createSlice({
882
803
  },
883
804
  },
884
805
  });
885
- export const { fetchTransactionCategorization, updateTransactionCategorizationUIState, initializeTransactionCategorizationViewLocalData, saveTransactionCategorizationLocalData, fetchTransactionCategorizationFailure, saveTransactionCategorization, updateTransactionCategorization, updateCurrentSelectedTransactionCategorizationTab, updateTransactionCategorizationCompletedSubTab, updateTransactionCategorizationSaveStatus, markTransactionAsNotMiscategorized, updateStatusForTransactionNotMiscategorizedUpdateForCategorization, updateSelectedVendorForTransaction, updateSelectedCustomerForTransaction, setAllItemsToCategoryClassInLocalDataForCategorization, updateTotalCountForTransactionCategorization, updateParentTotalCountForTab, fetchTransactionCategorizationSuccess, resetOtherTabsFetchState, fetchTransactionCategorizationView, updateSelectedCheckboxTransactionIds, clearExpenseAutomationTransactionsViewPerTabView, clearExpenseAutomationTransactionsView, setEntityRecommendationForLineIdsForCategorization, updateSelectedTransactionId, syncTransactionCategorizationFromDetailSave, backgroundRefetchReviewTab, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } = expenseAutomationTransactionsView.actions;
806
+ export const { fetchTransactionCategorization, updateTransactionCategorizationUIState, initializeTransactionCategorizationViewLocalData, saveTransactionCategorizationLocalData, fetchTransactionCategorizationFailure, saveTransactionCategorization, updateTransactionCategorization, updateCurrentSelectedTransactionCategorizationTab, updateTransactionCategorizationSaveStatus, markTransactionAsNotMiscategorized, updateStatusForTransactionNotMiscategorizedUpdateForCategorization, updateSelectedVendorForTransaction, updateSelectedCustomerForTransaction, setAllItemsToCategoryClassInLocalDataForCategorization, updateTotalCountForTransactionCategorization, fetchTransactionCategorizationSuccess, resetOtherTabsFetchState, fetchTransactionCategorizationView, updateSelectedCheckboxTransactionIds, clearExpenseAutomationTransactionsViewPerTabView, clearExpenseAutomationTransactionsView, setEntityRecommendationForLineIdsForCategorization, updateSelectedTransactionId, syncTransactionCategorizationFromDetailSave, backgroundRefetchReviewTab, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } = expenseAutomationTransactionsView.actions;
886
807
  export default expenseAutomationTransactionsView.reducer;
@@ -10,7 +10,7 @@ import { getProjectList } from '../../projectList/projectListSelector';
10
10
  import { getAllSteps } from '../selectorTypes/expenseAutomationViewSelectorTypes';
11
11
  export function getExpenseAutomationTransactionView(state) {
12
12
  const { accountState, classState, classListState, accountListState, expenseAutomationTransactionsViewState, expenseAutomationViewState, projectState, projectListState, transactionState, monthEndCloseChecksState, monthEndCloseChecksViewState, } = state;
13
- const { selectedTransactionCategorizationCompletedSubTab, selectedTransactionCategorizationTab, } = expenseAutomationTransactionsViewState;
13
+ const { selectedTransactionCategorizationTab } = expenseAutomationTransactionsViewState;
14
14
  const { uiState, refreshStatus, saveStatus, markAsNotMiscategorizedStatus, transactionIdsBySelectedPeriod, transactionReviewLocalDataById, selectedCheckBoxTransactionIds, transactionIdsWithUnsavedData, uploadReceiptStatusById, selectedTransactionId, selectedTransactionLineId, } = expenseAutomationTransactionsViewState.transactionCategorizationView[selectedTransactionCategorizationTab];
15
15
  const uncategorizedIncomeExpense = getUncategorizedAccounts(accountState, accountListState, 'accountList');
16
16
  const accountList = getAccountList(accountState, accountListState, 'accountList');
@@ -63,27 +63,10 @@ export function getExpenseAutomationTransactionView(state) {
63
63
  .uiState.totalCount;
64
64
  const totalCountByAutoCat = expenseAutomationTransactionsViewState.transactionCategorizationView
65
65
  .autoCategorized.uiState.totalCount;
66
- // Per-(sub-)tab counts powering pagination, in-list "showing X of Y", and
67
- // any save/refresh round-trips. Sourced from `uiState.totalCount` which
68
- // mirrors the response's `total_count` for whatever tab/sub-tab the user is
69
- // viewing (e.g. only the Manual sub-tab rows for Completed → Manual).
70
66
  const totalCountByTab = {
71
67
  review: monthYearPeriodId != null ? totalCountByReview[monthYearPeriodId] : 0,
72
68
  autoCategorized: monthYearPeriodId != null ? totalCountByAutoCat[monthYearPeriodId] : 0,
73
69
  };
74
- // Parent-tab badge counts. Sourced from `parent_tab_total_count` in the
75
- // listing response and used exclusively by the navbar / tab strip badges.
76
- // Independent of which Completed sub-tab is active so the badge stays
77
- // stable across sub-tab switches.
78
- const parentTotalCountByTab = expenseAutomationTransactionsViewState.parentTotalCountByTab;
79
- const parentTabTotalCountByTab = {
80
- review: monthYearPeriodId != null
81
- ? (parentTotalCountByTab.review[monthYearPeriodId] ?? 0)
82
- : 0,
83
- autoCategorized: monthYearPeriodId != null
84
- ? (parentTotalCountByTab.autoCategorized[monthYearPeriodId] ?? 0)
85
- : 0,
86
- };
87
70
  const fetchStateByTab = {
88
71
  review: {
89
72
  fetchState: expenseAutomationTransactionsViewState.transactionCategorizationView
@@ -125,11 +108,9 @@ export function getExpenseAutomationTransactionView(state) {
125
108
  markAsNotMiscategorizedStatus,
126
109
  completionStatus,
127
110
  totalCountByTab,
128
- parentTabTotalCountByTab,
129
111
  fetchStateByTransactionTabs: fetchStateByTab,
130
112
  uploadReceiptStatusById,
131
113
  selectedTransactionId,
132
114
  selectedTransactionLineId,
133
- selectedTransactionCategorizationCompletedSubTab,
134
115
  };
135
116
  }
@@ -39,6 +39,8 @@ const BULK_UPLOAD_RESULTS_TABS = ['completed', 'unmatched'];
39
39
  export const toBulkUploadResultsTab = (v) => stringToUnion(v.trim().toLowerCase(), BULK_UPLOAD_RESULTS_TABS);
40
40
  const MISSING_RECEIPTS_TABS = ['missing', 'completed', 'unmatched'];
41
41
  export const toMissingReceiptsTab = (v) => stringToUnion(v.trim().toLowerCase(), MISSING_RECEIPTS_TABS);
42
+ const COMPLETED_SUB_TABS = ['all', 'ai_accountant', 'manual'];
43
+ export const toCompletedSubTab = (v) => stringToUnion(v.trim().toLowerCase(), COMPLETED_SUB_TABS);
42
44
  const MATCH_SOURCES = ['ai', 'manual'];
43
45
  export const toMatchSource = (v) => stringToUnion(v.trim().toLowerCase(), MATCH_SOURCES);
44
46
  const BULK_UPLOAD_SORT_KEYS = [
@@ -0,0 +1,113 @@
1
+ import orderBy from 'lodash/orderBy';
2
+ import { stringToUnion } from '../../commonStateTypes/stringToUnion';
3
+ /**
4
+ * View-model helpers for the new Journal Entry table view (see
5
+ * web-components `journalEntryTable`). Keeps presentation-agnostic
6
+ * logic — totals, sort, line-filter — colocated in epic-state so it
7
+ * is testable and reusable.
8
+ */
9
+ // ---------------------------------------------------------------------------
10
+ // Sort keys
11
+ // ---------------------------------------------------------------------------
12
+ export const JOURNAL_ENTRY_SORT_KEYS = [
13
+ 'description',
14
+ 'name',
15
+ 'category',
16
+ 'class',
17
+ 'debit',
18
+ 'credit',
19
+ ];
20
+ export const toJournalEntrySortKey = (v) => stringToUnion(v, JOURNAL_ENTRY_SORT_KEYS);
21
+ export const journalEntryDefaultSortConfig = {
22
+ sortKey: 'description',
23
+ sortOrder: 'ascending',
24
+ };
25
+ /**
26
+ * Sums the `amount.amount` field of every line and returns an `Amount`
27
+ * whose currencyCode/currencySymbol are taken from the first line.
28
+ * Returns `undefined` for an empty list.
29
+ *
30
+ * Mirrors legacy `calculateTotal` in
31
+ * `web-components/src/components/transactionDetail/items/TransactionLinesJournalEntry.tsx`
32
+ * but without the `Object.assign` ceremony and with stable currency carry-over.
33
+ */
34
+ export const sumJournalEntryAmounts = (lines) => {
35
+ if (lines.length === 0) {
36
+ return undefined;
37
+ }
38
+ const first = lines[0].amount;
39
+ let total = 0;
40
+ for (const line of lines) {
41
+ total += line.amount?.amount ?? 0;
42
+ }
43
+ return {
44
+ amount: total,
45
+ currencyCode: first?.currencyCode ?? '',
46
+ currencySymbol: first?.currencySymbol ?? '',
47
+ };
48
+ };
49
+ /**
50
+ * Splits `lines` by `postingType` into debit/credit totals.
51
+ *
52
+ * Fixes the operator-precedence bug from legacy
53
+ * `calculateCombinedTotalAmount` where
54
+ * `totalAmount?.amount ?? 0 + (...) + (...)` parses as
55
+ * `totalAmount?.amount ?? (0 + ... + ...)` so the `(...)`'s only get
56
+ * added when `totalAmount` is nullish. The new implementation just sums
57
+ * every debit (or credit) line including the un/miscategorized ones in
58
+ * one pass, so the result is always the true sum.
59
+ */
60
+ export const journalEntryTotalsByPostingSide = (lines) => {
61
+ const debitLines = [];
62
+ const creditLines = [];
63
+ for (const line of lines) {
64
+ if (line.postingType === 'debit') {
65
+ debitLines.push(line);
66
+ }
67
+ else if (line.postingType === 'credit') {
68
+ creditLines.push(line);
69
+ }
70
+ }
71
+ return {
72
+ debitTotal: sumJournalEntryAmounts(debitLines),
73
+ creditTotal: sumJournalEntryAmounts(creditLines),
74
+ };
75
+ };
76
+ // ---------------------------------------------------------------------------
77
+ // Filter
78
+ // ---------------------------------------------------------------------------
79
+ /**
80
+ * Drops `linked_transaction_line` entries — equivalent to legacy
81
+ * `filterOutLinkedTransactionLine` in `transactionDetail.helpers.ts`.
82
+ */
83
+ export const filterJournalEntryLinesExcludingLinked = (lines) => lines?.filter((line) => line.type !== 'linked_transaction_line') ?? [];
84
+ const sortOrderToLodash = (sortOrder) => sortOrder === 'descending' ? 'desc' : 'asc';
85
+ /**
86
+ * Stable, accessor-driven sort over arbitrary line shapes. Lines that
87
+ * resolve to the same key value preserve their original relative order
88
+ * thanks to lodash's stable `orderBy`.
89
+ *
90
+ * Strings are lower-cased before comparison so the order is predictable
91
+ * across mixed-case data. Numbers (debit/credit) compare directly.
92
+ */
93
+ export const sortJournalEntryLines = (lines, config, accessors) => {
94
+ const accessor = (line) => {
95
+ switch (config.sortKey) {
96
+ case 'description':
97
+ return accessors.description(line).toLowerCase();
98
+ case 'name':
99
+ return accessors.name(line).toLowerCase();
100
+ case 'category':
101
+ return accessors.category(line).toLowerCase();
102
+ case 'class':
103
+ return accessors.class(line).toLowerCase();
104
+ case 'debit':
105
+ return accessors.debit(line);
106
+ case 'credit':
107
+ return accessors.credit(line);
108
+ default:
109
+ return accessors.description(line).toLowerCase();
110
+ }
111
+ };
112
+ return orderBy([...lines], [accessor], [sortOrderToLodash(config.sortOrder)]);
113
+ };
@@ -0,0 +1,243 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { JOURNAL_ENTRY_SORT_KEYS, filterJournalEntryLinesExcludingLinked, journalEntryDefaultSortConfig, journalEntryTotalsByPostingSide, sortJournalEntryLines, sumJournalEntryAmounts, } from './journalEntryLinesViewModel';
3
+ const usd = (amount) => ({
4
+ amount,
5
+ currencyCode: 'USD',
6
+ currencySymbol: '$',
7
+ });
8
+ const debit = (n) => ({
9
+ amount: usd(n),
10
+ postingType: 'debit',
11
+ });
12
+ const credit = (n) => ({
13
+ amount: usd(n),
14
+ postingType: 'credit',
15
+ });
16
+ describe('sumJournalEntryAmounts', () => {
17
+ it('returns undefined for an empty list', () => {
18
+ expect(sumJournalEntryAmounts([])).toBeUndefined();
19
+ });
20
+ it('sums a single line as-is', () => {
21
+ expect(sumJournalEntryAmounts([{ amount: usd(42) }])).toEqual(usd(42));
22
+ });
23
+ it('sums multiple lines preserving the first line currency', () => {
24
+ const total = sumJournalEntryAmounts([
25
+ { amount: usd(10) },
26
+ { amount: usd(20.5) },
27
+ { amount: usd(0.5) },
28
+ ]);
29
+ expect(total).toEqual(usd(31));
30
+ });
31
+ it('treats nullish amount.amount as 0 without crashing', () => {
32
+ const total = sumJournalEntryAmounts([
33
+ { amount: usd(10) },
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
+ { amount: { currencyCode: 'USD', currencySymbol: '$' } },
36
+ { amount: usd(5) },
37
+ ]);
38
+ expect(total).toEqual(usd(15));
39
+ });
40
+ it('uses an empty currency code/symbol when first line lacks them', () => {
41
+ const total = sumJournalEntryAmounts([
42
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
+ { amount: { amount: 7 } },
44
+ { amount: usd(3) },
45
+ ]);
46
+ expect(total).toEqual({ amount: 10, currencyCode: '', currencySymbol: '' });
47
+ });
48
+ });
49
+ describe('journalEntryTotalsByPostingSide', () => {
50
+ it('returns undefined totals for an empty list', () => {
51
+ expect(journalEntryTotalsByPostingSide([])).toEqual({
52
+ debitTotal: undefined,
53
+ creditTotal: undefined,
54
+ });
55
+ });
56
+ it('sums debits and credits separately when both sides present', () => {
57
+ const { debitTotal, creditTotal } = journalEntryTotalsByPostingSide([
58
+ debit(100),
59
+ debit(50),
60
+ credit(120),
61
+ credit(30),
62
+ ]);
63
+ expect(debitTotal).toEqual(usd(150));
64
+ expect(creditTotal).toEqual(usd(150));
65
+ });
66
+ it('returns only the populated side when one side is missing', () => {
67
+ const onlyDebits = journalEntryTotalsByPostingSide([debit(10), debit(20)]);
68
+ expect(onlyDebits.debitTotal).toEqual(usd(30));
69
+ expect(onlyDebits.creditTotal).toBeUndefined();
70
+ const onlyCredits = journalEntryTotalsByPostingSide([credit(99)]);
71
+ expect(onlyCredits.creditTotal).toEqual(usd(99));
72
+ expect(onlyCredits.debitTotal).toBeUndefined();
73
+ });
74
+ /**
75
+ * Regression test for the operator-precedence bug in legacy
76
+ * `calculateCombinedTotalAmount` where
77
+ * `totalAmount?.amount ?? 0 + (uncategorized?.amount ?? 0) + (miscategorized?.amount ?? 0)`
78
+ * parses as `totalAmount?.amount ?? (0 + ... + ...)`. With the bug,
79
+ * an existing `totalAmount` would short-circuit and the uncat/miscat
80
+ * pieces would be ignored. The new implementation always adds every
81
+ * matching line, so 100 (cat) + 25 (uncat) + 10 (miscat) = 135.
82
+ */
83
+ it('does not drop uncategorized/miscategorized contributions (precedence-bug regression)', () => {
84
+ const { debitTotal } = journalEntryTotalsByPostingSide([
85
+ debit(100),
86
+ debit(25),
87
+ debit(10),
88
+ ]);
89
+ expect(debitTotal).toEqual(usd(135));
90
+ });
91
+ it('ignores lines with neither debit nor credit posting type', () => {
92
+ const totals = journalEntryTotalsByPostingSide([
93
+ debit(40),
94
+ credit(40),
95
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
96
+ { amount: usd(999), postingType: 'unknown' },
97
+ ]);
98
+ expect(totals.debitTotal).toEqual(usd(40));
99
+ expect(totals.creditTotal).toEqual(usd(40));
100
+ });
101
+ });
102
+ describe('filterJournalEntryLinesExcludingLinked', () => {
103
+ it('returns [] for undefined input', () => {
104
+ expect(filterJournalEntryLinesExcludingLinked(undefined)).toEqual([]);
105
+ });
106
+ it('filters out linked_transaction_line entries', () => {
107
+ const lines = [
108
+ { id: 'a', type: 'journal_entry_transaction_line' },
109
+ { id: 'b', type: 'linked_transaction_line' },
110
+ { id: 'c', type: 'journal_entry_transaction_line' },
111
+ ];
112
+ const filtered = filterJournalEntryLinesExcludingLinked(lines);
113
+ expect(filtered).toHaveLength(2);
114
+ expect(filtered[0].id).toBe('a');
115
+ expect(filtered[1].id).toBe('c');
116
+ });
117
+ it('returns input unchanged when no linked lines exist', () => {
118
+ const lines = [
119
+ { id: 'a', type: 'journal_entry_transaction_line' },
120
+ { id: 'b', type: 'journal_entry_transaction_line' },
121
+ ];
122
+ expect(filterJournalEntryLinesExcludingLinked(lines)).toHaveLength(2);
123
+ });
124
+ });
125
+ describe('sortJournalEntryLines', () => {
126
+ const accessors = {
127
+ description: (r) => r.description,
128
+ name: (r) => r.name,
129
+ category: (r) => r.category,
130
+ class: (r) => r.class,
131
+ debit: (r) => r.debit,
132
+ credit: (r) => r.credit,
133
+ };
134
+ const rows = [
135
+ {
136
+ id: '1',
137
+ description: 'Beta',
138
+ name: 'Acme',
139
+ category: 'Rent',
140
+ class: 'Ops',
141
+ debit: 100,
142
+ credit: 0,
143
+ },
144
+ {
145
+ id: '2',
146
+ description: 'alpha',
147
+ name: 'Beta Co',
148
+ category: 'Travel',
149
+ class: 'GA',
150
+ debit: 200,
151
+ credit: 0,
152
+ },
153
+ {
154
+ id: '3',
155
+ description: 'Gamma',
156
+ name: 'acme',
157
+ category: 'Rent',
158
+ class: 'Sales',
159
+ debit: 0,
160
+ credit: 50,
161
+ },
162
+ ];
163
+ it('exposes every supported sort key via JOURNAL_ENTRY_SORT_KEYS', () => {
164
+ expect([...JOURNAL_ENTRY_SORT_KEYS]).toEqual([
165
+ 'description',
166
+ 'name',
167
+ 'category',
168
+ 'class',
169
+ 'debit',
170
+ 'credit',
171
+ ]);
172
+ });
173
+ it('sorts by description case-insensitively ascending by default', () => {
174
+ const sorted = sortJournalEntryLines(rows, journalEntryDefaultSortConfig, accessors);
175
+ expect(sorted.map((r) => r.id)).toEqual(['2', '1', '3']);
176
+ });
177
+ it('sorts by description descending when configured', () => {
178
+ const config = {
179
+ sortKey: 'description',
180
+ sortOrder: 'descending',
181
+ };
182
+ const sorted = sortJournalEntryLines(rows, config, accessors);
183
+ expect(sorted.map((r) => r.id)).toEqual(['3', '1', '2']);
184
+ });
185
+ it.each([
186
+ ['name', 'ascending', ['1', '3', '2']],
187
+ ['name', 'descending', ['2', '1', '3']],
188
+ ['category', 'ascending', ['1', '3', '2']],
189
+ ['class', 'ascending', ['2', '1', '3']],
190
+ ['debit', 'ascending', ['3', '1', '2']],
191
+ ['debit', 'descending', ['2', '1', '3']],
192
+ ['credit', 'ascending', ['1', '2', '3']],
193
+ ['credit', 'descending', ['3', '1', '2']],
194
+ ])('sorts by %s %s producing the expected order', (key, order, expected) => {
195
+ const config = {
196
+ sortKey: key,
197
+ sortOrder: order,
198
+ };
199
+ const sorted = sortJournalEntryLines(rows, config, accessors);
200
+ expect(sorted.map((r) => r.id)).toEqual([...expected]);
201
+ });
202
+ it('keeps stable order for ties on the sort key', () => {
203
+ const tied = [
204
+ {
205
+ id: 'a',
206
+ description: 'same',
207
+ name: '',
208
+ category: '',
209
+ class: '',
210
+ debit: 0,
211
+ credit: 0,
212
+ },
213
+ {
214
+ id: 'b',
215
+ description: 'same',
216
+ name: '',
217
+ category: '',
218
+ class: '',
219
+ debit: 0,
220
+ credit: 0,
221
+ },
222
+ {
223
+ id: 'c',
224
+ description: 'same',
225
+ name: '',
226
+ category: '',
227
+ class: '',
228
+ debit: 0,
229
+ credit: 0,
230
+ },
231
+ ];
232
+ const sortedAsc = sortJournalEntryLines(tied, { sortKey: 'description', sortOrder: 'ascending' }, accessors);
233
+ expect(sortedAsc.map((r) => r.id)).toEqual(['a', 'b', 'c']);
234
+ const sortedDesc = sortJournalEntryLines(tied, { sortKey: 'description', sortOrder: 'descending' }, accessors);
235
+ expect(sortedDesc.map((r) => r.id)).toEqual(['a', 'b', 'c']);
236
+ });
237
+ it('does not mutate the input array', () => {
238
+ const input = [...rows];
239
+ const before = input.map((r) => r.id);
240
+ sortJournalEntryLines(input, { sortKey: 'description', sortOrder: 'descending' }, accessors);
241
+ expect(input.map((r) => r.id)).toEqual(before);
242
+ });
243
+ });