feat: implement tax calculations for subscription and SMS wallet payments
- Updated SubscriptionPeriod interface to include tax-related fields: tax_percent, tax_rials, and payable_rials. - Modified payment API documentation to reflect changes in tax handling for subscriptions and SMS wallet charges. - Adjusted PaymentController to calculate payment amounts based on subscription period details instead of client input. - Enhanced PaymentManager to handle net amounts for SMS wallet charges, ensuring tax is not credited to the wallet. - Created PaymentTaxCalculator and SubscriptionTaxCalculator services to manage tax calculations consistently across payment types. - Added tests for tax calculations in both subscription and SMS wallet contexts, ensuring correct behavior with and without tax enabled. - Updated frontend components to display tax information appropriately during payment processes.
This commit is contained in:
@@ -11,6 +11,8 @@ interface PaymentConfig {
|
||||
test_mode: boolean;
|
||||
appointment_fee_rials: number;
|
||||
gateways: PaymentGatewayInfo[];
|
||||
/** نرخ مالیات اشتراک و شارژ کیف پول؛ صفر یعنی خاموش. */
|
||||
tax_percent: number;
|
||||
}
|
||||
|
||||
export function usePaymentConfig() {
|
||||
@@ -22,5 +24,6 @@ export function usePaymentConfig() {
|
||||
return {
|
||||
isTestMode: data?.data?.test_mode ?? false,
|
||||
gateways: data?.data?.gateways ?? [],
|
||||
taxPercent: data?.data?.tax_percent ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/utils';
|
||||
import { formatRial, tomanToRial } from '../lib/utils';
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
vi.mock('../lib/api', () => ({
|
||||
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
ApiError: class extends Error {},
|
||||
}));
|
||||
|
||||
import { api } from '../lib/api';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import SmsWalletPage from './SmsWalletPage';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
|
||||
/**
|
||||
* مبلغِ واردشده اعتبارِ کیف پول است — خالص. مالیات رویش اضافه میشود، پس عددِ
|
||||
* دکمهٔ پرداخت باید بزرگتر از مبلغ واردشده باشد وگرنه کاربر سرِ درگاه غافلگیر
|
||||
* میشود.
|
||||
*/
|
||||
function mockApi(taxPercent: number) {
|
||||
get.mockImplementation((url: string) => {
|
||||
if (url.includes('/sms/wallet/balance')) {
|
||||
return Promise.resolve({ success: true, data: { balance_rials: 0, sms_price_rials: 5000 } });
|
||||
}
|
||||
if (url.includes('/sms/wallet/logs')) {
|
||||
return Promise.resolve({ success: true, data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } });
|
||||
}
|
||||
if (url.includes('/sms/settings')) return Promise.resolve({ success: true, data: null });
|
||||
// FeatureGate صفحه را پشت قابلیت پنل پیامک نگه میدارد.
|
||||
if (url.includes('/subscription/my')) {
|
||||
return Promise.resolve({
|
||||
success: true,
|
||||
data: { subscription: null, used_trial: false, effective_plan: { features: { sms_panel: true } } },
|
||||
});
|
||||
}
|
||||
if (url.includes('/payment/config')) {
|
||||
return Promise.resolve({
|
||||
success: true,
|
||||
data: { test_mode: false, appointment_fee_rials: 0, tax_percent: taxPercent, gateways: [{ name: 'mellat', label: 'بانک ملت' }] },
|
||||
});
|
||||
}
|
||||
return Promise.resolve({ success: true, data: null });
|
||||
});
|
||||
}
|
||||
|
||||
async function openChargeModalWith(amountToman: string) {
|
||||
renderWithProviders(<SmsWalletPage />, { route: '/admin/sms-wallet' });
|
||||
fireEvent.click(await screen.findByText('شارژ کیف پول'));
|
||||
|
||||
const input = await screen.findByLabelText('مبلغ شارژ (تومان)');
|
||||
fireEvent.change(input, { target: { value: amountToman } });
|
||||
}
|
||||
|
||||
describe('SmsWalletPage — tax', () => {
|
||||
beforeEach(() => {
|
||||
get.mockReset();
|
||||
// useSubscription فقط برای این نقشها کوئری میزند؛ بدونش FeatureGate صفحه را میبندد.
|
||||
useAuthStore.setState({ primaryRole: 'doctor', context: null } as any);
|
||||
});
|
||||
|
||||
it('adds tax on top of the credit and shows the split', async () => {
|
||||
mockApi(10);
|
||||
await openChargeModalWith('100000');
|
||||
|
||||
const net = tomanToRial(100000);
|
||||
expect(await screen.findByText('اعتباری که به کیف پول اضافه میشود')).toBeInTheDocument();
|
||||
expect(screen.getByText('مالیات بر ارزش افزوده ۱۰٪')).toBeInTheDocument();
|
||||
expect(screen.getByText(formatRial(net * 0.1))).toBeInTheDocument();
|
||||
expect(screen.getAllByText(formatRial(net * 1.1)).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('shows no tax row and charges the plain amount when tax is off', async () => {
|
||||
mockApi(0);
|
||||
await openChargeModalWith('100000');
|
||||
|
||||
expect(await screen.findByText(/پرداخت .* از طریق بانک ملت/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('اعتباری که به کیف پول اضافه میشود')).not.toBeInTheDocument();
|
||||
expect(screen.getByText(new RegExp(formatRial(tomanToRial(100000))))).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -66,7 +66,7 @@ function SmsWalletPageInner() {
|
||||
queryFn: () => api.get('/api/v1/sms/settings'),
|
||||
});
|
||||
|
||||
const { isTestMode } = usePaymentConfig();
|
||||
const { isTestMode, taxPercent } = usePaymentConfig();
|
||||
|
||||
const balance = balanceData?.data;
|
||||
const logs = logsData?.data ?? EMPTY_LOGS;
|
||||
@@ -76,6 +76,12 @@ function SmsWalletPageInner() {
|
||||
const chargeForm = useForm<ChargeForm>({ resolver: zodResolver(chargeSchema) });
|
||||
const watchAmount = chargeForm.watch('amount_rials');
|
||||
|
||||
// مبلغِ واردشده خالص است — همان چیزی که به کیف پول مینشیند. مالیات رویش اضافه
|
||||
// میشود، دقیقاً با همان فرمولِ بکاند، تا عددِ مودال با صفحهٔ بانک یکی باشد.
|
||||
const chargeNet = tomanToRial(Number(watchAmount) || 0);
|
||||
const chargeTax = Math.round(chargeNet * taxPercent / 100);
|
||||
const chargePayable = chargeNet + chargeTax;
|
||||
|
||||
const chargeMutation = useMutation({
|
||||
mutationFn: ({ amount_rials }: ChargeForm) =>
|
||||
api.post<{ data: { payment_url: string } }>('/api/v1/sms/wallet/charge', {
|
||||
@@ -548,6 +554,31 @@ function SmsWalletPageInner() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{watchAmount && Number(watchAmount) >= 1000 && taxPercent > 0 && (
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', gap: 6,
|
||||
background: 'var(--surface-2)', borderRadius: 8,
|
||||
padding: '10px 14px', fontSize: 13, color: 'var(--text-2)',
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>اعتباری که به کیف پول اضافه میشود</span>
|
||||
<span style={{ direction: 'ltr' }}>{formatRial(chargeNet)}</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>مالیات بر ارزش افزوده {formatNumber(taxPercent)}٪</span>
|
||||
<span style={{ direction: 'ltr' }}>{formatRial(chargeTax)}</span>
|
||||
</div>
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between',
|
||||
borderTop: '1px solid var(--border)', paddingTop: 6,
|
||||
color: 'var(--text)', fontWeight: 700,
|
||||
}}>
|
||||
<span>مبلغ قابل پرداخت</span>
|
||||
<span style={{ direction: 'ltr' }}>{formatRial(chargePayable)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{watchAmount && Number(watchAmount) >= 1000 && (
|
||||
<div style={{
|
||||
background: isTestMode ? 'var(--warning-bg)' : 'var(--primary-soft)',
|
||||
@@ -556,8 +587,8 @@ function SmsWalletPageInner() {
|
||||
fontSize: 13, color: isTestMode ? 'var(--warning)' : 'var(--primary)', fontWeight: 500,
|
||||
}}>
|
||||
{isTestMode
|
||||
? `پرداخت آزمایشی ${formatRial(tomanToRial(Number(watchAmount)))}`
|
||||
: `پرداخت ${formatRial(tomanToRial(Number(watchAmount)))} از طریق ${gateway === 'mellat' ? 'بانک ملت' : 'سپ'}`
|
||||
? `پرداخت آزمایشی ${formatRial(chargePayable)}`
|
||||
: `پرداخت ${formatRial(chargePayable)} از طریق ${gateway === 'mellat' ? 'بانک ملت' : 'سپ'}`
|
||||
}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -136,3 +136,49 @@ describe('SubscriptionPage', () => {
|
||||
expect(await screen.findByText('در حال حاضر پلنی برای نمایش وجود ندارد.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Tax ────────────────────────────────────────────────────────────────────
|
||||
// قیمت دوره خالص است و مالیات رویش مینشیند؛ کارت و مودال باید جمع کل را نشان
|
||||
// دهند نه قیمت خالص را، وگرنه کاربر سرِ درگاه عدد دیگری میبیند.
|
||||
|
||||
const TAXED_PLANS = [
|
||||
{ uuid: 'p-basic', name: 'basic', level: 1, max_secretaries: 3, max_resources: 3,
|
||||
features: { patient_records: true, services: true, sms_panel: false }, active: true,
|
||||
periods: [
|
||||
{ uuid: 'per-1m', label: 'یک ماهه', duration_months: 1, price_rials: 1000000,
|
||||
tax_percent: 10, tax_rials: 100000, payable_rials: 1100000, is_trial: false },
|
||||
] },
|
||||
];
|
||||
|
||||
describe('SubscriptionPage — tax', () => {
|
||||
beforeEach(() => { get.mockReset(); mockApi({ plans: TAXED_PLANS }); });
|
||||
|
||||
it('shows the payable amount on the plan card, not the net price', async () => {
|
||||
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
|
||||
const card = within(await screen.findByTestId('plan-card-basic'));
|
||||
|
||||
expect(card.getByText(formatRial(1100000))).toBeInTheDocument();
|
||||
expect(card.queryByText(formatRial(1000000))).not.toBeInTheDocument();
|
||||
expect(card.getByText(/۱۰٪ مالیات بر ارزش افزوده/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('breaks the price down inside the payment modal', async () => {
|
||||
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
|
||||
const card = within(await screen.findByTestId('plan-card-basic'));
|
||||
fireEvent.click(card.getByText('تمدید اشتراک'));
|
||||
|
||||
await screen.findByText('پرداخت اشتراک');
|
||||
expect(screen.getByText('قیمت دوره')).toBeInTheDocument();
|
||||
expect(screen.getByText('مالیات بر ارزش افزوده ۱۰٪')).toBeInTheDocument();
|
||||
expect(screen.getByText('جمع کل')).toBeInTheDocument();
|
||||
expect(screen.getAllByText(formatRial(1100000)).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('falls back to the net price when the backend sends no tax fields', async () => {
|
||||
mockApi({ plans: PLANS });
|
||||
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
|
||||
const card = within(await screen.findByTestId('plan-card-basic'));
|
||||
|
||||
expect(card.getByText(formatRial(9000000))).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,15 @@ import {
|
||||
SparkleIcon, PlanCardPerson, CloseCircleFilled, GiftIcon, InfoCircleRedFilled,
|
||||
} from './subscriptionIcons';
|
||||
|
||||
// ── Tax helpers ───────────────────────────────────────────────────────────
|
||||
// `price_rials` خالص است و مالیات رویش مینشیند. فیلدهای مالیاتی را بکاند حساب
|
||||
// میکند؛ fallback فقط برای پاسخِ کششدهٔ نسخهٔ قبلی است.
|
||||
|
||||
export const taxOf = (p: Pick<SubscriptionPeriod, 'tax_rials'>): number => p.tax_rials ?? 0;
|
||||
|
||||
export const payableOf = (p: Pick<SubscriptionPeriod, 'price_rials' | 'payable_rials'>): number =>
|
||||
p.payable_rials ?? p.price_rials;
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** Shared feature labels (also consumed by PaymentSuccessPage). */
|
||||
@@ -92,9 +101,10 @@ export default function SubscriptionPage() {
|
||||
});
|
||||
|
||||
const purchaseMutation = useMutation({
|
||||
mutationFn: ({ period_uuid, gateway, amount_rials }: { period_uuid: string; gateway: string; amount_rials: number }) =>
|
||||
// مبلغ فرستاده نمیشود: بکاند خودش قیمت دوره + مالیات را حساب میکند.
|
||||
mutationFn: ({ period_uuid, gateway }: { period_uuid: string; gateway: string }) =>
|
||||
api.post<{ data: { pay_url?: string; redirect_url?: string; payment_url?: string } }>('/api/v1/subscription-payment', {
|
||||
period_uuid, gateway, amount_rials,
|
||||
period_uuid, gateway,
|
||||
// Gateway returns here (with ?payment_uuid&status); the success page reads them.
|
||||
frontend_address: `${window.location.origin}/admin/subscription/success`,
|
||||
}),
|
||||
@@ -191,11 +201,36 @@ export default function SubscriptionPage() {
|
||||
<div style={{ textAlign: 'left' }}>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 2 }}>مبلغ قابل پرداخت</div>
|
||||
<div style={{ fontWeight: 800, fontSize: 20, color: 'var(--primary)' }}>
|
||||
{formatRial(purchaseTarget.period.price_rials)}
|
||||
{formatRial(payableOf(purchaseTarget.period))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{taxOf(purchaseTarget.period) > 0 && (
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', gap: 6,
|
||||
background: 'var(--surface-2)', borderRadius: 'var(--r-sm)',
|
||||
padding: '10px 12px', fontSize: 13, color: 'var(--text-2)',
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>قیمت دوره</span>
|
||||
<span style={{ direction: 'ltr' }}>{formatRial(purchaseTarget.period.price_rials)}</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>مالیات بر ارزش افزوده {formatNumber(purchaseTarget.period.tax_percent)}٪</span>
|
||||
<span style={{ direction: 'ltr' }}>{formatRial(taxOf(purchaseTarget.period))}</span>
|
||||
</div>
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between',
|
||||
borderTop: '1px solid var(--border)', paddingTop: 6,
|
||||
color: 'var(--text)', fontWeight: 700,
|
||||
}}>
|
||||
<span>جمع کل</span>
|
||||
<span style={{ direction: 'ltr' }}>{formatRial(payableOf(purchaseTarget.period))}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isTestMode ? (
|
||||
<div style={{
|
||||
background: 'var(--warning-bg)', border: '1px solid var(--warning)',
|
||||
@@ -248,12 +283,12 @@ export default function SubscriptionPage() {
|
||||
style={{ flex: 1, height: 44 }}
|
||||
disabled={purchaseMutation.isPending || (!isTestMode && (gateways.length === 0 || selectedGateway === ''))}
|
||||
onClick={() =>
|
||||
purchaseMutation.mutate({ period_uuid: purchaseTarget.period.uuid, gateway: selectedGateway, amount_rials: purchaseTarget.period.price_rials })
|
||||
purchaseMutation.mutate({ period_uuid: purchaseTarget.period.uuid, gateway: selectedGateway })
|
||||
}
|
||||
>
|
||||
{purchaseMutation.isPending
|
||||
? 'در حال انتقال...'
|
||||
: `پرداخت ${formatRial(purchaseTarget.period.price_rials)}`}
|
||||
: `پرداخت ${formatRial(payableOf(purchaseTarget.period))}`}
|
||||
</button>
|
||||
<button className="btn ghost" style={{ height: 44 }} onClick={() => setPurchaseTarget(null)}>
|
||||
انصراف
|
||||
@@ -478,11 +513,18 @@ function PlanCard({
|
||||
justifyContent: 'flex-end', width: '100%',
|
||||
}}>
|
||||
<span style={{ fontSize: 14, color: 'var(--text)', fontWeight: 600, direction: 'ltr' }}>
|
||||
{formatRial(selectedPeriod.price_rials)}
|
||||
{formatRial(payableOf(selectedPeriod))}
|
||||
</span>
|
||||
<span style={{ fontSize: 14, color: 'var(--text)', fontWeight: 500 }}>: قیمت</span>
|
||||
</div>
|
||||
)}
|
||||
{!isFree && selectedPeriod && taxOf(selectedPeriod) > 0 && (
|
||||
<div style={{
|
||||
fontSize: 11, color: 'var(--text-3)', textAlign: 'left', marginTop: -4,
|
||||
}}>
|
||||
شامل {formatNumber(selectedPeriod.tax_percent)}٪ مالیات بر ارزش افزوده
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -574,7 +574,13 @@ export interface SubscriptionPeriod {
|
||||
uuid: string;
|
||||
label: string;
|
||||
duration_months: number;
|
||||
/** قیمت خالص، بدون مالیات. */
|
||||
price_rials: number;
|
||||
/** درصد مالیات؛ با مالیاتِ خاموش برابر صفر. */
|
||||
tax_percent: number;
|
||||
tax_rials: number;
|
||||
/** قیمت خالص + مالیات — مبلغی که واقعاً پرداخت میشود. */
|
||||
payable_rials: number;
|
||||
is_trial: boolean;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user