Auto-detect expense currency from the selected account
On create: if accountId is set, use that account's currency; else fall back to the company's base currency (not hardcoded THB). On update: if account changes, also update the expense currency to match, so the ledger entry posts in the right currency. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import {
|
||||
users,
|
||||
categories,
|
||||
companyAccounts,
|
||||
companies,
|
||||
invoices,
|
||||
parties,
|
||||
packages,
|
||||
@@ -196,6 +197,29 @@ export const actions: Actions = {
|
||||
.limit(1);
|
||||
if (!proj) return fail(400, { action: 'submitExpense', error: 'Project not found' });
|
||||
|
||||
// Resolve currency: use the selected account's currency, else company base
|
||||
let resolvedCurrency = 'THB';
|
||||
if (accountId) {
|
||||
const [acct] = await db
|
||||
.select({ currency: companyAccounts.currency })
|
||||
.from(companyAccounts)
|
||||
.where(
|
||||
and(
|
||||
eq(companyAccounts.id, accountId),
|
||||
eq(companyAccounts.companyId, params.companyId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (acct) resolvedCurrency = acct.currency;
|
||||
} else {
|
||||
const [company] = await db
|
||||
.select({ currency: companies.currency })
|
||||
.from(companies)
|
||||
.where(eq(companies.id, params.companyId))
|
||||
.limit(1);
|
||||
if (company) resolvedCurrency = company.currency;
|
||||
}
|
||||
|
||||
await db.insert(expenses).values({
|
||||
projectId: resolvedProjectId,
|
||||
categoryId: categoryId || null,
|
||||
@@ -205,7 +229,7 @@ export const actions: Actions = {
|
||||
title,
|
||||
description,
|
||||
amount: Number(amountStr).toFixed(2),
|
||||
currency: 'THB',
|
||||
currency: resolvedCurrency,
|
||||
expenseDate,
|
||||
status: 'pending'
|
||||
});
|
||||
|
||||
@@ -213,6 +213,22 @@ export const actions: Actions = {
|
||||
const amountChanged = newAmount !== existing.amount;
|
||||
const accountChanged = (accountId ?? null) !== (existing.accountId ?? null);
|
||||
|
||||
// Resolve currency from the (possibly new) account
|
||||
let resolvedCurrency: string | undefined = undefined;
|
||||
if (accountId) {
|
||||
const [acct] = await db
|
||||
.select({ currency: companyAccounts.currency })
|
||||
.from(companyAccounts)
|
||||
.where(
|
||||
and(
|
||||
eq(companyAccounts.id, accountId),
|
||||
eq(companyAccounts.companyId, params.companyId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (acct) resolvedCurrency = acct.currency;
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(expenses)
|
||||
@@ -226,6 +242,7 @@ export const actions: Actions = {
|
||||
partyId,
|
||||
accountId,
|
||||
invoiceId,
|
||||
...(resolvedCurrency ? { currency: resolvedCurrency } : {}),
|
||||
updatedAt: new Date()
|
||||
})
|
||||
.where(eq(expenses.id, params.expenseId));
|
||||
|
||||
Reference in New Issue
Block a user