Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

Implement currency conversion features and enhance deal handling

Lewis Carhartc4d19805ac53
diff --git a/apps/agent/agent/lib/accounts.ts b/apps/agent/agent/lib/accounts.ts
index 79ae965c..45406d29 100644
--- a/apps/agent/agent/lib/accounts.ts
+++ b/apps/agent/agent/lib/accounts.ts
@@ -270,6 +270,7 @@ export type DealHistory = {
deal: {
id: string;
name: string;
+ description: string | null;
stage: string;
open: boolean;
daysInStage: number;
@@ -313,6 +314,7 @@ export async function readDealHistory(
select: {
id: true,
name: true,
+ description: true,
stage: true,
stageChangedAt: true,
amount: true,
@@ -419,6 +421,7 @@ export async function readDealHistory(
deal: {
id: deal.id,
name: deal.name,
+ description: deal.description,
stage: deal.stage,
open: isOpen(deal.stage),
daysInStage: daysSince(deal.stageChangedAt, now),
diff --git a/apps/agent/agent/lib/preamble.ts b/apps/agent/agent/lib/preamble.ts
index 4dd2b8e0..10afea4a 100644
--- a/apps/agent/agent/lib/preamble.ts
+++ b/apps/agent/agent/lib/preamble.ts
@@ -230,6 +230,7 @@ export async function dealPreamble(
where: { id: dealId },
select: {
name: true,
+ description: true,
stage: true,
amount: true,
currency: true,
@@ -280,6 +281,9 @@ export async function dealPreamble(
deal.lastActivityAt
? `Last touched ${deal.lastActivityAt.toDateString()}.`
: "Nothing has happened on it yet.",
+ ...(deal.description
+ ? [`The rep's own description of it: "${deal.description}"`]
+ : []),
people ? `People on it: ${people}` : "Nobody is attached to it yet.",
"",
opening(
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
index 66ecce7d..0d758d0e 100644
--- a/apps/api/src/app.module.ts
+++ b/apps/api/src/app.module.ts
@@ -11,6 +11,7 @@ import { validateEnv } from "./config/env.validation";
import { ContactsModule } from "./contacts/contacts.module";
import { ConversationsModule } from "./conversations/conversations.module";
import { CrmModule } from "./crm/crm.module";
+import { CurrencyModule } from "./currency/currency.module";
import { DashboardModule } from "./dashboard/dashboard.module";
import { DatabaseModule } from "./database/database.module";
import { DealsModule } from "./deals/deals.module";
@@ -44,6 +45,7 @@ import { WorkspaceModule } from "./workspace/workspace.module";
CompaniesModule,
ContactsModule,
ConversationsModule,
+ CurrencyModule,
DealsModule,
ActivitiesModule,
DashboardModule,
diff --git a/apps/api/src/companies/companies.module.ts b/apps/api/src/companies/companies.module.ts
index 38745d46..40625ecb 100644
--- a/apps/api/src/companies/companies.module.ts
+++ b/apps/api/src/companies/companies.module.ts
@@ -1,5 +1,6 @@
import { Module } from "@nestjs/common";
import { AgentModule } from "../agent/agent.module";
+import { CurrencyModule } from "../currency/currency.module";
import { TrpcModule } from "../trpc/trpc.module";
import { CompaniesRouter } from "./companies.router";
import { CompaniesService } from "./companies.service";
@@ -7,7 +8,7 @@ import { CompanyDirectoryService } from "./company-directory.service";
import { FaviconService } from "./favicon.service";
@Module({
- imports: [TrpcModule, AgentModule],
+ imports: [TrpcModule, AgentModule, CurrencyModule],
providers: [
CompaniesService,
CompanyDirectoryService,
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
index 92743993..df589aa9 100644
--- a/apps/api/src/companies/companies.service.ts
+++ b/apps/api/src/companies/companies.service.ts
@@ -19,6 +19,7 @@ import {
type StampTargets,
} from "../crm/activity-stamp.service";
import { blankToNull, toCents } from "../crm/values";
+import { ConversionService } from "../currency/conversion.service";
import { InjectDatabase } from "../database/database.constants";
import { OPEN_DEAL_STAGES } from "../deals/deal-stage";
import {
@@ -94,6 +95,7 @@ export class CompaniesService {
private readonly queue: AgentQueueService,
private readonly favicon: FaviconService,
private readonly stamp: ActivityStampService,
+ private readonly conversion: ConversionService,
) {}
async list(input: CompanyListInput): Promise<ListResult<CompanyRow>> {
@@ -226,6 +228,7 @@ export class CompaniesService {
stage: true,
amount: true,
currency: true,
+ baseAmount: true,
expectedCloseDate: true,
owner: { select: OWNER_SELECT },
},
@@ -246,10 +249,13 @@ export class CompaniesService {
enrichedAt: enrichedAt?.toISOString() ?? null,
primaryContactId: primaryContact?.id ?? null,
primaryContact,
+ reportingCurrency: await this.conversion.reportingCurrency(),
deals: deals.map((deal) => ({
...deal,
amount: undefined,
+ baseAmount: undefined,
amountCents: toCents(deal.amount),
+ baseAmountCents: toCents(deal.baseAmount),
expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,
})),
};
diff --git a/apps/api/src/crm/values.ts b/apps/api/src/crm/values.ts
index c49013ee..52d8c8ed 100644
--- a/apps/api/src/crm/values.ts
+++ b/apps/api/src/crm/values.ts
@@ -1,4 +1,5 @@
import type { Prisma } from "@crm/db";
+import { Prisma as PrismaNamespace } from "@crm/db";
export function toCents(amount: Prisma.Decimal | null): number | null {
return amount === null ? null : amount.times(100).toNumber();
@@ -8,6 +9,14 @@ export function fromCents(cents: number | null | undefined): number | null {
return cents === null || cents === undefined ? null : cents / 100;
}
+export function decimalFromCents(
+ cents: number | null | undefined,
+): Prisma.Decimal | null {
+ return cents === null || cents === undefined
+ ? null
+ : new PrismaNamespace.Decimal(cents).dividedBy(100);
+}
+
export function blankToNull(value: string): string | null {
const trimmed = value.trim();
return trimmed === "" ? null : trimmed;
diff --git a/apps/api/src/currency/conversion.service.ts b/apps/api/src/currency/conversion.service.ts
new file mode 100644
index 00000000..34262203
--- /dev/null
+++ b/apps/api/src/currency/conversion.service.ts
@@ -0,0 +1,179 @@
+import type { Db, Prisma as PrismaTypes } from "@crm/db";
+import { Prisma } from "@crm/db";
+import { minorUnitsOf, normalizeCurrency } from "@crm/db/currency";
+import {
+ applyRate,
+ type Conversion,
+ type ResolvedRate,
+ resolveRate,
+} from "@crm/db/fx";
+import { readReportingCurrency } from "@crm/db/settings";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+export interface DealFxFields {
+ baseAmount: PrismaTypes.Decimal | null;
+ fxRate: PrismaTypes.Decimal | null;
+ fxRateAt: Date | null;
+}
+
+export interface Unconverted {
+ count: number;
+ currencies: string[];
+}
+
+export interface RerateResult {
+ converted: number;
+ cleared: number;
+ missing: string[];
+}
+
+@Injectable()
+export class ConversionService {
+ private readonly logger = new Logger(ConversionService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async reportingCurrency(): Promise<string> {
+ return readReportingCurrency(this.db);
+ }
+
+ async rateFor(currency: string): Promise<ResolvedRate | null> {
+ const base = await this.reportingCurrency();
+ return resolveRate(this.db, base, currency);
+ }
+
+ async convert(
+ amount: PrismaTypes.Decimal | null,
+ currency: string,
+ ): Promise<Conversion | null> {
+ if (amount === null) return null;
+
+ const base = await this.reportingCurrency();
+ const rate = await resolveRate(this.db, base, currency);
+
+ return rate ? applyRate(amount, rate, base) : null;
+ }
+
+ async dealFields(
+ amount: PrismaTypes.Decimal | null,
+ currency: string,
+ ): Promise<DealFxFields> {
+ const converted = await this.convert(amount, currency);
+
+ if (!converted) {
+ return { baseAmount: null, fxRate: null, fxRateAt: null };
+ }
+
+ return {
+ baseAmount: converted.baseAmount,
+ fxRate: converted.fxRate,
+ fxRateAt: converted.fxRateAt,
+ };
+ }
+
+ async unconverted(
+ where: PrismaTypes.DealWhereInput = {},
+ ): Promise<Unconverted> {
+ const rows = await this.db.deal.groupBy({
+ by: ["currency"],
+ where: { ...where, amount: { not: null }, baseAmount: null },
+ _count: { _all: true },
+ });
+
+ return {
+ count: rows.reduce((total, row) => total + row._count._all, 0),
+ currencies: rows
+ .map((row) => normalizeCurrency(row.currency))
+ .filter((code, index, all) => all.indexOf(code) === index)
+ .sort(),
+ };
+ }
+
+ async rerateAll(): Promise<RerateResult> {
+ return this.rerate(false);
+ }
+
+ async fillMissing(): Promise<RerateResult> {
+ return this.rerate(true);
+ }
+
+ private async rerate(onlyMissing: boolean): Promise<RerateResult> {
+ const base = await this.reportingCurrency();
+
+ const groups = await this.db.deal.groupBy({
+ by: ["currency"],
+ where: {
+ amount: { not: null },
+ ...(onlyMissing ? { baseAmount: null } : {}),
+ },
+ _count: { _all: true },
+ });
+
+ const places = minorUnitsOf(base);
+ let converted = 0;
+ let cleared = 0;
+ const missing: string[] = [];
+
+ for (const group of groups) {
+ const code = normalizeCurrency(group.currency);
+ const rate = await resolveRate(this.db, base, code);
+
+ if (!rate) {
+ missing.push(code);
+
+ if (!onlyMissing) {
+ cleared += await this.clear(code);
+ }
+
+ continue;
+ }
+
+ converted += await this.write(code, rate, places, onlyMissing);
+ }
+
+ this.logger.log({
+ message: onlyMissing
+ ? "Filled in deal amounts that had no rate"
+ : "Re-rated every deal against the reporting currency",
+ base,
+ converted,
+ cleared,
+ missing,
+ });
+
+ return { converted, cleared, missing: missing.sort() };
+ }
+
+ private async write(
+ code: string,
+ rate: ResolvedRate,
+ places: number,
+ onlyMissing: boolean,
+ ): Promise<number> {
+ const value = new Prisma.Decimal(rate.rate).toString();
+
+ const filter = onlyMissing
+ ? Prisma.sql`AND "baseAmount" IS NULL`
+ : Prisma.empty;
+
+ return this.db.$executeRaw`
+ UPDATE "deal"
+ SET "baseAmount" = ROUND("amount" * ${value}::numeric, ${places}::int),
+ "fxRate" = ${value}::numeric,
+ "fxRateAt" = ${rate.asOf}
+ WHERE "amount" IS NOT NULL
+ AND upper(btrim("currency")) = ${code}
+ ${filter}
+ `;
+ }
+
+ private async clear(code: string): Promise<number> {
+ return this.db.$executeRaw`
+ UPDATE "deal"
+ SET "baseAmount" = NULL, "fxRate" = NULL, "fxRateAt" = NULL
+ WHERE upper(btrim("currency")) = ${code}
+ AND "baseAmount" IS NOT NULL
+ `;
+ }
+}
diff --git a/apps/api/src/currency/currency.contracts.ts b/apps/api/src/currency/currency.contracts.ts
new file mode 100644
index 00000000..df0bf058
--- /dev/null
+++ b/apps/api/src/currency/currency.contracts.ts
@@ -0,0 +1,32 @@
+import { isCurrencyCode } from "@crm/db/currency";
+import { z } from "zod";
+
+const currencyCode = z
+ .string()
+ .trim()
+ .length(3, "A currency code is three letters, like USD.")
+ .refine(isCurrencyCode, "That is not a currency this CRM can convert.");
+
+export const setReportingCurrencyInput = z.object({
+ currency: currencyCode,
+});
+
+export type SetReportingCurrencyInput = z.infer<
+ typeof setReportingCurrencyInput
+>;
+
+export const setManualRateInput = z.object({
+ currency: currencyCode,
+ rate: z
+ .number()
+ .positive("A rate has to be greater than zero.")
+ .finite("That is not a rate."),
+});
+
+export type SetManualRateInput = z.infer<typeof setManualRateInput>;
+
+export const removeManualRateInput = z.object({
+ currency: currencyCode,
+});
+
+export type RemoveManualRateInput = z.infer<typeof removeManualRateInput>;
diff --git a/apps/api/src/currency/currency.module.ts b/apps/api/src/currency/currency.module.ts
new file mode 100644
index 00000000..ba643cd7
--- /dev/null
+++ b/apps/api/src/currency/currency.module.ts
@@ -0,0 +1,15 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { ConversionService } from "./conversion.service";
+import { CurrencyRouter } from "./currency.router";
+import { CurrencyService } from "./currency.service";
+import { RatesController } from "./rates.controller";
+import { RatesService } from "./rates.service";
+
+@Module({
+ imports: [TrpcModule],
+ controllers: [RatesController],
+ providers: [ConversionService, RatesService, CurrencyService, CurrencyRouter],
+ exports: [ConversionService],
+})
+export class CurrencyModule {}
diff --git a/apps/api/src/currency/currency.router.ts b/apps/api/src/currency/currency.router.ts
new file mode 100644
index 00000000..2046c127
--- /dev/null
+++ b/apps/api/src/currency/currency.router.ts
@@ -0,0 +1,47 @@
+import { Inject } from "@nestjs/common";
+import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import type { z } from "zod";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import {
+ removeManualRateInput,
+ setManualRateInput,
+ setReportingCurrencyInput,
+} from "./currency.contracts";
+import { CurrencyService } from "./currency.service";
+
+@Router({ alias: "currency" })
+@UseMiddlewares(AuthMiddleware)
+export class CurrencyRouter {
+ constructor(
+ @Inject(CurrencyService) private readonly currency: CurrencyService,
+ ) {}
+
+ @Query()
+ async settings() {
+ return this.currency.settings();
+ }
+
+ @Mutation({ input: setReportingCurrencyInput })
+ async setReportingCurrency(
+ @Input() input: z.infer<typeof setReportingCurrencyInput>,
+ ) {
+ return this.currency.setReportingCurrency(input.currency);
+ }
+
+ @Mutation({ input: setManualRateInput })
+ async setManualRate(@Input() input: z.infer<typeof setManualRateInput>) {
+ return this.currency.setManualRate(input.currency, input.rate);
+ }
+
+ @Mutation({ input: removeManualRateInput })
+ async removeManualRate(
+ @Input() input: z.infer<typeof removeManualRateInput>,
+ ) {
+ return this.currency.removeManualRate(input.currency);
+ }
+
+ @Mutation()
+ async refreshRates() {
+ return this.currency.refresh();
+ }
+}
diff --git a/apps/api/src/currency/currency.service.ts b/apps/api/src/currency/currency.service.ts
new file mode 100644
index 00000000..8da54375
--- /dev/null
+++ b/apps/api/src/currency/currency.service.ts
@@ -0,0 +1,221 @@
+import type { Db } from "@crm/db";
+import { Prisma, RateSource } from "@crm/db";
+import {
+ CURRENCIES,
+ type CurrencyMeta,
+ currencyName,
+ normalizeCurrency,
+} from "@crm/db/currency";
+import { writeReportingCurrency } from "@crm/db/settings";
+import { BadRequestException, Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { ConversionService, type Unconverted } from "./conversion.service";
+import { RatesService } from "./rates.service";
+
+export interface CurrencyRate {
+ currency: string;
+ name: string | null;
+ rate: number;
+ asOf: string;
+ source: RateSource;
+ provider: string | null;
+ overriding: boolean;
+}
+
+export interface CurrencyInUse {
+ currency: string;
+ name: string | null;
+ deals: number;
+ convertible: boolean;
+}
+
+export interface CurrencySettings {
+ reportingCurrency: string;
+ refreshedAt: string | null;
+ rates: CurrencyRate[];
+ inUse: CurrencyInUse[];
+ unconverted: Unconverted;
+ catalog: CurrencyMeta[];
+}
+
+@Injectable()
+export class CurrencyService {
+ private readonly logger = new Logger(CurrencyService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly conversion: ConversionService,
+ private readonly rates: RatesService,
+ ) {}
+
+ async settings(): Promise<CurrencySettings> {
+ const reportingCurrency = await this.conversion.reportingCurrency();
+
+ const [rows, refreshedAt, unconverted, usage] = await Promise.all([
+ this.db.exchangeRate.findMany({
+ where: { baseCurrency: reportingCurrency },
+ select: {
+ quoteCurrency: true,
+ rate: true,
+ asOf: true,
+ source: true,
+ provider: true,
+ },
+ }),
+ this.rates.refreshedAt(),
+ this.conversion.unconverted(),
+ this.db.deal.groupBy({
+ by: ["currency"],
+ where: { amount: { not: null } },
+ _count: { _all: true },
+ }),
+ ]);
+
+ const manual = new Set(
+ rows
+ .filter((row) => row.source === RateSource.MANUAL)
+ .map((row) => row.quoteCurrency),
+ );
+
+ const effective = new Map<string, CurrencyRate>();
+
+ for (const row of rows) {
+ const currency = normalizeCurrency(row.quoteCurrency);
+
+ if (row.source === RateSource.FETCHED && manual.has(row.quoteCurrency)) {
+ continue;
+ }
+
+ effective.set(currency, {
+ currency,
+ name: currencyName(currency),
+ rate: row.rate.toNumber(),
+ asOf: row.asOf.toISOString(),
+ source: row.source,
+ provider: row.provider,
+ overriding:
+ row.source === RateSource.MANUAL && manual.has(row.quoteCurrency),
+ });
+ }
+
+ const convertible = new Set([reportingCurrency, ...effective.keys()]);
+
+ return {
+ reportingCurrency,
+ refreshedAt: refreshedAt?.toISOString() ?? null,
+ rates: [...effective.values()].sort((a, b) =>
+ a.currency.localeCompare(b.currency),
+ ),
+ inUse: usage
+ .map((row) => {
+ const currency = normalizeCurrency(row.currency);
+ return {
+ currency,
+ name: currencyName(currency),
+ deals: row._count._all,
+ convertible: convertible.has(currency),
+ };
+ })
+ .sort(
+ (a, b) => b.deals - a.deals || a.currency.localeCompare(b.currency),
+ ),
+ unconverted,
+ catalog: [...CURRENCIES],
+ };
+ }
+
+ async setReportingCurrency(code: string): Promise<CurrencySettings> {
+ const currency = normalizeCurrency(code);
+ const current = await this.conversion.reportingCurrency();
+
+ if (currency === current) return this.settings();
+
+ await writeReportingCurrency(this.db, currency);
+
+ const refresh = await this.rates.refresh();
+ const rerated = await this.conversion.rerateAll();
+
+ this.logger.log({
+ message: "Reporting currency changed",
+ from: current,
+ to: currency,
+ ratesFetched: refresh.written,
+ converted: rerated.converted,
+ cleared: rerated.cleared,
+ missing: rerated.missing,
+ });
+
+ return this.settings();
+ }
+
+ async setManualRate(code: string, rate: number): Promise<CurrencySettings> {
+ const quoteCurrency = normalizeCurrency(code);
+ const baseCurrency = await this.conversion.reportingCurrency();
+
+ if (quoteCurrency === baseCurrency) {
+ throw new BadRequestException(
+ `${baseCurrency} is the reporting currency — its rate is always 1.`,
+ );
+ }
+
+ const asOf = new Date();
+
+ await this.db.exchangeRate.upsert({
+ where: {
+ baseCurrency_quoteCurrency_source: {
+ baseCurrency,
+ quoteCurrency,
+ source: RateSource.MANUAL,
+ },
+ },
+ create: {
+ baseCurrency,
+ quoteCurrency,
+ rate: new Prisma.Decimal(rate),
+ asOf,
+ source: RateSource.MANUAL,
+ },
+ update: { rate: new Prisma.Decimal(rate), asOf },
+ });
+
+ const filled = await this.conversion.fillMissing();
+
+ this.logger.log({
+ message: "Manual exchange rate saved",
+ baseCurrency,
+ quoteCurrency,
+ converted: filled.converted,
+ });
+
+ return this.settings();
+ }
+
+ async removeManualRate(code: string): Promise<CurrencySettings> {
+ const quoteCurrency = normalizeCurrency(code);
+ const baseCurrency = await this.conversion.reportingCurrency();
+
+ await this.db.exchangeRate.deleteMany({
+ where: { baseCurrency, quoteCurrency, source: RateSource.MANUAL },
+ });
+
+ this.logger.log({
+ message: "Manual exchange rate removed",
+ baseCurrency,
+ quoteCurrency,
+ });
+
+ return this.settings();
+ }
+
+ async refresh(): Promise<CurrencySettings> {
+ const refresh = await this.rates.refresh();
+
+ if (!refresh.ok) {
+ throw new BadRequestException(refresh.reason ?? "Could not fetch rates.");
+ }
+
+ await this.conversion.fillMissing();
+
+ return this.settings();
+ }
+}
diff --git a/apps/api/src/currency/rates.controller.ts b/apps/api/src/currency/rates.controller.ts
new file mode 100644
index 00000000..2ac65291
--- /dev/null
+++ b/apps/api/src/currency/rates.controller.ts
@@ -0,0 +1,72 @@
+import {
+ Controller,
+ ForbiddenException,
+ Get,
+ Headers,
+ Logger,
+ Post,
+ ServiceUnavailableException,
+} from "@nestjs/common";
+import { ConfigService } from "@nestjs/config";
+import { AllowAnonymous } from "@thallesp/nestjs-better-auth";
+import type { EnvironmentVariables } from "../config/env.validation";
+import { ConversionService } from "./conversion.service";
+import { RatesService } from "./rates.service";
+
+@Controller("internal/sync")
+export class RatesController {
+ private readonly logger = new Logger(RatesController.name);
+ private readonly secret: string | undefined;
+
+ constructor(
+ private readonly rates: RatesService,
+ private readonly conversion: ConversionService,
+ config: ConfigService<EnvironmentVariables, true>,
+ ) {
+ this.secret = config.get("CRON_SECRET", { infer: true });
+ }
+
+ @Get("rates")
+ @AllowAnonymous()
+ async ratesViaGet(@Headers("authorization") authorization?: string) {
+ return this.run(authorization);
+ }
+
+ @Post("rates")
+ @AllowAnonymous()
+ async ratesViaPost(@Headers("authorization") authorization?: string) {
+ return this.run(authorization);
+ }
+
+ private async run(authorization?: string) {
+ if (!this.secret) {
+ this.logger.error({
+ message: "CRON_SECRET is not set — refusing to run the rates route.",
+ });
+ throw new ServiceUnavailableException("Rate refresh is not configured.");
+ }
+
+ if (!timingSafeEquals(authorization ?? "", `Bearer ${this.secret}`)) {
+ throw new ForbiddenException();
+ }
+
+ const refresh = await this.rates.refresh();
+
+ if (!refresh.ok) return refresh;
+
+ const filled = await this.conversion.fillMissing();
+
+ return { ...refresh, converted: filled.converted, missing: filled.missing };
+ }
+}
+
+function timingSafeEquals(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+
+ let mismatch = 0;
+ for (let index = 0; index < a.length; index += 1) {
+ mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
+ }
+
+ return mismatch === 0;
+}
diff --git a/apps/api/src/currency/rates.service.ts b/apps/api/src/currency/rates.service.ts
new file mode 100644
index 00000000..5c22ccaf
--- /dev/null
+++ b/apps/api/src/currency/rates.service.ts
@@ -0,0 +1,172 @@
+import type { Db } from "@crm/db";
+import { Prisma, RateSource } from "@crm/db";
+import { isCurrencyCode, normalizeCurrency } from "@crm/db/currency";
+import {
+ readRatesRefreshedAt,
+ readReportingCurrency,
+ writeRatesRefreshedAt,
+} from "@crm/db/settings";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+export const RATES_PROVIDER = "frankfurter.dev";
+
+const RATES_URL = "https://api.frankfurter.dev/v1/latest";
+
+const RATES_TIMEOUT_MS = 8_000;
+
+export interface RateRefresh {
+ ok: boolean;
+ base: string;
+ written: number;
+ asOf: string | null;
+ reason: string | null;
+}
+
+interface FrankfurterResponse {
+ base?: unknown;
+ date?: unknown;
+ rates?: Record<string, unknown>;
+}
+
+function parseAsOf(value: unknown): Date | null {
+ if (typeof value !== "string") return null;
+ const date = new Date(`${value}T00:00:00.000Z`);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
+@Injectable()
+export class RatesService {
+ private readonly logger = new Logger(RatesService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async refreshedAt(): Promise<Date | null> {
+ return readRatesRefreshedAt(this.db);
+ }
+
+ async refresh(): Promise<RateRefresh> {
+ const base = await readReportingCurrency(this.db);
+ const quotes = await this.fetch(base);
+
+ if (!quotes) {
+ return {
+ ok: false,
+ base,
+ written: 0,
+ asOf: null,
+ reason: `Could not reach ${RATES_PROVIDER}. Rates entered by hand are unaffected.`,
+ };
+ }
+
+ const written = await this.store(base, quotes.rates, quotes.asOf);
+
+ await writeRatesRefreshedAt(this.db, new Date());
+
+ this.logger.log({
+ message: "Exchange rates refreshed",
+ base,
+ written,
+ asOf: quotes.asOf.toISOString(),
+ });
+
+ return {
+ ok: true,
+ base,
+ written,
+ asOf: quotes.asOf.toISOString(),
+ reason: null,
+ };
+ }
+
+ private async store(
+ base: string,
+ rates: Map<string, Prisma.Decimal>,
+ asOf: Date,
+ ): Promise<number> {
+ let written = 0;
+
+ for (const [quoteCurrency, rate] of rates) {
+ await this.db.exchangeRate.upsert({
+ where: {
+ baseCurrency_quoteCurrency_source: {
+ baseCurrency: base,
+ quoteCurrency,
+ source: RateSource.FETCHED,
+ },
+ },
+ create: {
+ baseCurrency: base,
+ quoteCurrency,
+ rate,
+ asOf,
+ source: RateSource.FETCHED,
+ provider: RATES_PROVIDER,
+ },
+ update: { rate, asOf, provider: RATES_PROVIDER },
+ });
+
+ written += 1;
+ }
+
+ return written;
+ }
+
+ private async fetch(
+ base: string,
+ ): Promise<{ rates: Map<string, Prisma.Decimal>; asOf: Date } | null> {
+ try {
+ const response = await fetch(
+ `${RATES_URL}?base=${encodeURIComponent(base)}`,
+ {
+ headers: { accept: "application/json" },
+ signal: AbortSignal.timeout(RATES_TIMEOUT_MS),
+ },
+ );
+
+ if (!response.ok) {
+ this.logger.warn({
+ message: "Exchange rate request failed",
+ status: response.status,
+ base,
+ });
+ return null;
+ }
+
+ const body = (await response.json()) as FrankfurterResponse;
+ const asOf = parseAsOf(body.date) ?? new Date();
+ const rates = new Map<string, Prisma.Decimal>();
+
+ for (const [code, value] of Object.entries(body.rates ?? {})) {
+ const quoteCurrency = normalizeCurrency(code);
+ if (!isCurrencyCode(quoteCurrency)) continue;
+ if (quoteCurrency === normalizeCurrency(base)) continue;
+
+ const perBase = Number(value);
+ if (!Number.isFinite(perBase) || perBase <= 0) continue;
+
+ rates.set(
+ quoteCurrency,
+ new Prisma.Decimal(1).dividedBy(perBase).toDecimalPlaces(10),
+ );
+ }
+
+ if (rates.size === 0) {
+ this.logger.warn({
+ message: "Exchange rate response carried no usable rates",
+ base,
+ });
+ return null;
+ }
+
+ return { rates, asOf };
+ } catch (error) {
+ this.logger.warn({
+ message: "Exchange rates unavailable",
+ base,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+ }
+}
diff --git a/apps/api/src/dashboard/dashboard.module.ts b/apps/api/src/dashboard/dashboard.module.ts
index 8150e508..db9a2ceb 100644
--- a/apps/api/src/dashboard/dashboard.module.ts
+++ b/apps/api/src/dashboard/dashboard.module.ts
@@ -1,10 +1,11 @@
import { Module } from "@nestjs/common";
+import { CurrencyModule } from "../currency/currency.module";
import { TrpcModule } from "../trpc/trpc.module";
import { DashboardRouter } from "./dashboard.router";
import { DashboardService } from "./dashboard.service";
@Module({
- imports: [TrpcModule],
+ imports: [TrpcModule, CurrencyModule],
providers: [DashboardService, DashboardRouter],
})
export class DashboardModule {}
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
index d2e56369..9a0d7080 100644
--- a/apps/api/src/dashboard/dashboard.service.ts
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -1,6 +1,7 @@
import { ActivityType, type Db, DealStage } from "@crm/db";
import { Injectable } from "@nestjs/common";
import { toCents } from "../crm/values";
+import { ConversionService } from "../currency/conversion.service";
import { InjectDatabase } from "../database/database.constants";
import { OPEN_DEAL_STAGES } from "../deals/deal-stage";
import type { DashboardSummaryInput } from "./dashboard.contracts";
@@ -30,7 +31,10 @@ function monthKey(date: Date): number {
@Injectable()
export class DashboardService {
- constructor(@InjectDatabase() private readonly db: Db) {}
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly conversion: ConversionService,
+ ) {}
async summary(actingUserId: string, input: DashboardSummaryInput) {
const mine = input.scope === "me";
@@ -50,12 +54,14 @@ export class DashboardService {
biggestOpen,
overdueTasks,
recentActivity,
+ reportingCurrency,
+ unconverted,
] = await Promise.all([
this.db.deal.groupBy({
by: ["stage"],
where: { ...owned, stage: { in: [...OPEN_DEAL_STAGES] } },
_count: { _all: true },
- _sum: { amount: true },
+ _sum: { baseAmount: true },
}),
this.db.deal.findMany({
where: {
@@ -66,7 +72,7 @@ export class DashboardService {
],
},
select: {
- amount: true,
+ baseAmount: true,
stage: true,
createdAt: true,
closedAt: true,
@@ -79,12 +85,12 @@ export class DashboardService {
expectedCloseDate: { gte: startOfMonth, lt: startOfNextMonth },
},
_count: { _all: true },
- _sum: { amount: true },
+ _sum: { baseAmount: true },
}),
this.db.deal.findMany({
where: { ...owned, stage: { in: [...OPEN_DEAL_STAGES] } },
orderBy: [
- { amount: { sort: "desc", nulls: "last" } },
+ { baseAmount: { sort: "desc", nulls: "last" } },
{ expectedCloseDate: "asc" },
],
take: 6,
@@ -94,6 +100,7 @@ export class DashboardService {
stage: true,
amount: true,
currency: true,
+ baseAmount: true,
expectedCloseDate: true,
stageChangedAt: true,
company: {
@@ -141,6 +148,8 @@ export class DashboardService {
deal: { select: { id: true, name: true } },
},
}),
+ this.conversion.reportingCurrency(),
+ this.conversion.unconverted(owned),
]);
const stages = OPEN_DEAL_STAGES.map((stage) => {
@@ -148,7 +157,7 @@ export class DashboardService {
return {
stage: stage as DealStage,
count: group?._count._all ?? 0,
- valueCents: toCents(group?._sum.amount ?? null) ?? 0,
+ valueCents: toCents(group?._sum.baseAmount ?? null) ?? 0,
};
});
@@ -167,7 +176,7 @@ export class DashboardService {
let cycleDays = 0;
for (const deal of recentDeals) {
- const cents = toCents(deal.amount) ?? 0;
+ const cents = toCents(deal.baseAmount) ?? 0;
const created = trend[monthKey(deal.createdAt) - firstBucket];
if (created) created.created += cents;
@@ -203,6 +212,8 @@ export class DashboardService {
return {
scope: input.scope,
+ reportingCurrency,
+ unconverted,
pipeline: {
stages,
totalCents: stages.reduce((total, s) => total + s.valueCents, 0),
@@ -221,12 +232,19 @@ export class DashboardService {
trend,
closingThisMonthTotal: {
count: closingThisMonthTotals._count._all,
- valueCents: toCents(closingThisMonthTotals._sum.amount) ?? 0,
+ valueCents: toCents(closingThisMonthTotals._sum.baseAmount) ?? 0,
},
biggestOpen: biggestOpen.map(
- ({ amount, expectedCloseDate, stageChangedAt, ...deal }) => ({
+ ({
+ amount,
+ baseAmount,
+ expectedCloseDate,
+ stageChangedAt,
+ ...deal
+ }) => ({
...deal,
amountCents: toCents(amount),
+ baseAmountCents: toCents(baseAmount),
expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
stageChangedAt: stageChangedAt.toISOString(),
}),
diff --git a/apps/api/src/deals/deals.contracts.ts b/apps/api/src/deals/deals.contracts.ts
index cee609c9..bdf4a2e1 100644
--- a/apps/api/src/deals/deals.contracts.ts
+++ b/apps/api/src/deals/deals.contracts.ts
@@ -1,4 +1,5 @@
import { DealStage } from "@crm/db";
+import { isCurrencyCode } from "@crm/db/currency";
import { z } from "zod";
import { listInput } from "../trpc/list-input";
@@ -31,7 +32,12 @@ export const dealCreateInput = z.object({
ownerId: z.string().min(1, "A deal needs an owner."),
stage: stageEnum.optional(),
amountCents: z.number().int().min(0).nullable().optional(),
- currency: z.string().length(3).optional(),
+ currency: z
+ .string()
+ .trim()
+ .length(3, "A currency code is three letters, like USD.")
+ .refine(isCurrencyCode, "That is not a currency this CRM can convert.")
+ .optional(),
expectedCloseDate: z.string().nullable().optional(),
});
@@ -39,10 +45,16 @@ export type DealCreateInput = z.infer<typeof dealCreateInput>;
const dealUpdateInput = z.object({
name: z.string().trim().min(1).optional(),
+ description: z.string().nullable().optional(),
companyId: z.string().optional(),
ownerId: z.string().optional(),
amountCents: z.number().int().min(0).nullable().optional(),
- currency: z.string().length(3).optional(),
+ currency: z
+ .string()
+ .trim()
+ .length(3, "A currency code is three letters, like USD.")
+ .refine(isCurrencyCode, "That is not a currency this CRM can convert.")
+ .optional(),
expectedCloseDate: z.string().nullable().optional(),
});
diff --git a/apps/api/src/deals/deals.module.ts b/apps/api/src/deals/deals.module.ts
index f35cf882..a75081e4 100644
--- a/apps/api/src/deals/deals.module.ts
+++ b/apps/api/src/deals/deals.module.ts
@@ -1,10 +1,11 @@
import { Module } from "@nestjs/common";
+import { CurrencyModule } from "../currency/currency.module";
import { TrpcModule } from "../trpc/trpc.module";
import { DealsRouter } from "./deals.router";
import { DealsService } from "./deals.service";
@Module({
- imports: [TrpcModule],
+ imports: [TrpcModule, CurrencyModule],
providers: [DealsService, DealsRouter],
exports: [DealsService],
})
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
index c3af0c6c..18f5ce04 100644
--- a/apps/api/src/deals/deals.service.ts
+++ b/apps/api/src/deals/deals.service.ts
@@ -5,6 +5,7 @@ import {
type Prisma,
Prisma as PrismaNamespace,
} from "@crm/db";
+import { normalizeCurrency } from "@crm/db/currency";
import {
BadRequestException,
Injectable,
@@ -15,7 +16,13 @@ import {
ActivityStampService,
type StampTargets,
} from "../crm/activity-stamp.service";
-import { fromCents, toCents } from "../crm/values";
+import {
+ blankToNull,
+ decimalFromCents,
+ fromCents,
+ toCents,
+} from "../crm/values";
+import { ConversionService } from "../currency/conversion.service";
import { InjectDatabase } from "../database/database.constants";
import {
countsByKey,
@@ -66,7 +73,7 @@ const SORTABLE: Record<
name: (dir) => [{ name: dir }],
company: (dir) => [{ company: { name: dir } }, { name: "asc" }],
stage: (dir) => [{ stage: dir }, { expectedCloseDate: "asc" }],
- amount: (dir) => [{ amount: dir }],
+ amount: (dir) => [{ baseAmount: { sort: dir, nulls: "last" } }],
expectedCloseDate: (dir) => [{ expectedCloseDate: dir }],
createdAt: (dir) => [{ createdAt: dir }],
owner: (dir) => [{ owner: { name: dir } }, { name: "asc" }],
@@ -80,13 +87,23 @@ export class DealsService {
constructor(
@InjectDatabase() private readonly db: Db,
private readonly stamp: ActivityStampService,
+ private readonly conversion: ConversionService,
) {}
async list(input: DealListInput) {
const where = this.buildWhere(input);
const { skip, take } = paginate(input);
- const [rows, total, facetCounts, openValue] = await Promise.all([
+ const openWhere = { ...where, stage: { in: [...OPEN_DEAL_STAGES] } };
+
+ const [
+ rows,
+ total,
+ facetCounts,
+ openValue,
+ reportingCurrency,
+ unconverted,
+ ] = await Promise.all([
this.db.deal.findMany({
where,
skip,
@@ -98,6 +115,7 @@ export class DealsService {
stage: true,
amount: true,
currency: true,
+ baseAmount: true,
expectedCloseDate: true,
closedAt: true,
company: { select: COMPANY_SELECT },
@@ -109,15 +127,18 @@ export class DealsService {
this.db.deal.count({ where }),
this.facetCounts(input),
this.db.deal.aggregate({
- where: { ...where, stage: { in: [...OPEN_DEAL_STAGES] } },
- _sum: { amount: true },
+ where: openWhere,
+ _sum: { baseAmount: true },
}),
+ this.conversion.reportingCurrency(),
+ this.conversion.unconverted(openWhere),
]);
return {
rows: rows.map(
({
amount,
+ baseAmount,
expectedCloseDate,
closedAt,
lastActivityAt,
@@ -126,6 +147,7 @@ export class DealsService {
}) => ({
...row,
amountCents: toCents(amount),
+ baseAmountCents: toCents(baseAmount),
expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
closedAt: closedAt?.toISOString() ?? null,
lastActivityAt: lastActivityAt?.toISOString() ?? null,
@@ -134,8 +156,14 @@ export class DealsService {
),
total,
facetCounts,
- openValueCents: toCents(openValue._sum.amount),
- } satisfies ListResult<unknown> & { openValueCents: number | null };
+ openValueCents: toCents(openValue._sum.baseAmount),
+ reportingCurrency,
+ unconverted,
+ } satisfies ListResult<unknown> & {
+ openValueCents: number | null;
+ reportingCurrency: string;
+ unconverted: { count: number; currencies: string[] };
+ };
}
async byId(id: string) {
@@ -144,10 +172,14 @@ export class DealsService {
select: {
id: true,
name: true,
+ description: true,
stage: true,
stageChangedAt: true,
amount: true,
currency: true,
+ baseAmount: true,
+ fxRate: true,
+ fxRateAt: true,
expectedCloseDate: true,
closedAt: true,
closedReason: true,
@@ -176,11 +208,15 @@ export class DealsService {
throw new NotFoundException(`No deal with id ${id}.`);
}
- const { contacts, amount, ...rest } = deal;
+ const { contacts, amount, baseAmount, fxRate, fxRateAt, ...rest } = deal;
return {
...rest,
amountCents: toCents(amount),
+ baseAmountCents: toCents(baseAmount),
+ reportingCurrency: await this.conversion.reportingCurrency(),
+ fxRate: fxRate?.toNumber() ?? null,
+ fxRateAt: fxRateAt?.toISOString() ?? null,
stageChangedAt: deal.stageChangedAt.toISOString(),
expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,
closedAt: deal.closedAt?.toISOString() ?? null,
@@ -194,6 +230,14 @@ export class DealsService {
const closed = isClosedStage(stage);
const now = new Date();
+ const currency = normalizeCurrency(
+ input.currency ?? (await this.conversion.reportingCurrency()),
+ );
+ const fx = await this.conversion.dealFields(
+ decimalFromCents(input.amountCents),
+ currency,
+ );
+
try {
const deal = await this.db.deal.create({
data: {
@@ -204,7 +248,8 @@ export class DealsService {
stageChangedAt: now,
closedAt: closed ? now : null,
amount: fromCents(input.amountCents),
- currency: input.currency ?? "USD",
+ currency,
+ ...fx,
expectedCloseDate: parseDate(input.expectedCloseDate),
},
select: { id: true, name: true, companyId: true },
@@ -222,6 +267,10 @@ export class DealsService {
const data: Prisma.DealUpdateInput = {};
if (input.name !== undefined) data.name = input.name.trim();
+ if (input.description !== undefined) {
+ data.description =
+ input.description === null ? null : blankToNull(input.description);
+ }
if (input.companyId !== undefined) {
data.company = { connect: { id: input.companyId } };
}
@@ -231,11 +280,35 @@ export class DealsService {
if (input.amountCents !== undefined) {
data.amount = fromCents(input.amountCents);
}
- if (input.currency !== undefined) data.currency = input.currency;
+ if (input.currency !== undefined) {
+ data.currency = normalizeCurrency(input.currency);
+ }
if (input.expectedCloseDate !== undefined) {
data.expectedCloseDate = parseDate(input.expectedCloseDate);
}
+ if (input.amountCents !== undefined || input.currency !== undefined) {
+ const current = await this.db.deal.findUnique({
+ where: { id },
+ select: { amount: true, currency: true },
+ });
+
+ if (!current) {
+ throw new NotFoundException(`No deal with id ${id}.`);
+ }
+
+ const amount =
+ input.amountCents !== undefined
+ ? decimalFromCents(input.amountCents)
+ : current.amount;
+ const currency =
+ input.currency !== undefined
+ ? normalizeCurrency(input.currency)
+ : normalizeCurrency(current.currency);
+
+ Object.assign(data, await this.conversion.dealFields(amount, currency));
+ }
+
try {
return await this.db.deal.update({
where: { id },
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
index 499b12df..69becaec 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -17,6 +17,7 @@ import { timelineInput, timelineCountsInput, myTasksInput, activityCreateInput,
import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInput, companyUpdateArgs, setPrimaryContactInput } from "../companies/companies.contracts";
import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs, factDecisionInput } from "../contacts/contacts.contracts";
import { conversationListInput, conversationEventsInput, conversationSaveInput, conversationIdInput } from "../conversations/conversations.contracts";
+import { setReportingCurrencyInput, setManualRateInput, removeManualRateInput } from "../currency/currency.contracts";
import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";
import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput } from "../deals/deals.contracts";
import { setAutoCreateInput, suppressDomainInput, threadInput, calendarEventInput } from "../google/google.contracts";
@@ -27,6 +28,7 @@ import type { ActivitiesRouter } from "../activities/activities.router";
import type { CompaniesRouter } from "../companies/companies.router";
import type { ContactsRouter } from "../contacts/contacts.router";
import type { ConversationsRouter } from "../conversations/conversations.router";
+import type { CurrencyRouter } from "../currency/currency.router";
import type { DashboardRouter } from "../dashboard/dashboard.router";
import type { DealsRouter } from "../deals/deals.router";
import type { GoogleRouter } from "../google/google.router";
@@ -120,6 +122,21 @@ const appRouter = t.router({
.input(conversationIdInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["remove"]>>)
}),
+ currency: t.router({
+ settings: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CurrencyRouter["settings"]>>),
+ setReportingCurrency: publicProcedure
+ .input(setReportingCurrencyInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CurrencyRouter["setReportingCurrency"]>>),
+ setManualRate: publicProcedure
+ .input(setManualRateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CurrencyRouter["setManualRate"]>>),
+ removeManualRate: publicProcedure
+ .input(removeManualRateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CurrencyRouter["removeManualRate"]>>),
+ refreshRates: publicProcedure
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CurrencyRouter["refreshRates"]>>)
+ }),
dashboard: t.router({
summary: publicProcedure
.input(dashboardSummaryInput)
diff --git a/apps/api/test/currency-totals.integration.spec.ts b/apps/api/test/currency-totals.integration.spec.ts
new file mode 100644
index 00000000..34b17580
--- /dev/null
+++ b/apps/api/test/currency-totals.integration.spec.ts
@@ -0,0 +1,235 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { db, RateSource } from "@crm/db";
+import { SETTINGS_ID, writeReportingCurrency } from "@crm/db/settings";
+import { ActivityStampService } from "../src/crm/activity-stamp.service";
+import { ConversionService } from "../src/currency/conversion.service";
+import { DashboardService } from "../src/dashboard/dashboard.service";
+import { DealsService } from "../src/deals/deals.service";
+
+const suffix = process.env.TEST_RUN_ID ?? "currency-totals-spec";
+const userId = `user-${suffix}`;
+const domain = `money-${suffix}.test`;
+
+const conversion = new ConversionService(db);
+const deals = new DealsService(db, new ActivityStampService(db), conversion);
+const dashboard = new DashboardService(db, conversion);
+
+let companyId: string;
+let previousReportingCurrency: string | null = null;
+
+const MILLION = 100_000_000;
+const HALF_MILLION = 50_000_000;
+
+async function rate(quote: string, value: string, source: RateSource) {
+ await db.exchangeRate.upsert({
+ where: {
+ baseCurrency_quoteCurrency_source: {
+ baseCurrency: "USD",
+ quoteCurrency: quote,
+ source,
+ },
+ },
+ create: {
+ baseCurrency: "USD",
+ quoteCurrency: quote,
+ rate: value,
+ asOf: new Date("2026-08-01T00:00:00.000Z"),
+ source,
+ },
+ update: { rate: value },
+ });
+}
+
+async function clearRates() {
+ await db.exchangeRate.deleteMany({
+ where: {
+ baseCurrency: { in: ["USD", "EUR"] },
+ quoteCurrency: { in: ["USD", "EUR", "CHF"] },
+ },
+ });
+}
+
+async function pipelineCents(): Promise<number> {
+ const summary = await dashboard.summary(userId, { scope: "me" });
+ return summary.pipeline.totalCents;
+}
+
+beforeAll(async () => {
+ const existing = await db.appSetting.findUnique({
+ where: { id: SETTINGS_ID },
+ select: { reportingCurrency: true },
+ });
+ previousReportingCurrency = existing?.reportingCurrency ?? null;
+
+ await writeReportingCurrency(db, "USD");
+ await clearRates();
+
+ await db.user.upsert({
+ where: { id: userId },
+ create: {
+ id: userId,
+ name: "Rate Tester",
+ email: `rates@${domain}`,
+ emailVerified: true,
+ },
+ update: {},
+ });
+
+ const company = await db.company.upsert({
+ where: { domain },
+ create: { name: `Money Co ${suffix}`, domain },
+ update: {},
+ select: { id: true },
+ });
+ companyId = company.id;
+
+ await rate("EUR", "1.10", RateSource.FETCHED);
+});
+
+afterAll(async () => {
+ await db.deal.deleteMany({ where: { companyId } });
+ await db.company.deleteMany({ where: { domain } });
+ await db.user.deleteMany({ where: { id: userId } });
+ await clearRates();
+ await db.appSetting.update({
+ where: { id: SETTINGS_ID },
+ data: { reportingCurrency: previousReportingCurrency },
+ });
+
+ await conversion.rerateAll();
+});
+
+describe("a total across currencies", () => {
+ it("converts on write and never adds two currencies together", async () => {
+ await deals.create({
+ name: `Domestic ${suffix}`,
+ companyId,
+ ownerId: userId,
+ amountCents: MILLION,
+ currency: "USD",
+ });
+
+ await deals.create({
+ name: `Continental ${suffix}`,
+ companyId,
+ ownerId: userId,
+ amountCents: MILLION,
+ currency: "EUR",
+ });
+
+ expect(await pipelineCents()).toBe(MILLION + 1.1 * MILLION);
+ });
+
+ it("locks the rate onto the deal, so the row says how it was converted", async () => {
+ const row = await db.deal.findFirst({
+ where: { companyId, currency: "EUR" },
+ select: { amount: true, baseAmount: true, fxRate: true, fxRateAt: true },
+ });
+
+ expect(row?.amount?.toNumber()).toBe(1_000_000);
+ expect(row?.baseAmount?.toNumber()).toBe(1_100_000);
+ expect(row?.fxRate?.toNumber()).toBe(1.1);
+ expect(row?.fxRateAt).toBeInstanceOf(Date);
+ });
+
+ it("leaves a deal it cannot convert out of the total, and says so", async () => {
+ const before = await pipelineCents();
+
+ await deals.create({
+ name: `Alpine ${suffix}`,
+ companyId,
+ ownerId: userId,
+ amountCents: HALF_MILLION,
+ currency: "CHF",
+ });
+
+ expect(await pipelineCents()).toBe(before);
+
+ const summary = await dashboard.summary(userId, { scope: "me" });
+ expect(summary.reportingCurrency).toBe("USD");
+ expect(summary.unconverted.count).toBe(1);
+ expect(summary.unconverted.currencies).toEqual(["CHF"]);
+ });
+
+ it("picks the waiting deal up when a rate finally arrives", async () => {
+ await rate("CHF", "1.25", RateSource.MANUAL);
+
+ const filled = await conversion.fillMissing();
+ expect(filled.converted).toBeGreaterThan(0);
+
+ expect(await pipelineCents()).toBe(
+ MILLION + 1.1 * MILLION + 1.25 * HALF_MILLION,
+ );
+
+ const summary = await dashboard.summary(userId, { scope: "me" });
+ expect(summary.unconverted.count).toBe(0);
+ });
+
+ it("does not re-rate a deal that already has a rate", async () => {
+ await rate("EUR", "9.99", RateSource.FETCHED);
+
+ await conversion.fillMissing();
+
+ const row = await db.deal.findFirst({
+ where: { companyId, currency: "EUR" },
+ select: { baseAmount: true },
+ });
+
+ expect(row?.baseAmount?.toNumber()).toBe(1_100_000);
+ });
+
+ it("lets a rate entered by hand beat the fetched one on a re-rate", async () => {
+ await rate("EUR", "1.50", RateSource.MANUAL);
+
+ await conversion.rerateAll();
+
+ const row = await db.deal.findFirst({
+ where: { companyId, currency: "EUR" },
+ select: { baseAmount: true, fxRate: true },
+ });
+
+ expect(row?.fxRate?.toNumber()).toBe(1.5);
+ expect(row?.baseAmount?.toNumber()).toBe(1_500_000);
+ });
+
+ it("re-rates everything when the reporting currency changes", async () => {
+ await writeReportingCurrency(db, "EUR");
+
+ const rerated = await conversion.rerateAll();
+ expect(rerated.missing).toContain("USD");
+
+ const summary = await dashboard.summary(userId, { scope: "me" });
+
+ expect(summary.reportingCurrency).toBe("EUR");
+ expect(summary.pipeline.totalCents).toBe(MILLION);
+ expect(summary.unconverted.currencies).toEqual(["CHF", "USD"]);
+ });
+});
+
+describe("the deals list", () => {
+ it("reports its open pipeline in the reporting currency and discloses the rest", async () => {
+ await writeReportingCurrency(db, "USD");
+ await conversion.rerateAll();
+
+ const list = await deals.list({
+ q: "",
+ page: 1,
+ pageSize: 25,
+ sort: "amount",
+ dir: "desc",
+ status: "open",
+ owner: userId,
+ stage: "all",
+ closing: "all",
+ });
+
+ expect(list.reportingCurrency).toBe("USD");
+ expect(list.unconverted.count).toBe(0);
+ expect(list.openValueCents).toBe(
+ MILLION + 1.5 * MILLION + 1.25 * HALF_MILLION,
+ );
+
+ const amounts = list.rows.map((row) => row.baseAmountCents);
+ expect(amounts).toEqual([...amounts].sort((a, b) => (b ?? 0) - (a ?? 0)));
+ });
+});
diff --git a/apps/api/test/record-delete.spec.ts b/apps/api/test/record-delete.spec.ts
index 8c567f7b..f8dfe6c4 100644
--- a/apps/api/test/record-delete.spec.ts
+++ b/apps/api/test/record-delete.spec.ts
@@ -8,6 +8,7 @@ import { FaviconService } from "../src/companies/favicon.service";
import { ContactsService } from "../src/contacts/contacts.service";
import { ActivityStampService } from "../src/crm/activity-stamp.service";
import { EnrichmentLogService } from "../src/crm/enrichment-log.service";
+import { ConversionService } from "../src/currency/conversion.service";
import { GoogleMatchService } from "../src/google/google-match.service";
const suffix = process.env.TEST_RUN_ID ?? "record-delete-spec";
@@ -30,6 +31,7 @@ const agent = {
const directory = new CompanyDirectoryService(db, agent);
const log = new EnrichmentLogService(db, stamp);
const queue = new AgentQueueService(db);
+const conversion = new ConversionService(db);
const contacts = new ContactsService(db, directory, agent, queue, stamp);
const companies = new CompaniesService(
@@ -38,6 +40,7 @@ const companies = new CompaniesService(
queue,
{ backfill: async () => undefined } as unknown as FaviconService,
stamp,
+ conversion,
);
const match = new GoogleMatchService(db, directory, agent, log);
diff --git a/apps/app/app/(app)/[slug]/dashboard-summary.tsx b/apps/app/app/(app)/[slug]/dashboard-summary.tsx
index 2ea1128d..1ba1a716 100644
--- a/apps/app/app/(app)/[slug]/dashboard-summary.tsx
+++ b/apps/app/app/(app)/[slug]/dashboard-summary.tsx
@@ -83,7 +83,7 @@ export function DashboardSummary() {
const { biggestOpen, overdueTasks, recentActivity } = summary;
const mine = scope === "me";
- const largestOpenCents = biggestOpen[0]?.amountCents ?? 0;
+ const largestOpenCents = biggestOpen[0]?.baseAmountCents ?? 0;
const openColumns: SimpleTableColumn[] = [
{ header: "Deal" },
@@ -154,7 +154,8 @@ export function DashboardSummary() {
<ValueMeter
share={
largestOpenCents > 0
- ? ((deal.amountCents ?? 0) / largestOpenCents) * 100
+ ? ((deal.baseAmountCents ?? 0) / largestOpenCents) *
+ 100
: 0
}
color={dealStageColor(deal.stage)}
diff --git a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
index d83e311b..60d0b64b 100644
--- a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
+++ b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
@@ -1,6 +1,7 @@
"use client";
import Add from "@carbon/icons-react/es/Add";
+import { CURRENCIES } from "@crm/db/currency";
import { Button } from "@crm/ui/components/button";
import { DatePicker } from "@crm/ui/components/date-picker";
import {
@@ -71,6 +72,7 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
const [ownerId, setOwnerId] = useState(UNSET);
const [stage, setStage] = useState<string>("DEMO_BOOKED");
const [amount, setAmount] = useState("");
+ const [currency, setCurrency] = useState("");
const [closeDate, setCloseDate] = useState("");
const nameId = useId();
@@ -80,8 +82,11 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
const users = useQuery(trpc.users.list.queryOptions());
const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const me = useQuery(trpc.users.me.queryOptions());
+ const currencies = useQuery(trpc.currency.settings.queryOptions());
const resolvedOwner = ownerId || me.data?.id || UNSET;
+ const resolvedCurrency =
+ currency || currencies.data?.reportingCurrency || "USD";
const create = useMutation(
trpc.deals.create.mutationOptions({
@@ -91,6 +96,7 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
await setOpen(null);
setName("");
setAmount("");
+ setCurrency("");
setCloseDate("");
openRecord({ kind: "deal", id: deal.id });
},
@@ -128,6 +134,7 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
amountCents: Number.isFinite(parsed)
? Math.round(parsed * 100)
: null,
+ currency: resolvedCurrency,
expectedCloseDate: closeDate || null,
});
}}
@@ -198,15 +205,32 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
</Field>
<Field>
- <FieldLabel htmlFor={amountId}>Amount (USD)</FieldLabel>
- <Input
- id={amountId}
- value={amount}
- onChange={(event) => setAmount(event.target.value)}
- placeholder="24000"
- inputMode="decimal"
- autoComplete="off"
- />
+ <FieldLabel htmlFor={amountId}>Amount</FieldLabel>
+ <div className="flex gap-2">
+ <Input
+ id={amountId}
+ value={amount}
+ onChange={(event) => setAmount(event.target.value)}
+ placeholder="24000"
+ inputMode="decimal"
+ autoComplete="off"
+ />
+ <Select value={resolvedCurrency} onValueChange={setCurrency}>
+ <SelectTrigger
+ aria-label="Currency"
+ className="w-28 shrink-0"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {CURRENCIES.map((entry) => (
+ <SelectItem key={entry.code} value={entry.code}>
+ {entry.code}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
</Field>
<Field>
diff --git a/apps/app/app/(app)/[slug]/deals/deals-table.tsx b/apps/app/app/(app)/[slug]/deals/deals-table.tsx
index 01cf6d8f..a40ad2fd 100644
--- a/apps/app/app/(app)/[slug]/deals/deals-table.tsx
+++ b/apps/app/app/(app)/[slug]/deals/deals-table.tsx
@@ -159,6 +159,8 @@ export function DealsTable() {
];
const openValueCents = deals.data?.openValueCents;
+ const reportingCurrency = deals.data?.reportingCurrency;
+ const unconverted = deals.data?.unconverted;
return (
<DataTable
@@ -186,8 +188,17 @@ export function DealsTable() {
openValueCents === null || openValueCents === undefined ? undefined : (
<span>
{deals.data?.total ?? 0} deals ·{" "}
- <span className="tabular-nums">{formatMoney(openValueCents)}</span>{" "}
+ <span className="tabular-nums">
+ {formatMoney(openValueCents, reportingCurrency)}
+ </span>{" "}
open pipeline
+ {unconverted && unconverted.count > 0 ? (
+ <span className="text-muted-foreground">
+ {" "}
+ · {unconverted.count} not counted (no{" "}
+ {unconverted.currencies.join(", ")} rate)
+ </span>
+ ) : null}
</span>
)
}
diff --git a/apps/app/app/(app)/[slug]/sales-dashboard.tsx b/apps/app/app/(app)/[slug]/sales-dashboard.tsx
index 721d72a0..a7594794 100644
--- a/apps/app/app/(app)/[slug]/sales-dashboard.tsx
+++ b/apps/app/app/(app)/[slug]/sales-dashboard.tsx
@@ -53,8 +53,17 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
performance,
trend,
closingThisMonthTotal,
+ reportingCurrency,
+ unconverted,
} = summary;
+ const money = (cents: number) => formatMoneyCompact(cents, reportingCurrency);
+ const exact = (value: unknown) =>
+ formatMoney(
+ typeof value === "number" ? value : Number(value),
+ reportingCurrency,
+ );
+
const hasTrend = trend.some((point) => point.won > 0 || point.created > 0);
const stageSlices = pipeline.stages
@@ -72,18 +81,18 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
<StatGroup>
<StatCard
label="Closed won this month"
- value={formatMoneyCompact(wonThisMonth.valueCents)}
+ value={money(wonThisMonth.valueCents)}
delta={changeDelta(
wonThisMonth.valueCents,
wonPrevMonth.valueCents,
"vs. last month",
)}
- description={`${formatCount(wonThisMonth.count, "deal")} · ${formatMoneyCompact(wonPrevMonth.valueCents)} last month`}
+ description={`${formatCount(wonThisMonth.count, "deal")} · ${money(wonPrevMonth.valueCents)} last month`}
/>
<StatCard
label="Open pipeline"
- value={formatMoneyCompact(pipeline.totalCents)}
- description={`${formatCount(pipeline.totalDeals, "deal")} in progress · ${formatMoneyCompact(closingThisMonthTotal.valueCents)} due this month`}
+ value={money(pipeline.totalCents)}
+ description={`${formatCount(pipeline.totalDeals, "deal")} in progress · ${money(closingThisMonthTotal.valueCents)} due this month`}
/>
<StatCard
label={`Win rate (${performance.windowDays}d)`}
@@ -103,7 +112,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
value={
performance.avgDealCents === null
? "—"
- : formatMoneyCompact(performance.avgDealCents)
+ : money(performance.avgDealCents)
}
description={
performance.avgCycleDays === null
@@ -113,6 +122,24 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
/>
</StatGroup>
+ {unconverted.count > 0 ? (
+ <p className="text-muted-foreground text-xs">
+ Every figure above is in {reportingCurrency}.{" "}
+ {formatCount(unconverted.count, "deal")} in{" "}
+ {unconverted.currencies.join(", ")}{" "}
+ {unconverted.count === 1 ? "is" : "are"} not included — there is no
+ rate to convert {unconverted.currencies.length === 1 ? "it" : "them"}{" "}
+ with.{" "}
+ <Link
+ href={workspaceUrl("/settings/currencies")}
+ className="underline hover:no-underline"
+ >
+ Set one
+ </Link>
+ .
+ </p>
+ ) : null}
+
<DashboardRow split="hero">
<ChartPanel
title="Closed won vs. new pipeline"
@@ -128,9 +155,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
variant="gradient"
bloom="high"
showLegend
- formatValue={(value) =>
- formatMoney(typeof value === "number" ? value : Number(value))
- }
+ formatValue={exact}
/>
</div>
) : (
@@ -147,11 +172,9 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
<DonutStat
data={stageSlices}
height={168}
- centerValue={formatMoneyCompact(pipeline.totalCents)}
+ centerValue={money(pipeline.totalCents)}
centerLabel="open"
- formatValue={(value) =>
- formatMoney(typeof value === "number" ? value : Number(value))
- }
+ formatValue={exact}
/>
<ul className="flex flex-col px-5 pb-1 md:px-6">
{stageSlices.map((slice) => (
@@ -172,7 +195,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
{slice.count}
</span>
<span className="w-14 shrink-0 text-right font-medium tabular-nums">
- {formatMoneyCompact(slice.value)}
+ {money(slice.value)}
</span>
</Link>
</li>
diff --git a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx
new file mode 100644
index 00000000..a54effb7
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx
@@ -0,0 +1,348 @@
+"use client";
+
+import { CURRENCIES } from "@crm/db/currency";
+import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
+import { CardTableEmpty } from "@crm/ui/components/card-table";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { Field, FieldDescription, FieldLabel } from "@crm/ui/components/field";
+import { Input } from "@crm/ui/components/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import {
+ SimpleTable,
+ type SimpleTableColumn,
+ SimpleTableRow,
+} from "@crm/ui/components/simple-table";
+import { Spinner } from "@crm/ui/components/spinner";
+import { StatusIndicator } from "@crm/ui/components/status-indicator";
+import { TableCell } from "@crm/ui/components/table";
+import { formatCount, relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+
+const CELL = "px-3 py-2.5 align-middle";
+
+const RATE_COLUMNS: SimpleTableColumn[] = [
+ { header: "Currency" },
+ { header: "Rate", width: "w-32", align: "right" },
+ { header: "Source", width: "w-28" },
+ { header: "As of", width: "w-24", align: "right" },
+ { srLabel: "Actions", width: "w-20" },
+];
+
+const USAGE_COLUMNS: SimpleTableColumn[] = [
+ { header: "Currency" },
+ { header: "Deals", width: "w-20", align: "right" },
+ { header: "Convertible", width: "w-32", align: "right" },
+];
+
+export function CurrencySettings() {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+
+ const baseId = useId();
+ const rateCurrencyId = useId();
+ const rateValueId = useId();
+
+ const [draftCurrency, setDraftCurrency] = useState("");
+ const [draftRate, setDraftRate] = useState("");
+
+ const settings = useQuery(trpc.currency.settings.queryOptions());
+
+ const invalidate = () => cache.currency();
+
+ const setBase = useMutation(
+ trpc.currency.setReportingCurrency.mutationOptions({
+ onSuccess: async (next) => {
+ await invalidate();
+ toast.success(
+ `Every total is now reported in ${next.reportingCurrency}.`,
+ );
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const setRate = useMutation(
+ trpc.currency.setManualRate.mutationOptions({
+ onSuccess: async () => {
+ await invalidate();
+ setDraftCurrency("");
+ setDraftRate("");
+ toast.success("Rate saved.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const removeRate = useMutation(
+ trpc.currency.removeManualRate.mutationOptions({
+ onSuccess: async () => {
+ await invalidate();
+ toast.success("Rate removed.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const refresh = useMutation(
+ trpc.currency.refreshRates.mutationOptions({
+ onSuccess: async () => {
+ await invalidate();
+ toast.success("Rates refreshed.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ if (!settings.data) return null;
+
+ const { reportingCurrency, refreshedAt, rates, inUse, unconverted } =
+ settings.data;
+
+ const busy =
+ setBase.isPending ||
+ setRate.isPending ||
+ removeRate.isPending ||
+ refresh.isPending;
+
+ return (
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Reporting currency</CardTitle>
+ <CardDescription>
+ Every total, chart and average in the CRM is expressed in this
+ currency. Each deal keeps the currency it was sold in.
+ </CardDescription>
+ </CardHeader>
+
+ <CardContent>
+ <Field>
+ <FieldLabel htmlFor={baseId}>Report totals in</FieldLabel>
+ <Select
+ value={reportingCurrency}
+ disabled={busy}
+ onValueChange={(currency) => setBase.mutate({ currency })}
+ >
+ <SelectTrigger id={baseId} className="w-full max-w-sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {CURRENCIES.map((entry) => (
+ <SelectItem key={entry.code} value={entry.code}>
+ {entry.code} · {entry.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Changing this re-converts every deal at today's rates. Figures
+ already reported will move.
+ </FieldDescription>
+ </Field>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Exchange rates</CardTitle>
+ <CardDescription>
+ How many {reportingCurrency} one unit of each currency buys. Fetched
+ daily from the European Central Bank; a rate you enter here wins.
+ </CardDescription>
+ <CardAction>
+ <Button
+ variant="contrast"
+ size="sm"
+ disabled={busy}
+ onClick={() => refresh.mutate()}
+ >
+ {refresh.isPending ? <Spinner data-icon="inline-start" /> : null}
+ Refresh
+ </Button>
+ </CardAction>
+ </CardHeader>
+
+ <CardContent>
+ <form
+ className="flex flex-wrap items-end gap-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const rate = Number.parseFloat(draftRate);
+ if (!Number.isFinite(rate) || rate <= 0) {
+ toast.error("A rate has to be a number greater than zero.");
+ return;
+ }
+ setRate.mutate({ currency: draftCurrency, rate });
+ }}
+ >
+ <Field className="w-48">
+ <FieldLabel htmlFor={rateCurrencyId}>Currency</FieldLabel>
+ <Select
+ value={draftCurrency}
+ disabled={busy}
+ onValueChange={setDraftCurrency}
+ >
+ <SelectTrigger id={rateCurrencyId} className="w-full">
+ <SelectValue placeholder="Pick one" />
+ </SelectTrigger>
+ <SelectContent>
+ {CURRENCIES.filter(
+ (entry) => entry.code !== reportingCurrency,
+ ).map((entry) => (
+ <SelectItem key={entry.code} value={entry.code}>
+ {entry.code} · {entry.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field className="w-48">
+ <FieldLabel htmlFor={rateValueId}>
+ 1 {draftCurrency || "unit"} = ? {reportingCurrency}
+ </FieldLabel>
+ <Input
+ id={rateValueId}
+ value={draftRate}
+ inputMode="decimal"
+ placeholder="1.09"
+ disabled={busy}
+ onChange={(event) => setDraftRate(event.target.value)}
+ />
+ </Field>
+
+ <Button
+ type="submit"
+ disabled={busy || draftCurrency === "" || draftRate.trim() === ""}
+ >
+ {setRate.isPending ? <Spinner data-icon="inline-start" /> : null}
+ Save rate
+ </Button>
+ </form>
+ </CardContent>
+
+ {rates.length === 0 ? (
+ <CardTableEmpty>
+ No rates yet. Refresh to fetch them, or enter one by hand.
+ </CardTableEmpty>
+ ) : (
+ <SimpleTable columns={RATE_COLUMNS}>
+ {rates.map((rate) => (
+ <SimpleTableRow key={rate.currency}>
+ <TableCell className={CELL}>
+ <span className="font-medium">{rate.currency}</span>
+ <span className="text-muted-foreground">
+ {rate.name ? ` · ${rate.name}` : ""}
+ </span>
+ </TableCell>
+ <TableCell className={`${CELL} text-right tabular-nums`}>
+ {rate.rate}
+ </TableCell>
+ <TableCell className={CELL}>
+ <StatusIndicator
+ size="sm"
+ tone={rate.source === "MANUAL" ? "warning" : "success"}
+ label={rate.source === "MANUAL" ? "By hand" : "Fetched"}
+ />
+ </TableCell>
+ <TableCell
+ className={`${CELL} text-right text-muted-foreground`}
+ >
+ <span suppressHydrationWarning>
+ {relativeTimeFromIso(rate.asOf)}
+ </span>
+ </TableCell>
+ <TableCell className={`${CELL} text-right`}>
+ {rate.source === "MANUAL" ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy}
+ onClick={() =>
+ removeRate.mutate({ currency: rate.currency })
+ }
+ >
+ Remove
+ </Button>
+ ) : null}
+ </TableCell>
+ </SimpleTableRow>
+ ))}
+ </SimpleTable>
+ )}
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Currencies in use</CardTitle>
+ <CardDescription>
+ {unconverted.count === 0
+ ? "Every deal with an amount can be converted into the reporting currency."
+ : `${formatCount(unconverted.count, "deal")} cannot be converted, so ${unconverted.count === 1 ? "it is" : "they are"} left out of every total.`}
+ {refreshedAt ? (
+ <>
+ {" "}
+ Rates last fetched{" "}
+ <span suppressHydrationWarning>
+ {relativeTimeFromIso(refreshedAt)}
+ </span>
+ .
+ </>
+ ) : null}
+ </CardDescription>
+ </CardHeader>
+
+ {inUse.length === 0 ? (
+ <CardTableEmpty>No deals have an amount yet.</CardTableEmpty>
+ ) : (
+ <SimpleTable columns={USAGE_COLUMNS}>
+ {inUse.map((row) => (
+ <SimpleTableRow key={row.currency}>
+ <TableCell className={CELL}>
+ <span className="font-medium">{row.currency}</span>
+ <span className="text-muted-foreground">
+ {row.name ? ` · ${row.name}` : ""}
+ </span>
+ {row.currency === reportingCurrency ? (
+ <span className="text-muted-foreground">
+ {" "}
+ · reporting currency
+ </span>
+ ) : null}
+ </TableCell>
+ <TableCell className={`${CELL} text-right tabular-nums`}>
+ {row.deals}
+ </TableCell>
+ <TableCell className={`${CELL} text-right`}>
+ {row.convertible ? (
+ <StatusIndicator size="sm" tone="success" label="Yes" />
+ ) : (
+ <StatusIndicator size="sm" tone="error" label="No rate" />
+ )}
+ </TableCell>
+ </SimpleTableRow>
+ ))}
+ </SimpleTable>
+ )}
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/settings/currencies/page.tsx b/apps/app/app/(app)/[slug]/settings/currencies/page.tsx
new file mode 100644
index 00000000..3fdba12d
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/settings/currencies/page.tsx
@@ -0,0 +1,58 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellLoading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { CurrencySettings } from "./currency-settings";
+
+export const metadata: Metadata = {
+ title: "Currencies",
+};
+
+export default function CurrenciesSettingsPage() {
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Currencies</PageShellTitle>
+ <PageShellDescription>
+ What your numbers are reported in, and how the other currencies get
+ there.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <Suspense fallback={<PageShellLoading />}>
+ <Currencies />
+ </Suspense>
+ </PageShellContent>
+ </PageShell>
+ );
+}
+
+async function Currencies() {
+ await requireSession();
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+
+ await queryClient.prefetchQuery(trpc.currency.settings.queryOptions());
+
+ return (
+ <HydrateClient>
+ <div className="flex max-w-3xl flex-col gap-6">
+ <CurrencySettings />
+ </div>
+ </HydrateClient>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
index 4b19cc32..062c2bc6 100644
--- a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
+++ b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
@@ -16,6 +16,7 @@ const ROOT = "/settings";
const ITEMS: SettingsNavItem[] = [
{ title: "General", href: ROOT },
+ { title: "Currencies", href: `${ROOT}/currencies` },
{ title: "Members", href: `${ROOT}/members` },
{ title: "SSO", href: `${ROOT}/sso` },
{ title: "Connections", href: `${ROOT}/connections` },
diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsx
index a731467f..f7d386d5 100644
--- a/apps/app/components/crm/inline-field.tsx
+++ b/apps/app/components/crm/inline-field.tsx
@@ -13,6 +13,7 @@ import {
} from "@crm/ui/components/select";
import { SOURCED_VALUE, SourcedValue } from "@crm/ui/components/sourced-value";
import { Spinner } from "@crm/ui/components/spinner";
+import { Textarea } from "@crm/ui/components/textarea";
import { cn } from "@crm/ui/lib/utils";
import { useId, useState } from "react";
import { PROPERTY_LABEL, PROPERTY_ROW } from "@/components/detail-sheet";
@@ -21,6 +22,10 @@ const ROW = cn(PROPERTY_ROW, "items-center");
const LABEL = PROPERTY_LABEL;
const CONTROL =
"h-8 w-full justify-start px-2 font-normal hover:border-input hover:bg-muted/40 border border-transparent";
+const BLOCK_CONTROL = cn(
+ CONTROL,
+ "h-auto min-h-16 items-start whitespace-pre-wrap py-2 text-left leading-5",
+);
export function savingField(update: {
isPending: boolean;
@@ -140,6 +145,75 @@ export function InlineField({
);
}
+export function InlineTextArea({
+ label,
+ value,
+ onSave,
+ saving = false,
+ placeholder,
+}: {
+ label: string;
+ value: string | null;
+ onSave: (next: string) => void;
+ saving?: boolean;
+ placeholder?: string;
+}) {
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(value ?? "");
+
+ const commit = () => {
+ setEditing(false);
+ if (draft.trim() !== (value ?? "")) onSave(draft.trim());
+ };
+
+ if (editing) {
+ return (
+ <Textarea
+ aria-label={label}
+ autoFocus
+ value={draft}
+ placeholder={placeholder}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ commit();
+ }
+ if (event.key === "Escape") {
+ setDraft(value ?? "");
+ setEditing(false);
+ }
+ }}
+ />
+ );
+ }
+
+ const shown = saving ? draft.trim() : (value ?? "");
+
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label={label}
+ className={BLOCK_CONTROL}
+ onClick={() => {
+ setDraft(value ?? "");
+ setEditing(true);
+ }}
+ >
+ {saving ? <Spinner /> : null}
+ {shown ? (
+ <span className="min-w-0">{shown}</span>
+ ) : (
+ <span className="min-w-0 text-muted-foreground">
+ {placeholder ?? <EmptyCellValue />}
+ </span>
+ )}
+ </Button>
+ );
+}
+
export function InlineDateField({
label,
value,
diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsx
index 12f3a2dc..d7150b58 100644
--- a/apps/app/components/crm/record-sheet/company-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx
@@ -188,9 +188,12 @@ export function CompanySheet({ companyId }: { companyId: string }) {
const openDeals =
company?.deals.filter((deal) => OPEN_STAGES.includes(deal.stage)) ?? [];
const openValueCents = openDeals.reduce(
- (total, deal) => total + (deal.amountCents ?? 0),
+ (total, deal) => total + (deal.baseAmountCents ?? 0),
0,
);
+ const openUncounted = openDeals.filter(
+ (deal) => deal.amountCents !== null && deal.baseAmountCents === null,
+ ).length;
const closing = nextClose(openDeals);
const tabs: DetailSheetTab[] = company
@@ -301,8 +304,14 @@ export function CompanySheet({ companyId }: { companyId: string }) {
<DetailSheetStats>
<DetailSheetStat label="Open pipeline">
<span className="tabular-nums">
- {formatMoney(openValueCents)}
+ {formatMoney(openValueCents, company.reportingCurrency)}
</span>
+ {openUncounted > 0 ? (
+ <span className="text-muted-foreground">
+ {" "}
+ +{openUncounted} unconverted
+ </span>
+ ) : null}
</DetailSheetStat>
<DetailSheetStat label="Open deals">
<span className="tabular-nums">{openDeals.length}</span>
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
index 09b5d646..e14f7c58 100644
--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -1,6 +1,7 @@
"use client";
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
+import { CURRENCIES } from "@crm/db/currency";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
import {
EntityLogo,
@@ -17,10 +18,12 @@ import {
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { AgentPanel } from "@/components/crm/agent-panel";
+import { contactName } from "@/components/crm/contact-name";
import {
InlineDateField,
InlineField,
InlineSelectField,
+ InlineTextArea,
savingField,
} from "@/components/crm/inline-field";
import { OwnerCell } from "@/components/crm/owner-cell";
@@ -46,6 +49,30 @@ import { useOpenRecord, useRecordSheetView } from "./record-stack";
type Deal = RouterOutputs["deals"]["byId"];
+const CURRENCY_OPTIONS = CURRENCIES.map((entry) => ({
+ value: entry.code,
+ label: `${entry.code} · ${entry.name}`,
+}));
+
+function ReportedValue({ deal }: { deal: Deal }) {
+ if (deal.currency === deal.reportingCurrency) return null;
+ if (deal.amountCents === null) return null;
+
+ return (
+ <DetailSheetProperty label={`In ${deal.reportingCurrency}`}>
+ {deal.baseAmountCents === null ? (
+ <span className="text-muted-foreground">
+ No {deal.currency} rate — left out of totals
+ </span>
+ ) : (
+ <span className="tabular-nums text-muted-foreground">
+ ≈ {formatMoney(deal.baseAmountCents, deal.reportingCurrency)}
+ </span>
+ )}
+ </DetailSheetProperty>
+ );
+}
+
const CONTACT_COLUMNS = [
{ header: "Name", width: "w-[30%]", className: "pl-5" },
{ header: "Role", width: "w-[20%]" },
@@ -195,21 +222,6 @@ function DealOverview({ deal }: { deal: Deal }) {
<DetailSheetBody>
<DetailSheetSection title="Stage">
<StageStepper dealId={deal.id} stage={deal.stage} />
-
- {deal.closedReason ? (
- <DetailSheetProperties>
- <DetailSheetProperty label="Closed">
- {deal.closedAt ? (
- dateFormat.format(new Date(deal.closedAt))
- ) : (
- <EmptyCellValue />
- )}
- </DetailSheetProperty>
- <DetailSheetProperty label="Reason" wide>
- {deal.closedReason}
- </DetailSheetProperty>
- </DetailSheetProperties>
- ) : null}
</DetailSheetSection>
<DetailSheetSection title="Details">
@@ -240,18 +252,13 @@ function DealOverview({ deal }: { deal: Deal }) {
formatMoney(Math.round(Number(value) * 100), deal.currency)
}
/>
- <InlineField
+ <InlineSelectField
label="Currency"
value={deal.currency}
- saving={isSaving("currency")}
- onSave={(currency) => {
- if (currency.length !== 3) {
- toast.error("Use a three-letter currency code, like USD.");
- return;
- }
- save({ currency: currency.toUpperCase() });
- }}
+ options={CURRENCY_OPTIONS}
+ onSave={(currency) => save({ currency })}
/>
+ <ReportedValue deal={deal} />
<InlineDateField
label="Close date"
value={deal.expectedCloseDate}
@@ -278,10 +285,81 @@ function DealOverview({ deal }: { deal: Deal }) {
/>
</DetailSheetProperties>
</DetailSheetSection>
+
+ <DetailSheetSection title="Description">
+ <InlineTextArea
+ label="Description"
+ value={deal.description}
+ placeholder={`What ${deal.company.name} is buying, why now, and what stands in the way.`}
+ saving={isSaving("description")}
+ onSave={(description) => save({ description })}
+ />
+ </DetailSheetSection>
+
+ <WhereItStands deal={deal} />
</DetailSheetBody>
);
}
+function WhereItStands({ deal }: { deal: Deal }) {
+ const openRecord = useOpenRecord();
+
+ return (
+ <DetailSheetSection title="Where it stands">
+ <DetailSheetProperties>
+ <DetailSheetProperty label="Opened">
+ {dateFormat.format(new Date(deal.createdAt))}
+ </DetailSheetProperty>
+
+ <DetailSheetProperty label="In stage since">
+ {dateFormat.format(new Date(deal.stageChangedAt))}
+ </DetailSheetProperty>
+
+ {deal.closedAt ? (
+ <DetailSheetProperty label="Closed">
+ {dateFormat.format(new Date(deal.closedAt))}
+ </DetailSheetProperty>
+ ) : null}
+
+ {deal.closedReason ? (
+ <DetailSheetProperty label="Reason" wide>
+ {deal.closedReason}
+ </DetailSheetProperty>
+ ) : null}
+
+ <DetailSheetProperty label="On it" wide>
+ {deal.contacts.length === 0 ? (
+ <span className="text-muted-foreground">
+ Nobody from {deal.company.name} is attached yet.
+ </span>
+ ) : (
+ <span className="flex flex-wrap items-center gap-x-3 gap-y-0.5">
+ {deal.contacts.map((contact) => {
+ const aside = contact.role ?? contact.title;
+ return (
+ <button
+ key={contact.id}
+ type="button"
+ onClick={() =>
+ openRecord({ kind: "contact", id: contact.id })
+ }
+ className="min-w-0 truncate underline-offset-2 hover:underline"
+ >
+ {contactName(contact)}
+ {aside ? (
+ <span className="text-muted-foreground"> ({aside})</span>
+ ) : null}
+ </button>
+ );
+ })}
+ </span>
+ )}
+ </DetailSheetProperty>
+ </DetailSheetProperties>
+ </DetailSheetSection>
+ );
+}
+
function DealContacts({ deal }: { deal: Deal }) {
const openRecord = useOpenRecord();
@@ -307,17 +385,11 @@ function DealContacts({ deal }: { deal: Deal }) {
<span className="flex min-w-0 items-center gap-2">
<PersonAvatar
src={contact.imageUrl}
- name={[contact.firstName, contact.lastName]
- .filter(Boolean)
- .join(" ")}
+ name={contactName(contact)}
email={contact.email}
size="sm"
/>
- <span className="truncate">
- {[contact.firstName, contact.lastName]
- .filter(Boolean)
- .join(" ")}
- </span>
+ <span className="truncate">{contactName(contact)}</span>
</span>
</TableCell>
<TableCell className="truncate px-3 py-2.5">
diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.ts
index 320ef94e..4b14c377 100644
--- a/apps/app/lib/trpc/cache.ts
+++ b/apps/app/lib/trpc/cache.ts
@@ -19,6 +19,7 @@ export type CrmCache = {
activity(options?: Options): Promise<void>;
google(options?: Options): Promise<void>;
settings(options?: Options): Promise<void>;
+ currency(options?: Options): Promise<void>;
workspace(options?: Options): Promise<void>;
sso(options?: Options): Promise<void>;
everything(): Promise<void>;
@@ -98,6 +99,7 @@ export function useCrmCache(): CrmCache {
trpc.companies.byId.queryKey(),
...activityKeys(),
trpc.dashboard.summary.queryKey(),
+ trpc.currency.settings.queryKey(),
],
options,
),
@@ -169,6 +171,18 @@ export function useCrmCache(): CrmCache {
options,
),
+ currency: (options) =>
+ run(
+ [trpc.currency.settings.queryKey()],
+ [
+ ...listKeys(),
+ trpc.deals.byId.queryKey(),
+ trpc.companies.byId.queryKey(),
+ trpc.dashboard.summary.queryKey(),
+ ],
+ options,
+ ),
+
workspace: (options) =>
run(
[trpc.workspace.get.queryKey(), trpc.workspace.members.queryKey()],
diff --git a/docs/api.md b/docs/api.md
index 14538d1a..d457aacb 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -535,6 +535,113 @@ reconnection recomputes it. The delete itself is still translated: a record
removed between the pre-check and the delete is the documented 404, not a P2025
escaping as a 500.
+## A deal is sold in one currency and reported in another
+
+A deal has always carried a `currency`, and every place that printed *one* deal
+honoured it. What did not was every place that printed a **total**: `_sum:
+{ amount: true }` added the decimals column across whatever currencies happened
+to be in the rows, and the dashboard then rendered the result through
+`formatMoneyCompact(cents)` with no currency argument at all — which defaults to
+`usd`. A €1M deal beside a $1M deal read **`$2.0M`**. Nothing errored, nothing
+logged, and the number was wrong in the one direction a sales dashboard is never
+questioned in.
+
+So there are now two amounts on a deal, and only one of them is ever summed.
+
+- **`amount` + `currency` is what the customer is paying.** It is what a rep
+ types, what the deal sheet shows, and it is never converted in place.
+- **`baseAmount` is that figure in the workspace's reporting currency, and it is
+ the only column any total, chart, average or sort may touch.** `fxRate` and
+ `fxRateAt` sit beside it saying how it got there, so a quarter's number can be
+ explained a year later.
+
+**The rate is resolved once, at the moment the amount is set, and then frozen.**
+`DealsService.create` and `.update` call `ConversionService.dealFields` whenever
+`amount` *or* `currency` changes — and an update that changes only one of them
+reads the other back inside the same call, because converting a new amount
+against a stale currency is how you get a figure that matches neither. Freezing
+is the point: rates move daily, and a closed-won quarter that changes value
+every morning is not a report. Converting on read was the simpler schema and it
+is wrong for exactly that reason.
+
+- **A missing rate is a null, and a null is disclosed rather than counted as
+ zero.** `baseAmount` stays null when nothing can convert the currency, which
+ keeps it out of every `_sum` automatically — and `ConversionService.unconverted`
+ counts those rows so the dashboard, the deals list and the company sheet can
+ say *3 deals in CHF are not included*. A total that silently drops rows is the
+ same class of bug as the one above, wearing a nicer hat.
+- **The work is recovered from the record, not held in a queue.** A deal written
+ with no rate is not retried by anything; it is simply a row with a null
+ `baseAmount`, which is what `fillMissing()` looks for the moment a rate
+ arrives — from the cron or from somebody typing one in. Same shape as a
+ `PENDING` company waiting on a research key.
+- **`fillMissing()` never touches a deal that already converted**, which is what
+ keeps the freeze true when the daily cron brings in new rates.
+ `rerateAll()` is the one thing that overwrites a locked rate, and it runs only
+ when the reporting currency changes — because at that point every stored
+ `baseAmount` is denominated in a currency the workspace no longer reports in,
+ so leaving them would be worse than moving them. Settings says so before you
+ change it.
+
+**Rates live in `ExchangeRate`, and `rate` means one thing only: how many units
+of `baseCurrency` one unit of `quoteCurrency` buys.** So `baseAmount = amount ×
+rate`, in that direction, everywhere. The public feed quotes the opposite way (1
+USD = 0.8655 EUR), so `RatesService` inverts on ingest rather than at every
+call site — one place to be wrong instead of six.
+
+- **Two sources, and by-hand wins.** The unique key is
+ `(baseCurrency, quoteCurrency, source)`, so a `FETCHED` row and a `MANUAL` row
+ coexist and `resolveRate` prefers the manual one. That is what makes the
+ fetcher optional rather than load-bearing: an install behind a firewall, or
+ one dealing in a currency the ECB does not publish, types its own rates on
+ **Settings → Currencies** and everything downstream is identical.
+- **`resolveRate` refuses a rate of zero or less** instead of converting with
+ it. A `baseAmount` of 0 is indistinguishable from a free deal.
+- **The reporting currency is a row, not a variable** —
+ `AppSetting.reportingCurrency`, read through `readReportingCurrency` in
+ [`@crm/db/settings`](../packages/db/src/settings.ts), which is the only reader
+ and falls back to `DEFAULT_REPORTING_CURRENCY`. Same reasoning as the agent's
+ model and the Context key: an admin who cannot redeploy has to be able to
+ change it.
+- **A currency code is validated against a list, not a regex.**
+ `isCurrencyCode` in [`@crm/db/currency`](../packages/db/src/currency.ts) is the
+ gate, and it is what `deals.contracts.ts` refines on. `z.string().length(3)`
+ accepted `ZZZ`, which is well-formed enough that `Intl` renders it happily as
+ `ZZZ 1,234.50` and nothing can ever convert it. Shape and membership are two
+ different questions and the module answers both separately —
+ `isWellFormedCurrency` exists because `Intl.NumberFormat` throws a
+ `RangeError` on anything that is not three letters, so a *formatter* has to
+ check shape even where membership is not its business.
+- **`minorUnitsOf` is why conversion rounds correctly.** JPY has no decimal
+ places and KWD has three; `applyRate` rounds to the *reporting* currency's
+ own units rather than to two. The `×100` cents transport across tRPC is
+ untouched and still round-trips, because it is a scaling convention and not a
+ claim about decimals — but note it cannot represent a three-decimal currency's
+ minor unit, and neither can `Decimal(14, 2)`. A KWD deal is stored to the
+ fils, not the fils-tenth.
+
+**The fetcher is in the API, and that is a deliberate exception to the rule at
+the top of this file.** A daily rate is not intelligence: it decides nothing
+about a person or a company, there is no confidence model, no identity to match
+and no judgement to drift. It is the same category as `FaviconService`, which
+also makes an outbound request from Nest. The load-bearing reason is timing —
+`DealsService` needs a rate *synchronously* to write `baseAmount` in the same
+transaction as the amount, and routing that through the agent's task queue would
+make a rep's pipeline total wrong for the seconds it took a session to start. If
+this ever grows a judgement — deciding *which* provider to trust, or whether a
+rate looks wrong — that part belongs in `apps/agent`.
+
+- **`POST /internal/sync/rates`** is the cron entry, guarded by `CRON_SECRET`
+ through the same `timingSafeEquals` check as the Google sync, and it **fails
+ closed when the secret is unset**. It refreshes and then calls
+ `fillMissing()`, so one daily hit both updates the rates and rescues the deals
+ that were waiting on them.
+- **An unreachable provider is not an error.** `RatesService.refresh` warns and
+ returns `{ ok: false }`; nothing throws, no deal changes, and the manual rates
+ keep working. Only the *interactive* refresh on the settings page turns that
+ into a `BadRequestException`, because there a person is standing there waiting
+ to be told.
+
## Freshness: invalidate the query, don't disable the cache
There is no HTTP response cache in front of tRPC. Freshness is TanStack Query's
diff --git a/docs/environment.md b/docs/environment.md
index 73ff7fc1..96e43f2b 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -348,7 +348,7 @@ nothing, and Calendar reads from `now` onwards.
| Variable | Required | Notes |
| --- | --- | --- |
-| `CRON_SECRET` | in deployed environments | Bearer guard on `POST /internal/sync/google`. Vercel sends it automatically as `Authorization: Bearer $CRON_SECRET`. Minimum 16 characters; the route **fails closed** if unset, so locally the cron simply never runs. |
+| `CRON_SECRET` | in deployed environments | Bearer guard on `POST /internal/sync/google` **and `POST /internal/sync/rates`**. Vercel sends it automatically as `Authorization: Bearer $CRON_SECRET`. Minimum 16 characters; both routes **fail closed** if unset, so locally the crons simply never run. |
The absences are deliberate:
@@ -361,6 +361,12 @@ The absences are deliberate:
internal, and it is seeded into the sync's "us" set alongside the `User`
table. Two sources for one fact is how a colleague becomes a lead.
- **No `GMAIL_BACKFILL_DAYS`.** There is no backfill.
+- **No exchange-rate provider variable.** The rate feed is a constant in
+ `apps/api/src/currency/rates.service.ts` and needs no key; an install that
+ cannot reach it types its own rates on Settings → Currencies instead. See
+ [the currency rules](./api.md#a-deal-is-sold-in-one-currency-and-reported-in-another).
+ `POST /internal/sync/rates` wants a **daily** schedule beside the five-minute
+ Google one.
Two things to do in Google Cloud before this works:
diff --git a/packages/db/package.json b/packages/db/package.json
index 9ec5fe2d..490bc356 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -8,8 +8,10 @@
"./agent-tasks": "./src/agent-tasks.ts",
"./blob": "./src/blob.ts",
"./client": "./src/client.ts",
+ "./currency": "./src/currency.ts",
"./enums": "./src/generated/prisma/enums.ts",
"./favicon": "./src/favicon.ts",
+ "./fx": "./src/fx.ts",
"./images": "./src/images.ts",
"./safe-fetch": "./src/safe-fetch.ts",
"./settings": "./src/settings.ts",
diff --git a/packages/db/prisma/migrations/20260805120000_deal_description/migration.sql b/packages/db/prisma/migrations/20260805120000_deal_description/migration.sql
new file mode 100644
index 00000000..71b729d7
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805120000_deal_description/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "deal" ADD COLUMN "description" TEXT;
diff --git a/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql b/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql
new file mode 100644
index 00000000..d505afc0
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql
@@ -0,0 +1,55 @@
+-- CreateEnum
+CREATE TYPE "RateSource" AS ENUM ('FETCHED', 'MANUAL');
+
+-- AlterTable
+ALTER TABLE "appSetting" ADD COLUMN "reportingCurrency" TEXT,
+ADD COLUMN "ratesRefreshedAt" TIMESTAMP(3);
+
+-- AlterTable
+ALTER TABLE "deal" ADD COLUMN "baseAmount" DECIMAL(18,4),
+ADD COLUMN "fxRate" DECIMAL(20,10),
+ADD COLUMN "fxRateAt" TIMESTAMP(3);
+
+-- CreateTable
+CREATE TABLE "exchangeRate" (
+ "id" TEXT NOT NULL,
+ "baseCurrency" TEXT NOT NULL,
+ "quoteCurrency" TEXT NOT NULL,
+ "rate" DECIMAL(20,10) NOT NULL,
+ "asOf" TIMESTAMP(3) NOT NULL,
+ "source" "RateSource" NOT NULL,
+ "provider" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "exchangeRate_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "exchangeRate_baseCurrency_quoteCurrency_source_key" ON "exchangeRate"("baseCurrency", "quoteCurrency", "source");
+
+-- CreateIndex
+CREATE INDEX "exchangeRate_baseCurrency_quoteCurrency_idx" ON "exchangeRate"("baseCurrency", "quoteCurrency");
+
+-- CreateIndex
+CREATE INDEX "deal_baseAmount_idx" ON "deal"("baseAmount");
+
+-- CreateIndex
+CREATE INDEX "deal_currency_idx" ON "deal"("currency");
+
+-- Backfill: every deal already recorded is in the reporting currency, because
+-- until now there was only one. Skipping this would drop every existing deal
+-- out of every total the moment this migration lands.
+UPDATE "deal"
+SET "baseAmount" = "amount",
+ "fxRate" = 1,
+ "fxRateAt" = CURRENT_TIMESTAMP
+WHERE "amount" IS NOT NULL
+ AND upper(btrim("currency")) = COALESCE(
+ (
+ SELECT upper(btrim("reportingCurrency"))
+ FROM "appSetting"
+ WHERE "id" = 'app' AND btrim(COALESCE("reportingCurrency", '')) <> ''
+ ),
+ 'USD'
+ );
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 99f028c3..350c8723 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -383,6 +383,7 @@ model Deal {
id String @id @default(cuid())
conversations AgentConversation[]
name String
+ description String?
companyId String
company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
ownerId String
@@ -396,6 +397,10 @@ model Deal {
closedAt DateTime?
closedReason String?
+ baseAmount Decimal? @db.Decimal(18, 4)
+ fxRate Decimal? @db.Decimal(20, 10)
+ fxRateAt DateTime?
+
lastActivityAt DateTime?
contacts DealContact[]
@@ -408,9 +413,32 @@ model Deal {
@@index([stage])
@@index([expectedCloseDate])
@@index([lastActivityAt])
+ @@index([baseAmount])
+ @@index([currency])
@@map("deal")
}
+enum RateSource {
+ FETCHED
+ MANUAL
+}
+
+model ExchangeRate {
+ id String @id @default(cuid())
+ baseCurrency String
+ quoteCurrency String
+ rate Decimal @db.Decimal(20, 10)
+ asOf DateTime
+ source RateSource
+ provider String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([baseCurrency, quoteCurrency, source])
+ @@index([baseCurrency, quoteCurrency])
+ @@map("exchangeRate")
+}
+
model DealContact {
dealId String
deal Deal @relation(fields: [dealId], references: [id], onDelete: Cascade)
@@ -620,6 +648,10 @@ model AppSetting {
contextDevApiKey String?
+ reportingCurrency String?
+
+ ratesRefreshedAt DateTime?
+
updatedAt DateTime @updatedAt
@@map("appSetting")
diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.ts
index aee7235c..7941dff7 100644
--- a/packages/db/prisma/seed.ts
+++ b/packages/db/prisma/seed.ts
@@ -1,7 +1,11 @@
import { mirror } from "../src/blob";
import { db } from "../src/client";
import { resolveFavicon } from "../src/favicon";
-import { ActivityType, DealStage } from "../src/generated/prisma/enums";
+import {
+ ActivityType,
+ DealStage,
+ RateSource,
+} from "../src/generated/prisma/enums";
function makeRandom(seed: number): () => number {
let a = seed;
@@ -253,6 +257,14 @@ const CLOSED_STAGES = [
DealStage.UNQUALIFIED_TO_BUY,
] as const;
+const DEAL_DESCRIPTIONS = [
+ "Replacing a spreadsheet-and-Drive evidence process before their first SOC 2 audit. Security owns the decision, finance signs.",
+ "Expansion onto the platform team after the security org went live. Blocked on whether the current contract can be co-termed.",
+ "Inbound from a failed vendor renewal. They want automated evidence collection and one auditor-ready report.",
+ "Their enterprise deals keep stalling on security questionnaires. The buying trigger is the pipeline, not the audit.",
+ "Champion ran the evaluation themselves and wants the agent, not the checklist. Procurement is the long pole.",
+] as const;
+
const LOST_REASONS = [
"Went with an incumbent vendor",
"No budget this cycle",
@@ -462,6 +474,62 @@ type SeededDeal = {
closed: boolean;
};
+const SEED_RATES: Record<string, number> = {
+ EUR: 1.09,
+ GBP: 1.27,
+ CAD: 0.73,
+ AUD: 0.66,
+ JPY: 0.0067,
+};
+
+const DEAL_CURRENCIES = ["USD", "USD", "USD", "EUR", "GBP", "JPY", "CAD"];
+
+async function seedRates(): Promise<number> {
+ const asOf = daysFromNow(-1);
+
+ await db.appSetting.upsert({
+ where: { id: "app" },
+ create: { id: "app", reportingCurrency: "USD" },
+ update: { reportingCurrency: "USD" },
+ });
+
+ for (const [quoteCurrency, rate] of Object.entries(SEED_RATES)) {
+ await db.exchangeRate.upsert({
+ where: {
+ baseCurrency_quoteCurrency_source: {
+ baseCurrency: "USD",
+ quoteCurrency,
+ source: RateSource.FETCHED,
+ },
+ },
+ create: {
+ baseCurrency: "USD",
+ quoteCurrency,
+ rate,
+ asOf,
+ source: RateSource.FETCHED,
+ provider: "seed",
+ },
+ update: { rate, asOf, provider: "seed" },
+ });
+ }
+
+ return Object.keys(SEED_RATES).length;
+}
+
+function money(usdAmount: number, currency: string) {
+ const rate = SEED_RATES[currency] ?? 1;
+ const places = currency === "JPY" ? 0 : 2;
+ const amount = Number((usdAmount / rate).toFixed(places));
+
+ return {
+ amount,
+ currency,
+ baseAmount: Number((amount * rate).toFixed(2)),
+ fxRate: rate,
+ };
+}
+
async function seedDeals(
companies: { id: string; name: string }[],
contacts: SeededContact[],
@@ -495,12 +563,24 @@ async function seedDeals(
n === 0
? `${company.name} — Comp AI`
: `${company.name} — expansion`,
+ description: pick(DEAL_DESCRIPTIONS),
companyId: company.id,
ownerId,
stage,
stageChangedAt,
- amount: integer(6, 90) * 1000,
- currency: "USD",
+ ...(() => {
+ const { amount, currency, baseAmount, fxRate } = money(
+ integer(6, 90) * 1000,
+ pick(DEAL_CURRENCIES),
+ );
+ return {
+ amount,
+ currency,
+ baseAmount,
+ fxRate,
+ fxRateAt: daysFromNow(-1),
+ };
+ })(),
expectedCloseDate: daysFromNow(
closedDaysAgo === null
? integer(-10, 75)
@@ -659,6 +739,7 @@ async function seedActivities(
}
async function main() {
+ const rates = await seedRates();
const ownerIds = await seedOwners();
const companies = await seedCompanies(ownerIds);
const contacts = await seedContacts(companies, ownerIds);
@@ -667,7 +748,7 @@ async function main() {
console.log(
`Seeded ${companies.length} companies, ${contacts.length} contacts, ` +
- `${deals.length} deals, ${activities} activities.`,
+ `${deals.length} deals, ${activities} activities, ${rates} exchange rates.`,
);
}
diff --git a/packages/db/src/currency.ts b/packages/db/src/currency.ts
new file mode 100644
index 00000000..9ccad623
--- /dev/null
+++ b/packages/db/src/currency.ts
@@ -0,0 +1,101 @@
+export interface CurrencyMeta {
+ code: string;
+ name: string;
+ minorUnits: number;
+}
+
+export const DEFAULT_REPORTING_CURRENCY = "USD";
+
+const CURRENCY_LIST: readonly CurrencyMeta[] = [
+ { code: "AED", name: "UAE Dirham", minorUnits: 2 },
+ { code: "ARS", name: "Argentine Peso", minorUnits: 2 },
+ { code: "AUD", name: "Australian Dollar", minorUnits: 2 },
+ { code: "BGN", name: "Bulgarian Lev", minorUnits: 2 },
+ { code: "BHD", name: "Bahraini Dinar", minorUnits: 3 },
+ { code: "BRL", name: "Brazilian Real", minorUnits: 2 },
+ { code: "CAD", name: "Canadian Dollar", minorUnits: 2 },
+ { code: "CHF", name: "Swiss Franc", minorUnits: 2 },
+ { code: "CLP", name: "Chilean Peso", minorUnits: 0 },
+ { code: "CNY", name: "Chinese Yuan", minorUnits: 2 },
+ { code: "COP", name: "Colombian Peso", minorUnits: 2 },
+ { code: "CZK", name: "Czech Koruna", minorUnits: 2 },
+ { code: "DKK", name: "Danish Krone", minorUnits: 2 },
+ { code: "EGP", name: "Egyptian Pound", minorUnits: 2 },
+ { code: "EUR", name: "Euro", minorUnits: 2 },
+ { code: "GBP", name: "Pound Sterling", minorUnits: 2 },
+ { code: "HKD", name: "Hong Kong Dollar", minorUnits: 2 },
+ { code: "HUF", name: "Hungarian Forint", minorUnits: 2 },
+ { code: "IDR", name: "Indonesian Rupiah", minorUnits: 2 },
+ { code: "ILS", name: "Israeli New Shekel", minorUnits: 2 },
+ { code: "INR", name: "Indian Rupee", minorUnits: 2 },
+ { code: "ISK", name: "Icelandic Króna", minorUnits: 0 },
+ { code: "JOD", name: "Jordanian Dinar", minorUnits: 3 },
+ { code: "JPY", name: "Japanese Yen", minorUnits: 0 },
+ { code: "KES", name: "Kenyan Shilling", minorUnits: 2 },
+ { code: "KRW", name: "South Korean Won", minorUnits: 0 },
+ { code: "KWD", name: "Kuwaiti Dinar", minorUnits: 3 },
+ { code: "MAD", name: "Moroccan Dirham", minorUnits: 2 },
+ { code: "MXN", name: "Mexican Peso", minorUnits: 2 },
+ { code: "MYR", name: "Malaysian Ringgit", minorUnits: 2 },
+ { code: "NGN", name: "Nigerian Naira", minorUnits: 2 },
+ { code: "NOK", name: "Norwegian Krone", minorUnits: 2 },
+ { code: "NZD", name: "New Zealand Dollar", minorUnits: 2 },
+ { code: "OMR", name: "Omani Rial", minorUnits: 3 },
+ { code: "PEN", name: "Peruvian Sol", minorUnits: 2 },
+ { code: "PHP", name: "Philippine Peso", minorUnits: 2 },
+ { code: "PKR", name: "Pakistani Rupee", minorUnits: 2 },
+ { code: "PLN", name: "Polish Złoty", minorUnits: 2 },
+ { code: "QAR", name: "Qatari Riyal", minorUnits: 2 },
+ { code: "RON", name: "Romanian Leu", minorUnits: 2 },
+ { code: "RSD", name: "Serbian Dinar", minorUnits: 2 },
+ { code: "SAR", name: "Saudi Riyal", minorUnits: 2 },
+ { code: "SEK", name: "Swedish Krona", minorUnits: 2 },
+ { code: "SGD", name: "Singapore Dollar", minorUnits: 2 },
+ { code: "THB", name: "Thai Baht", minorUnits: 2 },
+ { code: "TND", name: "Tunisian Dinar", minorUnits: 3 },
+ { code: "TRY", name: "Turkish Lira", minorUnits: 2 },
+ { code: "TWD", name: "New Taiwan Dollar", minorUnits: 2 },
+ { code: "UAH", name: "Ukrainian Hryvnia", minorUnits: 2 },
+ { code: "USD", name: "US Dollar", minorUnits: 2 },
+ { code: "UYU", name: "Uruguayan Peso", minorUnits: 2 },
+ { code: "VND", name: "Vietnamese Dong", minorUnits: 0 },
+ { code: "ZAR", name: "South African Rand", minorUnits: 2 },
+] as const;
+
+export const CURRENCIES = CURRENCY_LIST;
+
+const BY_CODE = new Map(CURRENCY_LIST.map((entry) => [entry.code, entry]));
+
+export const CURRENCY_CODES: readonly string[] = CURRENCY_LIST.map(
+ (entry) => entry.code,
+);
+
+const SHAPE = /^[A-Za-z]{3}$/;
+
+export function normalizeCurrency(value: string | null | undefined): string {
+ return (value ?? "").trim().toUpperCase();
+}
+
+export function isCurrencyCode(value: string | null | undefined): boolean {
+ return BY_CODE.has(normalizeCurrency(value));
+}
+
+export function currencyMeta(
+ value: string | null | undefined,
+): CurrencyMeta | null {
+ return BY_CODE.get(normalizeCurrency(value)) ?? null;
+}
+
+export function currencyName(value: string | null | undefined): string | null {
+ return currencyMeta(value)?.name ?? null;
+}
+
+export function minorUnitsOf(value: string | null | undefined): number {
+ return currencyMeta(value)?.minorUnits ?? 2;
+}
+
+export function isWellFormedCurrency(
+ value: string | null | undefined,
+): boolean {
+ return SHAPE.test((value ?? "").trim());
+}
diff --git a/packages/db/src/fx.ts b/packages/db/src/fx.ts
new file mode 100644
index 00000000..89bea0c4
--- /dev/null
+++ b/packages/db/src/fx.ts
@@ -0,0 +1,86 @@
+import type { Db } from "./client";
+import { minorUnitsOf, normalizeCurrency } from "./currency";
+import { Prisma } from "./generated/prisma/client";
+import { RateSource } from "./generated/prisma/enums";
+
+export type RateOrigin = "IDENTITY" | "MANUAL" | "FETCHED";
+
+export interface ResolvedRate {
+ rate: Prisma.Decimal;
+ asOf: Date;
+ origin: RateOrigin;
+ provider: string | null;
+}
+
+export interface Conversion {
+ baseAmount: Prisma.Decimal;
+ fxRate: Prisma.Decimal;
+ fxRateAt: Date;
+ origin: RateOrigin;
+}
+
+export const ONE = new Prisma.Decimal(1);
+
+export async function resolveRate(
+ db: Db,
+ base: string,
+ quote: string,
+ now: Date = new Date(),
+): Promise<ResolvedRate | null> {
+ const baseCurrency = normalizeCurrency(base);
+ const quoteCurrency = normalizeCurrency(quote);
+
+ if (!baseCurrency || !quoteCurrency) return null;
+
+ if (baseCurrency === quoteCurrency) {
+ return { rate: ONE, asOf: now, origin: "IDENTITY", provider: null };
+ }
+
+ const rows = await db.exchangeRate.findMany({
+ where: { baseCurrency, quoteCurrency },
+ select: { rate: true, asOf: true, source: true, provider: true },
+ });
+
+ const manual = rows.find((row) => row.source === RateSource.MANUAL);
+ const chosen =
+ manual ?? rows.find((row) => row.source === RateSource.FETCHED);
+
+ if (!chosen || chosen.rate.lessThanOrEqualTo(0)) return null;
+
+ return {
+ rate: chosen.rate,
+ asOf: chosen.asOf,
+ origin: chosen.source === RateSource.MANUAL ? "MANUAL" : "FETCHED",
+ provider: chosen.provider,
+ };
+}
+
+export function applyRate(
+ amount: Prisma.Decimal,
+ rate: ResolvedRate,
+ baseCurrency: string,
+): Conversion {
+ return {
+ baseAmount: amount
+ .times(rate.rate)
+ .toDecimalPlaces(minorUnitsOf(baseCurrency)),
+ fxRate: rate.rate,
+ fxRateAt: rate.asOf,
+ origin: rate.origin,
+ };
+}
+
+export async function convertToBase(
+ db: Db,
+ amount: Prisma.Decimal | null,
+ from: string,
+ base: string,
+ now: Date = new Date(),
+): Promise<Conversion | null> {
+ if (amount === null) return null;
+
+ const rate = await resolveRate(db, base, from, now);
+ if (!rate) return null;
+
+ return applyRate(amount, rate, base);
+}
diff --git a/packages/db/src/settings.ts b/packages/db/src/settings.ts
index f5ccb135..7e90d5ba 100644
--- a/packages/db/src/settings.ts
+++ b/packages/db/src/settings.ts
@@ -1,4 +1,9 @@
import type { Db } from "./client";
+import {
+ DEFAULT_REPORTING_CURRENCY,
+ isCurrencyCode,
+ normalizeCurrency,
+} from "./currency";
export const SETTINGS_ID = "app";
@@ -70,6 +75,52 @@ export async function writeContextDevKey(db: Db, key: string): Promise<void> {
});
}
+export async function readReportingCurrency(db: Db): Promise<string> {
+ const row = await db.appSetting.findUnique({
+ where: { id: SETTINGS_ID },
+ select: { reportingCurrency: true },
+ });
+
+ const stored = normalizeCurrency(row?.reportingCurrency);
+
+ return isCurrencyCode(stored) ? stored : DEFAULT_REPORTING_CURRENCY;
+}
+
+export async function writeReportingCurrency(
+ db: Db,
+ code: string,
+): Promise<string> {
+ const reportingCurrency = normalizeCurrency(code);
+
+ await db.appSetting.upsert({
+ where: { id: SETTINGS_ID },
+ create: { id: SETTINGS_ID, reportingCurrency },
+ update: { reportingCurrency },
+ });
+
+ return reportingCurrency;
+}
+
+export async function readRatesRefreshedAt(db: Db): Promise<Date | null> {
+ const row = await db.appSetting.findUnique({
+ where: { id: SETTINGS_ID },
+ select: { ratesRefreshedAt: true },
+ });
+
+ return row?.ratesRefreshedAt ?? null;
+}
+
+export async function writeRatesRefreshedAt(
+ db: Db,
+ ratesRefreshedAt: Date,
+): Promise<void> {
+ await db.appSetting.upsert({
+ where: { id: SETTINGS_ID },
+ create: { id: SETTINGS_ID, ratesRefreshedAt },
+ update: { ratesRefreshedAt },
+ });
+}
+
export function maskKey(key: string): string {
const trimmed = key.trim();
return trimmed.length > 4 ? `••••${trimmed.slice(-4)}` : "••••";
diff --git a/packages/db/test/currency.spec.ts b/packages/db/test/currency.spec.ts
new file mode 100644
index 00000000..58fc3ebd
--- /dev/null
+++ b/packages/db/test/currency.spec.ts
@@ -0,0 +1,175 @@
+import { describe, expect, it } from "bun:test";
+import type { Db } from "../src/client";
+import {
+ currencyName,
+ isCurrencyCode,
+ isWellFormedCurrency,
+ minorUnitsOf,
+ normalizeCurrency,
+} from "../src/currency";
+import { applyRate, type ResolvedRate, resolveRate } from "../src/fx";
+import { Prisma } from "../src/generated/prisma/client";
+import { RateSource } from "../src/generated/prisma/enums";
+
+type Row = {
+ rate: Prisma.Decimal;
+ asOf: Date;
+ source: RateSource;
+ provider: string | null;
+};
+
+function fakeDb(rows: Row[]): { db: Db; calls: number } {
+ const state = { calls: 0 };
+
+ const db = {
+ exchangeRate: {
+ findMany: async () => {
+ state.calls += 1;
+ return rows;
+ },
+ },
+ } as unknown as Db;
+
+ return {
+ db,
+ get calls() {
+ return state.calls;
+ },
+ };
+}
+
+function row(
+ rate: string,
+ source: RateSource,
+ provider: string | null = null,
+): Row {
+ return {
+ rate: new Prisma.Decimal(rate),
+ asOf: new Date("2026-08-01T00:00:00.000Z"),
+ source,
+ provider,
+ };
+}
+
+describe("normalizeCurrency and isCurrencyCode", () => {
+ it("accepts a code however a rep typed it", () => {
+ for (const input of [" usd ", "Usd", "USD"]) {
+ expect(normalizeCurrency(input)).toBe("USD");
+ expect(isCurrencyCode(input)).toBe(true);
+ }
+ });
+
+ it("refuses a three-letter string that is not a currency", () => {
+ expect(isCurrencyCode("ZZZ")).toBe(false);
+ expect(isCurrencyCode("QQ")).toBe(false);
+ expect(isCurrencyCode("")).toBe(false);
+ expect(isCurrencyCode(null)).toBe(false);
+ });
+
+ it("knows the difference between well formed and real", () => {
+ expect(isWellFormedCurrency("ZZZ")).toBe(true);
+ expect(isCurrencyCode("ZZZ")).toBe(false);
+ expect(isWellFormedCurrency("QQ")).toBe(false);
+ });
+
+ it("names the currencies it knows", () => {
+ expect(currencyName("jpy")).toBe("Japanese Yen");
+ expect(currencyName("ZZZ")).toBeNull();
+ });
+});
+
+describe("minorUnitsOf", () => {
+ it("knows the currencies that are not two-decimal", () => {
+ expect(minorUnitsOf("JPY")).toBe(0);
+ expect(minorUnitsOf("KRW")).toBe(0);
+ expect(minorUnitsOf("KWD")).toBe(3);
+ expect(minorUnitsOf("BHD")).toBe(3);
+ });
+
+ it("assumes two for anything else, so an amount still round-trips", () => {
+ expect(minorUnitsOf("USD")).toBe(2);
+ expect(minorUnitsOf("ZZZ")).toBe(2);
+ });
+});
+
+describe("resolveRate", () => {
+ it("answers 1 for the reporting currency itself, without a read", async () => {
+ const fake = fakeDb([]);
+ const rate = await resolveRate(fake.db, "USD", "usd");
+
+ expect(rate?.rate.toNumber()).toBe(1);
+ expect(rate?.origin).toBe("IDENTITY");
+ expect(fake.calls).toBe(0);
+ });
+
+ it("prefers a rate entered by hand over a fetched one", async () => {
+ const fake = fakeDb([
+ row("1.05", RateSource.FETCHED, "frankfurter.dev"),
+ row("1.20", RateSource.MANUAL),
+ ]);
+
+ const rate = await resolveRate(fake.db, "USD", "EUR");
+
+ expect(rate?.rate.toNumber()).toBe(1.2);
+ expect(rate?.origin).toBe("MANUAL");
+ });
+
+ it("falls back to the fetched rate when nobody has overridden it", async () => {
+ const fake = fakeDb([row("1.05", RateSource.FETCHED, "frankfurter.dev")]);
+ const rate = await resolveRate(fake.db, "USD", "EUR");
+
+ expect(rate?.rate.toNumber()).toBe(1.05);
+ expect(rate?.origin).toBe("FETCHED");
+ expect(rate?.provider).toBe("frankfurter.dev");
+ });
+
+ it("is null when there is nowhere to get a rate", async () => {
+ expect(await resolveRate(fakeDb([]).db, "USD", "CHF")).toBeNull();
+ });
+
+ it("refuses a nonsense rate rather than converting with it", async () => {
+ expect(
+ await resolveRate(fakeDb([row("0", RateSource.MANUAL)]).db, "USD", "EUR"),
+ ).toBeNull();
+ expect(
+ await resolveRate(
+ fakeDb([row("-2", RateSource.MANUAL)]).db,
+ "USD",
+ "EUR",
+ ),
+ ).toBeNull();
+ });
+
+ it("is null for a currency that is not a currency", async () => {
+ expect(await resolveRate(fakeDb([]).db, "USD", "")).toBeNull();
+ });
+});
+
+describe("applyRate", () => {
+ const rate = (value: string): ResolvedRate => ({
+ rate: new Prisma.Decimal(value),
+ asOf: new Date("2026-08-01T00:00:00.000Z"),
+ origin: "FETCHED",
+ provider: null,
+ });
+
+ it("converts into the reporting currency", () => {
+ const converted = applyRate(new Prisma.Decimal(1000), rate("1.09"), "USD");
+ expect(converted.baseAmount.toNumber()).toBe(1090);
+ });
+
+ it("rounds to the reporting currency's own decimals, not to two", () => {
+ const yen = applyRate(new Prisma.Decimal(100), rate("150.555"), "JPY");
+ expect(yen.baseAmount.decimalPlaces()).toBe(0);
+
+ const dollars = applyRate(new Prisma.Decimal(1000), rate("0.0067"), "USD");
+ expect(dollars.baseAmount.toNumber()).toBe(6.7);
+ });
+
+ it("carries the rate and its date onto the record, so a total is reproducible", () => {
+ const converted = applyRate(new Prisma.Decimal(1), rate("1.23"), "USD");
+ expect(converted.fxRate.toNumber()).toBe(1.23);
+ expect(converted.fxRateAt.toISOString()).toBe("2026-08-01T00:00:00.000Z");
+ expect(converted.origin).toBe("FETCHED");
+ });
+});
diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.ts
index d3b24230..7deb910a 100644
--- a/packages/ui/src/lib/format.ts
+++ b/packages/ui/src/lib/format.ts
@@ -10,11 +10,32 @@ function displayCurrencyCode(currency: string): string {
: "USD";
}
+const currencyDigits = new Map<string, number>();
+
+function fractionDigits(code: string): number {
+ const cached = currencyDigits.get(code);
+ if (cached !== undefined) return cached;
+
+ const digits =
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: code,
+ }).resolvedOptions().maximumFractionDigits ?? 2;
+
+ currencyDigits.set(code, digits);
+ return digits;
+}
+
export function formatMoney(cents: number, currency = "usd"): string {
+ const code = displayCurrencyCode(currency);
+ const whole = cents % 100 === 0;
+ const digits = fractionDigits(code);
+
return new Intl.NumberFormat(undefined, {
style: "currency",
- currency: displayCurrencyCode(currency),
- minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
+ currency: code,
+ minimumFractionDigits: whole ? 0 : Math.min(2, digits),
+ maximumFractionDigits: whole ? 0 : digits,
}).format(cents / 100);
}