Skip to content

Commit b292cec

Browse files
ShivaniNRclaude
andcommitted
Resolve CSV import categories against the user's real DB, not hardcoded names
The Discover parser hardcoded both sides of the bank-to-app category map, which meant importing rows with categories like "Services" pointed at names that didn't exist for the user - and addTransaction silently auto-created orphan categories to make the insert succeed. Split the concerns: the parser now holds bank-specific hints (keyword substrings), and getDefaultMapping cross-references those hints against the user's actual categories via useCategories(). Unmatched rows fall back to the user's "Other" category. resolveCategory gets an allowCreate flag; CSV imports pass false so unknown categories fail loudly per-row instead of seeding phantoms. Also disable the Import button while any row is unmapped, and remap Services/Government Services to Utilities on the web client (which still uses the old hardcoded map). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 0d769ea commit b292cec

5 files changed

Lines changed: 110 additions & 44 deletions

File tree

‎client/src/utils/parsers/discoverParser.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ const CATEGORY_MAP = {
2222
'Travel/ Entertainment': 'Entertainment',
2323
'Travel/Entertainment': 'Entertainment',
2424
'Medical Services': 'Healthcare',
25-
'Services': 'Services',
26-
'Government Services': 'Services',
25+
'Services': 'Utilities',
26+
'Government Services': 'Utilities',
2727
'Education': 'Education',
2828
'Automotive': 'Transport',
2929
'Warehouse Clubs': 'Groceries',

‎mobile/src/screens/ImportCSVScreen.js‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,11 @@ export default function ImportCSVScreen({ navigation }) {
6161
return;
6262
}
6363
const content = await FileSystem.readAsStringAsync(file.uri);
64-
const { rawRows: rows, defaultMapping } = parseAndGetMapping(bank, content);
64+
const { rawRows: rows, defaultMapping } = parseAndGetMapping(
65+
bank,
66+
content,
67+
userCategories
68+
);
6569
setRawRows(rows);
6670
setMapping(defaultMapping);
6771
setStage('mapping');
@@ -78,7 +82,7 @@ export default function ImportCSVScreen({ navigation }) {
7882
const failed = [];
7983
for (let i = 0; i < transactions.length; i++) {
8084
try {
81-
await addTransaction(transactions[i]);
85+
await addTransaction(transactions[i], { allowCreateCategory: false });
8286
succeeded++;
8387
} catch (err) {
8488
failed.push({ ...transactions[i], error: err.message || 'Unknown error' });
@@ -124,6 +128,7 @@ export default function ImportCSVScreen({ navigation }) {
124128
};
125129

126130
const mappingEntries = Object.entries(mapping);
131+
const hasUnmapped = mappingEntries.some(([, appCat]) => !appCat);
127132
const pct = progress.total > 0 ? Math.round((progress.current / progress.total) * 100) : 0;
128133
const bankLabel = SUPPORTED_BANKS.find((b) => b.key === bank)?.label || '';
129134

@@ -216,8 +221,16 @@ export default function ImportCSVScreen({ navigation }) {
216221
))}
217222
</View>
218223

219-
<TouchableOpacity style={styles.primaryBtn} onPress={startImport}>
220-
<Text style={styles.primaryBtnText}>Import {rawRows.length} transactions</Text>
224+
<TouchableOpacity
225+
style={[styles.primaryBtn, hasUnmapped && styles.btnDisabled]}
226+
onPress={startImport}
227+
disabled={hasUnmapped}
228+
>
229+
<Text style={styles.primaryBtnText}>
230+
{hasUnmapped
231+
? 'Pick a category for every row to continue'
232+
: `Import ${rawRows.length} transactions`}
233+
</Text>
221234
</TouchableOpacity>
222235
<TouchableOpacity style={styles.linkBtn} onPress={() => setStage('upload')}>
223236
<Text style={styles.linkText}>← Back</Text>

‎mobile/src/services/transactions.js‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@ export async function getTransactions({ limit = 50, offset = 0 } = {}) {
1111
return data.map(formatTransaction);
1212
}
1313

14-
export async function addTransaction(transaction) {
15-
// Resolve category name to ID
14+
export async function addTransaction(transaction, { allowCreateCategory = true } = {}) {
15+
// Resolve category name to ID. CSV import passes allowCreateCategory:false
16+
// so unknown categories fail loudly instead of silently seeding orphans.
1617
const categoryId = await resolveCategory(
1718
transaction.category,
18-
transaction.type
19+
transaction.type,
20+
{ allowCreate: allowCreateCategory }
1921
);
2022

2123
// Get current user ID for RLS — INSERT requires user_id to match auth.uid()
@@ -105,8 +107,9 @@ function localDateString() {
105107
return `${y}-${m}-${day}`;
106108
}
107109

108-
async function resolveCategory(categoryName, type) {
109-
// Try to find existing category
110+
async function resolveCategory(categoryName, type, { allowCreate = true } = {}) {
111+
if (!categoryName) throw new Error('Category is required.');
112+
110113
const { data: existing } = await supabase
111114
.from('categories')
112115
.select('id')
@@ -116,7 +119,10 @@ async function resolveCategory(categoryName, type) {
116119

117120
if (existing) return existing.id;
118121

119-
// Create new category
122+
if (!allowCreate) {
123+
throw new Error(`Category "${categoryName}" not found in your categories.`);
124+
}
125+
120126
const { data: created, error } = await supabase
121127
.from('categories')
122128
.insert({

‎mobile/src/utils/csvImport.js‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,12 @@ export const SUPPORTED_BANKS = [
2525
*
2626
* @param {string} bankKey
2727
* @param {string} content - the raw CSV text
28+
* @param {Array<{id, name, type}>} userCategories - user's real DB categories
29+
* used to build a default mapping that only references categories that
30+
* actually exist for this user.
2831
* @returns {{ rawRows: object[], defaultMapping: Record<string, string>, rowCount: number }}
2932
*/
30-
export function parseAndGetMapping(bankKey, content) {
33+
export function parseAndGetMapping(bankKey, content, userCategories = []) {
3134
const parser = PARSERS[bankKey];
3235
if (!parser) throw new Error(`Unsupported bank: ${bankKey}`);
3336

@@ -51,7 +54,7 @@ export function parseAndGetMapping(bankKey, content) {
5154
throw new Error(`Too many rows (${results.data.length}). Max is ${MAX_ROWS}.`);
5255
}
5356

54-
const defaultMapping = parser.getDefaultMapping(results.data);
57+
const defaultMapping = parser.getDefaultMapping(results.data, userCategories);
5558
return {
5659
rawRows: results.data,
5760
defaultMapping,

‎mobile/src/utils/parsers/discoverParser.js‎

Lines changed: 74 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44
* Discover exports: Trans. Date, Post Date, Description, Amount, Category
55
* Amount sign: positive = charge (EXPENSE), negative = payment/refund (INCOME)
66
* Date format: MM/DD/YYYY
7+
*
8+
* Mapping model:
9+
* - LEFT side (Discover's category strings) is hardcoded here — it's a
10+
* fact about Discover's export format.
11+
* - RIGHT side (target app category) is resolved at runtime against the
12+
* user's real DB categories via keyword hints. Unmatched entries fall
13+
* back to "Other".
714
*/
815

916
const DISCOVER_HEADERS = [
@@ -14,24 +21,28 @@ const DISCOVER_HEADERS = [
1421
'Category',
1522
];
1623

17-
const CATEGORY_MAP = {
18-
'Supermarkets': 'Groceries',
19-
'Gasoline': 'Transport',
20-
'Merchandise': 'Shopping',
21-
'Restaurants': 'Food & Dining',
22-
'Travel/ Entertainment': 'Entertainment',
23-
'Travel/Entertainment': 'Entertainment',
24-
'Medical Services': 'Healthcare',
25-
'Services': 'Services',
26-
'Government Services': 'Services',
27-
'Education': 'Education',
28-
'Automotive': 'Transport',
29-
'Warehouse Clubs': 'Groceries',
30-
'Payments and Credits': 'Other',
31-
'Awards and Rebate Credits': 'Other',
32-
'Department Stores': 'Shopping',
24+
// Hints are keyword substrings to fuzzy-match against user category names
25+
// (case-insensitive). First hint that matches an existing category wins.
26+
// Empty array = go straight to the "Other" fallback.
27+
const CATEGORY_HINTS = {
28+
'Supermarkets': ['grocer'],
29+
'Gasoline': ['transport', 'gas', 'fuel'],
30+
'Merchandise': ['shopping'],
31+
'Restaurants': ['dining', 'restaurant', 'food'],
32+
'Medical Services': ['health', 'medical'],
33+
'Services': ['utilit'],
34+
'Government Services': ['utilit'],
35+
'Education': ['education'],
36+
'Automotive': ['transport', 'auto'],
37+
'Warehouse Clubs': ['grocer'],
38+
'Department Stores': ['shopping'],
39+
'Payments and Credits': [],
40+
'Awards and Rebate Credits': [],
3341
};
3442

43+
const TRAVEL_RIDES_HINTS = ['transport'];
44+
const TRAVEL_OTHER_HINTS = ['entertain'];
45+
3546
const TRANSPORT_KEYWORDS = ['uber', 'lyft', 'taxi', 'cab', 'rideshare'];
3647

3748
const RIDES_SUFFIX = '::rides';
@@ -46,6 +57,26 @@ function isTravelEntertainment(bankCategory) {
4657
return bankCategory === 'Travel/ Entertainment' || bankCategory === 'Travel/Entertainment';
4758
}
4859

60+
/**
61+
* Fuzzy-match hints against the user's DB categories.
62+
* Returns the matched category NAME, or the name of "Other", or null.
63+
*/
64+
function matchCategory(hints, userCategories) {
65+
const expenseCats = userCategories.filter(
66+
(c) => (c.type || '').toUpperCase() === 'EXPENSE'
67+
);
68+
69+
for (const hint of hints) {
70+
const found = expenseCats.find((c) =>
71+
c.name.toLowerCase().includes(hint.toLowerCase())
72+
);
73+
if (found) return found.name;
74+
}
75+
76+
const other = expenseCats.find((c) => c.name.toLowerCase() === 'other');
77+
return other ? other.name : expenseCats[0]?.name || null;
78+
}
79+
4980
export function getMappingDisplayName(key) {
5081
if (key.endsWith(RIDES_SUFFIX)) {
5182
return key.replace(RIDES_SUFFIX, '') + ' (rides)';
@@ -61,7 +92,11 @@ export function validate(headers) {
6192
return DISCOVER_HEADERS.every((h) => normalized.includes(h));
6293
}
6394

64-
export function getDefaultMapping(rows) {
95+
/**
96+
* Build the default bankCategory → appCategoryName map by cross-referencing
97+
* parser hints against the user's real DB categories.
98+
*/
99+
export function getDefaultMapping(rows, userCategories = []) {
65100
const mapping = {};
66101
let hasRides = false;
67102
let hasOtherTravel = false;
@@ -82,18 +117,19 @@ export function getDefaultMapping(rows) {
82117
}
83118

84119
if (!mapping[bankCat]) {
85-
mapping[bankCat] = CATEGORY_MAP[bankCat] || 'Other';
120+
const hints = CATEGORY_HINTS[bankCat] || [];
121+
mapping[bankCat] = matchCategory(hints, userCategories) || '';
86122
}
87123
}
88124

89125
if (travelKey) {
90-
if (hasRides && hasOtherTravel) {
91-
mapping[travelKey + RIDES_SUFFIX] = 'Transport';
92-
mapping[travelKey + OTHER_SUFFIX] = 'Entertainment';
93-
} else if (hasRides) {
94-
mapping[travelKey + RIDES_SUFFIX] = 'Transport';
95-
} else {
96-
mapping[travelKey + OTHER_SUFFIX] = 'Entertainment';
126+
if (hasRides) {
127+
mapping[travelKey + RIDES_SUFFIX] =
128+
matchCategory(TRAVEL_RIDES_HINTS, userCategories) || '';
129+
}
130+
if (hasOtherTravel) {
131+
mapping[travelKey + OTHER_SUFFIX] =
132+
matchCategory(TRAVEL_OTHER_HINTS, userCategories) || '';
97133
}
98134
}
99135

@@ -121,14 +157,22 @@ export function parse(rows, categoryMapping) {
121157

122158
if (isTravelEntertainment(rawCategory) && categoryMapping) {
123159
const suffix = isTransportDescription(rawDescription) ? RIDES_SUFFIX : OTHER_SUFFIX;
124-
category = categoryMapping[rawCategory + suffix]
125-
|| categoryMapping[rawCategory]
126-
|| (isTransportDescription(rawDescription) ? 'Transport' : 'Entertainment');
160+
category =
161+
categoryMapping[rawCategory + suffix] ||
162+
categoryMapping[rawCategory] ||
163+
'';
127164
} else {
128-
category = categoryMapping?.[rawCategory] || CATEGORY_MAP[rawCategory] || 'Other';
165+
category = categoryMapping?.[rawCategory] || '';
129166
}
130167

131-
return { date, amount: numeric, description: rawDescription, type: 'EXPENSE', category, bankCategory: rawCategory };
168+
return {
169+
date,
170+
amount: numeric,
171+
description: rawDescription,
172+
type: 'EXPENSE',
173+
category,
174+
bankCategory: rawCategory,
175+
};
132176
})
133177
.filter(Boolean);
134178
}

0 commit comments

Comments
 (0)