Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Enhance currency conversion logic and improve deal handling
Lewis Carhartae528a45f1d6
diff --git a/apps/api/src/currency/conversion.service.ts b/apps/api/src/currency/conversion.service.tsindex 1ec3f63a..8f0af0a9 100644--- a/apps/api/src/currency/conversion.service.ts+++ b/apps/api/src/currency/conversion.service.ts@@ -86,7 +86,11 @@ export class ConversionService {pendingWhere(base: string): PrismaTypes.DealWhereInput {return {amount: { not: null },- OR: [{ baseAmount: null }, { baseCurrency: { not: base } }],+ OR: [+ { baseAmount: null },+ { baseCurrency: null },+ { baseCurrency: { not: base } },+ ],};}diff --git a/apps/api/test/currency-totals.integration.spec.ts b/apps/api/test/currency-totals.integration.spec.tsindex 9d8af124..b89b6ffc 100644--- a/apps/api/test/currency-totals.integration.spec.ts+++ b/apps/api/test/currency-totals.integration.spec.ts@@ -273,6 +273,43 @@ describe("a converted figure knows which currency it is in", () => {await db.deal.delete({ where: { id: deal.id } });});+ it("never lets a converted figure with no currency on it go unnoticed", async () => {+ await writeReportingCurrency(db, "USD");+ await conversion.rerateAll();++ const before = await pipelineCents();++ const orphan = await db.deal.create({+ data: {+ name: `Orphan ${suffix}`,+ companyId,+ ownerId: userId,+ amount: 50_000,+ currency: "USD",+ baseAmount: 50_000,+ fxRate: 1,+ fxRateAt: new Date(),+ },+ select: { id: true },+ });++ expect(await pipelineCents()).toBe(before);++ const summary = await dashboard.summary(userId, { scope: "me" });+ expect(summary.unconverted.count).toBe(1);++ await conversion.fillMissing();++ const healed = await db.deal.findUnique({+ where: { id: orphan.id },+ select: { baseCurrency: true },+ });+ expect(healed?.baseCurrency).toBe("USD");+ expect(await pipelineCents()).toBe(before + 5_000_000);++ await db.deal.delete({ where: { id: orphan.id } });+ });+it("counts a currency once however it was cased or padded", async () => {const rows = await Promise.all([" usd ", "Usd"].map((currency, index) =>diff --git a/docs/api.md b/docs/api.mdindex bd93ab19..2d9457c8 100644--- a/docs/api.md+++ b/docs/api.md@@ -574,6 +574,21 @@ So there are now two amounts on a deal, and only one of them is ever summed.- **It is composed with `AND`, never spread.** `pendingWhere` contains an `OR`,and the deals list's own `where` already carries one from the search filter —spreading the two would silently drop the caller's search.+ - **`pendingWhere` matches a null `baseCurrency` explicitly**, and leaving that+ clause out was a hole rather than a rounding error. `{ baseCurrency: { not:+ base } }` compiles to `baseCurrency <> 'USD'`, which is `NULL` — not true —+ for a row where the column is null. So a row carrying a `baseAmount` with no+ currency beside it was excluded from every total by `countedWhere` *and*+ invisible to the disclosure: it did not appear anywhere, and nothing would+ ever repair it.+ - **Anything that writes `baseAmount` writes `baseCurrency` in the same+ statement.** `ConversionService` is the only writer in the app, but+ `packages/db/prisma/seed.ts` is a second one, and it was setting the amount+ and not the currency — so a freshly seeded clone had twenty-three deals with+ converted figures and a pipeline of zero. The seed also converts at an+ identity rate when a deal is already in the reporting currency, which needs+ no rate table at all; only a genuine cross-currency deal under a non-USD base+ is left for the cron.**The rate is resolved once, at the moment the amount is set, and then frozen.**`DealsService.create` and `.update` call `ConversionService.dealFields` wheneverdiff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.tsindex 8f240607..45df8d7f 100644--- a/packages/db/prisma/seed.ts+++ b/packages/db/prisma/seed.ts@@ -484,7 +484,7 @@ const SEED_RATES: Record<string, number> = {const DEAL_CURRENCIES = ["USD", "USD", "USD", "EUR", "GBP", "JPY", "CAD"];-let seedBaseIsUsd = true;+let seedBase = "USD";async function seedRates(): Promise<number> {const asOf = daysFromNow(-1);@@ -496,12 +496,12 @@ async function seedRates(): Promise<number> {select: { reportingCurrency: true },});- seedBaseIsUsd = (setting.reportingCurrency ?? "USD").toUpperCase() === "USD";+ seedBase = (setting.reportingCurrency ?? "USD").trim().toUpperCase() || "USD";- if (!seedBaseIsUsd) {+ if (seedBase !== "USD") {console.log(- `Reporting currency is ${setting.reportingCurrency} — seeding amounts ` +- "without a converted figure; the rates cron will fill them in.",+ `Reporting currency is ${seedBase} — seeding a converted figure only for ` ++ `deals already in ${seedBase}; the rates cron converts the rest.`,);}@@ -534,15 +534,19 @@ function money(usdAmount: number, currency: string) {const places = currency === "JPY" ? 0 : 2;const amount = Number((usdAmount / rate).toFixed(places));- if (!seedBaseIsUsd) {- return { amount, currency, baseAmount: null, fxRate: null };- }+ const converted =+ currency === seedBase+ ? { baseAmount: amount, fxRate: 1 }+ : seedBase === "USD"+ ? { baseAmount: Number((amount * rate).toFixed(2)), fxRate: rate }+ : null;return {amount,currency,- baseAmount: Number((amount * rate).toFixed(2)),- fxRate: rate,+ baseAmount: converted?.baseAmount ?? null,+ baseCurrency: converted ? seedBase : null,+ fxRate: converted?.fxRate ?? null,};}@@ -585,14 +589,13 @@ async function seedDeals(stage,stageChangedAt,...(() => {- const { amount, currency, baseAmount, fxRate } = money(- integer(6, 90) * 1000,- pick(DEAL_CURRENCIES),- );+ const { amount, currency, baseAmount, baseCurrency, fxRate } =+ money(integer(6, 90) * 1000, pick(DEAL_CURRENCIES));return {amount,currency,baseAmount,+ baseCurrency,fxRate,fxRateAt: fxRate === null ? null : daysFromNow(-1),};