Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- You are about to drop the column `precision` on the `CachedCurrencyRate` table. All the data in the column will be lost.

*/
-- AlterTable
ALTER TABLE "CachedCurrencyRate" DROP COLUMN "precision";
1 change: 0 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,6 @@ model CachedCurrencyRate {
to String
date DateTime
rate Float
precision Int
lastFetched DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
2 changes: 1 addition & 1 deletion src/components/AddExpense/AddExpensePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { UploadFile } from './UploadFile';
import { UserInput } from './UserInput';
import { CurrencyInput } from '../ui/currency-input';
import { CurrencyConversion } from '../Friend/CurrencyConversion';
import { currencyConversion } from '~/utils/numbers';
import { currencyConversion, getRatePrecision } from '~/utils/numbers';
import { CURRENCY_CONVERSION_ICON } from '../ui/categoryIcons';

export const AddOrEditExpensePage: React.FC<{
Expand Down
33 changes: 23 additions & 10 deletions src/components/Friend/CurrencyConversion.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslationWithUtils } from '~/hooks/useTranslationWithUtils';
import { api } from '~/utils/api';
import { currencyConversion } from '~/utils/numbers';
import { MAX_RATE_PRECISION, currencyConversion, getRatePrecision } from '~/utils/numbers';

import { toast } from 'sonner';
import { env } from '~/env';
Expand Down Expand Up @@ -55,15 +55,21 @@ export const CurrencyConversion: React.FC<{

useEffect(() => {
setAmountStr(toUIString(amount, false, true));
setRate(editingRate ? editingRate.toFixed(4) : '');
if (editingRate) {
const precision = getRatePrecision(editingRate);
setRate(editingRate.toFixed(precision));
} else {
setRate('');
}
if (editingTargetCurrency && isCurrencyCode(editingTargetCurrency)) {
setTargetCurrency(editingTargetCurrency);
}
}, [amount, editingRate, editingTargetCurrency, toUIString]);

useEffect(() => {
if (getCurrencyRate.data?.rate) {
setRate(getCurrencyRate.data.rate.toFixed(4));
const precision = getRatePrecision(getCurrencyRate.data.rate);
setRate(getCurrencyRate.data.rate.toFixed(precision));
}
}, [getCurrencyRate.data]);

Expand Down Expand Up @@ -104,7 +110,7 @@ export const CurrencyConversion: React.FC<{
return;
}
const [int = '', dec = ''] = raw.split('.');
const trimmedDec = dec.slice(0, 4);
const trimmedDec = dec.slice(0, 10);
const normalized = raw.includes('.') ? `${int}.${trimmedDec}` : int;
setRate(normalized);
}, []);
Expand Down Expand Up @@ -153,6 +159,13 @@ export const CurrencyConversion: React.FC<{
}
}, [onSubmit, targetCurrency, amountStr, rate, currency, getCurrencyHelpersCached, t]);

const ratePrecision = useMemo(() => {
if (!rate) {
return 0;
}
return getRatePrecision(Number(rate));
}, [rate]);

