Compare commits

2 Commits
Author SHA1 Message Date
hamed 7716b40f6a 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.
2026-08-09 16:51:22 +03:30
hamed 2471c90cbb feat(payment): unify payment callback endpoint for all gateways and types 2026-08-09 16:02:48 +03:30
24 changed files with 967 additions and 116 deletions
+3
View File
@@ -11,6 +11,8 @@ interface PaymentConfig {
test_mode: boolean; test_mode: boolean;
appointment_fee_rials: number; appointment_fee_rials: number;
gateways: PaymentGatewayInfo[]; gateways: PaymentGatewayInfo[];
/** نرخ مالیات اشتراک و شارژ کیف پول؛ صفر یعنی خاموش. */
tax_percent: number;
} }
export function usePaymentConfig() { export function usePaymentConfig() {
@@ -22,5 +24,6 @@ export function usePaymentConfig() {
return { return {
isTestMode: data?.data?.test_mode ?? false, isTestMode: data?.data?.test_mode ?? false,
gateways: data?.data?.gateways ?? [], 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();
});
});
+34 -3
View File
@@ -66,7 +66,7 @@ function SmsWalletPageInner() {
queryFn: () => api.get('/api/v1/sms/settings'), queryFn: () => api.get('/api/v1/sms/settings'),
}); });
const { isTestMode } = usePaymentConfig(); const { isTestMode, taxPercent } = usePaymentConfig();
const balance = balanceData?.data; const balance = balanceData?.data;
const logs = logsData?.data ?? EMPTY_LOGS; const logs = logsData?.data ?? EMPTY_LOGS;
@@ -76,6 +76,12 @@ function SmsWalletPageInner() {
const chargeForm = useForm<ChargeForm>({ resolver: zodResolver(chargeSchema) }); const chargeForm = useForm<ChargeForm>({ resolver: zodResolver(chargeSchema) });
const watchAmount = chargeForm.watch('amount_rials'); 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({ const chargeMutation = useMutation({
mutationFn: ({ amount_rials }: ChargeForm) => mutationFn: ({ amount_rials }: ChargeForm) =>
api.post<{ data: { payment_url: string } }>('/api/v1/sms/wallet/charge', { api.post<{ data: { payment_url: string } }>('/api/v1/sms/wallet/charge', {
@@ -548,6 +554,31 @@ function SmsWalletPageInner() {
)} )}
</div> </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 && ( {watchAmount && Number(watchAmount) >= 1000 && (
<div style={{ <div style={{
background: isTestMode ? 'var(--warning-bg)' : 'var(--primary-soft)', background: isTestMode ? 'var(--warning-bg)' : 'var(--primary-soft)',
@@ -556,8 +587,8 @@ function SmsWalletPageInner() {
fontSize: 13, color: isTestMode ? 'var(--warning)' : 'var(--primary)', fontWeight: 500, fontSize: 13, color: isTestMode ? 'var(--warning)' : 'var(--primary)', fontWeight: 500,
}}> }}>
{isTestMode {isTestMode
? `پرداخت آزمایشی ${formatRial(tomanToRial(Number(watchAmount)))}` ? `پرداخت آزمایشی ${formatRial(chargePayable)}`
: `پرداخت ${formatRial(tomanToRial(Number(watchAmount)))} از طریق ${gateway === 'mellat' ? 'بانک ملت' : 'سپ'}` : `پرداخت ${formatRial(chargePayable)} از طریق ${gateway === 'mellat' ? 'بانک ملت' : 'سپ'}`
} }
</div> </div>
)} )}
@@ -136,3 +136,49 @@ describe('SubscriptionPage', () => {
expect(await screen.findByText('در حال حاضر پلنی برای نمایش وجود ندارد.')).toBeInTheDocument(); 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();
});
});
+48 -6
View File
@@ -14,6 +14,15 @@ import {
SparkleIcon, PlanCardPerson, CloseCircleFilled, GiftIcon, InfoCircleRedFilled, SparkleIcon, PlanCardPerson, CloseCircleFilled, GiftIcon, InfoCircleRedFilled,
} from './subscriptionIcons'; } 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 ───────────────────────────────────────────────────────────── // ── Constants ─────────────────────────────────────────────────────────────
/** Shared feature labels (also consumed by PaymentSuccessPage). */ /** Shared feature labels (also consumed by PaymentSuccessPage). */
@@ -92,9 +101,10 @@ export default function SubscriptionPage() {
}); });
const purchaseMutation = useMutation({ 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', { 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. // Gateway returns here (with ?payment_uuid&status); the success page reads them.
frontend_address: `${window.location.origin}/admin/subscription/success`, frontend_address: `${window.location.origin}/admin/subscription/success`,
}), }),
@@ -191,11 +201,36 @@ export default function SubscriptionPage() {
<div style={{ textAlign: 'left' }}> <div style={{ textAlign: 'left' }}>
<div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 2 }}>مبلغ قابل پرداخت</div> <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 2 }}>مبلغ قابل پرداخت</div>
<div style={{ fontWeight: 800, fontSize: 20, color: 'var(--primary)' }}> <div style={{ fontWeight: 800, fontSize: 20, color: 'var(--primary)' }}>
{formatRial(purchaseTarget.period.price_rials)} {formatRial(payableOf(purchaseTarget.period))}
</div> </div>
</div> </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 ? ( {isTestMode ? (
<div style={{ <div style={{
background: 'var(--warning-bg)', border: '1px solid var(--warning)', background: 'var(--warning-bg)', border: '1px solid var(--warning)',
@@ -248,12 +283,12 @@ export default function SubscriptionPage() {
style={{ flex: 1, height: 44 }} style={{ flex: 1, height: 44 }}
disabled={purchaseMutation.isPending || (!isTestMode && (gateways.length === 0 || selectedGateway === ''))} disabled={purchaseMutation.isPending || (!isTestMode && (gateways.length === 0 || selectedGateway === ''))}
onClick={() => 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 {purchaseMutation.isPending
? 'در حال انتقال...' ? 'در حال انتقال...'
: `پرداخت ${formatRial(purchaseTarget.period.price_rials)}`} : `پرداخت ${formatRial(payableOf(purchaseTarget.period))}`}
</button> </button>
<button className="btn ghost" style={{ height: 44 }} onClick={() => setPurchaseTarget(null)}> <button className="btn ghost" style={{ height: 44 }} onClick={() => setPurchaseTarget(null)}>
انصراف انصراف
@@ -478,11 +513,18 @@ function PlanCard({
justifyContent: 'flex-end', width: '100%', justifyContent: 'flex-end', width: '100%',
}}> }}>
<span style={{ fontSize: 14, color: 'var(--text)', fontWeight: 600, direction: 'ltr' }}> <span style={{ fontSize: 14, color: 'var(--text)', fontWeight: 600, direction: 'ltr' }}>
{formatRial(selectedPeriod.price_rials)} {formatRial(payableOf(selectedPeriod))}
</span> </span>
<span style={{ fontSize: 14, color: 'var(--text)', fontWeight: 500 }}>: قیمت</span> <span style={{ fontSize: 14, color: 'var(--text)', fontWeight: 500 }}>: قیمت</span>
</div> </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> </div>
</div> </div>
+6
View File
@@ -574,7 +574,13 @@ export interface SubscriptionPeriod {
uuid: string; uuid: string;
label: string; label: string;
duration_months: number; duration_months: number;
/** قیمت خالص، بدون مالیات. */
price_rials: number; price_rials: number;
/** درصد مالیات؛ با مالیاتِ خاموش برابر صفر. */
tax_percent: number;
tax_rials: number;
/** قیمت خالص + مالیات — مبلغی که واقعاً پرداخت می‌شود. */
payable_rials: number;
is_trial: boolean; is_trial: boolean;
} }
+2 -3
View File
@@ -42,7 +42,7 @@ security:
security: false security: false
payment_callback: payment_callback:
pattern: ^/api/v1/(payment/(callback|pay|order)/|subscription-payment/callback/) pattern: ^/api/v1/payment/(callback|pay/|order/)
stateless: true stateless: true
security: false security: false
@@ -85,10 +85,9 @@ security:
- { path: ^/oauth/token$, roles: PUBLIC_ACCESS } - { path: ^/oauth/token$, roles: PUBLIC_ACCESS }
- { path: ^/oauth/token/refresh$, roles: PUBLIC_ACCESS } - { path: ^/oauth/token/refresh$, roles: PUBLIC_ACCESS }
- { path: ^/session/token, roles: PUBLIC_ACCESS } - { path: ^/session/token, roles: PUBLIC_ACCESS }
- { path: ^/api/v1/payment/callback/, roles: PUBLIC_ACCESS } - { path: ^/api/v1/payment/callback, roles: PUBLIC_ACCESS }
- { path: ^/api/v1/payment/pay/, roles: PUBLIC_ACCESS } - { path: ^/api/v1/payment/pay/, roles: PUBLIC_ACCESS }
- { path: ^/api/v1/payment/order/, roles: PUBLIC_ACCESS } - { path: ^/api/v1/payment/order/, roles: PUBLIC_ACCESS }
- { path: ^/api/v1/subscription-payment/callback/, roles: PUBLIC_ACCESS }
- { path: ^/api/v1/categorys/, roles: PUBLIC_ACCESS } - { path: ^/api/v1/categorys/, roles: PUBLIC_ACCESS }
- { path: ^/api/v1/doctors$, roles: PUBLIC_ACCESS } - { path: ^/api/v1/doctors$, roles: PUBLIC_ACCESS }
- path: '^/api/v1/doctor/[^/]+$' - path: '^/api/v1/doctor/[^/]+$'
+37 -17
View File
@@ -58,7 +58,7 @@
**کمیسیون دامنه‌محور (post-action):** نماینده‌ی مبدأ از `payment.frontend_address` با `DomainContextResolver` تعیین می‌شود؛ کمیسیون (نوبت و اشتراک) فقط وقتی ثبت می‌شود که این نماینده فعال باشد **و** پزشک/کلینیک موضوع خرید `representation_id` همان نماینده را داشته باشد — جزئیات در `docs/api/representation.md` §قانون کمیسیون دامنه‌محور. **کمیسیون دامنه‌محور (post-action):** نماینده‌ی مبدأ از `payment.frontend_address` با `DomainContextResolver` تعیین می‌شود؛ کمیسیون (نوبت و اشتراک) فقط وقتی ثبت می‌شود که این نماینده فعال باشد **و** پزشک/کلینیک موضوع خرید `representation_id` همان نماینده را داشته باشد — جزئیات در `docs/api/representation.md` §قانون کمیسیون دامنه‌محور.
**یکدستیِ typeها:** هر سه نوع (`appointment`/`subscription`/`sms_wallet`) از همان `GET /payment/pay/{orderId}` عبور می‌کنند؛ `PaymentManager::callbackUrl()` پیشوند callback را بر اساس `type` انتخاب می‌کند. POST این endpointها فقط `Payment` pending می‌سازد و `pay_url` برمی‌گرداند (نه `redirect_url`). **یکدستیِ typeها:** هر سه نوع (`appointment`/`subscription`/`sms_wallet`) از همان `GET /payment/pay/{orderId}` عبور می‌کنند و روی همان یک `POST|GET /api/v1/payment/callback` برمی‌گردند؛ `PaymentManager::callbackUrl()` دیگر بر اساس `type` شاخه نمی‌زند. POST این endpointها فقط `Payment` pending می‌سازد و `pay_url` برمی‌گرداند (نه `redirect_url`).
**افزودن درگاه جدید (Open/Closed):** یک کلاس جدید implements `PaymentGatewayInterface` بساز، در `GatewayFactory::$gateways` + `LABELS` ثبت کن. `PaymentController`/`PaymentManager` تغییر نمی‌کنند. **افزودن درگاه جدید (Open/Closed):** یک کلاس جدید implements `PaymentGatewayInterface` بساز، در `GatewayFactory::$gateways` + `LABELS` ثبت کن. `PaymentController`/`PaymentManager` تغییر نمی‌کنند.
@@ -106,7 +106,8 @@
"appointment_fee_rials": 150000, "appointment_fee_rials": 150000,
"gateways": [ "gateways": [
{ "name": "mellat", "label": "بانک ملت" } { "name": "mellat", "label": "بانک ملت" }
] ],
"tax_percent": 10
} }
} }
``` ```
@@ -116,6 +117,7 @@
| `test_mode` | boolean | `true` = درگاه آزمایشی فعال است — backend از MockGateway استفاده می‌کند و پول واقعی کسر نمی‌شود | | `test_mode` | boolean | `true` = درگاه آزمایشی فعال است — backend از MockGateway استفاده می‌کند و پول واقعی کسر نمی‌شود |
| `appointment_fee_rials` | integer | مبلغ هر نوبت به ریال (از تنظیمات سایت، کلید `appointment_fee_rials`). frontend برای نمایش «مبلغ قابل پرداخت» از این می‌خواند؛ مبلغِ واقعیِ تراکنش هم در backend از همین کلید خوانده می‌شود (نه از client) | | `appointment_fee_rials` | integer | مبلغ هر نوبت به ریال (از تنظیمات سایت، کلید `appointment_fee_rials`). frontend برای نمایش «مبلغ قابل پرداخت» از این می‌خواند؛ مبلغِ واقعیِ تراکنش هم در backend از همین کلید خوانده می‌شود (نه از client) |
| `gateways` | array | فقط درگاه‌های **فعال** (اعتبارنامه‌شان در تنظیمات سایت یا env ست شده). هر عضو: `{ name, label }`. frontend فقط همین‌ها را برای انتخاب نمایش می‌دهد. در `test_mode` تنها `[{ "name": "mellat", "label": "بانک ملت (آزمایشی)" }]` برمی‌گردد. اگر هیچ درگاهی فعال نباشد آرایه خالی است و frontend باید پرداخت را غیرفعال کند. | | `gateways` | array | فقط درگاه‌های **فعال** (اعتبارنامه‌شان در تنظیمات سایت یا env ست شده). هر عضو: `{ name, label }`. frontend فقط همین‌ها را برای انتخاب نمایش می‌دهد. در `test_mode` تنها `[{ "name": "mellat", "label": "بانک ملت (آزمایشی)" }]` برمی‌گردد. اگر هیچ درگاهی فعال نباشد آرایه خالی است و frontend باید پرداخت را غیرفعال کند. |
| `tax_percent` | number | نرخ مالیات بر ارزش افزوده برای **اشتراک** و **شارژ کیف پول پیامک**. صفر یعنی مالیات خاموش است (`tax_enabled=0`). frontend با این عدد جمع کل را پیش از ارسال درخواست نشان می‌دهد؛ مبلغ نهایی همیشه در backend دوباره حساب می‌شود. نوبت این نرخ را به این شکل به‌کار نمی‌برد — آنجا مبلغ شامل مالیات است. |
فعال‌بودن هر درگاه با `PaymentGatewayInterface::isConfigured()` **و** کلید فعال‌سازی در تنظیمات سایت تعیین می‌شود: `mellat` نیازمند `mellat_terminal_id` + `mellat_username` + `mellat_password`؛ `sep` نیازمند `sep_terminal_id`. علاوه بر این، اگر ادمین درگاه را در تنظیمات غیرفعال کند (`mellat_enabled` / `sep_enabled` = `"0"`)، آن درگاه از این لیست حذف می‌شود و در `initiate` نیز رد می‌شود (خطای ۴۲۲: «درگاه پرداخت نامعتبر یا غیرفعال است»). کلید تنظیم‌نشده = فعال (پیش‌فرض). فعال‌بودن هر درگاه با `PaymentGatewayInterface::isConfigured()` **و** کلید فعال‌سازی در تنظیمات سایت تعیین می‌شود: `mellat` نیازمند `mellat_terminal_id` + `mellat_username` + `mellat_password`؛ `sep` نیازمند `sep_terminal_id`. علاوه بر این، اگر ادمین درگاه را در تنظیمات غیرفعال کند (`mellat_enabled` / `sep_enabled` = `"0"`)، آن درگاه از این لیست حذف می‌شود و در `initiate` نیز رد می‌شود (خطای ۴۲۲: «درگاه پرداخت نامعتبر یا غیرفعال است»). کلید تنظیم‌نشده = فعال (پیش‌فرض).
@@ -268,23 +270,37 @@ Initiate payment for an appointment. Returns a redirect URL to the payment gatew
--- ---
## POST `/api/v1/payment/callback/{gateway}` ## POST `/api/v1/payment/callback`
## GET `/api/v1/payment/callback/{gateway}` ## GET `/api/v1/payment/callback`
Payment gateway callback. Called by the bank after user completes (or cancels) payment. هر درگاه callback مخصوص خودش را دارد؛ URL آن هنگام `initiate` از `APP_BASE_URL` ساخته می‌شود: Payment gateway callback. Called by the bank after user completes (or cancels) payment.
**یک آدرس برای همه.** همهٔ درگاه‌ها (`mellat`، `sep`، `mock`) و همهٔ نوع‌های پرداخت
(`appointment`، `subscription`، `sms_wallet`) روی همین یک مسیر برمی‌گردند؛ درگاه و سفارش
به‌صورت query param می‌روند. URL هنگام `initiate` در `PaymentManager::callbackUrl()` از
`APP_BASE_URL` و ثابت `PaymentManager::CALLBACK_PATH` ساخته می‌شود:
``` ```
{APP_BASE_URL}/api/v1/payment/callback/{gateway}?order_id={orderId} {APP_BASE_URL}/api/v1/payment/callback?gateway={gateway}&order_id={orderId}
``` ```
دلیل: مسیر ثابت می‌ماند، پس آدرسِ ثبت‌شده در پنل پذیرندگی بانک با اضافه‌شدن درگاه یا نوع
پرداخت جدید عوض نمی‌شود.
> **Breaking change.** دو مسیر قدیمی حذف شده‌اند و `404` می‌دهند:
> `POST|GET /api/v1/payment/callback/{gateway}` و
> `POST|GET /api/v1/subscription-payment/callback/{gateway}`.
> آدرس ثبت‌شده در پنل ملت و سپ باید به مسیر جدید به‌روز شود.
**نکته IPG ملت:** طبق راهنمای درگاه ملت، `callBackUrl` باید روی **دامنهٔ ثبت‌شدهٔ پذیرنده** باشد و **IP مجاز نیست** (در غیر این صورت کد پاسخ `62` — «مسیر back call در دامنهٔ ثبت‌شده نیست»). بنابراین `APP_BASE_URL` در پروداکشن باید دقیقاً `https://clinic-pro.ir` (دامنهٔ ثبت‌شده نزد ملت/شاپرک) باشد. **نکته IPG ملت:** طبق راهنمای درگاه ملت، `callBackUrl` باید روی **دامنهٔ ثبت‌شدهٔ پذیرنده** باشد و **IP مجاز نیست** (در غیر این صورت کد پاسخ `62` — «مسیر back call در دامنهٔ ثبت‌شده نیست»). بنابراین `APP_BASE_URL` در پروداکشن باید دقیقاً `https://clinic-pro.ir` (دامنهٔ ثبت‌شده نزد ملت/شاپرک) باشد.
**Permission:** `PUBLIC`. **نکتهٔ مهم:** درگاه‌های **ملت و سپ** نتیجه را با **ریدایرکتِ مرورگرِ کاربر** (POST/GET) برمی‌گردانند، نه server-to-server؛ پس IP دریافتی، IPِ کاربر است و **allowlist شاپرک اعمال نمی‌شود** (برای `gateway ∈ {mellat, sep}` و نیز `test_mode`). در غیر این صورت هر callback واقعی — از جمله «لغو» توسط کاربر — با «دسترسی غیرمجاز» رد می‌شد. امنیت از طریق **چک ضد-دستکاری** (`RefId==gateway_token`، `SaleOrderId==payment.id`) و **verify سمت بانک** در `PaymentManager` تأمین می‌شود. `isAllowedCallbackIp` فقط برای درگاه‌های آیندهٔ server-to-server معنی دارد. **Permission:** `PUBLIC`. **نکتهٔ مهم:** درگاه‌های **ملت و سپ** نتیجه را با **ریدایرکتِ مرورگرِ کاربر** (POST/GET) برمی‌گردانند، نه server-to-server؛ پس IP دریافتی، IPِ کاربر است و **allowlist شاپرک اعمال نمی‌شود** (برای `gateway ∈ {mellat, sep}` و نیز `test_mode`). در غیر این صورت هر callback واقعی — از جمله «لغو» توسط کاربر — با «دسترسی غیرمجاز» رد می‌شد. امنیت از طریق **چک ضد-دستکاری** (`RefId==gateway_token`، `SaleOrderId==payment.id`) و **verify سمت بانک** در `PaymentManager` تأمین می‌شود. `isAllowedCallbackIp` فقط برای درگاه‌های آیندهٔ server-to-server معنی دارد.
### Path Parameters ### Query Parameters
| Param | Type | Description | | Param | Type | Required | Description |
|-------|------|-------------| |-------|------|----------|-------------|
| `gateway` | string | `mellat` or `sep` | | `order_id` | string | yes | شناسهٔ سفارش (`ORD-…`)؛ در نبودش `ResNum` خوانده می‌شود |
| `gateway` | string | no | `mellat` \| `sep` \| `mock`. در نبودش از فیلد `gateway` همان رکورد پرداخت خوانده می‌شود |
### Request (varies by gateway) ### Request (varies by gateway)
**Mellat POST fields:** **Mellat POST fields:**
@@ -327,7 +343,7 @@ Initiate a subscription / wallet top-up payment (not tied to a specific appointm
```json ```json
{ {
"gateway": "mellat", "gateway": "mellat",
"amount_rials": 1000000, "period_uuid": "uuid-of-subscription-period",
"frontend_address": "https://myapp.com/wallet/result" "frontend_address": "https://myapp.com/wallet/result"
} }
``` ```
@@ -335,9 +351,14 @@ Initiate a subscription / wallet top-up payment (not tied to a specific appointm
| Field | Type | Required | Description | | Field | Type | Required | Description |
|-------|------|----------|-------------| |-------|------|----------|-------------|
| `gateway` | string | ✅ | `"mellat"` or `"sep"` | | `gateway` | string | ✅ | `"mellat"` or `"sep"` |
| `amount_rials` | integer | ✅ | Amount in Rials (min: 10,000) | | `period_uuid` | string | ✅ | دورهٔ اشتراک؛ مبلغ از آن محاسبه می‌شود |
| `frontend_address` | string | ❌ | Redirect URL after payment | | `frontend_address` | string | ❌ | Redirect URL after payment |
> `amount_rials` دیگر خوانده نمی‌شود. مبلغ = `price_rials + tax_rials` همان دوره، محاسبه‌شده در
> `SubscriptionTaxCalculator`. قیمت دوره خالص است و مالیات رویش اضافه می‌شود — جزئیات در
> [subscription.md](subscription.md#مالیات-دورهها). پاسخ هم هر چهار عدد را برمی‌گرداند:
> `price_rials`، `tax_percent`، `tax_rials`، `payable_rials`.
### Response `200` ### Response `200`
```json ```json
{ {
@@ -350,7 +371,7 @@ Initiate a subscription / wallet top-up payment (not tied to a specific appointm
} }
``` ```
> مثل appointment: کلاینت مرورگر را به `pay_url` هدایت می‌کند؛ init درگاه در `GET /api/v1/payment/pay/{orderId}` انجام می‌شود (نه در این POST). Callback این نوع به `/api/v1/subscription-payment/callback/` می‌رود. > مثل appointment: کلاینت مرورگر را به `pay_url` هدایت می‌کند؛ init درگاه در `GET /api/v1/payment/pay/{orderId}` انجام می‌شود (نه در این POST). Callback این نوع هم به همان `/api/v1/payment/callback` می‌رود.
### Errors ### Errors
| Code | HTTP | Description | | Code | HTTP | Description |
@@ -371,11 +392,10 @@ Initiate a subscription / wallet top-up payment (not tied to a specific appointm
--- ---
## POST/GET `/api/v1/subscription-payment/callback/{gateway}` ## ~~POST/GET `/api/v1/subscription-payment/callback/{gateway}`~~ — حذف شد
Callback for subscription payments. Same behavior as appointment callback but credits wallet instead. پرداخت اشتراک callback اختصاصی ندارد. از [`/api/v1/payment/callback`](#post-apiv1paymentcallback)
استفاده کنید؛ نوع پرداخت از خودِ رکورد `Payment` خوانده می‌شود.
**Permission:** `PUBLIC`
--- ---
+25 -1
View File
@@ -349,13 +349,37 @@ Updated template with `status: "rejected"`.
"data": { "data": {
"payment_uuid": "...", "payment_uuid": "...",
"pay_url": "{APP_BASE_URL}/api/v1/payment/pay/ORD-...", "pay_url": "{APP_BASE_URL}/api/v1/payment/pay/ORD-...",
"order_id": "ORD-..." "order_id": "ORD-...",
"net_rials": 50000,
"tax_percent": 10,
"tax_rials": 5000,
"payable_rials": 55000
} }
} }
``` ```
> این endpoint فقط `Payment` (type=`sms_wallet`) می‌سازد و `pay_url` می‌دهد؛ **ارتباط با بانک اینجا انجام نمی‌شود** و از flow واحد پرداخت (`GET /payment/pay/{orderId}` → callback → `PaymentManager`) عبور می‌کند. کلاینت باید مرورگر را به `pay_url` هدایت کند. پس از پرداخت موفق، `PaymentManager` موجودی کیف را خودکار شارژ می‌کند. > این endpoint فقط `Payment` (type=`sms_wallet`) می‌سازد و `pay_url` می‌دهد؛ **ارتباط با بانک اینجا انجام نمی‌شود** و از flow واحد پرداخت (`GET /payment/pay/{orderId}` → callback → `PaymentManager`) عبور می‌کند. کلاینت باید مرورگر را به `pay_url` هدایت کند. پس از پرداخت موفق، `PaymentManager` موجودی کیف را خودکار شارژ می‌کند.
#### مالیات
`amount_rials` ورودی **خالص** است — همان اعتباری که به کیف پول می‌نشیند. مالیات رویش
**اضافه** می‌شود و مبلغی که به بانک می‌رود `payable_rials` است.
| فیلد | معنی |
|------|------|
| `net_rials` | اعتباری که بعد از پرداخت موفق به کیف پول اضافه می‌شود |
| `tax_percent` | درصد مؤثر؛ با `tax_enabled=0` برابر `0` |
| `tax_rials` | `round(net_rials × tax_percent / 100)` |
| `payable_rials` | `net_rials + tax_rials` — مبلغ رکورد `Payment` و مبلغ درگاه |
نرخ از همان کلیدهای سراسری `tax_enabled` / `tax_percent` می‌آید؛ محاسبه در
`App\Payment\Service\PaymentTaxCalculator`.
**اعتبار کیف پول هرگز شامل مالیات نیست.** مقدار خالص در `metadata.net_rials` رکورد پرداخت
ذخیره می‌شود و `PaymentManager::handleSmsWalletCharge` همان را شارژ می‌کند — نه
`amount_rials` را. استرداد هم قرینهٔ همین است. پرداخت‌های قدیمی که `net_rials` ندارند به
مبلغ کلشان fallback می‌کنند.
### GET /api/v1/sms/wallet/logs ### GET /api/v1/sms/wallet/logs
تراکنش‌های کیف پیامک (paginated). تراکنش‌های کیف پیامک (paginated).
+36 -6
View File
@@ -12,6 +12,25 @@
> `max_resources` سقف منابع محیط است. مقدار `-1` یعنی نامحدود. مقادیر شیپ‌شده: `free` = ۱، `basic` = ۳، `professional` = `-1`. اجرای این سقف در `POST /api/v1/resource` است — [resource.md](resource.md). > `max_resources` سقف منابع محیط است. مقدار `-1` یعنی نامحدود. مقادیر شیپ‌شده: `free` = ۱، `basic` = ۳، `professional` = `-1`. اجرای این سقف در `POST /api/v1/resource` است — [resource.md](resource.md).
### مالیات دوره‌ها
`price_rials` هر دوره **خالص** است و مالیات رویش **اضافه** می‌شود. این برعکسِ نوبت است؛ آنجا
مبلغ شامل مالیات است و `CommissionService` مالیات را از دلش استخراج می‌کند.
نرخ از همان کلیدهای سراسری `tax_enabled` و `tax_percent` در SiteConfig می‌آید — کلید جداگانه‌ای
برای اشتراک وجود ندارد. محاسبه در `App\Subscription\Service\SubscriptionTaxCalculator`.
هر دوره سه فیلد محاسبه‌شدهٔ اضافه دارد. `price_rials` دست‌نخورده می‌ماند تا کلاینت قدیمی نشکند:
| فیلد | معنی |
|------|------|
| `price_rials` | قیمت خالص، بدون مالیات — همان چیزی که ادمین وارد می‌کند |
| `tax_percent` | درصد مؤثر؛ با `tax_enabled=0` برابر `0` |
| `tax_rials` | `round(price_rials × tax_percent / 100)` |
| `payable_rials` | `price_rials + tax_rials` — مبلغی که واقعاً پرداخت می‌شود |
دورهٔ رایگان یا تریال (`price_rials = 0`) مالیات نمی‌گیرد.
**Response 200:** **Response 200:**
```json ```json
{ {
@@ -42,6 +61,9 @@
"label": "یک ماهه", "label": "یک ماهه",
"duration_months": 1, "duration_months": 1,
"price_rials": 290000, "price_rials": 290000,
"tax_percent": 10,
"tax_rials": 29000,
"payable_rials": 319000,
"is_trial": false, "is_trial": false,
"active": true, "active": true,
"sort_order": 1 "sort_order": 1
@@ -141,7 +163,6 @@
```json ```json
{ {
"gateway": "mellat", "gateway": "mellat",
"amount_rials": 290000,
"period_uuid": "uuid-of-subscription-period", "period_uuid": "uuid-of-subscription-period",
"frontend_address": "https://example.com/payment-result" "frontend_address": "https://example.com/payment-result"
} }
@@ -150,27 +171,36 @@
| فیلد | نوع | الزامی | | فیلد | نوع | الزامی |
|------|-----|--------| |------|-----|--------|
| gateway | string (mellat\|sep) | ✅ | | gateway | string (mellat\|sep) | ✅ |
| amount_rials | integer | ✅ |
| period_uuid | string (UUID) | ✅ | | period_uuid | string (UUID) | ✅ |
| frontend_address | string (URL) | ❌ | | frontend_address | string (URL) | ❌ |
> **`amount_rials` دیگر پذیرفته نمی‌شود.** مبلغ سمت سرور از دورهٔ اشتراک محاسبه می‌شود:
> `price_rials + tax_rials`. اگر کلاینت آن را بفرستد نادیده گرفته می‌شود. دلیلش بستنِ راهِ
> دستکاری قیمت است. دورهٔ ناموجود یا غیرفعال → `422 ERR_VALIDATION_001` روی فیلد `period_uuid`.
**Response 200:** **Response 200:**
```json ```json
{ {
"success": true, "success": true,
"data": { "data": {
"payment_uuid": "...", "payment_uuid": "...",
"redirect_url": "https://gateway.shaparak.ir/...", "pay_url": "https://clinic-pro.ir/api/v1/payment/pay/ORD-XXXXXXXXXXXXXXXX",
"order_id": "ORD-XXXXXXXXXXXXXXXX" "order_id": "ORD-XXXXXXXXXXXXXXXX",
"price_rials": 290000,
"tax_percent": 10,
"tax_rials": 29000,
"payable_rials": 319000
} }
} }
``` ```
--- ---
## GET /api/v1/subscription-payment/callback/{gateway} ## POST|GET /api/v1/payment/callback
callback درگاه پرداخت — پس از پرداخت موفق، `ClinicSubscription` به صورت خودکار ایجاد می‌شود (بر اساس `period_uuid` ذخیره‌شده در metadata پرداخت). callback مشترک همهٔ درگاه‌ها و همهٔ نوع‌های پرداخت — پس از پرداخت موفق، `ClinicSubscription` به صورت خودکار ایجاد می‌شود (بر اساس `period_uuid` ذخیره‌شده در metadata پرداخت).
مسیر اختصاصی قبلی `/api/v1/subscription-payment/callback/{gateway}` حذف شده و `404` می‌دهد. قرارداد کامل: [payment.md](payment.md#post-apiv1paymentcallback).
--- ---
+57 -55
View File
@@ -41,6 +41,9 @@ class PaymentController extends BaseController
private readonly SecretaryAccessChecker $secretaryAccess, private readonly SecretaryAccessChecker $secretaryAccess,
private readonly \App\Clinic\Security\ClinicDoctorAccessChecker $clinicDoctorAccess, private readonly \App\Clinic\Security\ClinicDoctorAccessChecker $clinicDoctorAccess,
private readonly EntityContextResolver $contextResolver, private readonly EntityContextResolver $contextResolver,
private readonly \App\Subscription\Repository\SubscriptionPeriodRepository $subscriptionPeriodRepo,
private readonly \App\Subscription\Service\SubscriptionTaxCalculator $subscriptionTax,
private readonly \App\Payment\Service\PaymentTaxCalculator $paymentTax,
private readonly string $appBaseUrl, private readonly string $appBaseUrl,
private readonly string $allowedFrontendHosts = '', private readonly string $allowedFrontendHosts = '',
) {} ) {}
@@ -296,13 +299,20 @@ class PaymentController extends BaseController
// ── Payment Callback (public — no JWT) ─────────────────────────────────── // ── Payment Callback (public — no JWT) ───────────────────────────────────
#[OA\Post( #[OA\Post(
path: '/api/v1/payment/callback/{gateway}', path: '/api/v1/payment/callback',
summary: 'Payment gateway callback (public, IP-restricted)', summary: 'Payment gateway callback — single endpoint for every gateway and payment type (public)',
parameters: [ parameters: [
new OA\Parameter( new OA\Parameter(
name: 'gateway', name: 'order_id',
in: 'path', in: 'query',
required: true, required: true,
schema: new OA\Schema(type: 'string', example: 'ORD-1712345678-ab12')
),
new OA\Parameter(
name: 'gateway',
in: 'query',
required: false,
description: 'Falls back to the gateway stored on the payment when omitted',
schema: new OA\Schema(type: 'string', enum: ['mellat', 'sep']) schema: new OA\Schema(type: 'string', enum: ['mellat', 'sep'])
), ),
], ],
@@ -322,10 +332,23 @@ class PaymentController extends BaseController
new OA\Response(response: 404, description: 'Payment not found'), new OA\Response(response: 404, description: 'Payment not found'),
] ]
)] )]
#[Route('/api/v1/payment/callback/{gateway}', methods: ['POST', 'GET'])] #[Route(PaymentManager::CALLBACK_PATH, methods: ['POST', 'GET'])]
public function callback(string $gateway, Request $request): \Symfony\Component\HttpFoundation\Response public function callback(Request $request): \Symfony\Component\HttpFoundation\Response
{ {
$clientIp = $request->getClientIp() ?? ''; $clientIp = $request->getClientIp() ?? '';
$callbackData = array_merge($request->query->all(), $request->request->all());
$orderId = $callbackData['order_id'] ?? $callbackData['ResNum'] ?? '';
// تک مسیر برای همهٔ درگاه‌ها: نام درگاه از query می‌آید و در نبودش از خودِ
// رکورد پرداخت خوانده می‌شود، تا آدرسِ ثبت‌شده نزد بانک هیچ‌وقت عوض نشود.
$gateway = (string) ($callbackData['gateway'] ?? '');
if ($gateway === '') {
$gateway = $this->paymentRepo->findByOrderId((string) $orderId)?->getGateway() ?? '';
}
if ($gateway === '') {
return $this->renderPaymentResult('notfound');
}
// درگاه‌های ملت و سپ نتیجه را با ریدایرکتِ مرورگرِ کاربر (POST/GET) برمی‌گردانند، // درگاه‌های ملت و سپ نتیجه را با ریدایرکتِ مرورگرِ کاربر (POST/GET) برمی‌گردانند،
// نه server-to-server؛ پس IP دریافتی، IPِ کاربر است و allowlist شاپرک اعمال نمی‌شود // نه server-to-server؛ پس IP دریافتی، IPِ کاربر است و allowlist شاپرک اعمال نمی‌شود
// (در غیر این صورت هر callback واقعی — از جمله «لغو» — رد می‌شد). امنیت از طریق چک // (در غیر این صورت هر callback واقعی — از جمله «لغو» — رد می‌شد). امنیت از طریق چک
@@ -336,9 +359,6 @@ class PaymentController extends BaseController
return $this->renderPaymentResult('forbidden'); return $this->renderPaymentResult('forbidden');
} }
$callbackData = array_merge($request->query->all(), $request->request->all());
$orderId = $callbackData['order_id'] ?? $callbackData['ResNum'] ?? '';
// verify امن (transaction + قفل + idempotent + post-action + log) در سرویس. // verify امن (transaction + قفل + idempotent + post-action + log) در سرویس.
$payment = $this->paymentManager->processCallback($gateway, $callbackData, $clientIp, $orderId); $payment = $this->paymentManager->processCallback($gateway, $callbackData, $clientIp, $orderId);
if ($payment === null) { if ($payment === null) {
@@ -396,11 +416,7 @@ class PaymentController extends BaseController
$data = json_decode($request->getContent(), true) ?? []; $data = json_decode($request->getContent(), true) ?? [];
$gatewayName = trim($data['gateway'] ?? 'mellat'); $gatewayName = trim($data['gateway'] ?? 'mellat');
$frontendAddress = trim($data['frontend_address'] ?? ''); $frontendAddress = trim($data['frontend_address'] ?? '');
$amountRials = (int) ($data['amount_rials'] ?? 0); $periodUuid = trim($data['period_uuid'] ?? '');
if ($amountRials <= 0) {
return $this->error(ErrorCodes::ERR_PAYMENT_002, ErrorCodes::message(ErrorCodes::ERR_PAYMENT_002), 422);
}
if (!empty($frontendAddress) && !$this->isAllowedFrontend($frontendAddress)) { if (!empty($frontendAddress) && !$this->isAllowedFrontend($frontendAddress)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'آدرس بازگشت مجاز نیست', 422, 'frontend_address'); return $this->error(ErrorCodes::ERR_VALIDATION_001, 'آدرس بازگشت مجاز نیست', 422, 'frontend_address');
@@ -417,54 +433,37 @@ class PaymentController extends BaseController
return $this->error(ErrorCodes::ERR_PAYMENT_004, ErrorCodes::message(ErrorCodes::ERR_PAYMENT_004), 422); return $this->error(ErrorCodes::ERR_PAYMENT_004, ErrorCodes::message(ErrorCodes::ERR_PAYMENT_004), 422);
} }
$periodUuid = trim($data['period_uuid'] ?? ''); // مبلغ از دورهٔ اشتراک محاسبه می‌شود، نه از بدنهٔ درخواست: قیمت دوره خالص
$payment = new Payment($user, $amountRials, $gatewayName, Payment::TYPE_SUBSCRIPTION, $frontendAddress); // است و مالیات رویش می‌نشیند، و کلاینت نباید بتواند مبلغ را تعیین کند.
$payment->assignTenant($owner); $period = $periodUuid !== '' ? $this->subscriptionPeriodRepo->findByUuid($periodUuid) : null;
if ($periodUuid !== '') { if ($period === null || !$period->isActive()) {
$payment->setMetadata(['period_uuid' => $periodUuid]); return $this->error(ErrorCodes::ERR_VALIDATION_001, 'دورهٔ اشتراک نامعتبر است', 422, 'period_uuid');
} }
$amountRials = $this->subscriptionTax->payableForPeriod($period);
if ($amountRials <= 0) {
return $this->error(ErrorCodes::ERR_PAYMENT_002, ErrorCodes::message(ErrorCodes::ERR_PAYMENT_002), 422);
}
$payment = new Payment($user, $amountRials, $gatewayName, Payment::TYPE_SUBSCRIPTION, $frontendAddress);
$payment->assignTenant($owner);
$payment->setMetadata(['period_uuid' => $periodUuid]);
$this->paymentRepo->save($payment); $this->paymentRepo->save($payment);
// مثل appointment: ارتباط با بانک اینجا نیست؛ در GET /payment/pay انجام می‌شود. // مثل appointment: ارتباط با بانک اینجا نیست؛ در GET /payment/pay انجام می‌شود.
return $this->success([ return $this->success([
'payment_uuid' => $payment->getUuid(), 'payment_uuid' => $payment->getUuid(),
'pay_url' => $this->appBaseUrl . '/api/v1/payment/pay/' . $payment->getOrderId(), 'pay_url' => $this->appBaseUrl . '/api/v1/payment/pay/' . $payment->getOrderId(),
'order_id' => $payment->getOrderId(), 'order_id' => $payment->getOrderId(),
'price_rials' => $period->getPriceRials(),
'tax_percent' => $this->subscriptionTax->percent(),
'tax_rials' => $this->subscriptionTax->taxOf($period->getPriceRials()),
'payable_rials' => $amountRials,
]); ]);
} }
#[OA\Post( // پرداخت اشتراک callback اختصاصی ندارد؛ همان `callback()` مشترک همهٔ نوع‌ها را
path: '/api/v1/subscription-payment/callback/{gateway}', // پردازش می‌کند و نوع را از رکورد پرداخت می‌خواند.
summary: 'Subscription payment gateway callback (public, IP-restricted)',
parameters: [
new OA\Parameter(
name: 'gateway',
in: 'path',
required: true,
schema: new OA\Schema(type: 'string', enum: ['mellat', 'sep'])
),
],
responses: [
new OA\Response(
response: 200,
description: 'Callback processed — either a redirect or JSON result',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'success', type: 'boolean'),
new OA\Property(property: 'payment', type: 'object'),
]
)
),
new OA\Response(response: 302, description: 'Redirect to frontend with payment result'),
new OA\Response(response: 403, description: 'Forbidden — IP not in allowed Shaparak ranges'),
new OA\Response(response: 404, description: 'Payment not found'),
]
)]
#[Route('/api/v1/subscription-payment/callback/{gateway}', methods: ['POST', 'GET'])]
public function subscriptionCallback(string $gateway, Request $request): \Symfony\Component\HttpFoundation\Response
{
return $this->callback($gateway, $request);
}
// ── Status ──────────────────────────────────────────────────────────────── // ── Status ────────────────────────────────────────────────────────────────
@@ -515,6 +514,9 @@ class PaymentController extends BaseController
'test_mode' => $this->gateways->isTestMode(), 'test_mode' => $this->gateways->isTestMode(),
'appointment_fee_rials' => (int) ($this->configRepo->get('appointment_fee_rials') ?: 0), 'appointment_fee_rials' => (int) ($this->configRepo->get('appointment_fee_rials') ?: 0),
'gateways' => $this->gateways->activeGateways(), 'gateways' => $this->gateways->activeGateways(),
// نرخ مالیاتِ اشتراک و شارژ کیف پول، تا کلاینت بتواند جمع کل را پیش از
// ارسال درخواست نشان دهد. صفر یعنی مالیات خاموش است.
'tax_percent' => $this->paymentTax->percent(),
]); ]);
} }
+17 -6
View File
@@ -249,12 +249,18 @@ final class PaymentManager
}); });
} }
/**
* تک آدرس بازگشت برای همهٔ درگاه‌ها و همهٔ نوع‌های پرداخت؛ درگاه و سفارش
* به‌صورت query param می‌روند تا مسیر ثابت و قابل ثبت در پنل بانک بماند.
*/
public const CALLBACK_PATH = '/api/v1/payment/callback';
public function callbackUrl(Payment $payment): string public function callbackUrl(Payment $payment): string
{ {
$prefix = $payment->getType() === Payment::TYPE_SUBSCRIPTION return $this->appBaseUrl . self::CALLBACK_PATH . '?' . http_build_query([
? '/api/v1/subscription-payment/callback/' 'gateway' => $payment->getGateway(),
: '/api/v1/payment/callback/'; 'order_id' => $payment->getOrderId(),
return $this->appBaseUrl . $prefix . $payment->getGateway() . '?order_id=' . $payment->getOrderId(); ]);
} }
// ── Post-actions ────────────────────────────────────────────────────────── // ── Post-actions ──────────────────────────────────────────────────────────
@@ -299,8 +305,10 @@ final class PaymentManager
if ($entityType === null || $entityId === null) { if ($entityType === null || $entityId === null) {
return; return;
} }
// قرینهٔ handleSmsWalletCharge: همان مبلغی که اعتبار شده بود پس گرفته می‌شود.
$wallet = $this->smsWalletService->getOrCreate($entityType, $entityId); $wallet = $this->smsWalletService->getOrCreate($entityType, $entityId);
$this->smsWalletService->deduct($wallet, $payment->getAmountRials(), 'استرداد شارژ کیف پیامک'); $credit = (int) ($meta['net_rials'] ?? $payment->getAmountRials());
$this->smsWalletService->deduct($wallet, $credit, 'استرداد شارژ کیف پیامک');
} }
/** /**
@@ -380,8 +388,11 @@ final class PaymentManager
return; return;
} }
// اعتبار = مبلغ خالص، نه مبلغ پرداختی: مالیات سهم دولت است نه شارژ کاربر.
// پرداخت‌های قدیمی `net_rials` ندارند و همان مبلغ کلشان اعتبار می‌شود.
$wallet = $this->smsWalletService->getOrCreate($entityType, $entityId); $wallet = $this->smsWalletService->getOrCreate($entityType, $entityId);
$this->smsWalletService->charge($wallet, $payment->getAmountRials(), $payment); $credit = (int) ($meta['net_rials'] ?? $payment->getAmountRials());
$this->smsWalletService->charge($wallet, $credit, $payment);
} }
// ── Helpers ─────────────────────────────────────────────────────────────── // ── Helpers ───────────────────────────────────────────────────────────────
@@ -0,0 +1,61 @@
<?php
namespace App\Payment\Service;
use App\Config\Repository\SiteConfigRepository;
/**
* مالیات پرداخت‌هایی که مبلغشان **خالص** است و مالیات رویشان اضافه می‌شود:
* اشتراک و شارژ کیف پول پیامک.
*
* نوبت از این کلاس استفاده نمی‌کند؛ آنجا مبلغ شامل مالیات است و
* `CommissionService` مالیات را از دلش استخراج می‌کند — دو فرمول متفاوت‌اند.
*
* نرخ از همان کلیدهای سراسری `tax_enabled` / `tax_percent` می‌آید تا دو نرخ
* موازی در سیستم نداشته باشیم.
*/
class PaymentTaxCalculator
{
public function __construct(private readonly SiteConfigRepository $configRepo) {}
/** درصد مؤثر؛ خاموش‌بودن مالیات یعنی صفر. */
public function percent(): float
{
if ($this->configRepo->get('tax_enabled') !== '1') {
return 0.0;
}
return max(0.0, (float) $this->configRepo->get('tax_percent'));
}
public function taxOf(int $netRials): int
{
$percent = $this->percent();
if ($percent <= 0.0 || $netRials <= 0) {
return 0;
}
return (int) round($netRials * $percent / 100);
}
/** مبلغی که کاربر واقعاً می‌پردازد: مبلغ خالص + مالیات. */
public function payableOf(int $netRials): int
{
return $netRials + $this->taxOf($netRials);
}
/**
* تفکیک کامل، برای برگرداندن در پاسخ API.
*
* @return array{net_rials: int, tax_percent: float, tax_rials: int, payable_rials: int}
*/
public function breakdown(int $netRials): array
{
return [
'net_rials' => $netRials,
'tax_percent' => $this->percent(),
'tax_rials' => $this->taxOf($netRials),
'payable_rials' => $this->payableOf($netRials),
];
}
}
@@ -33,8 +33,7 @@ class SecurityHeadersSubscriber implements EventSubscriberInterface
$isPaymentPage = $isPaymentPage =
str_starts_with($path, '/api/v1/payment/order/') str_starts_with($path, '/api/v1/payment/order/')
|| str_starts_with($path, '/api/v1/payment/pay/') || str_starts_with($path, '/api/v1/payment/pay/')
|| str_starts_with($path, '/api/v1/payment/callback/') || $path === '/api/v1/payment/callback';
|| str_starts_with($path, '/api/v1/subscription-payment/callback/');
$response->headers->set( $response->headers->set(
'Content-Security-Policy', 'Content-Security-Policy',
+16 -4
View File
@@ -40,6 +40,7 @@ class SmsWalletController extends BaseController
private readonly \App\Config\Repository\SiteConfigRepository $configRepo, private readonly \App\Config\Repository\SiteConfigRepository $configRepo,
private readonly \App\Secretary\Security\SecretaryAccessChecker $secretaryAccess, private readonly \App\Secretary\Security\SecretaryAccessChecker $secretaryAccess,
private readonly \App\Clinic\Security\ClinicDoctorAccessChecker $clinicDoctorAccess, private readonly \App\Clinic\Security\ClinicDoctorAccessChecker $clinicDoctorAccess,
private readonly \App\Payment\Service\PaymentTaxCalculator $tax,
private readonly string $appBaseUrl, private readonly string $appBaseUrl,
) {} ) {}
@@ -82,12 +83,18 @@ class SmsWalletController extends BaseController
$data = json_decode($request->getContent(), true) ?? []; $data = json_decode($request->getContent(), true) ?? [];
$gatewayName = trim($data['gateway'] ?? 'mellat'); $gatewayName = trim($data['gateway'] ?? 'mellat');
$amountRials = (int) ($data['amount_rials'] ?? 0); // `amount_rials` مبلغی است که به کیف پول می‌نشیند — خالص، بدون مالیات.
$netRials = (int) ($data['amount_rials'] ?? 0);
if ($amountRials <= 0) { if ($netRials <= 0) {
return $this->error(ErrorCodes::ERR_PAYMENT_002, 'مبلغ شارژ نامعتبر است', 422); return $this->error(ErrorCodes::ERR_PAYMENT_002, 'مبلغ شارژ نامعتبر است', 422);
} }
// مالیات روی مبلغ شارژ اضافه می‌شود؛ اعتبارِ کیف پول همان مبلغ خالص می‌ماند،
// وگرنه کاربر مالیات را هم به‌صورت اعتبار پیامک پس می‌گرفت.
$breakdown = $this->tax->breakdown($netRials);
$amountRials = $breakdown['payable_rials'];
// فقط اعتبارسنجی درگاه؛ ارتباط با بانک در flow واحد (GET /payment/pay) انجام می‌شود. // فقط اعتبارسنجی درگاه؛ ارتباط با بانک در flow واحد (GET /payment/pay) انجام می‌شود.
if ($this->gateways->resolve($gatewayName) === null) { if ($this->gateways->resolve($gatewayName) === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'درگاه پرداخت نامعتبر است', 422); return $this->error(ErrorCodes::ERR_VALIDATION_001, 'درگاه پرداخت نامعتبر است', 422);
@@ -96,14 +103,19 @@ class SmsWalletController extends BaseController
$frontendAddress = trim($data['frontend_address'] ?? ''); $frontendAddress = trim($data['frontend_address'] ?? '');
$payment = new Payment($user, $amountRials, $gatewayName, Payment::TYPE_SMS_WALLET, $frontendAddress); $payment = new Payment($user, $amountRials, $gatewayName, Payment::TYPE_SMS_WALLET, $frontendAddress);
$payment->assignTenantPair($entityType, $entityId); $payment->assignTenantPair($entityType, $entityId);
$payment->setMetadata(['entity_type' => $entityType, 'entity_id' => $entityId]); $payment->setMetadata([
'entity_type' => $entityType,
'entity_id' => $entityId,
// اعتباری که بعد از پرداخت موفق به کیف پول می‌نشیند — بدون مالیات.
'net_rials' => $netRials,
]);
$this->paymentRepo->save($payment); $this->paymentRepo->save($payment);
return $this->success([ return $this->success([
'payment_uuid' => $payment->getUuid(), 'payment_uuid' => $payment->getUuid(),
'pay_url' => $this->appBaseUrl . '/api/v1/payment/pay/' . $payment->getOrderId(), 'pay_url' => $this->appBaseUrl . '/api/v1/payment/pay/' . $payment->getOrderId(),
'order_id' => $payment->getOrderId(), 'order_id' => $payment->getOrderId(),
]); ] + $breakdown);
} }
#[Route('/api/v1/sms/wallet/logs', methods: ['GET'])] #[Route('/api/v1/sms/wallet/logs', methods: ['GET'])]
@@ -15,6 +15,7 @@ use App\Subscription\Repository\SubscriptionPlanRepository;
use App\Subscription\Repository\SubscriptionPeriodRepository; use App\Subscription\Repository\SubscriptionPeriodRepository;
use App\Subscription\Repository\ClinicSubscriptionRepository; use App\Subscription\Repository\ClinicSubscriptionRepository;
use App\Subscription\Service\SubscriptionService; use App\Subscription\Service\SubscriptionService;
use App\Subscription\Service\SubscriptionTaxCalculator;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -36,6 +37,7 @@ class SubscriptionController extends BaseController
private readonly UserActiveContextRepository $contextRepo, private readonly UserActiveContextRepository $contextRepo,
private readonly EntityManagerInterface $em, private readonly EntityManagerInterface $em,
private readonly \App\Secretary\Security\SecretaryAccessChecker $secretaryAccess, private readonly \App\Secretary\Security\SecretaryAccessChecker $secretaryAccess,
private readonly SubscriptionTaxCalculator $tax,
) {} ) {}
// ── Public ────────────────────────────────────────────────────────────── // ── Public ──────────────────────────────────────────────────────────────
@@ -45,10 +47,10 @@ class SubscriptionController extends BaseController
{ {
$plans = $this->planRepo->findAllActive(); $plans = $this->planRepo->findAllActive();
return $this->success(array_map( return $this->success($this->tax->decoratePlans(array_map(
fn(SubscriptionPlan $p) => $p->toArray(withPeriods: true), fn(SubscriptionPlan $p) => $p->toArray(withPeriods: true),
$plans $plans
)); )));
} }
// ── Authenticated ──────────────────────────────────────────────────────── // ── Authenticated ────────────────────────────────────────────────────────
@@ -123,7 +125,7 @@ class SubscriptionController extends BaseController
$plans = $this->planRepo->findAllForAdmin(); $plans = $this->planRepo->findAllForAdmin();
return $this->paginated( return $this->paginated(
array_map(fn(SubscriptionPlan $p) => $p->toArray(withPeriods: true), $plans), $this->tax->decoratePlans(array_map(fn(SubscriptionPlan $p) => $p->toArray(withPeriods: true), $plans)),
count($plans), count($plans),
1, 1,
100 100
@@ -247,7 +249,7 @@ class SubscriptionController extends BaseController
$this->periodRepo->save($period); $this->periodRepo->save($period);
return $this->success($period->toArray(), 201); return $this->success($this->tax->decoratePeriod($period->toArray()), 201);
} }
#[Route('/api/v1/admin/subscription/period/{uuid}', methods: ['PATCH'])] #[Route('/api/v1/admin/subscription/period/{uuid}', methods: ['PATCH'])]
@@ -269,7 +271,7 @@ class SubscriptionController extends BaseController
$this->periodRepo->save($period); $this->periodRepo->save($period);
return $this->success($period->toArray()); return $this->success($this->tax->decoratePeriod($period->toArray()));
} }
#[Route('/api/v1/admin/subscription/period/{uuid}', methods: ['DELETE'])] #[Route('/api/v1/admin/subscription/period/{uuid}', methods: ['DELETE'])]
@@ -0,0 +1,73 @@
<?php
namespace App\Subscription\Service;
use App\Payment\Service\PaymentTaxCalculator;
use App\Subscription\Entity\SubscriptionPeriod;
/**
* لایهٔ اشتراکیِ مالیات: حساب را به `PaymentTaxCalculator` می‌سپارد و فقط شکلِ
* دوره/پلن را می‌شناسد.
*
* قیمت دوره (`price_rials`) خالص است و مالیات رویش اضافه می‌شود؛ پس مبلغ قابل
* پرداخت از قیمت پلن بیشتر است.
*/
class SubscriptionTaxCalculator
{
public function __construct(private readonly PaymentTaxCalculator $tax) {}
public function percent(): float
{
return $this->tax->percent();
}
public function taxOf(int $netRials): int
{
return $this->tax->taxOf($netRials);
}
public function payableOf(int $netRials): int
{
return $this->tax->payableOf($netRials);
}
public function payableForPeriod(SubscriptionPeriod $period): int
{
return $this->tax->payableOf($period->getPriceRials());
}
/**
* سه فیلد مالیاتی را کنار `price_rials` می‌گذارد. کلیدِ خودِ قیمت دست نمی‌خورد
* تا کلاینت‌های قدیمی نشکنند.
*
* @param array<string, mixed> $period خروجی `SubscriptionPeriod::toArray()`
* @return array<string, mixed>
*/
public function decoratePeriod(array $period): array
{
$net = (int) ($period['price_rials'] ?? 0);
return $period + [
'tax_percent' => $this->tax->percent(),
'tax_rials' => $this->tax->taxOf($net),
'payable_rials' => $this->tax->payableOf($net),
];
}
/**
* همان کار را روی `periods` هر پلن انجام می‌دهد.
*
* @param array<int, array<string, mixed>> $plans خروجی `SubscriptionPlan::toArray(withPeriods: true)`
* @return array<int, array<string, mixed>>
*/
public function decoratePlans(array $plans): array
{
return array_map(function (array $plan): array {
if (isset($plan['periods']) && is_array($plan['periods'])) {
$plan['periods'] = array_map($this->decoratePeriod(...), $plan['periods']);
}
return $plan;
}, $plans);
}
}
@@ -56,7 +56,8 @@ class AppointmentPaidConfirmFilesSessionTest extends ApiTestCase
private function fireCallback(Payment $payment): void private function fireCallback(Payment $payment): void
{ {
$this->client->request('POST', '/api/v1/payment/callback/mock?' . http_build_query([ // بدون `gateway` فرستاده می‌شود تا fallbackِ خواندن درگاه از رکورد پرداخت هم پوشش بخورد.
$this->client->request('POST', '/api/v1/payment/callback?' . http_build_query([
'order_id' => $payment->getOrderId(), 'order_id' => $payment->getOrderId(),
'mock' => '1', 'mock' => '1',
'ResCode' => '0', 'ResCode' => '0',
+4 -2
View File
@@ -37,7 +37,8 @@ class PaymentCallbackAmountTest extends ApiTestCase
private function fireCallback(Payment $payment, int $reportedAmount): void private function fireCallback(Payment $payment, int $reportedAmount): void
{ {
$this->client->request('POST', '/api/v1/payment/callback/mock?' . http_build_query([ $this->client->request('POST', '/api/v1/payment/callback?' . http_build_query([
'gateway' => 'mock',
'order_id' => $payment->getOrderId(), 'order_id' => $payment->getOrderId(),
'mock' => '1', 'mock' => '1',
'ResCode' => '0', 'ResCode' => '0',
@@ -91,7 +92,8 @@ class PaymentCallbackAmountTest extends ApiTestCase
private function fireCallbackWithRef(Payment $payment, string $refId, int $reportedAmount): void private function fireCallbackWithRef(Payment $payment, string $refId, int $reportedAmount): void
{ {
$this->client->request('POST', '/api/v1/payment/callback/mock?' . http_build_query([ $this->client->request('POST', '/api/v1/payment/callback?' . http_build_query([
'gateway' => 'mock',
'order_id' => $payment->getOrderId(), 'order_id' => $payment->getOrderId(),
'mock' => '1', 'mock' => '1',
'ResCode' => '0', 'ResCode' => '0',
+17 -4
View File
@@ -34,6 +34,18 @@ class PaymentTenantTest extends ApiTestCase
parent::tearDown(); parent::tearDown();
} }
private function makePricedPeriod(int $priceRials): \App\Subscription\Entity\SubscriptionPeriod
{
$plan = new \App\Subscription\Entity\SubscriptionPlan('plan-' . bin2hex(random_bytes(4)), 5, 1, []);
$this->em->persist($plan);
$period = new \App\Subscription\Entity\SubscriptionPeriod($plan, 'یک ماهه', 1, $priceRials);
$this->em->persist($period);
$this->em->flush();
return $period;
}
private function makeDoctor(): Doctor private function makeDoctor(): Doctor
{ {
$doctor = new Doctor($this->createUser(['ROLE_DOCTOR']), 'دکتر پرداخت'); $doctor = new Doctor($this->createUser(['ROLE_DOCTOR']), 'دکتر پرداخت');
@@ -105,9 +117,10 @@ class PaymentTenantTest extends ApiTestCase
{ {
$doctor = $this->makeDoctor(); $doctor = $this->makeDoctor();
// مبلغ از خودِ دوره می‌آید (قیمت خالص + مالیات)، نه از بدنهٔ درخواست.
$res = $this->authJson('POST', '/api/v1/subscription-payment', $doctor->getUser(), [ $res = $this->authJson('POST', '/api/v1/subscription-payment', $doctor->getUser(), [
'gateway' => 'mellat', 'gateway' => 'mellat',
'amount_rials' => 1_000_000, 'period_uuid' => $this->makePricedPeriod(1_000_000)->getUuid(),
]); ]);
self::assertSame(200, $this->responseCode()); self::assertSame(200, $this->responseCode());
@@ -123,8 +136,8 @@ class PaymentTenantTest extends ApiTestCase
public function testSubscriptionPaymentWithoutAnOwnedEnvironmentIsRejected(): void public function testSubscriptionPaymentWithoutAnOwnedEnvironmentIsRejected(): void
{ {
$res = $this->authJson('POST', '/api/v1/subscription-payment', $this->createUser(['ROLE_USER']), [ $res = $this->authJson('POST', '/api/v1/subscription-payment', $this->createUser(['ROLE_USER']), [
'gateway' => 'mellat', 'gateway' => 'mellat',
'amount_rials' => 1_000_000, 'period_uuid' => $this->makePricedPeriod(1_000_000)->getUuid(),
]); ]);
self::assertSame(422, $this->responseCode()); self::assertSame(422, $this->responseCode());
@@ -0,0 +1,125 @@
<?php
namespace App\Tests\Payment;
use App\Config\Entity\SiteConfig;
use App\Payment\Entity\Payment;
use App\Payment\Service\PaymentManager;
use App\Tests\ApiTestCase;
/**
* Every gateway and every payment type shares one callback path. The gateway
* and the order travel as query params so the URL registered with the bank
* never has to change.
*/
class UnifiedPaymentCallbackTest extends ApiTestCase
{
private function enableTestMode(): void
{
$cfg = $this->em->getRepository(SiteConfig::class)->findOneBy(['configKey' => 'payment_test_mode']);
if ($cfg === null) {
$cfg = new SiteConfig('payment_test_mode', '1');
$this->em->persist($cfg);
} else {
$cfg->setValue('1');
}
$this->em->flush();
}
private function makePayment(string $type, string $gateway = 'mock'): Payment
{
$payment = $this->stampTenant(new Payment($this->createUser(), 50000, $gateway, $type));
$this->em->persist($payment);
$this->em->flush();
return $payment;
}
private function reload(Payment $payment): Payment
{
$this->em->clear();
return $this->em->getRepository(Payment::class)->find($payment->getId());
}
/** @param array<string, string> $extra */
private function fireCallback(Payment $payment, array $extra = []): void
{
$this->client->request('POST', PaymentManager::CALLBACK_PATH . '?' . http_build_query(array_merge([
'order_id' => $payment->getOrderId(),
'mock' => '1',
'ResCode' => '0',
'mock_amount' => '50000',
], $extra)));
}
/** @return array<string, array{string}> */
public static function paymentTypeProvider(): array
{
return [
'appointment' => [Payment::TYPE_APPOINTMENT],
'subscription' => [Payment::TYPE_SUBSCRIPTION],
'sms wallet' => [Payment::TYPE_SMS_WALLET],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('paymentTypeProvider')]
public function testEveryPaymentTypeUsesTheSameCallbackPath(string $type): void
{
$this->enableTestMode();
$payment = $this->makePayment($type);
$url = static::getContainer()->get(PaymentManager::class)->callbackUrl($payment);
$this->assertStringContainsString(PaymentManager::CALLBACK_PATH . '?', $url);
$this->assertStringNotContainsString('/subscription-payment/', $url);
$this->assertStringContainsString('gateway=mock', $url);
$this->assertStringContainsString('order_id=' . $payment->getOrderId(), $url);
}
public function testCallbackAcceptsGatewayAsQueryParam(): void
{
$this->enableTestMode();
$payment = $this->makePayment(Payment::TYPE_SMS_WALLET);
$this->fireCallback($payment, ['gateway' => 'mock']);
$this->assertSame(Payment::STATUS_SUCCESS, $this->reload($payment)->getStatus());
}
public function testCallbackFallsBackToTheGatewayStoredOnThePayment(): void
{
$this->enableTestMode();
$payment = $this->makePayment(Payment::TYPE_SMS_WALLET);
$this->fireCallback($payment);
$this->assertSame(Payment::STATUS_SUCCESS, $this->reload($payment)->getStatus());
}
public function testUnknownOrderWithoutGatewayIsNotFound(): void
{
$this->enableTestMode();
$this->client->request('POST', PaymentManager::CALLBACK_PATH . '?' . http_build_query([
'order_id' => 'ORD-DOES-NOT-EXIST',
'mock' => '1',
'ResCode' => '0',
]));
$this->assertSame(200, $this->client->getResponse()->getStatusCode());
$this->assertStringContainsString('یافت نشد', (string) $this->client->getResponse()->getContent());
}
public function testRemovedLegacyCallbackRoutesReturn404(): void
{
$this->enableTestMode();
$payment = $this->makePayment(Payment::TYPE_SUBSCRIPTION);
$query = '?' . http_build_query(['order_id' => $payment->getOrderId()]);
foreach (['/api/v1/payment/callback/mock', '/api/v1/subscription-payment/callback/mock'] as $legacy) {
$this->client->request('POST', $legacy . $query);
$this->assertSame(404, $this->client->getResponse()->getStatusCode(), $legacy);
}
}
}
+1 -1
View File
@@ -53,6 +53,7 @@ class ApiLeastPrivilegeTest extends ApiTestCase
'practice_domain_list' => 'حوزه‌های فعالیت — دادهٔ مرجع', 'practice_domain_list' => 'حوزه‌های فعالیت — دادهٔ مرجع',
'app_subscription_subscription_plans' => 'پلن‌های اشتراک — کاتالوگ عمومی', 'app_subscription_subscription_plans' => 'پلن‌های اشتراک — کاتالوگ عمومی',
'app_payment_payment_config' => 'نام درگاه‌ها و کارمزد — بدون مقدار محرمانه', 'app_payment_payment_config' => 'نام درگاه‌ها و کارمزد — بدون مقدار محرمانه',
'app_payment_payment_callback' => 'callback بانک — عمدا PUBLIC؛ بدون order_id معتبر فقط صفحهٔ «یافت نشد» می‌دهد',
'app_representation_sitecontext_resolve' => 'حل دامنه به شهر/نماینده — ورودی رندر سایت', 'app_representation_sitecontext_resolve' => 'حل دامنه به شهر/نماینده — ورودی رندر سایت',
'resource_strategies' => 'فهرست ثابتِ استراتژی‌های تخصیص منبع', 'resource_strategies' => 'فهرست ثابتِ استراتژی‌های تخصیص منبع',
'app_clinicservice_clinicservice_listservicecategories' => 'دسته‌های ثابت خدمت (سرپایی/بستری)', 'app_clinicservice_clinicservice_listservicecategories' => 'دسته‌های ثابت خدمت (سرپایی/بستری)',
@@ -116,7 +117,6 @@ class ApiLeastPrivilegeTest extends ApiTestCase
'app_auth_auth_resetpassword' => 'بازیابی رمز', 'app_auth_auth_resetpassword' => 'بازیابی رمز',
'app_auth_preregistration_submit' => 'پیش‌ثبت‌نام عمومی', 'app_auth_preregistration_submit' => 'پیش‌ثبت‌نام عمومی',
'app_payment_payment_callback' => 'کال‌بک درگاه — بدون توکن فراخوانی می‌شود', 'app_payment_payment_callback' => 'کال‌بک درگاه — بدون توکن فراخوانی می‌شود',
'app_payment_payment_subscriptioncallback' => 'کال‌بک درگاه اشتراک',
// ── اکشن روی دادهٔ خودِ کاربر: منبعی در رجیستری ندارد ───────────────── // ── اکشن روی دادهٔ خودِ کاربر: منبعی در رجیستری ندارد ─────────────────
'app_auth_auth_changepassword' => 'تغییر رمزِ خودِ کاربر', 'app_auth_auth_changepassword' => 'تغییر رمزِ خودِ کاربر',
+116
View File
@@ -0,0 +1,116 @@
<?php
namespace App\Tests\Sms;
use App\Config\Entity\SiteConfig;
use App\Doctor\Entity\Doctor;
use App\Payment\Entity\Payment;
use App\Sms\Service\SmsWalletService;
use App\Tests\ApiTestCase;
/**
* شارژ کیف پول پیامک مثل اشتراک است: مبلغ درخواستی خالص است و مالیات رویش اضافه
* می‌شود. نکتهٔ اصلی این است که **اعتبارِ کیف پول همان مبلغ خالص می‌ماند** — اگر
* مالیات هم اعتبار می‌شد، کاربر آن را به‌صورت پیامک پس می‌گرفت.
*/
class SmsWalletTaxTest extends ApiTestCase
{
private function setConfig(string $key, string $value): void
{
$cfg = $this->em->getRepository(SiteConfig::class)->findOneBy(['configKey' => $key]);
if ($cfg === null) {
$this->em->persist(new SiteConfig($key, $value));
} else {
$cfg->setValue($value);
}
$this->em->flush();
}
private function enableTax(string $percent = '10'): void
{
$this->setConfig('tax_enabled', '1');
$this->setConfig('tax_percent', $percent);
}
private function makeDoctor(): Doctor
{
$doctor = new Doctor($this->createUser(['ROLE_DOCTOR']), 'دکتر کیف پول');
$this->em->persist($doctor);
$this->em->flush();
return $doctor;
}
/** @return array<string, mixed> */
private function charge(Doctor $doctor, int $netRials): array
{
$res = $this->authJson('POST', '/api/v1/sms/wallet/charge', $doctor->getUser(), [
'gateway' => 'mellat',
'amount_rials' => $netRials,
]);
self::assertSame(200, $this->responseCode());
return $res['data'];
}
public function testChargeResponseSplitsNetAndTax(): void
{
$this->enableTax('10');
$data = $this->charge($this->makeDoctor(), 1_000_000);
self::assertSame(1_000_000, $data['net_rials']);
// JSON عدد اعشاریِ ۱۰٫۰ را ۱۰ سریالایز می‌کند، پس مقایسه با نوعِ شل.
self::assertEquals(10, $data['tax_percent']);
self::assertSame(100_000, $data['tax_rials']);
self::assertSame(1_100_000, $data['payable_rials']);
}
public function testThePaymentRowCarriesTheTaxedAmount(): void
{
$this->enableTax('10');
$data = $this->charge($this->makeDoctor(), 1_000_000);
$payment = $this->em->getRepository(Payment::class)->findOneBy(['uuid' => $data['payment_uuid']]);
self::assertSame(1_100_000, $payment->getAmountRials(), 'مبلغ بانک باید شامل مالیات باشد');
self::assertSame(1_000_000, $payment->getMetadata()['net_rials']);
}
public function testWalletIsCreditedWithTheNetAmountNotTheTaxedOne(): void
{
$this->enableTax('10');
$doctor = $this->makeDoctor();
$wallets = static::getContainer()->get(SmsWalletService::class);
$before = $wallets->getBalance('doctor', $doctor->getId());
$data = $this->charge($doctor, 1_000_000);
$payment = $this->em->getRepository(Payment::class)->findOneBy(['uuid' => $data['payment_uuid']]);
$this->client->request('POST', \App\Payment\Service\PaymentManager::CALLBACK_PATH . '?' . http_build_query([
'gateway' => 'mellat',
'order_id' => $payment->getOrderId(),
'mock' => '1',
'ResCode' => '0',
'mock_amount' => '1100000',
]));
$this->em->clear();
self::assertSame(
$before + 1_000_000,
$wallets->getBalance('doctor', $doctor->getId()),
'مالیات نباید به اعتبار پیامک تبدیل شود',
);
}
public function testDisabledTaxKeepsChargeAmountUnchanged(): void
{
$this->setConfig('tax_enabled', '0');
$this->setConfig('tax_percent', '10');
$data = $this->charge($this->makeDoctor(), 1_000_000);
self::assertSame(0, $data['tax_rials']);
self::assertSame(1_000_000, $data['payable_rials']);
}
}
+150
View File
@@ -0,0 +1,150 @@
<?php
namespace App\Tests\Subscription;
use App\Config\Entity\SiteConfig;
use App\Payment\Entity\Payment;
use App\Subscription\Entity\SubscriptionPeriod;
use App\Subscription\Entity\SubscriptionPlan;
use App\Subscription\Service\SubscriptionTaxCalculator;
use App\Tests\ApiTestCase;
/**
* قیمت دورهٔ اشتراک خالص است و مالیات رویش اضافه می‌شود — برخلاف نوبت که مبلغش
* شامل مالیات است. پس مبلغِ پرداختی همیشه ≥ قیمت پلن است، و مبلغ از سمت سرور
* محاسبه می‌شود نه از بدنهٔ درخواست.
*/
class SubscriptionTaxTest extends ApiTestCase
{
private function setConfig(string $key, string $value): void
{
$cfg = $this->em->getRepository(SiteConfig::class)->findOneBy(['configKey' => $key]);
if ($cfg === null) {
$this->em->persist(new SiteConfig($key, $value));
} else {
$cfg->setValue($value);
}
$this->em->flush();
}
private function enableTax(string $percent = '10'): void
{
$this->setConfig('tax_enabled', '1');
$this->setConfig('tax_percent', $percent);
}
private function makePeriod(int $priceRials): SubscriptionPeriod
{
$plan = new SubscriptionPlan('plan-' . bin2hex(random_bytes(4)), 5, 1, []);
$this->em->persist($plan);
$period = new SubscriptionPeriod($plan, 'یک ماهه', 1, $priceRials);
$this->em->persist($period);
$this->em->flush();
return $period;
}
private function calculator(): SubscriptionTaxCalculator
{
return static::getContainer()->get(SubscriptionTaxCalculator::class);
}
public function testTaxIsAddedOnTopOfTheNetPrice(): void
{
$this->enableTax('10');
$calc = $this->calculator();
self::assertSame(29_000, $calc->taxOf(290_000));
self::assertSame(319_000, $calc->payableOf(290_000), 'مالیات باید اضافه شود، نه استخراج');
}
public function testDisabledTaxLeavesThePriceUntouched(): void
{
$this->setConfig('tax_enabled', '0');
$this->setConfig('tax_percent', '10');
$calc = $this->calculator();
self::assertSame(0.0, $calc->percent());
self::assertSame(0, $calc->taxOf(290_000));
self::assertSame(290_000, $calc->payableOf(290_000));
}
public function testFreePeriodStaysFree(): void
{
$this->enableTax('10');
self::assertSame(0, $this->calculator()->payableOf(0));
}
public function testPublicPlanListExposesTaxPerPeriod(): void
{
$this->enableTax('10');
$this->makePeriod(290_000);
// این روت پشت firewall نشسته (بر خلاف چیزی که docs می‌گوید)، پس با توکن زده می‌شود.
$this->authJson('GET', '/api/v1/subscription/plans', $this->createUser());
self::assertSame(200, $this->responseCode());
$periods = [];
foreach (json_decode((string) $this->client->getResponse()->getContent(), true)['data'] as $plan) {
foreach ($plan['periods'] ?? [] as $period) {
$periods[] = $period;
}
}
self::assertNotEmpty($periods, 'حداقل یک دوره باید برگردد');
foreach ($periods as $period) {
self::assertArrayHasKey('tax_percent', $period);
self::assertArrayHasKey('tax_rials', $period);
self::assertArrayHasKey('payable_rials', $period);
self::assertSame(
$period['price_rials'] + $period['tax_rials'],
$period['payable_rials'],
);
}
}
public function testPaymentChargesPricePlusTaxAndIgnoresTheClientAmount(): void
{
$this->enableTax('10');
$period = $this->makePeriod(290_000);
$user = $this->createUser(['ROLE_DOCTOR']);
$doctor = new \App\Doctor\Entity\Doctor($user, 'دکتر مالیات');
$this->em->persist($doctor);
$this->em->flush();
$this->authJson('POST', '/api/v1/subscription-payment', $user, [
'gateway' => 'mellat',
'period_uuid' => $period->getUuid(),
// مبلغِ دستکاری‌شده باید نادیده گرفته شود.
'amount_rials' => 1_000,
]);
self::assertSame(200, $this->responseCode());
$body = json_decode((string) $this->client->getResponse()->getContent(), true)['data'];
self::assertSame(290_000, $body['price_rials']);
self::assertSame(29_000, $body['tax_rials']);
self::assertSame(319_000, $body['payable_rials']);
$payment = $this->em->getRepository(Payment::class)->findOneBy(['uuid' => $body['payment_uuid']]);
self::assertSame(319_000, $payment->getAmountRials(), 'مبلغ ذخیره‌شده باید شامل مالیات باشد');
}
public function testPaymentRejectsAnUnknownPeriod(): void
{
$this->enableTax('10');
$user = $this->createUser(['ROLE_DOCTOR']);
$doctor = new \App\Doctor\Entity\Doctor($user, 'دکتر بدون دوره');
$this->em->persist($doctor);
$this->em->flush();
$this->authJson('POST', '/api/v1/subscription-payment', $user, [
'gateway' => 'mellat',
'period_uuid' => 'does-not-exist',
'amount_rials' => 290_000,
]);
self::assertSame(422, $this->responseCode());
}
}