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

Enhance currency handling and conversion logic

Lewis Carhartd9305085260c
diff --git a/apps/api/src/currency/conversion.service.ts b/apps/api/src/currency/conversion.service.ts
index 34262203..1ec3f63a 100644
--- a/apps/api/src/currency/conversion.service.ts
+++ b/apps/api/src/currency/conversion.service.ts
@@ -2,8 +2,8 @@ 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,
+ convertToBase,
type ResolvedRate,
resolveRate,
} from "@crm/db/fx";
@@ -13,6 +13,7 @@ import { InjectDatabase } from "../database/database.constants";
export interface DealFxFields {
baseAmount: PrismaTypes.Decimal | null;
+ baseCurrency: string | null;
fxRate: PrismaTypes.Decimal | null;
fxRateAt: Date | null;
}
@@ -47,12 +48,12 @@ export class ConversionService {
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;
+ return convertToBase(
+ this.db,
+ amount,
+ currency,
+ await this.reportingCurrency(),
+ );
}
async dealFields(
@@ -62,22 +63,41 @@ export class ConversionService {
const converted = await this.convert(amount, currency);
if (!converted) {
- return { baseAmount: null, fxRate: null, fxRateAt: null };
+ return {
+ baseAmount: null,
+ baseCurrency: null,
+ fxRate: null,
+ fxRateAt: null,
+ };
}
return {
baseAmount: converted.baseAmount,
+ baseCurrency: converted.baseCurrency,
fxRate: converted.fxRate,
fxRateAt: converted.fxRateAt,
};
}
+ countedWhere(base: string): PrismaTypes.DealWhereInput {
+ return { baseAmount: { not: null }, baseCurrency: base };
+ }
+
+ pendingWhere(base: string): PrismaTypes.DealWhereInput {
+ return {
+ amount: { not: null },
+ OR: [{ baseAmount: null }, { baseCurrency: { not: base } }],
+ };
+ }
+
async unconverted(
where: PrismaTypes.DealWhereInput = {},
): Promise<Unconverted> {
+ const base = await this.reportingCurrency();
+
const rows = await this.db.deal.groupBy({
by: ["currency"],
- where: { ...where, amount: { not: null }, baseAmount: null },
+ where: { AND: [where, this.pendingWhere(base)] },
_count: { _all: true },
});
@@ -103,33 +123,31 @@ export class ConversionService {
const groups = await this.db.deal.groupBy({
by: ["currency"],
- where: {
- amount: { not: null },
- ...(onlyMissing ? { baseAmount: null } : {}),
- },
+ where: onlyMissing ? this.pendingWhere(base) : { amount: { not: null } },
_count: { _all: true },
});
+ const codes = [
+ ...new Set(groups.map((group) => normalizeCurrency(group.currency))),
+ ];
+
const places = minorUnitsOf(base);
let converted = 0;
let cleared = 0;
const missing: string[] = [];
- for (const group of groups) {
- const code = normalizeCurrency(group.currency);
+ for (const code of codes) {
const rate = await resolveRate(this.db, base, code);
if (!rate) {
missing.push(code);
- if (!onlyMissing) {
- cleared += await this.clear(code);
- }
+ cleared += await this.clear(code);
continue;
}
- converted += await this.write(code, rate, places, onlyMissing);
+ converted += await this.write(base, code, rate, places, onlyMissing);
}
this.logger.log({
@@ -146,6 +164,7 @@ export class ConversionService {
}
private async write(
+ base: string,
code: string,
rate: ResolvedRate,
places: number,
@@ -154,12 +173,13 @@ export class ConversionService {
const value = new Prisma.Decimal(rate.rate).toString();
const filter = onlyMissing
- ? Prisma.sql`AND "baseAmount" IS NULL`
+ ? Prisma.sql`AND ("baseAmount" IS NULL OR "baseCurrency" IS DISTINCT FROM ${base})`
: Prisma.empty;
return this.db.$executeRaw`
UPDATE "deal"
SET "baseAmount" = ROUND("amount" * ${value}::numeric, ${places}::int),
+ "baseCurrency" = ${base},
"fxRate" = ${value}::numeric,
"fxRateAt" = ${rate.asOf}
WHERE "amount" IS NOT NULL
@@ -171,7 +191,10 @@ export class ConversionService {
private async clear(code: string): Promise<number> {
return this.db.$executeRaw`
UPDATE "deal"
- SET "baseAmount" = NULL, "fxRate" = NULL, "fxRateAt" = NULL
+ SET "baseAmount" = NULL,
+ "baseCurrency" = 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
index df0bf058..8530d966 100644
--- a/apps/api/src/currency/currency.contracts.ts
+++ b/apps/api/src/currency/currency.contracts.ts
@@ -1,7 +1,7 @@
import { isCurrencyCode } from "@crm/db/currency";
import { z } from "zod";
-const currencyCode = z
+export const currencyCode = z
.string()
.trim()
.length(3, "A currency code is three letters, like USD.")
diff --git a/apps/api/src/currency/currency.router.ts b/apps/api/src/currency/currency.router.ts
index 2046c127..e0a7cc0b 100644
--- a/apps/api/src/currency/currency.router.ts
+++ b/apps/api/src/currency/currency.router.ts
@@ -1,6 +1,14 @@
import { Inject } from "@nestjs/common";
-import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import {
+ Ctx,
+ Input,
+ Mutation,
+ Query,
+ Router,
+ UseMiddlewares,
+} from "nestjs-trpc";
import type { z } from "zod";
+import type { AuthedTrpcContext } from "../trpc/context.types";
import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
import {
removeManualRateInput,
@@ -17,31 +25,36 @@ export class CurrencyRouter {
) {}
@Query()
- async settings() {
- return this.currency.settings();
+ async settings(@Ctx() ctx: AuthedTrpcContext) {
+ return this.currency.settings(ctx.user.id);
}
@Mutation({ input: setReportingCurrencyInput })
async setReportingCurrency(
+ @Ctx() ctx: AuthedTrpcContext,
@Input() input: z.infer<typeof setReportingCurrencyInput>,
) {
- return this.currency.setReportingCurrency(input.currency);
+ return this.currency.setReportingCurrency(ctx.user.id, input.currency);
}
@Mutation({ input: setManualRateInput })
- async setManualRate(@Input() input: z.infer<typeof setManualRateInput>) {
- return this.currency.setManualRate(input.currency, input.rate);
+ async setManualRate(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof setManualRateInput>,
+ ) {
+ return this.currency.setManualRate(ctx.user.id, input.currency, input.rate);
}
@Mutation({ input: removeManualRateInput })
async removeManualRate(
+ @Ctx() ctx: AuthedTrpcContext,
@Input() input: z.infer<typeof removeManualRateInput>,
) {
- return this.currency.removeManualRate(input.currency);
+ return this.currency.removeManualRate(ctx.user.id, input.currency);
}
@Mutation()
- async refreshRates() {
- return this.currency.refresh();
+ async refreshRates(@Ctx() ctx: AuthedTrpcContext) {
+ return this.currency.refresh(ctx.user.id);
}
}
diff --git a/apps/api/src/currency/currency.service.ts b/apps/api/src/currency/currency.service.ts
index 8da54375..40870820 100644
--- a/apps/api/src/currency/currency.service.ts
+++ b/apps/api/src/currency/currency.service.ts
@@ -1,3 +1,9 @@
+import {
+ canManageCurrency,
+ isWorkspaceRole,
+ WORKSPACE_ID,
+ type WorkspaceRole,
+} from "@crm/auth";
import type { Db } from "@crm/db";
import { Prisma, RateSource } from "@crm/db";
import {
@@ -7,7 +13,12 @@ import {
normalizeCurrency,
} from "@crm/db/currency";
import { writeReportingCurrency } from "@crm/db/settings";
-import { BadRequestException, Injectable, Logger } from "@nestjs/common";
+import {
+ BadRequestException,
+ ForbiddenException,
+ Injectable,
+ Logger,
+} from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
import { ConversionService, type Unconverted } from "./conversion.service";
import { RatesService } from "./rates.service";
@@ -36,6 +47,7 @@ export interface CurrencySettings {
inUse: CurrencyInUse[];
unconverted: Unconverted;
catalog: CurrencyMeta[];
+ canManage: boolean;
}
@Injectable()
@@ -48,7 +60,7 @@ export class CurrencyService {
private readonly rates: RatesService,
) {}
- async settings(): Promise<CurrencySettings> {
+ async settings(actingUserId: string): Promise<CurrencySettings> {
const reportingCurrency = await this.conversion.reportingCurrency();
const [rows, refreshedAt, unconverted, usage] = await Promise.all([
@@ -121,14 +133,41 @@ export class CurrencyService {
),
unconverted,
catalog: [...CURRENCIES],
+ canManage: canManageCurrency(await this.roleOf(actingUserId)),
};
}
- async setReportingCurrency(code: string): Promise<CurrencySettings> {
+ private async roleOf(userId: string): Promise<WorkspaceRole | null> {
+ const member = await this.db.member.findUnique({
+ where: {
+ organizationId_userId: { organizationId: WORKSPACE_ID, userId },
+ },
+ select: { role: true },
+ });
+
+ if (!member) return null;
+
+ return isWorkspaceRole(member.role) ? member.role : "member";
+ }
+
+ private async requireManager(userId: string): Promise<void> {
+ if (!canManageCurrency(await this.roleOf(userId))) {
+ throw new ForbiddenException(
+ "Only an owner or an admin can change how money is reported.",
+ );
+ }
+ }
+
+ async setReportingCurrency(
+ actingUserId: string,
+ code: string,
+ ): Promise<CurrencySettings> {
+ await this.requireManager(actingUserId);
+
const currency = normalizeCurrency(code);
const current = await this.conversion.reportingCurrency();
- if (currency === current) return this.settings();
+ if (currency === current) return this.settings(actingUserId);
await writeReportingCurrency(this.db, currency);
@@ -145,10 +184,16 @@ export class CurrencyService {
missing: rerated.missing,
});
- return this.settings();
+ return this.settings(actingUserId);
}
- async setManualRate(code: string, rate: number): Promise<CurrencySettings> {
+ async setManualRate(
+ actingUserId: string,
+ code: string,
+ rate: number,
+ ): Promise<CurrencySettings> {
+ await this.requireManager(actingUserId);
+
const quoteCurrency = normalizeCurrency(code);
const baseCurrency = await this.conversion.reportingCurrency();
@@ -187,10 +232,15 @@ export class CurrencyService {
converted: filled.converted,
});
- return this.settings();
+ return this.settings(actingUserId);
}
- async removeManualRate(code: string): Promise<CurrencySettings> {
+ async removeManualRate(
+ actingUserId: string,
+ code: string,
+ ): Promise<CurrencySettings> {
+ await this.requireManager(actingUserId);
+
const quoteCurrency = normalizeCurrency(code);
const baseCurrency = await this.conversion.reportingCurrency();
@@ -204,10 +254,12 @@ export class CurrencyService {
quoteCurrency,
});
- return this.settings();
+ return this.settings(actingUserId);
}
- async refresh(): Promise<CurrencySettings> {
+ async refresh(actingUserId: string): Promise<CurrencySettings> {
+ await this.requireManager(actingUserId);
+
const refresh = await this.rates.refresh();
if (!refresh.ok) {
@@ -216,6 +268,6 @@ export class CurrencyService {
await this.conversion.fillMissing();
- return this.settings();
+ return this.settings(actingUserId);
}
}
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
index 9a0d7080..09283f3e 100644
--- a/apps/api/src/dashboard/dashboard.service.ts
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -47,20 +47,29 @@ export class DashboardService {
const trendStart = monthStart(now, -(TREND_MONTHS - 1));
const rateStart = new Date(now.getTime() - RATE_WINDOW_DAYS * DAY_MS);
+ const base = await this.conversion.reportingCurrency();
+ const counted = this.conversion.countedWhere(base);
+
const [
openByStage,
+ openValueByStage,
recentDeals,
closingThisMonthTotals,
biggestOpen,
overdueTasks,
recentActivity,
- reportingCurrency,
unconverted,
] = await Promise.all([
this.db.deal.groupBy({
by: ["stage"],
where: { ...owned, stage: { in: [...OPEN_DEAL_STAGES] } },
_count: { _all: true },
+ }),
+ this.db.deal.groupBy({
+ by: ["stage"],
+ where: {
+ AND: [{ ...owned, stage: { in: [...OPEN_DEAL_STAGES] } }, counted],
+ },
_sum: { baseAmount: true },
}),
this.db.deal.findMany({
@@ -73,6 +82,7 @@ export class DashboardService {
},
select: {
baseAmount: true,
+ baseCurrency: true,
stage: true,
createdAt: true,
closedAt: true,
@@ -80,9 +90,14 @@ export class DashboardService {
}),
this.db.deal.aggregate({
where: {
- ...owned,
- stage: { in: [...OPEN_DEAL_STAGES] },
- expectedCloseDate: { gte: startOfMonth, lt: startOfNextMonth },
+ AND: [
+ {
+ ...owned,
+ stage: { in: [...OPEN_DEAL_STAGES] },
+ expectedCloseDate: { gte: startOfMonth, lt: startOfNextMonth },
+ },
+ counted,
+ ],
},
_count: { _all: true },
_sum: { baseAmount: true },
@@ -148,16 +163,16 @@ export class DashboardService {
deal: { select: { id: true, name: true } },
},
}),
- this.conversion.reportingCurrency(),
this.conversion.unconverted(owned),
]);
const stages = OPEN_DEAL_STAGES.map((stage) => {
const group = openByStage.find((row) => row.stage === stage);
+ const value = openValueByStage.find((row) => row.stage === stage);
return {
stage: stage as DealStage,
count: group?._count._all ?? 0,
- valueCents: toCents(group?._sum.baseAmount ?? null) ?? 0,
+ valueCents: toCents(value?._sum.baseAmount ?? null) ?? 0,
};
});
@@ -176,7 +191,8 @@ export class DashboardService {
let cycleDays = 0;
for (const deal of recentDeals) {
- const cents = toCents(deal.baseAmount) ?? 0;
+ const cents =
+ deal.baseCurrency === base ? (toCents(deal.baseAmount) ?? 0) : 0;
const created = trend[monthKey(deal.createdAt) - firstBucket];
if (created) created.created += cents;
@@ -212,7 +228,7 @@ export class DashboardService {
return {
scope: input.scope,
- reportingCurrency,
+ reportingCurrency: base,
unconverted,
pipeline: {
stages,
diff --git a/apps/api/src/deals/deals.contracts.ts b/apps/api/src/deals/deals.contracts.ts
index bdf4a2e1..1ff83a98 100644
--- a/apps/api/src/deals/deals.contracts.ts
+++ b/apps/api/src/deals/deals.contracts.ts
@@ -1,8 +1,18 @@
import { DealStage } from "@crm/db";
-import { isCurrencyCode } from "@crm/db/currency";
import { z } from "zod";
+import { currencyCode } from "../currency/currency.contracts";
import { listInput } from "../trpc/list-input";
+export const MAX_AMOUNT_CENTS = 99_999_999_999_999;
+
+const amountCents = z
+ .number()
+ .int()
+ .min(0)
+ .max(MAX_AMOUNT_CENTS, "That amount is too large to record.")
+ .nullable()
+ .optional();
+
export const CLOSING_WINDOWS = [
"overdue",
"this-month",
@@ -31,13 +41,8 @@ export const dealCreateInput = z.object({
companyId: z.string().min(1, "A deal belongs to a company."),
ownerId: z.string().min(1, "A deal needs an owner."),
stage: stageEnum.optional(),
- amountCents: z.number().int().min(0).nullable().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(),
+ amountCents,
+ currency: currencyCode.optional(),
expectedCloseDate: z.string().nullable().optional(),
});
@@ -48,13 +53,8 @@ const dealUpdateInput = z.object({
description: z.string().nullable().optional(),
companyId: z.string().optional(),
ownerId: z.string().optional(),
- amountCents: z.number().int().min(0).nullable().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(),
+ amountCents,
+ currency: currencyCode.optional(),
expectedCloseDate: z.string().nullable().optional(),
});
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
index 18f5ce04..610234ee 100644
--- a/apps/api/src/deals/deals.service.ts
+++ b/apps/api/src/deals/deals.service.ts
@@ -95,44 +95,38 @@ export class DealsService {
const { skip, take } = paginate(input);
const openWhere = { ...where, stage: { in: [...OPEN_DEAL_STAGES] } };
-
- const [
- rows,
- total,
- facetCounts,
- openValue,
- reportingCurrency,
- unconverted,
- ] = await Promise.all([
- this.db.deal.findMany({
- where,
- skip,
- take,
- orderBy: resolveOrderBy(input, SORTABLE, [{ createdAt: "desc" }]),
- select: {
- id: true,
- name: true,
- stage: true,
- amount: true,
- currency: true,
- baseAmount: true,
- expectedCloseDate: true,
- closedAt: true,
- company: { select: COMPANY_SELECT },
- owner: { select: OWNER_SELECT },
- lastActivityAt: true,
- createdAt: true,
- },
- }),
- this.db.deal.count({ where }),
- this.facetCounts(input),
- this.db.deal.aggregate({
- where: openWhere,
- _sum: { baseAmount: true },
- }),
- this.conversion.reportingCurrency(),
- this.conversion.unconverted(openWhere),
- ]);
+ const base = await this.conversion.reportingCurrency();
+
+ const [rows, total, facetCounts, openValue, unconverted] =
+ await Promise.all([
+ this.db.deal.findMany({
+ where,
+ skip,
+ take,
+ orderBy: resolveOrderBy(input, SORTABLE, [{ createdAt: "desc" }]),
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ baseAmount: true,
+ expectedCloseDate: true,
+ closedAt: true,
+ company: { select: COMPANY_SELECT },
+ owner: { select: OWNER_SELECT },
+ lastActivityAt: true,
+ createdAt: true,
+ },
+ }),
+ this.db.deal.count({ where }),
+ this.facetCounts(input),
+ this.db.deal.aggregate({
+ where: { AND: [openWhere, this.conversion.countedWhere(base)] },
+ _sum: { baseAmount: true },
+ }),
+ this.conversion.unconverted(openWhere),
+ ]);
return {
rows: rows.map(
@@ -157,7 +151,7 @@ export class DealsService {
total,
facetCounts,
openValueCents: toCents(openValue._sum.baseAmount),
- reportingCurrency,
+ reportingCurrency: base,
unconverted,
} satisfies ListResult<unknown> & {
openValueCents: number | null;
diff --git a/apps/api/test/currency-totals.integration.spec.ts b/apps/api/test/currency-totals.integration.spec.ts
index 34b17580..9d8af124 100644
--- a/apps/api/test/currency-totals.integration.spec.ts
+++ b/apps/api/test/currency-totals.integration.spec.ts
@@ -91,10 +91,12 @@ afterAll(async () => {
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 },
- });
+
+ if (previousReportingCurrency) {
+ await writeReportingCurrency(db, previousReportingCurrency);
+ } else {
+ await db.appSetting.updateMany({ data: { reportingCurrency: null } });
+ }
await conversion.rerateAll();
});
@@ -233,3 +235,78 @@ describe("the deals list", () => {
expect(amounts).toEqual([...amounts].sort((a, b) => (b ?? 0) - (a ?? 0)));
});
});
+
+describe("a converted figure knows which currency it is in", () => {
+ it("leaves a deal whose baseAmount predates a currency change out of totals", async () => {
+ await writeReportingCurrency(db, "USD");
+ await conversion.rerateAll();
+
+ const before = await pipelineCents();
+ const summary = await dashboard.summary(userId, { scope: "me" });
+ expect(summary.unconverted.count).toBe(0);
+
+ const deal = await deals.create({
+ name: `Stale ${suffix}`,
+ companyId,
+ ownerId: userId,
+ amountCents: MILLION,
+ currency: "USD",
+ });
+
+ expect(await pipelineCents()).toBe(before + MILLION);
+
+ await db.deal.update({
+ where: { id: deal.id },
+ data: { baseCurrency: "JPY" },
+ });
+
+ expect(await pipelineCents()).toBe(before);
+
+ const stale = await dashboard.summary(userId, { scope: "me" });
+ expect(stale.unconverted.count).toBe(1);
+
+ const filled = await conversion.fillMissing();
+ expect(filled.converted).toBeGreaterThan(0);
+
+ expect(await pipelineCents()).toBe(before + MILLION);
+
+ await db.deal.delete({ where: { id: deal.id } });
+ });
+
+ it("counts a currency once however it was cased or padded", async () => {
+ const rows = await Promise.all(
+ [" usd ", "Usd"].map((currency, index) =>
+ db.deal.create({
+ data: {
+ name: `Variant ${index} ${suffix}`,
+ companyId,
+ ownerId: userId,
+ amount: 1000,
+ currency,
+ },
+ select: { id: true },
+ }),
+ ),
+ );
+
+ const rerated = await conversion.rerateAll();
+
+ const written = await db.deal.findMany({
+ where: { id: { in: rows.map((row) => row.id) } },
+ select: { baseAmount: true, baseCurrency: true },
+ });
+
+ for (const row of written) {
+ expect(row.baseCurrency).toBe("USD");
+ expect(row.baseAmount?.toNumber()).toBe(1000);
+ }
+
+ expect(rerated.converted).toBe(
+ await db.deal.count({ where: { amount: { not: null } } }),
+ );
+
+ await db.deal.deleteMany({
+ where: { id: { in: rows.map((row) => row.id) } },
+ });
+ });
+});
diff --git a/apps/api/vercel.json b/apps/api/vercel.json
new file mode 100644
index 00000000..994ee9b1
--- /dev/null
+++ b/apps/api/vercel.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://openapi.vercel.sh/vercel.json",
+ "crons": [
+ {
+ "path": "/internal/sync/google",
+ "schedule": "*/5 * * * *"
+ },
+ {
+ "path": "/internal/sync/rates",
+ "schedule": "0 6 * * *"
+ }
+ ]
+}
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 60d0b64b..bdb040c7 100644
--- a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
+++ b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
@@ -85,8 +85,8 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
const currencies = useQuery(trpc.currency.settings.queryOptions());
const resolvedOwner = ownerId || me.data?.id || UNSET;
- const resolvedCurrency =
- currency || currencies.data?.reportingCurrency || "USD";
+ const workspaceCurrency = currencies.data?.reportingCurrency;
+ const resolvedCurrency = currency || workspaceCurrency || "USD";
const create = useMutation(
trpc.deals.create.mutationOptions({
@@ -134,7 +134,7 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
amountCents: Number.isFinite(parsed)
? Math.round(parsed * 100)
: null,
- currency: resolvedCurrency,
+ currency: currency || workspaceCurrency,
expectedCloseDate: closeDate || null,
});
}}
diff --git a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx
index 104b4442..df7ff27a 100644
--- a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx
+++ b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx
@@ -113,10 +113,17 @@ export function CurrencySettings() {
if (!settings.data) return null;
- const { reportingCurrency, refreshedAt, rates, inUse, unconverted } =
- settings.data;
+ const {
+ reportingCurrency,
+ refreshedAt,
+ rates,
+ inUse,
+ unconverted,
+ canManage,
+ } = settings.data;
const busy =
+ !canManage ||
setBase.isPending ||
setRate.isPending ||
removeRate.isPending ||
@@ -153,8 +160,9 @@ export function CurrencySettings() {
</SelectContent>
</Select>
<FieldDescription>
- Changing this re-converts every deal at today's rates. Figures
- already reported will move.
+ {canManage
+ ? "Changing this re-converts every deal at today's rates. Figures already reported will move."
+ : "Only an owner or an admin can change how money is reported."}
</FieldDescription>
</Field>
</CardContent>
diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsx
index f7d386d5..c81e392a 100644
--- a/apps/app/components/crm/inline-field.tsx
+++ b/apps/app/components/crm/inline-field.tsx
@@ -96,6 +96,7 @@ export function InlineField({
variant="ghost"
size="sm"
className={CONTROL}
+ disabled={saving}
onClick={() => {
setDraft(value ?? "");
setEditing(true);
@@ -197,6 +198,7 @@ export function InlineTextArea({
size="sm"
aria-label={label}
className={BLOCK_CONTROL}
+ disabled={saving}
onClick={() => {
setDraft(value ?? "");
setEditing(true);
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
index e14f7c58..82a8cf67 100644
--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -256,6 +256,7 @@ function DealOverview({ deal }: { deal: Deal }) {
label="Currency"
value={deal.currency}
options={CURRENCY_OPTIONS}
+ placeholder={`${deal.currency} — no longer supported`}
onSave={(currency) => save({ currency })}
/>
<ReportedValue deal={deal} />
diff --git a/docs/api.md b/docs/api.md
index 3eb3ccb7..bd93ab19 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -554,6 +554,26 @@ So there are now two amounts on a deal, and only one of them is ever summed.
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.
+- **`baseCurrency` says which currency `baseAmount` is denominated in, and
+ without it the invariant is unprovable.** Re-rating is a read of the distinct
+ currencies followed by an `UPDATE` per currency — not one atomic statement — so
+ a deal written concurrently with a reporting-currency change can commit a
+ figure converted against the *old* base. Nothing about the row said so: a
+ number with no currency attached cannot be told apart from a correct one, and
+ it would have sat in the pipeline total forever.
+ - **Every money aggregate filters on it**, through `countedWhere(base)`. A row
+ whose `baseCurrency` is not the current one is excluded rather than summed,
+ which is what stops the wrong figure being reported for the window before
+ anything fixes it. Counts are deliberately *not* filtered — a deal with no
+ amount is still an open deal — so the stage groups read their counts from one
+ query and their sums from another.
+ - **`pendingWhere(base)` is the other half**: null `baseAmount` *or* a
+ `baseCurrency` that is not the current one. It is what `unconverted` reports
+ and what `fillMissing()` repairs, so the daily cron heals a straggler and the
+ disclosure and the totals never disagree about which rows were counted.
+ - **It is composed with `AND`, never spread.** `pendingWhere` contains an `OR`,
+ and the deals list's own `where` already carries one from the search filter —
+ spreading the two would silently drop the caller's search.
**The rate is resolved once, at the moment the amount is set, and then frozen.**
`DealsService.create` and `.update` call `ConversionService.dealFields` whenever
@@ -597,6 +617,18 @@ call site — one place to be wrong instead of six.
**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.
+- **Re-rating groups by the raw column and then works in normalised codes.**
+ `currency` was free text once, so ` usd ` and `USD` are two groups that mean
+ one currency — and each pass matches on `upper(btrim(...))`, so every pass
+ updated every variant. The counts came back multiples too high (80 rows
+ reported for 28) and the same rows were written repeatedly. The codes are
+ deduplicated through a `Set` before any rate is resolved.
+- **An amount has an upper bound, and it is the column's.** `MAX_AMOUNT_CENTS`
+ in `deals.contracts.ts` is what `Decimal(14, 2)` can hold; without it a large
+ enough amount failed as a Postgres numeric overflow — a 500 on input that
+ passed validation. `baseAmount` is `Decimal(24, 4)` rather than `(18, 4)` for
+ the same reason from the other direction: the *product* of a legal amount and
+ a legal rate has to fit.
- **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
@@ -672,6 +704,15 @@ and needs no account, which is what keeps it out of `.env` entirely.
ceiling stays low enough for the interactive Refresh button on the settings
page to be worth pressing.
+**Changing how money is reported is an owner-or-admin action.** `canManageCurrency`
+in [`@crm/auth`](../packages/auth/src/organization.ts) sits beside
+`canRenameWorkspace` and `canConfigureSso` and answers the same way, and
+`CurrencyService` enforces it on every mutation while `settings` returns
+`canManage` so the page disables the controls it would refuse — the button and
+the 403 cannot disagree. `AuthMiddleware` alone was not enough here: it proves
+who is asking, and this router can re-rate every deal in the CRM, which is not
+something any member should be able to do to everyone else's numbers.
+
**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
@@ -688,6 +729,12 @@ rate looks wrong — that part belongs in `apps/agent`.
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.
+- **A route is not a schedule.** `apps/api/vercel.json` is what actually makes
+ either cron run, and it had been deleted — so the Gmail and Calendar sync had
+ not been firing on Vercel either, while this file went on documenting a
+ `*/5 * * * *` entry that no longer existed. Adding an internal route means
+ adding it there in the same change; nothing else in the repo will tell you it
+ is dead.
- **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
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 4fed1a17..cbd838e8 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -3,6 +3,7 @@ export { AUTH_COOKIE_PREFIX } from "./cookies";
export { isGoogleConfigured } from "./env";
export {
canChangeRole,
+ canManageCurrency,
canRenameWorkspace,
DEFAULT_WORKSPACE_NAME,
ensureWorkspaceMembership,
diff --git a/packages/auth/src/organization.ts b/packages/auth/src/organization.ts
index 35397ec5..5ed81a75 100644
--- a/packages/auth/src/organization.ts
+++ b/packages/auth/src/organization.ts
@@ -25,6 +25,10 @@ export function canChangeRole(role: WorkspaceRole | null): boolean {
return isWorkspaceAdmin(role);
}
+export function canManageCurrency(role: WorkspaceRole | null): boolean {
+ return isWorkspaceAdmin(role);
+}
+
export async function ensureWorkspaceMembership(
userId: string,
): Promise<string | undefined> {
diff --git a/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql b/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql
index d505afc0..7518d952 100644
--- a/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql
+++ b/packages/db/prisma/migrations/20260805130000_multi_currency/migration.sql
@@ -37,9 +37,16 @@ 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.
+-- Backfill: convert the rows we can account for without inventing a rate, which
+-- is the ones already denominated in the reporting currency. Skipping this would
+-- drop every existing deal out of every total the moment this migration lands.
+--
+-- Rows in any other currency are deliberately left null rather than counted at
+-- 1:1 — the currency column has been free text until now, so a deal really can
+-- be sitting there in EUR, and calling that figure dollars would be worse than
+-- leaving it out. A null is excluded from every total AND reported by the
+-- unconverted disclosure, and the first rates refresh picks it up through
+-- fillMissing().
UPDATE "deal"
SET "baseAmount" = "amount",
"fxRate" = 1,
diff --git a/packages/db/prisma/migrations/20260805150000_deal_base_currency/migration.sql b/packages/db/prisma/migrations/20260805150000_deal_base_currency/migration.sql
new file mode 100644
index 00000000..096880b4
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805150000_deal_base_currency/migration.sql
@@ -0,0 +1,19 @@
+-- AlterTable
+ALTER TABLE "deal" ALTER COLUMN "baseAmount" TYPE DECIMAL(24,4);
+
+-- AlterTable
+ALTER TABLE "deal" ADD COLUMN "baseCurrency" TEXT;
+
+-- Backfill: a converted figure that does not say which currency it is in cannot
+-- be told apart from a stale one. Every row that already has a baseAmount was
+-- converted against the current reporting currency, so name it.
+UPDATE "deal"
+SET "baseCurrency" = COALESCE(
+ (
+ SELECT upper(btrim("reportingCurrency"))
+ FROM "appSetting"
+ WHERE "id" = 'app' AND btrim(COALESCE("reportingCurrency", '')) <> ''
+ ),
+ 'USD'
+ )
+WHERE "baseAmount" IS NOT NULL;
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 350c8723..cd1bf4c8 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -397,9 +397,10 @@ model Deal {
closedAt DateTime?
closedReason String?
- baseAmount Decimal? @db.Decimal(18, 4)
- fxRate Decimal? @db.Decimal(20, 10)
- fxRateAt DateTime?
+ baseAmount Decimal? @db.Decimal(24, 4)
+ baseCurrency String?
+ fxRate Decimal? @db.Decimal(20, 10)
+ fxRateAt DateTime?
lastActivityAt DateTime?
diff --git a/packages/db/src/fx.ts b/packages/db/src/fx.ts
index 89bea0c4..d6b46f25 100644
--- a/packages/db/src/fx.ts
+++ b/packages/db/src/fx.ts
@@ -14,6 +14,7 @@ export interface ResolvedRate {
export interface Conversion {
baseAmount: Prisma.Decimal;
+ baseCurrency: string;
fxRate: Prisma.Decimal;
fxRateAt: Date;
origin: RateOrigin;
@@ -58,12 +59,15 @@ export async function resolveRate(
export function applyRate(
amount: Prisma.Decimal,
rate: ResolvedRate,
- baseCurrency: string,
+ base: string,
): Conversion {
+ const baseCurrency = normalizeCurrency(base);
+
return {
baseAmount: amount
.times(rate.rate)
.toDecimalPlaces(minorUnitsOf(baseCurrency)),
+ baseCurrency,
fxRate: rate.rate,
fxRateAt: rate.asOf,
origin: rate.origin,