return (
<AppDrawer
trigger={children}
Expand All @@ -175,7 +188,7 @@ export const CurrencyConversion: React.FC<{
<div className="w-full">
<div className="mx-auto grid w-full max-w-3xl grid-cols-1 place-items-center gap-x-4 gap-y-4 sm:grid-cols-3 sm:gap-y-16">
{/* From amount */}
<div className="flex w-full max-w-[240px] items-end gap-2 sm:col-span-2">
<div className="flex w-full max-w-60 items-end gap-2 sm:col-span-2">
<div className="flex flex-col gap-2">
<Label className="capitalize">{t('ui.expense.from')}</Label>
<Button variant="outline" className="text-base" disabled>
Expand All @@ -191,7 +204,7 @@ export const CurrencyConversion: React.FC<{
/>
</div>

<div className="flex w-full max-w-[240px] items-end gap-2 sm:col-span-2">
<div className="flex w-full max-w-60 items-end gap-2 sm:col-span-2">
<div className="flex flex-col gap-2">
<Label className="capitalize">{t('ui.expense.to')}</Label>
{editingTargetCurrency ? (
Expand Down Expand Up @@ -219,14 +232,14 @@ export const CurrencyConversion: React.FC<{
</div>

{/* Rate */}
<div className="flex w-full max-w-[240px] items-start sm:col-start-3 sm:row-span-2 sm:row-start-1 sm:h-full sm:flex-col sm:justify-between">
<div className="flex w-full max-w-60 items-start sm:col-start-3 sm:row-span-2 sm:row-start-1 sm:h-full sm:flex-col sm:justify-between">
<div className="flex w-1/2 flex-col gap-2 sm:w-full">
<Label className="capitalize">{t('currency_conversion.rate')}</Label>
<div className="flex flex-col">
<Input
aria-label="Rate"
type="number"
step="0.0001"
step={`0.${'0'.repeat(MAX_RATE_PRECISION - 1)}1`}
min={0}
value={rate}
inputMode="numeric"
Expand All @@ -241,10 +254,10 @@ export const CurrencyConversion: React.FC<{
{Boolean(rate) && (
<>
<span className="pointer-events-none text-xs text-gray-500">
1 {currency} = {Number(rate).toFixed(4)} {targetCurrency}
1 {currency} = {Number(rate).toFixed(ratePrecision)} {targetCurrency}
</span>
<span className="pointer-events-none text-xs text-gray-500">
1 {targetCurrency} = {(1 / Number(rate)).toFixed(4)} {currency}
1 {targetCurrency} = {(1 / Number(rate)).toFixed(ratePrecision)} {currency}
</span>
</>
)}
Expand Down
1 change: 1 addition & 0 deletions src/server/api/services/currencyRateService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ abstract class CurrencyRateProvider {

const cachedRate = await this.checkCache(from, to, date);
if (cachedRate) {
console.log(cachedRate);
return cachedRate;
}

Expand Down
2 changes: 1 addition & 1 deletion src/store/addStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { DEFAULT_CATEGORY } from '~/lib/category';
import { type CurrencyCode } from '~/lib/currency';
import type { TransactionAddInputModel } from '~/types';
import { shuffleArray } from '~/utils/array';
import { BigMath, gcd } from '~/utils/numbers';
import { BigMath } from '~/utils/numbers';
import { cyrb128, splitmix32 } from '~/utils/random';

export type Participant = User & { amount?: bigint };
Expand Down
20 changes: 18 additions & 2 deletions src/utils/numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,12 +259,28 @@ export function currencyConversion({
const toDecimalDigits = CURRENCIES[to].decimalDigits;
const preMultiplier = BigInt(10 ** Math.max(toDecimalDigits - fromDecimalDigits, 0));
const postMultiplier = BigInt(10 ** Math.max(fromDecimalDigits - toDecimalDigits, 0));
const precision = getRatePrecision(rate);
const ratePrecisionFactor = 10 ** precision;
return BigMath.roundDiv(
amount * preMultiplier * BigInt(Math.round(rate * 10000)),
postMultiplier * 10000n,
amount * preMultiplier * BigInt(Math.round(rate * ratePrecisionFactor)),
postMultiplier * BigInt(ratePrecisionFactor),
);
}

export const MAX_RATE_PRECISION = 10;

export const getRatePrecision = (value: number, maxPrecision = MAX_RATE_PRECISION) => {
const normalized = value.toString().trim();
if ('' === normalized) {
return 0;
}
const decimalIndex = normalized.indexOf('.');
if (-1 === decimalIndex) {
return 0;
}
return Math.min(Math.max(normalized.length - decimalIndex - 1, 0), maxPrecision);
};

export const BigMath = {
abs(x: bigint) {
return 0n > x ? -x : x;
Expand Down