improvements: Currency convertion api added for subscriptions calculation

This commit is contained in:
2026-10-23 21:19:12 +03:30
parent 7049b17882
commit 178b2bc7e0
9 changed files with 192 additions and 28 deletions

View File

@@ -0,0 +1,39 @@
import { quoteSecondary, unitsPerEuro } from './subscription-fx';
const rates = { usd: 1.08, irr: 500_000 };
describe('subscription currency quote', () => {
it('uses the dollar rate as units of one euro', () => {
expect(unitsPerEuro('DOLLAR', rates)).toBe(1.08);
});
it('turns Iranian rials into tomans', () => {
expect(unitsPerEuro('TOMAN', rates)).toBe(50_000);
});
it('hides a second amount when there is no cash currency or the org uses euros', () => {
expect(quoteSecondary(null, rates)).toEqual({
secondaryCurrency: null,
unitsPerEuro: null,
});
expect(quoteSecondary('EURO', rates)).toEqual({
secondaryCurrency: null,
unitsPerEuro: null,
});
expect(quoteSecondary('DOLLAR', null)).toEqual({
secondaryCurrency: null,
unitsPerEuro: null,
});
});
it('returns the billing currency beside the euro quote', () => {
expect(quoteSecondary('DOLLAR', rates)).toEqual({
secondaryCurrency: 'DOLLAR',
unitsPerEuro: 1.08,
});
expect(quoteSecondary('TOMAN', rates)).toEqual({
secondaryCurrency: 'TOMAN',
unitsPerEuro: 50_000,
});
});
});

View File

@@ -0,0 +1,66 @@
const RIALS_PER_TOMAN = 10;
const CACHE_MS = 24 * 60 * 60 * 1000;
const RATE_URL =
'https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.min.json';
export type SecondaryCurrency = 'DOLLAR' | 'TOMAN';
export type EuroRates = {
usd: number;
irr: number;
};
export type SubscriptionQuoteCurrency = {
secondaryCurrency: SecondaryCurrency | null;
unitsPerEuro: number | null;
};
type RateCache = EuroRates & { at: number };
let cache: RateCache | null = null;
function positive(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value > 0;
}
/** 1 euro in the billing currency. Iranian rials from the feed become tomans. */
export function unitsPerEuro(
currency: SecondaryCurrency,
rates: EuroRates,
): number | null {
if (currency === 'DOLLAR') return positive(rates.usd) ? rates.usd : null;
if (!positive(rates.irr)) return null;
return rates.irr / RIALS_PER_TOMAN;
}
export function quoteSecondary(
currency: SecondaryCurrency | 'EURO' | null,
rates: EuroRates | null,
): SubscriptionQuoteCurrency {
if (!rates || currency == null || currency === 'EURO') {
return { secondaryCurrency: null, unitsPerEuro: null };
}
const units = unitsPerEuro(currency, rates);
if (units == null) return { secondaryCurrency: null, unitsPerEuro: null };
return { secondaryCurrency: currency, unitsPerEuro: units };
}
export async function getCachedEuroRates(now = Date.now()): Promise<EuroRates | null> {
if (cache && now - cache.at < CACHE_MS) {
return { usd: cache.usd, irr: cache.irr };
}
try {
const response = await fetch(RATE_URL, { signal: AbortSignal.timeout(5000) });
if (!response.ok) return cache ? { usd: cache.usd, irr: cache.irr } : null;
const body = (await response.json()) as { eur?: { usd?: unknown; irr?: unknown } };
const usd = body.eur?.usd;
const irr = body.eur?.irr;
if (!positive(usd) || !positive(irr)) {
return cache ? { usd: cache.usd, irr: cache.irr } : null;
}
cache = { at: now, usd, irr };
return { usd, irr };
} catch {
return cache ? { usd: cache.usd, irr: cache.irr } : null;
}
}

View File

