@dizzlkheinz/ynab-mcpb 0.18.0 → 0.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -0
- package/CLAUDE.md +1 -1
- package/README.md +30 -136
- package/dist/bundle/index.cjs +40 -40
- package/dist/tools/deltaSupport.js +13 -0
- package/dist/tools/reconciliation/executor.js +0 -8
- package/dist/tools/transactionTools.js +240 -46
- package/docs/technical/receipt-itemization-spec.md +181 -0
- package/package.json +1 -1
- package/src/tools/__tests__/transactionTools.integration.test.ts +11 -1
- package/src/tools/__tests__/transactionTools.test.ts +647 -0
- package/src/tools/deltaSupport.ts +18 -0
- package/src/tools/reconciliation/__tests__/executor.integration.test.ts +12 -26
- package/src/tools/reconciliation/__tests__/executor.test.ts +36 -31
- package/src/tools/reconciliation/executor.ts +1 -26
- package/src/tools/transactionTools.ts +362 -53
|
@@ -78,9 +78,12 @@ describeIntegration('Reconciliation Executor - Bulk Create Integration', () => {
|
|
|
78
78
|
);
|
|
79
79
|
|
|
80
80
|
it(
|
|
81
|
-
'
|
|
81
|
+
'creates transactions without import_id to allow bank matching',
|
|
82
82
|
{ meta: { tier: 'domain', domain: 'reconciliation' } },
|
|
83
83
|
async function () {
|
|
84
|
+
// Note: import_id is intentionally omitted from reconciliation-created transactions
|
|
85
|
+
// so they can match with bank-imported transactions. YNAB-side duplicate detection
|
|
86
|
+
// is no longer used; the reconciliation matcher handles duplicate prevention.
|
|
84
87
|
const analysis = buildIntegrationAnalysis(accountSnapshot, 2, 9);
|
|
85
88
|
const params = buildIntegrationParams(
|
|
86
89
|
accountId,
|
|
@@ -88,23 +91,7 @@ describeIntegration('Reconciliation Executor - Bulk Create Integration', () => {
|
|
|
88
91
|
analysis.summary.target_statement_balance,
|
|
89
92
|
);
|
|
90
93
|
|
|
91
|
-
const
|
|
92
|
-
() =>
|
|
93
|
-
executeReconciliation({
|
|
94
|
-
ynabAPI,
|
|
95
|
-
analysis,
|
|
96
|
-
params,
|
|
97
|
-
budgetId,
|
|
98
|
-
accountId,
|
|
99
|
-
initialAccount: accountSnapshot,
|
|
100
|
-
currencyCode: 'USD',
|
|
101
|
-
}),
|
|
102
|
-
this,
|
|
103
|
-
);
|
|
104
|
-
if (!firstRun) return;
|
|
105
|
-
trackCreatedTransactions(firstRun);
|
|
106
|
-
|
|
107
|
-
const duplicateAttempt = await skipOnRateLimit(
|
|
94
|
+
const result = await skipOnRateLimit(
|
|
108
95
|
() =>
|
|
109
96
|
executeReconciliation({
|
|
110
97
|
ynabAPI,
|
|
@@ -117,15 +104,14 @@ describeIntegration('Reconciliation Executor - Bulk Create Integration', () => {
|
|
|
117
104
|
}),
|
|
118
105
|
this,
|
|
119
106
|
);
|
|
120
|
-
if (!
|
|
121
|
-
|
|
107
|
+
if (!result) return;
|
|
108
|
+
trackCreatedTransactions(result);
|
|
109
|
+
if (containsRateLimitFailure(result)) return;
|
|
122
110
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
)
|
|
126
|
-
expect(
|
|
127
|
-
expect(duplicateAttempt.bulk_operation_details?.duplicates_detected).toBeGreaterThan(0);
|
|
128
|
-
expect(duplicateAttempt.summary.transactions_created).toBe(0);
|
|
111
|
+
// Verify transactions were created successfully
|
|
112
|
+
expect(result.summary.transactions_created).toBe(2);
|
|
113
|
+
// Verify no YNAB-side duplicate detection occurred (because no import_id)
|
|
114
|
+
expect(result.bulk_operation_details?.duplicates_detected).toBe(0);
|
|
129
115
|
},
|
|
130
116
|
60000,
|
|
131
117
|
);
|
|
@@ -484,9 +484,10 @@ describe('executeReconciliation - bulk create mode', () => {
|
|
|
484
484
|
account_id: txn.account_id,
|
|
485
485
|
amount: txn.amount,
|
|
486
486
|
date: txn.date,
|
|
487
|
+
payee_name: txn.payee_name,
|
|
488
|
+
memo: txn.memo,
|
|
487
489
|
cleared: 'cleared',
|
|
488
490
|
approved: true,
|
|
489
|
-
import_id: txn.import_id, // Include import_id for correlation
|
|
490
491
|
}));
|
|
491
492
|
return { data: { transactions, duplicate_import_ids: [] } };
|
|
492
493
|
});
|
|
@@ -638,11 +639,12 @@ describe('executeReconciliation - bulk create mode', () => {
|
|
|
638
639
|
account_id: txn.account_id,
|
|
639
640
|
amount: txn.amount,
|
|
640
641
|
date: txn.date,
|
|
642
|
+
payee_name: txn.payee_name,
|
|
643
|
+
memo: txn.memo,
|
|
641
644
|
cleared: 'cleared',
|
|
642
645
|
approved: true,
|
|
643
|
-
import_id: txn.import_id, // Include import_id for correlation
|
|
644
646
|
}));
|
|
645
|
-
return { data: { transactions } };
|
|
647
|
+
return { data: { transactions, duplicate_import_ids: [] } };
|
|
646
648
|
});
|
|
647
649
|
|
|
648
650
|
const result = await executeReconciliation({
|
|
@@ -690,33 +692,35 @@ describe('executeReconciliation - bulk create mode', () => {
|
|
|
690
692
|
).rejects.toMatchObject({ status: 404 });
|
|
691
693
|
});
|
|
692
694
|
|
|
693
|
-
it('
|
|
694
|
-
|
|
695
|
+
it('creates all transactions without import_id (no YNAB-side duplicate detection)', async () => {
|
|
696
|
+
// Note: import_id is intentionally omitted from reconciliation-created transactions
|
|
697
|
+
// so they can match with bank-imported transactions. This means YNAB won't detect
|
|
698
|
+
// duplicates via import_id - the reconciliation matcher is responsible for that.
|
|
699
|
+
// Use amount of 100 to avoid early balance halting (tolerance is 10 milliunits)
|
|
700
|
+
const analysis = buildBulkAnalysis(3, 100);
|
|
695
701
|
const params = buildBulkParams(analysis.summary.target_statement_balance);
|
|
696
702
|
const initialAccount = { ...defaultAccountSnapshot };
|
|
697
703
|
const { api, mocks } = createMockYnabAPI(initialAccount);
|
|
698
704
|
|
|
699
705
|
mocks.createTransactions.mockImplementation(async (_budgetId, body: any) => {
|
|
700
|
-
const transactions = (body.transactions ?? []).map((txn: any, index: number) => {
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
}
|
|
714
|
-
const filtered = transactions.filter(Boolean);
|
|
715
|
-
const duplicateImportId = body.transactions?.[1]?.import_id;
|
|
706
|
+
const transactions = (body.transactions ?? []).map((txn: any, index: number) => ({
|
|
707
|
+
id: `created-${index}`,
|
|
708
|
+
account_id: txn.account_id,
|
|
709
|
+
amount: txn.amount,
|
|
710
|
+
date: txn.date,
|
|
711
|
+
payee_name: txn.payee_name,
|
|
712
|
+
memo: txn.memo,
|
|
713
|
+
cleared: 'cleared',
|
|
714
|
+
approved: true,
|
|
715
|
+
}));
|
|
716
|
+
// Verify no import_id is being sent
|
|
717
|
+
for (const txn of body.transactions ?? []) {
|
|
718
|
+
expect(txn.import_id).toBeUndefined();
|
|
719
|
+
}
|
|
716
720
|
return {
|
|
717
721
|
data: {
|
|
718
|
-
transactions
|
|
719
|
-
duplicate_import_ids:
|
|
722
|
+
transactions,
|
|
723
|
+
duplicate_import_ids: [],
|
|
720
724
|
},
|
|
721
725
|
};
|
|
722
726
|
});
|
|
@@ -731,10 +735,9 @@ describe('executeReconciliation - bulk create mode', () => {
|
|
|
731
735
|
currencyCode: 'USD',
|
|
732
736
|
});
|
|
733
737
|
|
|
734
|
-
|
|
735
|
-
expect(
|
|
736
|
-
expect(result.
|
|
737
|
-
expect(result.summary.transactions_created).toBe(2);
|
|
738
|
+
// Without import_id, YNAB creates all transactions (no duplicate detection)
|
|
739
|
+
expect(result.bulk_operation_details?.duplicates_detected).toBe(0);
|
|
740
|
+
expect(result.summary.transactions_created).toBe(3);
|
|
738
741
|
});
|
|
739
742
|
|
|
740
743
|
it('honors halting logic when balance aligns mid-batch', async () => {
|
|
@@ -749,11 +752,12 @@ describe('executeReconciliation - bulk create mode', () => {
|
|
|
749
752
|
account_id: txn.account_id,
|
|
750
753
|
amount: txn.amount,
|
|
751
754
|
date: txn.date,
|
|
755
|
+
payee_name: txn.payee_name,
|
|
756
|
+
memo: txn.memo,
|
|
752
757
|
cleared: 'cleared',
|
|
753
758
|
approved: true,
|
|
754
|
-
import_id: txn.import_id, // Include import_id for correlation
|
|
755
759
|
}));
|
|
756
|
-
return { data: { transactions } };
|
|
760
|
+
return { data: { transactions, duplicate_import_ids: [] } };
|
|
757
761
|
});
|
|
758
762
|
|
|
759
763
|
const result = await executeReconciliation({
|
|
@@ -794,11 +798,12 @@ describe('executeReconciliation - bulk create mode', () => {
|
|
|
794
798
|
account_id: txn.account_id,
|
|
795
799
|
amount: txn.amount,
|
|
796
800
|
date: txn.date,
|
|
801
|
+
payee_name: txn.payee_name,
|
|
802
|
+
memo: txn.memo,
|
|
797
803
|
cleared: 'cleared',
|
|
798
804
|
approved: true,
|
|
799
|
-
import_id: txn.import_id,
|
|
800
805
|
}));
|
|
801
|
-
return { data: { transactions } };
|
|
806
|
+
return { data: { transactions, duplicate_import_ids: [] } };
|
|
802
807
|
});
|
|
803
808
|
|
|
804
809
|
const result = await executeReconciliation({
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { createHash } from 'crypto';
|
|
2
1
|
import type * as ynab from 'ynab';
|
|
3
2
|
import type { SaveTransaction } from 'ynab/dist/models/SaveTransaction.js';
|
|
4
3
|
import { YNABAPIError, YNABErrorCode } from '../../server/errorHandler.js';
|
|
@@ -131,30 +130,6 @@ interface PreparedBulkCreateEntry {
|
|
|
131
130
|
correlationKey: string;
|
|
132
131
|
}
|
|
133
132
|
|
|
134
|
-
/**
|
|
135
|
-
* Generates a deterministic import_id for reconciliation-created transactions.
|
|
136
|
-
*
|
|
137
|
-
* Uses a dedicated `YNAB:bulk:` prefix to distinguish reconciliation-created transactions
|
|
138
|
-
* from manual bulk creates. This namespace separation is intentional:
|
|
139
|
-
* - Reconciliation operations are automated and system-generated
|
|
140
|
-
* - Manual bulk creates via create_transactions tool can use custom import_id formats
|
|
141
|
-
* - Both interact with YNAB's global duplicate detection via the same import_id mechanism
|
|
142
|
-
*
|
|
143
|
-
* The hash-based correlation in transactionTools.ts uses `hash:` prefix for correlation
|
|
144
|
-
* (when no import_id provided), which is separate from this import_id generation.
|
|
145
|
-
*/
|
|
146
|
-
function generateBulkImportId(
|
|
147
|
-
accountId: string,
|
|
148
|
-
date: string,
|
|
149
|
-
amountMilli: number,
|
|
150
|
-
payee?: string | null,
|
|
151
|
-
): string {
|
|
152
|
-
const normalizedPayee = (payee ?? '').trim().toLowerCase();
|
|
153
|
-
const raw = `${accountId}|${date}|${amountMilli}|${normalizedPayee}`;
|
|
154
|
-
const digest = createHash('sha256').update(raw).digest('hex').slice(0, 24);
|
|
155
|
-
return `YNAB:bulk:${digest}`;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
133
|
function parseISODate(dateStr: string | undefined): Date | undefined {
|
|
159
134
|
if (!dateStr) return undefined;
|
|
160
135
|
const d = new Date(dateStr);
|
|
@@ -313,7 +288,7 @@ export async function executeReconciliation(options: ExecutionOptions): Promise<
|
|
|
313
288
|
memo: truncateMemo(bankTxn.memo),
|
|
314
289
|
cleared: 'cleared',
|
|
315
290
|
approved: true,
|
|
316
|
-
|
|
291
|
+
// Note: import_id intentionally omitted so transactions can match with bank imports
|
|
317
292
|
};
|
|
318
293
|
const correlationKey = generateCorrelationKey(toCorrelationPayload(saveTransaction));
|
|
319
294
|
return {
|
|
@@ -535,10 +535,7 @@ function finalizeResponse(response: BulkCreateResponse): BulkCreateResponse {
|
|
|
535
535
|
const ReceiptSplitItemSchema = z
|
|
536
536
|
.object({
|
|
537
537
|
name: z.string().min(1, 'Item name is required'),
|
|
538
|
-
amount: z
|
|
539
|
-
.number()
|
|
540
|
-
.finite('Item amount must be a finite number')
|
|
541
|
-
.refine((value) => value >= 0, 'Item amount must be zero or greater'),
|
|
538
|
+
amount: z.number().finite('Item amount must be a finite number'),
|
|
542
539
|
quantity: z
|
|
543
540
|
.number()
|
|
544
541
|
.finite('Quantity must be a finite number')
|
|
@@ -571,10 +568,7 @@ export const CreateReceiptSplitTransactionSchema = z
|
|
|
571
568
|
.finite('Receipt subtotal must be a finite number')
|
|
572
569
|
.refine((value) => value >= 0, 'Receipt subtotal must be zero or greater')
|
|
573
570
|
.optional(),
|
|
574
|
-
receipt_tax: z
|
|
575
|
-
.number()
|
|
576
|
-
.finite('Receipt tax must be a finite number')
|
|
577
|
-
.refine((value) => value >= 0, 'Receipt tax must be zero or greater'),
|
|
571
|
+
receipt_tax: z.number().finite('Receipt tax must be a finite number'),
|
|
578
572
|
receipt_total: z
|
|
579
573
|
.number()
|
|
580
574
|
.finite('Receipt total must be a finite number')
|
|
@@ -1133,32 +1127,350 @@ function buildItemMemo(item: {
|
|
|
1133
1127
|
return item.name;
|
|
1134
1128
|
}
|
|
1135
1129
|
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1130
|
+
/**
|
|
1131
|
+
* Constants for smart collapse logic
|
|
1132
|
+
*/
|
|
1133
|
+
const BIG_TICKET_THRESHOLD_MILLIUNITS = 50000; // $50.00
|
|
1134
|
+
const COLLAPSE_THRESHOLD = 5; // Collapse if 5 or more remaining items
|
|
1135
|
+
const MAX_ITEMS_PER_MEMO = 5;
|
|
1136
|
+
const MAX_MEMO_LENGTH = 150;
|
|
1137
|
+
|
|
1138
|
+
/**
|
|
1139
|
+
* Applies smart collapse logic to receipt items according to the specification:
|
|
1140
|
+
* 1. Extract special items (big ticket, returns, discounts)
|
|
1141
|
+
* 2. Apply threshold to remaining items
|
|
1142
|
+
* 3. Collapse by category if needed
|
|
1143
|
+
* 4. Handle tax allocation
|
|
1144
|
+
*/
|
|
1145
|
+
function applySmartCollapseLogic(
|
|
1146
|
+
categoryCalculations: ReceiptCategoryCalculation[],
|
|
1147
|
+
taxMilliunits: number,
|
|
1148
|
+
): SubtransactionInput[] {
|
|
1149
|
+
// Step 1: Extract special items and classify remaining items
|
|
1150
|
+
interface SpecialItem {
|
|
1151
|
+
item: ReceiptCategoryCalculation['items'][0];
|
|
1152
|
+
category_id: string;
|
|
1153
|
+
category_name: string | undefined;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
interface CategoryItems {
|
|
1157
|
+
category_id: string;
|
|
1158
|
+
category_name: string | undefined;
|
|
1159
|
+
items: ReceiptCategoryCalculation['items'][0][];
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
const specialItems: SpecialItem[] = [];
|
|
1163
|
+
const remainingItemsByCategory: CategoryItems[] = [];
|
|
1164
|
+
|
|
1165
|
+
for (const category of categoryCalculations) {
|
|
1166
|
+
const categorySpecials: ReceiptCategoryCalculation['items'][0][] = [];
|
|
1167
|
+
const categoryRemaining: ReceiptCategoryCalculation['items'][0][] = [];
|
|
1168
|
+
|
|
1169
|
+
for (const item of category.items) {
|
|
1170
|
+
const isNegative = item.amount_milliunits < 0;
|
|
1171
|
+
const unitPrice = item.quantity
|
|
1172
|
+
? item.amount_milliunits / item.quantity
|
|
1173
|
+
: item.amount_milliunits;
|
|
1174
|
+
const isBigTicket = unitPrice > BIG_TICKET_THRESHOLD_MILLIUNITS;
|
|
1175
|
+
|
|
1176
|
+
if (isNegative || isBigTicket) {
|
|
1177
|
+
categorySpecials.push(item);
|
|
1178
|
+
} else {
|
|
1179
|
+
categoryRemaining.push(item);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// Add specials to the special items list (preserving category order)
|
|
1184
|
+
for (const item of categorySpecials) {
|
|
1185
|
+
specialItems.push({
|
|
1186
|
+
item,
|
|
1187
|
+
category_id: category.category_id,
|
|
1188
|
+
category_name: category.category_name,
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
// Track remaining items by category
|
|
1193
|
+
if (categoryRemaining.length > 0) {
|
|
1194
|
+
remainingItemsByCategory.push({
|
|
1195
|
+
category_id: category.category_id,
|
|
1196
|
+
category_name: category.category_name,
|
|
1197
|
+
items: categoryRemaining,
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// Step 2: Count total remaining positive items
|
|
1203
|
+
const totalRemainingItems = remainingItemsByCategory.reduce(
|
|
1204
|
+
(sum, cat) => sum + cat.items.length,
|
|
1205
|
+
0,
|
|
1206
|
+
);
|
|
1207
|
+
|
|
1208
|
+
// Step 3: Decide whether to collapse
|
|
1209
|
+
const shouldCollapse = totalRemainingItems >= COLLAPSE_THRESHOLD;
|
|
1210
|
+
|
|
1211
|
+
// Build subtransactions
|
|
1212
|
+
const subtransactions: SubtransactionInput[] = [];
|
|
1213
|
+
|
|
1214
|
+
// Add special items first (returns, discounts, big tickets)
|
|
1215
|
+
for (const special of specialItems) {
|
|
1216
|
+
const memo = buildItemMemo({
|
|
1217
|
+
name: special.item.name,
|
|
1218
|
+
quantity: special.item.quantity,
|
|
1219
|
+
memo: special.item.memo,
|
|
1220
|
+
});
|
|
1221
|
+
const payload: SubtransactionInput = {
|
|
1222
|
+
amount: -special.item.amount_milliunits,
|
|
1223
|
+
category_id: special.category_id,
|
|
1224
|
+
};
|
|
1225
|
+
if (memo) payload.memo = memo;
|
|
1226
|
+
subtransactions.push(payload);
|
|
1144
1227
|
}
|
|
1145
1228
|
|
|
1146
|
-
|
|
1147
|
-
|
|
1229
|
+
// Add remaining items (collapsed or itemized)
|
|
1230
|
+
if (shouldCollapse) {
|
|
1231
|
+
// Collapse by category
|
|
1232
|
+
for (const categoryGroup of remainingItemsByCategory) {
|
|
1233
|
+
const collapsedSubtransactions = collapseItemsByCategory(categoryGroup);
|
|
1234
|
+
subtransactions.push(...collapsedSubtransactions);
|
|
1235
|
+
}
|
|
1236
|
+
} else {
|
|
1237
|
+
// Itemize each remaining item individually
|
|
1238
|
+
for (const categoryGroup of remainingItemsByCategory) {
|
|
1239
|
+
for (const item of categoryGroup.items) {
|
|
1240
|
+
const memo = buildItemMemo({
|
|
1241
|
+
name: item.name,
|
|
1242
|
+
quantity: item.quantity,
|
|
1243
|
+
memo: item.memo,
|
|
1244
|
+
});
|
|
1245
|
+
const payload: SubtransactionInput = {
|
|
1246
|
+
amount: -item.amount_milliunits,
|
|
1247
|
+
category_id: categoryGroup.category_id,
|
|
1248
|
+
};
|
|
1249
|
+
if (memo) payload.memo = memo;
|
|
1250
|
+
subtransactions.push(payload);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1148
1253
|
}
|
|
1149
1254
|
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1255
|
+
// Step 4: Handle tax allocation
|
|
1256
|
+
const taxSubtransactions = allocateTax(categoryCalculations, taxMilliunits);
|
|
1257
|
+
subtransactions.push(...taxSubtransactions);
|
|
1258
|
+
|
|
1259
|
+
return subtransactions;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
/**
|
|
1263
|
+
* Collapses items within a category into groups of up to MAX_ITEMS_PER_MEMO
|
|
1264
|
+
*/
|
|
1265
|
+
function collapseItemsByCategory(categoryGroup: {
|
|
1266
|
+
category_id: string;
|
|
1267
|
+
category_name: string | undefined;
|
|
1268
|
+
items: ReceiptCategoryCalculation['items'][0][];
|
|
1269
|
+
}): SubtransactionInput[] {
|
|
1270
|
+
const subtransactions: SubtransactionInput[] = [];
|
|
1271
|
+
const items = categoryGroup.items;
|
|
1272
|
+
|
|
1273
|
+
let currentBatch: ReceiptCategoryCalculation['items'][0][] = [];
|
|
1274
|
+
let currentBatchTotal = 0;
|
|
1275
|
+
|
|
1276
|
+
for (const item of items) {
|
|
1277
|
+
// Check if we've hit the max items per memo
|
|
1278
|
+
if (currentBatch.length >= MAX_ITEMS_PER_MEMO) {
|
|
1279
|
+
// Flush current batch
|
|
1280
|
+
const memo = buildCollapsedMemo(currentBatch);
|
|
1281
|
+
subtransactions.push({
|
|
1282
|
+
amount: -currentBatchTotal,
|
|
1283
|
+
category_id: categoryGroup.category_id,
|
|
1284
|
+
memo,
|
|
1285
|
+
});
|
|
1286
|
+
currentBatch = [];
|
|
1287
|
+
currentBatchTotal = 0;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
// Try adding this item to the current batch
|
|
1291
|
+
const testBatch = [...currentBatch, item];
|
|
1292
|
+
const testMemo = buildCollapsedMemo(testBatch);
|
|
1293
|
+
|
|
1294
|
+
if (testMemo.length <= MAX_MEMO_LENGTH) {
|
|
1295
|
+
// Fits - add to batch
|
|
1296
|
+
currentBatch.push(item);
|
|
1297
|
+
currentBatchTotal += item.amount_milliunits;
|
|
1154
1298
|
} else {
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1299
|
+
// Doesn't fit - flush current batch and start new one
|
|
1300
|
+
if (currentBatch.length > 0) {
|
|
1301
|
+
const memo = buildCollapsedMemo(currentBatch);
|
|
1302
|
+
subtransactions.push({
|
|
1303
|
+
amount: -currentBatchTotal,
|
|
1304
|
+
category_id: categoryGroup.category_id,
|
|
1305
|
+
memo,
|
|
1306
|
+
});
|
|
1307
|
+
currentBatch = [item];
|
|
1308
|
+
currentBatchTotal = item.amount_milliunits;
|
|
1309
|
+
} else {
|
|
1310
|
+
// Edge case: single item is too long, use it anyway
|
|
1311
|
+
currentBatch = [item];
|
|
1312
|
+
currentBatchTotal = item.amount_milliunits;
|
|
1313
|
+
}
|
|
1160
1314
|
}
|
|
1161
|
-
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// Flush remaining batch
|
|
1318
|
+
if (currentBatch.length > 0) {
|
|
1319
|
+
const memo = buildCollapsedMemo(currentBatch);
|
|
1320
|
+
subtransactions.push({
|
|
1321
|
+
amount: -currentBatchTotal,
|
|
1322
|
+
category_id: categoryGroup.category_id,
|
|
1323
|
+
memo,
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
return subtransactions;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/**
|
|
1331
|
+
* Builds a collapsed memo from a list of items
|
|
1332
|
+
* Format: "Item1 $X.XX, Item2 $Y.YY, Item3 $Z.ZZ"
|
|
1333
|
+
* Truncates with "..." if needed
|
|
1334
|
+
*/
|
|
1335
|
+
function buildCollapsedMemo(items: ReceiptCategoryCalculation['items'][0][]): string {
|
|
1336
|
+
const parts: string[] = [];
|
|
1337
|
+
let currentLength = 0;
|
|
1338
|
+
|
|
1339
|
+
for (let i = 0; i < items.length; i++) {
|
|
1340
|
+
const item = items[i];
|
|
1341
|
+
if (!item) continue;
|
|
1342
|
+
const amount = milliunitsToAmount(item.amount_milliunits);
|
|
1343
|
+
const itemStr = `${item.name} $${amount.toFixed(2)}`;
|
|
1344
|
+
const separator = i > 0 ? ', ' : '';
|
|
1345
|
+
const testLength = currentLength + separator.length + itemStr.length;
|
|
1346
|
+
|
|
1347
|
+
// Check if adding this item would exceed limit
|
|
1348
|
+
if (parts.length > 0 && testLength + 4 > MAX_MEMO_LENGTH) {
|
|
1349
|
+
// Would exceed - stop here and add "..."
|
|
1350
|
+
break;
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
parts.push(itemStr);
|
|
1354
|
+
currentLength = testLength;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
let result = parts.join(', ');
|
|
1358
|
+
|
|
1359
|
+
// Add "..." if we didn't include all items
|
|
1360
|
+
if (parts.length < items.length) {
|
|
1361
|
+
result += '...';
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
return result;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
/**
|
|
1368
|
+
* Allocates tax across categories
|
|
1369
|
+
* - Positive categories get proportional tax subtransactions
|
|
1370
|
+
* - Negative tax creates a single tax refund subtransaction
|
|
1371
|
+
*/
|
|
1372
|
+
function allocateTax(
|
|
1373
|
+
categoryCalculations: ReceiptCategoryCalculation[],
|
|
1374
|
+
taxMilliunits: number,
|
|
1375
|
+
): SubtransactionInput[] {
|
|
1376
|
+
const subtransactions: SubtransactionInput[] = [];
|
|
1377
|
+
|
|
1378
|
+
// Handle tax = 0
|
|
1379
|
+
if (taxMilliunits === 0) {
|
|
1380
|
+
return subtransactions;
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// Handle negative tax (refund)
|
|
1384
|
+
if (taxMilliunits < 0) {
|
|
1385
|
+
// Find category with largest return
|
|
1386
|
+
let largestReturnCategory: ReceiptCategoryCalculation | undefined = undefined;
|
|
1387
|
+
let largestReturnAmount = 0;
|
|
1388
|
+
|
|
1389
|
+
for (const category of categoryCalculations) {
|
|
1390
|
+
const categoryReturnAmount = category.items
|
|
1391
|
+
.filter((item) => item.amount_milliunits < 0)
|
|
1392
|
+
.reduce((sum, item) => sum + Math.abs(item.amount_milliunits), 0);
|
|
1393
|
+
|
|
1394
|
+
if (categoryReturnAmount > largestReturnAmount) {
|
|
1395
|
+
largestReturnAmount = categoryReturnAmount;
|
|
1396
|
+
largestReturnCategory = category;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// Default to first category if no returns found
|
|
1401
|
+
if (!largestReturnCategory) {
|
|
1402
|
+
largestReturnCategory = categoryCalculations[0];
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
if (largestReturnCategory) {
|
|
1406
|
+
subtransactions.push({
|
|
1407
|
+
amount: -taxMilliunits,
|
|
1408
|
+
category_id: largestReturnCategory.category_id,
|
|
1409
|
+
memo: 'Tax refund',
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
return subtransactions;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
// Positive tax - allocate proportionally to positive categories only
|
|
1417
|
+
const positiveCategorySubtotals = categoryCalculations
|
|
1418
|
+
.map((cat) => ({
|
|
1419
|
+
category: cat,
|
|
1420
|
+
positiveSubtotal: cat.items
|
|
1421
|
+
.filter((item) => item.amount_milliunits > 0)
|
|
1422
|
+
.reduce((sum, item) => sum + item.amount_milliunits, 0),
|
|
1423
|
+
}))
|
|
1424
|
+
.filter((x) => x.positiveSubtotal > 0);
|
|
1425
|
+
|
|
1426
|
+
if (positiveCategorySubtotals.length === 0) {
|
|
1427
|
+
// No positive items, no tax allocation
|
|
1428
|
+
return subtransactions;
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
const totalPositiveSubtotal = positiveCategorySubtotals.reduce(
|
|
1432
|
+
(sum, x) => sum + x.positiveSubtotal,
|
|
1433
|
+
0,
|
|
1434
|
+
);
|
|
1435
|
+
|
|
1436
|
+
// Distribute tax using largest remainder method
|
|
1437
|
+
let allocatedTax = 0;
|
|
1438
|
+
const taxAllocations: {
|
|
1439
|
+
category: ReceiptCategoryCalculation;
|
|
1440
|
+
taxAmount: number;
|
|
1441
|
+
}[] = [];
|
|
1442
|
+
|
|
1443
|
+
for (let i = 0; i < positiveCategorySubtotals.length; i++) {
|
|
1444
|
+
const entry = positiveCategorySubtotals[i];
|
|
1445
|
+
if (!entry) continue;
|
|
1446
|
+
|
|
1447
|
+
const { category, positiveSubtotal } = entry;
|
|
1448
|
+
|
|
1449
|
+
if (i === positiveCategorySubtotals.length - 1) {
|
|
1450
|
+
// Last category gets remainder
|
|
1451
|
+
const taxAmount = taxMilliunits - allocatedTax;
|
|
1452
|
+
if (taxAmount > 0) {
|
|
1453
|
+
taxAllocations.push({ category, taxAmount });
|
|
1454
|
+
}
|
|
1455
|
+
} else {
|
|
1456
|
+
const taxAmount = Math.round((taxMilliunits * positiveSubtotal) / totalPositiveSubtotal);
|
|
1457
|
+
if (taxAmount > 0) {
|
|
1458
|
+
taxAllocations.push({ category, taxAmount });
|
|
1459
|
+
allocatedTax += taxAmount;
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// Create tax subtransactions
|
|
1465
|
+
for (const { category, taxAmount } of taxAllocations) {
|
|
1466
|
+
subtransactions.push({
|
|
1467
|
+
amount: -taxAmount,
|
|
1468
|
+
category_id: category.category_id,
|
|
1469
|
+
memo: `Tax - ${category.category_name ?? 'Uncategorized'}`,
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
return subtransactions;
|
|
1162
1474
|
}
|
|
1163
1475
|
|
|
1164
1476
|
export async function handleCreateReceiptSplitTransaction(
|
|
@@ -1226,32 +1538,29 @@ export async function handleCreateReceiptSplitTransaction(
|
|
|
1226
1538
|
);
|
|
1227
1539
|
}
|
|
1228
1540
|
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
const subtransactions: SubtransactionInput[] = categoryCalculations.flatMap((category) => {
|
|
1232
|
-
const itemSubtransactions: SubtransactionInput[] = category.items.map((item) => {
|
|
1233
|
-
const memo = buildItemMemo({ name: item.name, quantity: item.quantity, memo: item.memo });
|
|
1234
|
-
const payload: SubtransactionInput = {
|
|
1235
|
-
amount: -item.amount_milliunits,
|
|
1236
|
-
category_id: category.category_id,
|
|
1237
|
-
};
|
|
1238
|
-
if (memo) payload.memo = memo;
|
|
1239
|
-
return payload;
|
|
1240
|
-
});
|
|
1241
|
-
|
|
1242
|
-
const taxSubtransaction: SubtransactionInput[] =
|
|
1243
|
-
category.tax_milliunits > 0
|
|
1244
|
-
? [
|
|
1245
|
-
{
|
|
1246
|
-
amount: -category.tax_milliunits,
|
|
1247
|
-
category_id: category.category_id,
|
|
1248
|
-
memo: `Tax - ${category.category_name ?? 'Uncategorized'}`,
|
|
1249
|
-
},
|
|
1250
|
-
]
|
|
1251
|
-
: [];
|
|
1541
|
+
// Apply smart collapse logic
|
|
1542
|
+
const subtransactions = applySmartCollapseLogic(categoryCalculations, taxMilliunits);
|
|
1252
1543
|
|
|
1253
|
-
|
|
1254
|
-
|
|
1544
|
+
// Distribute tax proportionally for receipt_summary (only for positive categories)
|
|
1545
|
+
if (taxMilliunits > 0) {
|
|
1546
|
+
const positiveSubtotal = categoryCalculations.reduce(
|
|
1547
|
+
(sum, cat) => sum + Math.max(0, cat.subtotal_milliunits),
|
|
1548
|
+
0,
|
|
1549
|
+
);
|
|
1550
|
+
if (positiveSubtotal > 0) {
|
|
1551
|
+
let remainingTax = taxMilliunits;
|
|
1552
|
+
const positiveCats = categoryCalculations.filter((cat) => cat.subtotal_milliunits > 0);
|
|
1553
|
+
positiveCats.forEach((cat, index) => {
|
|
1554
|
+
if (index === positiveCats.length - 1) {
|
|
1555
|
+
cat.tax_milliunits = remainingTax;
|
|
1556
|
+
} else {
|
|
1557
|
+
const share = Math.round((cat.subtotal_milliunits / positiveSubtotal) * taxMilliunits);
|
|
1558
|
+
cat.tax_milliunits = share;
|
|
1559
|
+
remainingTax -= share;
|
|
1560
|
+
}
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1255
1564
|
|
|
1256
1565
|
const receiptSummary = {
|
|
1257
1566
|
subtotal: milliunitsToAmount(subtotalMilliunits),
|