fix: improve error handling in background expense processing

- Add proper array validation for existingExpenses API response
- Handle different API response structures (data.expenses vs data)
- Add try-catch blocks around individual expense processing loops
- Improve error messages to show specific error details
- Prevent TypeError when API response format is unexpected

Resolves 'gt.some is not a function' error in background processing.
This commit is contained in:
dlawler489 2026-05-05 20:55:33 +10:00
parent 212dc77df7
commit c1fc9309b1

View file

@ -79,7 +79,15 @@ export default function DataImport() {
try {
setBackgroundProcessing('Processing expenses from uploaded files...');
const existingExpenses = await api.get('/expenses').then(res => res.data);
const existingExpensesResponse = await api.get('/expenses');
const existingExpenses = existingExpensesResponse.data?.expenses || existingExpensesResponse.data || [];
// Ensure existingExpenses is an array
if (!Array.isArray(existingExpenses)) {
console.warn('Expected existingExpenses to be an array, got:', typeof existingExpenses, existingExpenses);
throw new Error('Invalid response format for existing expenses');
}
const expensesToCreate: any[] = [];
if (etsyFile) {
@ -88,6 +96,7 @@ export default function DataImport() {
// Add Etsy fees (check for duplicates)
etsyFees.forEach((fee: EtsyFeeRecord) => {
try {
const isDuplicate = existingExpenses.some((expense: any) =>
expense.description === fee.description &&
Math.abs(expense.amount - fee.amount) < 0.01 &&
@ -106,6 +115,9 @@ export default function DataImport() {
reference: fee.reference
});
}
} catch (error) {
console.error('Error processing Etsy fee:', fee, error);
}
});
}
@ -115,6 +127,7 @@ export default function DataImport() {
// Add shipping expenses (check for duplicates)
shippingRecords.forEach((shipping: ParsedShippingRecord) => {
try {
if (shipping.totalCost > 0) {
const isDuplicate = existingExpenses.some((expense: any) =>
expense.reference === shipping.trackingNumber &&
@ -135,6 +148,9 @@ export default function DataImport() {
});
}
}
} catch (error) {
console.error('Error processing shipping record:', shipping, error);
}
});
}
@ -169,7 +185,11 @@ export default function DataImport() {
}
} catch (error) {
console.error('Error in background expense processing:', error);
if (error instanceof Error) {
toast.error(`Error processing expenses: ${error.message}`);
} else {
toast.error('Error processing expenses in background');
}
} finally {
setBackgroundProcessing('');
}