@@ -24,7 +24,7 @@ describe('subscription date and price rules', () => {
expect(next.getTime() - NOW.getTime()).toBe(SUBSCRIPTION_MONTH_DAYS * 86_400_000);
});
it('prices base at $20 per month and each extra seat at $7 per month', () => {
it('prices base at 20 euros per month and each extra seat at 7 euros per month', () => {
expect(
quoteAmount({
baseSelected: true,

View File

@@ -7,7 +7,12 @@ import {
import { PrismaService } from '../../../prisma/prisma.service';
import { AppException, ErrorCode } from '../../common/errors';
import { hasEffectivePermission } from '../../common/membership-permissions';
import {
orgHasCashHistory,
resolveBillingCurrency,
} from '../billing/billing-currency';
import { UserNotificationService } from '../notifications/user-notification.service';
import { getCachedEuroRates, quoteSecondary } from './subscription-fx';
import {
startBaseTrial,
startBaseWithoutTrial,
@@ -373,8 +378,18 @@ export class SubscriptionService {
return membership;
}
private async quoteCurrency(organizationId: string) {
const [settings, hasCash, rates] = await Promise.all([
resolveBillingCurrency(this.prisma, organizationId),
orgHasCashHistory(this.prisma, organizationId),
getCachedEuroRates(),
]);
return quoteSecondary(hasCash ? settings.currency : null, rates);
}
private async buildCurrent(organizationId: string) {
const now = new Date();
const quote = await this.quoteCurrency(organizationId);
const org = await this.prisma.organization.findUnique({
where: { id: organizationId },
include: {
@@ -395,6 +410,7 @@ export class SubscriptionService {
seatsTotal: 0,
emptyIncludedCount: 0,
groups: [],
...quote,
};
}
@@ -454,6 +470,7 @@ export class SubscriptionService {
})),
};
}),
...quote,
};
}
}

View File

@@ -1164,6 +1164,7 @@
"inviteFromStaff": "Invite from Staff",
"addSeat": "Add seat",
"removeSeat": "Remove",
"disableBeforeRemoveSeat": "Disable this person in Staff before this seat can be removed.",
"selectAll": "Select all",
"extendSelected": "Extend selected",
"subscriptionMonths": "Months",
@@ -1471,7 +1472,7 @@
"SUBSCRIPTION_MANAGE_DENIED": "You cannot manage this subscription.",
"SUBSCRIPTION_SEAT_NOT_FOUND": "That seat was not found.",
"SUBSCRIPTION_SEAT_NOT_EXTRA": "Only an extra seat can be removed.",
"SUBSCRIPTION_SEAT_NOT_EMPTY": "Only an empty extra seat can be removed.",
"SUBSCRIPTION_SEAT_NOT_EMPTY": "Disable this staff member in Staff before removing their seat.",
"SUBSCRIPTION_NOTHING_SELECTED": "Select the base plan or at least one seat.",
"SUBSCRIPTION_MONTHS_INVALID": "Choose between 1 and 12 months.",
"SUBSCRIPTION_PLAN_MISSING": "The base plan is not available.",

View File

@@ -1165,6 +1165,7 @@
"inviteFromStaff": "دعوت از کارکنان",
"addSeat": "افزودن صندلی",
"removeSeat": "حذف",
"disableBeforeRemoveSeat": "پیش از حذف این صندلی، این شخص را در کارکنان غیرفعال کنید.",
"selectAll": "انتخاب همه",
"extendSelected": "تمدید موارد انتخاب‌شده",
"subscriptionMonths": "ماه",
@@ -1472,7 +1473,7 @@
"SUBSCRIPTION_MANAGE_DENIED": "شما نمی‌توانید این اشتراک را مدیریت کنید.",
"SUBSCRIPTION_SEAT_NOT_FOUND": "این صندلی پیدا نشد.",
"SUBSCRIPTION_SEAT_NOT_EXTRA": "فقط صندلی اضافی را می‌توان حذف کرد.",
"SUBSCRIPTION_SEAT_NOT_EMPTY": "فقط صندلی اضافی خالی را می‌توان حذف کرد.",
"SUBSCRIPTION_SEAT_NOT_EMPTY": "پیش از حذف این صندلی، این عضو را در کارکنان غیرفعال کنید.",
"SUBSCRIPTION_NOTHING_SELECTED": "طرح پایه یا حداقل یک صندلی را انتخاب کنید.",
"SUBSCRIPTION_MONTHS_INVALID": "بین ۱ تا ۱۲ ماه انتخاب کنید.",
"SUBSCRIPTION_PLAN_MISSING": "طرح پایه در دسترس نیست.",

View File

@@ -1164,6 +1164,7 @@
"inviteFromStaff": "Uitnodigen via Personeel",
"addSeat": "Plaats toevoegen",
"removeSeat": "Verwijderen",
"disableBeforeRemoveSeat": "Schakel deze persoon eerst uit bij Personeel voordat deze plaats kan worden verwijderd.",
"selectAll": "Alles selecteren",
"extendSelected": "Selectie verlengen",
"subscriptionMonths": "Maanden",
@@ -1471,7 +1472,7 @@
"SUBSCRIPTION_MANAGE_DENIED": "U kunt dit abonnement niet beheren.",
"SUBSCRIPTION_SEAT_NOT_FOUND": "Die plaats is niet gevonden.",
"SUBSCRIPTION_SEAT_NOT_EXTRA": "Alleen een extra plaats kan worden verwijderd.",
"SUBSCRIPTION_SEAT_NOT_EMPTY": "Alleen een lege extra plaats kan worden verwijderd.",
"SUBSCRIPTION_SEAT_NOT_EMPTY": "Schakel deze medewerker eerst uit bij Personeel voordat u de plaats verwijdert.",
"SUBSCRIPTION_NOTHING_SELECTED": "Selecteer het basisplan of minstens één plaats.",
"SUBSCRIPTION_MONTHS_INVALID": "Kies tussen 1 en 12 maanden.",
"SUBSCRIPTION_PLAN_MISSING": "Het basisplan is niet beschikbaar.",

View File

@@ -39,7 +39,24 @@ function selectionCardClass(selected: boolean): string {
}
function moneyLabel(amount: number, locale: string): string {
return `$${formatAppMoney(amount, locale)}`;
return `€${formatAppMoney(amount, locale)}`;
}
function extensionAmount(
euros: number,
locale: string,
secondaryCurrency: SubscriptionCurrent['secondaryCurrency'],
unitsPerEuro: number | null | undefined,
currencyName: (code: 'DOLLAR' | 'TOMAN') => string,
): string {
const euro = moneyLabel(euros, locale);
if (secondaryCurrency == null || unitsPerEuro == null || !Number.isFinite(unitsPerEuro)) {
return euro;
}
const converted = formatAppMoney(euros * unitsPerEuro, locale);
const secondary =
secondaryCurrency === 'DOLLAR' ? `$${converted}` : `${converted} ${currencyName(secondaryCurrency)}`;
return `${euro} · ${secondary}`;
}
export function SubscriptionsPage() {
@@ -179,7 +196,13 @@ export function SubscriptionsPage() {
title: t('extendSelected'),
message: t('extendBody', {
months: formatAppInteger(months, locale),
amount: moneyLabel(quote, locale),
amount: extensionAmount(
quote,
locale,
current?.secondaryCurrency,
current?.unitsPerEuro,
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
),
}),
confirmLabel: t('extendSelected'),
cancelLabel: tCommon('cancel'),
@@ -266,27 +289,34 @@ export function SubscriptionsPage() {
{extras.map((seat) => (
<article key={seat.id} className={selectionCardClass(selectedExtraIds.includes(seat.id))}>
<Checkbox
align="start"
checked={selectedExtraIds.includes(seat.id)}
onChange={(checked) => {
setSelectedExtraIds((ids) =>
checked ? [...ids, seat.id] : ids.filter((id) => id !== seat.id),
);
}}
label={
<span className="block">
<span className="block text-sm font-medium text-text-primary">
{seat.occupant ? occupantLabel(seat.occupant) : t('emptySeat')}
</span>
{seat.occupant ? (
<span className="mt-1 block text-xs text-text-secondary">
{t('assignedUser')}: {occupantLabel(seat.occupant)}
<div className="min-w-0 flex-1">
<Checkbox
align="start"
checked={selectedExtraIds.includes(seat.id)}
onChange={(checked) => {
setSelectedExtraIds((ids) =>
checked ? [...ids, seat.id] : ids.filter((id) => id !== seat.id),
);
}}
label={
<span className="block">
<span className="block text-sm font-medium text-text-primary">
{seat.occupant ? occupantLabel(seat.occupant) : t('emptySeat')}
</span>
) : null}
</span>
}
/>
{seat.occupant ? (
<span className="mt-1 block text-xs text-text-secondary">
{t('assignedUser')}: {occupantLabel(seat.occupant)}
</span>
) : null}
</span>
}
/>
{seat.occupant ? (
<Link href="/staff" className="ms-8 mt-1 block text-xs text-primary hover:opacity-90">
{t('disableBeforeRemoveSeat')}
</Link>
) : null}
</div>
<div className="flex shrink-0 flex-col items-end gap-2">
<p className="text-sm text-text-primary">
{t('seatPerMonth', { amount: moneyLabel(seatPrice, locale) })}
@@ -335,8 +365,15 @@ export function SubscriptionsPage() {
className="w-16 rounded-[var(--radius-sm)] border border-border bg-background-card px-2 py-1 text-text-primary"
/>
</label>
<p className="text-sm text-text-primary">
{t('extendTotal')}: {moneyLabel(quote, locale)}
<p className="text-base font-medium text-text-primary">
{t('extendTotal')}:{' '}
{extensionAmount(
quote,
locale,
current.secondaryCurrency,
current.unitsPerEuro,
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
)}
</p>
<Button type="button" disabled={!someSelected} onClick={() => extendSelected()}>
{t('extendSelected')}

View File

@@ -38,6 +38,8 @@ export type SubscriptionCurrent = {
seatsTotal: number;
emptyIncludedCount: number;
groups: SubscriptionGroup[];
secondaryCurrency?: 'DOLLAR' | 'TOMAN' | null;
unitsPerEuro?: number | null;
};
export const subscriptionsApi = {