fix(subscription): корректная цена за месяц при выборе периода

Для периодов короче месяца в карточке периода под ценой выводилась
та же сумма с подписью «/мес»: цена за 7 дней показывалась как цена
за месяц. Причина — деление на max(1, days / 30), которое для коротких
периодов даёт делитель 1.

Расчёт вынесен в getMonthlyPriceKopeks: месячная ставка считается
пропорцией (price * 30 / days) и не показывается для периодов в месяц
и короче, где она либо дублирует цену, либо вводит в заблуждение.
Тот же хелпер применён на экране продления, где месячная цена для
периодов вроде 45 дней считалась делением на округлённое число
месяцев.
This commit is contained in:
kewldan
2026-07-28 21:23:08 +03:00
parent 51d0f0431a
commit 888a02f397
4 changed files with 51 additions and 10 deletions

View File

@@ -8,6 +8,7 @@ import { useCurrency } from '../../../hooks/useCurrency';
import { usePromoDiscount } from '../../../hooks/usePromoDiscount';
import { usePlatform } from '../../../platform';
import { openPaymentUrl } from '../../../utils/openPaymentUrl';
import { getMonthlyPriceKopeks } from '../../../utils/pricing';
import InsufficientBalancePrompt from '../../InsufficientBalancePrompt';
import type { Tariff, TariffPeriod } from '../../../types';
@@ -279,10 +280,7 @@ export function TariffPurchaseForm({
const displayDiscount = promoPeriod.percent;
const displayOriginal = promoPeriod.original;
const displayPrice = promoPeriod.price;
const displayPerMonth =
displayPrice !== period.price_kopeks
? Math.round(displayPrice / Math.max(1, period.days / 30))
: period.price_per_month_kopeks;
const displayPerMonth = getMonthlyPriceKopeks(displayPrice, period.days);
return (
<button
@@ -317,9 +315,11 @@ export function TariffPurchaseForm({
</span>
)}
</div>
{displayPerMonth !== null && (
<div className="mt-1 text-xs text-dark-500">
{formatPrice(displayPerMonth)}/{t('subscription.month')}
</div>
)}
</button>
);
})}

View File

@@ -5,6 +5,7 @@ import { Navigate, useNavigate, useParams } from 'react-router';
import { subscriptionApi } from '../api/subscription';
import { useTheme } from '../hooks/useTheme';
import { getGlassColors } from '../utils/glassTheme';
import { getMonthlyPriceKopeks } from '../utils/pricing';
import { useCurrency } from '../hooks/useCurrency';
import { useHaptic } from '../platform';
import InsufficientBalancePrompt from '../components/InsufficientBalancePrompt';
@@ -143,8 +144,7 @@ export default function RenewSubscription() {
{options.map((option) => {
const isSelected = selectedPeriod === option.period_days;
const canAfford = balanceKopeks >= option.price_kopeks;
const months = Math.max(1, Math.round(option.period_days / 30));
const perMonth = option.price_kopeks / months;
const perMonth = getMonthlyPriceKopeks(option.price_kopeks, option.period_days);
return (
<button
@@ -181,7 +181,7 @@ export default function RenewSubscription() {
? t('subscription.free', 'Бесплатно')
: `${formatAmount(option.price_kopeks / 100)} ${currencySymbol}`}
</div>
{months > 1 && (
{perMonth !== null && (
<div className="text-[11px]" style={{ color: g.textSecondary }}>
{formatAmount(perMonth / 100)} {currencySymbol}/
{t('common.units.mo', 'мес')}

26
src/utils/pricing.test.ts Normal file
View File

@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { getMonthlyPriceKopeks } from './pricing';
describe('getMonthlyPriceKopeks', () => {
it('hides the monthly rate for periods of a month or shorter', () => {
expect(getMonthlyPriceKopeks(4830, 7)).toBeNull();
expect(getMonthlyPriceKopeks(9900, 14)).toBeNull();
expect(getMonthlyPriceKopeks(16030, 30)).toBeNull();
});
it('divides by whole months for multiples of 30 days', () => {
expect(getMonthlyPriceKopeks(30000, 90)).toBe(10000);
expect(getMonthlyPriceKopeks(60000, 180)).toBe(10000);
});
it('prorates periods that are not whole months', () => {
expect(getMonthlyPriceKopeks(15000, 45)).toBe(10000);
expect(getMonthlyPriceKopeks(100000, 365)).toBe(8219);
});
it('returns null for non-finite input', () => {
expect(getMonthlyPriceKopeks(Number.NaN, 90)).toBeNull();
expect(getMonthlyPriceKopeks(30000, Number.NaN)).toBeNull();
expect(getMonthlyPriceKopeks(30000, Number.POSITIVE_INFINITY)).toBeNull();
});
});

15
src/utils/pricing.ts Normal file
View File

@@ -0,0 +1,15 @@
/** Длина «месяца» в днях — тот же множитель, что использует бэкенд при расчёте цены за месяц. */
const DAYS_IN_MONTH = 30;
/**
* Цена за месяц (в копейках) для периода длиной `days` дней.
*
* Возвращает `null`, когда месячная ставка не имеет смысла: для периода
* в месяц и короче она либо повторяет цену периода (30 дней), либо
* выдаёт цену периода за месячную (7 дней → цена семи дней «за месяц»).
*/
export function getMonthlyPriceKopeks(priceKopeks: number, days: number): number | null {
if (!Number.isFinite(priceKopeks) || !Number.isFinite(days)) return null;
if (days <= DAYS_IN_MONTH) return null;
return Math.round((priceKopeks * DAYS_IN_MONTH) / days);
}