refactor: Move inline JavaScript to a separate file
- Move all JavaScript code from index.html to app.js. - Update index.html to include a script tag for app.js.
This commit is contained in:
parent
0ae3bda8be
commit
bc8998d57e
@ -1,10 +1,9 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
build: .
|
build: .
|
||||||
ports:
|
ports:
|
||||||
- "3001:3000"
|
- "3000:3000"
|
||||||
volumes:
|
volumes:
|
||||||
- ./ledger_db:/usr/src/app/data
|
- ./simpleledger.db:/usr/src/app/data/simpleledger.db
|
||||||
|
|
||||||
volumes:
|
|
||||||
ledger_db:
|
|
||||||
|
|||||||
1180
index.html
1180
index.html
File diff suppressed because it is too large
Load Diff
65
server.js
65
server.js
@ -552,16 +552,26 @@ app.get('/api/dashboard-summary', authenticateToken, (req, res) => {
|
|||||||
app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', maxCount: 1 }, { name: 'salesFile', maxCount: 1 }]), async (req, res) => {
|
app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', maxCount: 1 }, { name: 'salesFile', maxCount: 1 }]), async (req, res) => {
|
||||||
const userId = req.user.id;
|
const userId = req.user.id;
|
||||||
|
|
||||||
const rules = await new Promise((resolve, reject) => {
|
try {
|
||||||
|
const [rules, existingTransactions] = await Promise.all([
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
db.all('SELECT * FROM rules WHERE userId = ?', [userId], (err, rows) => {
|
db.all('SELECT * FROM rules WHERE userId = ?', [userId], (err, rows) => {
|
||||||
if (err) reject(err);
|
if (err) reject(err);
|
||||||
resolve(rows);
|
resolve(rows);
|
||||||
});
|
});
|
||||||
|
}),
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
db.all('SELECT date, description, amount FROM transactions WHERE userId = ?', [userId], (err, rows) => {
|
||||||
|
if (err) reject(err);
|
||||||
|
resolve(rows);
|
||||||
});
|
});
|
||||||
|
})
|
||||||
|
]);
|
||||||
|
|
||||||
let transactionsToInsert = []; // This will hold { tx, split } objects
|
const existingTxKeys = new Set(existingTransactions.map(tx => `${new Date(tx.date).toISOString().slice(0, 10)}:${tx.description.trim()}:${tx.amount.toFixed(2)}`));
|
||||||
|
let transactionsToInsert = [];
|
||||||
|
let skippedCount = 0;
|
||||||
|
|
||||||
// --- NEW: High-confidence "smart guess" logic ---
|
|
||||||
const smartGuessCategory = (description) => {
|
const smartGuessCategory = (description) => {
|
||||||
const desc = description.toUpperCase();
|
const desc = description.toUpperCase();
|
||||||
const guesses = {
|
const guesses = {
|
||||||
@ -573,40 +583,36 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
'Expense - Software/Subscriptions': ['OPENAI', 'CHATGPT', 'GOOGLE *', 'MSFT *', 'ADOBE'],
|
'Expense - Software/Subscriptions': ['OPENAI', 'CHATGPT', 'GOOGLE *', 'MSFT *', 'ADOBE'],
|
||||||
'Expense - Meals & Entertainment': ['RESTAURANT', 'DOORDASH', 'UBER EATS', 'GRUBHUB'],
|
'Expense - Meals & Entertainment': ['RESTAURANT', 'DOORDASH', 'UBER EATS', 'GRUBHUB'],
|
||||||
'Expense - Bank Fees': ['MAINTENANCE FEE', 'SQUARE PAYMENT PROCESSING'],
|
'Expense - Bank Fees': ['MAINTENANCE FEE', 'SQUARE PAYMENT PROCESSING'],
|
||||||
'Liability - Owner\'s Draw': ['PERSONAL', 'TRANSFER TO SELF'] // Added for owner's draw
|
'Liability - Owner\'s Draw': ['PERSONAL', 'TRANSFER TO SELF']
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const [category, keywords] of Object.entries(guesses)) {
|
for (const [category, keywords] of Object.entries(guesses)) {
|
||||||
for (const keyword of keywords) {
|
for (const keyword of keywords) {
|
||||||
if (desc.includes(keyword)) {
|
if (desc.includes(keyword)) {
|
||||||
return category; // Found a confident match
|
return category;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null; // No confident guess
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- MODIFIED: This function now tries smart guess first, then user rules ---
|
|
||||||
const applyCategorization = (tx, split) => {
|
const applyCategorization = (tx, split) => {
|
||||||
const desc = tx.description.toUpperCase();
|
const desc = tx.description.toUpperCase();
|
||||||
|
|
||||||
// 1. Try smart guess first
|
|
||||||
const guess = smartGuessCategory(tx.description);
|
const guess = smartGuessCategory(tx.description);
|
||||||
if (guess) {
|
if (guess) {
|
||||||
split.category = guess;
|
split.category = guess;
|
||||||
tx.reconciliation_status = 'categorized';
|
tx.reconciliation_status = 'categorized';
|
||||||
return; // Found a confident match
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. If no guess, apply user's rules
|
|
||||||
for (const rule of rules) {
|
for (const rule of rules) {
|
||||||
if (desc.includes(rule.keyword.toUpperCase())) {
|
if (desc.includes(rule.keyword.toUpperCase())) {
|
||||||
split.category = rule.category;
|
split.category = rule.category;
|
||||||
tx.reconciliation_status = 'categorized'; // Mark parent as categorized
|
tx.reconciliation_status = 'categorized';
|
||||||
return; // Stop after first match
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// If no guess and no rule, it remains 'Expense - Uncategorized'
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const processBankCSV = (data) => {
|
const processBankCSV = (data) => {
|
||||||
@ -616,8 +622,15 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
const credit = parseFloat(row.Credit) || 0;
|
const credit = parseFloat(row.Credit) || 0;
|
||||||
const amount = credit - debit;
|
const amount = credit - debit;
|
||||||
const description = row.Description ? row.Description.trim() : '';
|
const description = row.Description ? row.Description.trim() : '';
|
||||||
|
const key = `${date.toISOString().slice(0, 10)}:${description}:${amount.toFixed(2)}`;
|
||||||
|
|
||||||
if (!isNaN(date) && amount !== 0) {
|
if (!isNaN(date) && amount !== 0) {
|
||||||
|
if (existingTxKeys.has(key)) {
|
||||||
|
skippedCount++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
existingTxKeys.add(key);
|
||||||
|
|
||||||
let tx = {
|
let tx = {
|
||||||
date: date.toISOString(),
|
date: date.toISOString(),
|
||||||
description: description,
|
description: description,
|
||||||
@ -631,7 +644,6 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
description: description,
|
description: description,
|
||||||
amount: amount
|
amount: amount
|
||||||
};
|
};
|
||||||
// --- MODIFIED: Call the new function ---
|
|
||||||
applyCategorization(tx, split);
|
applyCategorization(tx, split);
|
||||||
transactionsToInsert.push({ tx, split });
|
transactionsToInsert.push({ tx, split });
|
||||||
}
|
}
|
||||||
@ -660,12 +672,19 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
|
|
||||||
const addTx = (desc, cat, amount) => {
|
const addTx = (desc, cat, amount) => {
|
||||||
if (amount !== 0) {
|
if (amount !== 0) {
|
||||||
|
const key = `${txDate.toISOString().slice(0, 10)}:${desc}:${amount.toFixed(2)}`;
|
||||||
|
if (existingTxKeys.has(key)) {
|
||||||
|
skippedCount++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
existingTxKeys.add(key);
|
||||||
|
|
||||||
let tx = {
|
let tx = {
|
||||||
date: txDate.toISOString(),
|
date: txDate.toISOString(),
|
||||||
description: desc,
|
description: desc,
|
||||||
amount: amount,
|
amount: amount,
|
||||||
source: 'sales_summary_csv',
|
source: 'sales_summary_csv',
|
||||||
reconciliation_status: 'categorized', // Sales data is pre-categorized
|
reconciliation_status: 'categorized',
|
||||||
createdAt: new Date().toISOString()
|
createdAt: new Date().toISOString()
|
||||||
};
|
};
|
||||||
let split = {
|
let split = {
|
||||||
@ -684,8 +703,6 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
addTx('Square Payment Processing Fees', 'Expense - Bank Fees', salesData['Square payment processing fees'] || 0);
|
addTx('Square Payment Processing Fees', 'Expense - Bank Fees', salesData['Square payment processing fees'] || 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 2. Parse files
|
|
||||||
try {
|
|
||||||
if (req.files.bankFile) {
|
if (req.files.bankFile) {
|
||||||
const file = req.files.bankFile[0];
|
const file = req.files.bankFile[0];
|
||||||
const content = fs.readFileSync(file.path, 'utf8');
|
const content = fs.readFileSync(file.path, 'utf8');
|
||||||
@ -701,14 +718,9 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
processSalesCSV(results.data, file.originalname);
|
processSalesCSV(results.data, file.originalname);
|
||||||
fs.unlinkSync(file.path);
|
fs.unlinkSync(file.path);
|
||||||
}
|
}
|
||||||
} catch (parseError) {
|
|
||||||
console.error("File parse error:", parseError);
|
|
||||||
return res.status(500).send('Error parsing files.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Insert transactions and their default splits
|
|
||||||
if (transactionsToInsert.length === 0) {
|
if (transactionsToInsert.length === 0) {
|
||||||
return res.status(400).send('No valid transactions found to insert.');
|
return res.status(200).send(`No new transactions to insert. Skipped ${skippedCount} duplicate transactions.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const txStmt = db.prepare('INSERT INTO transactions (userId, date, description, amount, source, createdAt, reconciliation_status) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
const txStmt = db.prepare('INSERT INTO transactions (userId, date, description, amount, source, createdAt, reconciliation_status) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
||||||
@ -736,9 +748,14 @@ app.post('/api/upload', authenticateToken, upload.fields([{ name: 'bankFile', ma
|
|||||||
console.error("DB commit error:", err);
|
console.error("DB commit error:", err);
|
||||||
return res.status(500).send('Error saving transactions.');
|
return res.status(500).send('Error saving transactions.');
|
||||||
}
|
}
|
||||||
res.status(201).send(`Successfully inserted ${transactionsToInsert.length} transactions.`);
|
res.status(201).send(`Successfully inserted ${transactionsToInsert.length} new transactions. Skipped ${skippedCount} duplicate transactions.`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing upload:", error);
|
||||||
|
res.status(500).send('Server error during file upload.');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- Serve Frontend ---
|
// --- Serve Frontend ---
|
||||||
|
|||||||
BIN
simpleledger.db
BIN
simpleledger.db
Binary file not shown.
Loading…
x
Reference in New Issue
Block a user