Add tests and implementation for ServiceDetailPage and PriceInput components
- Implement PriceInput component tests to validate Persian and Arabic numeral handling, input formatting, and controlled behavior. - Create ServiceDetailPage component with detailed service information, including pricing, insurance coverage, and editing capabilities. - Add API tests for service item detail retrieval and coverage synchronization with insurance contracts. - Ensure proper error handling and user feedback for service item retrieval and coverage management.
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/utils';
|
||||
|
||||
vi.mock('../lib/api', () => ({
|
||||
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
ApiError: class extends Error {},
|
||||
}));
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
import { api } from '../lib/api';
|
||||
import ServiceInsuranceModal from './ServiceInsuranceModal';
|
||||
import type { ServiceItem } from '../types';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
const put = api.put as ReturnType<typeof vi.fn>;
|
||||
|
||||
const item = { uuid: 'svc-1', name: 'سرم ۵۰۰cc' } as ServiceItem;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
get.mockImplementation((url: string) => {
|
||||
if (url.includes('service-coverage')) return Promise.resolve({ data: { data: [] } });
|
||||
return Promise.resolve({
|
||||
data: { data: [{ uuid: 'ins-1', insurance_name: 'بیمه ایران', insurance_kind: 'basic', coverage_percent: 70 }] },
|
||||
});
|
||||
});
|
||||
put.mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
const percentInput = async () => {
|
||||
const el = await screen.findByPlaceholderText('ارث از قرارداد');
|
||||
return el as HTMLInputElement;
|
||||
};
|
||||
|
||||
describe('ServiceInsuranceModal — فیلد درصد پوشش', () => {
|
||||
it('رقم فارسی را میپذیرد و NaN نمایش نمیدهد', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
const input = await percentInput();
|
||||
|
||||
fireEvent.change(input, { target: { value: '۲۵' } });
|
||||
|
||||
expect(input.value).toBe('25');
|
||||
expect(input.value).not.toContain('NaN');
|
||||
});
|
||||
|
||||
it('مقدار ذخیرهشده عدد معتبر است', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
fireEvent.change(await percentInput(), { target: { value: '۳۰' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
|
||||
await waitFor(() => expect(put).toHaveBeenCalled());
|
||||
expect(put.mock.calls[0][1]).toMatchObject({ service_item_uuid: 'svc-1', coverage_percent: 30 });
|
||||
});
|
||||
|
||||
it('بیش از ۱۰۰ به ۱۰۰ محدود میشود', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
fireEvent.change(await percentInput(), { target: { value: '۱۵۰' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
|
||||
await waitFor(() => expect(put).toHaveBeenCalled());
|
||||
expect(put.mock.calls[0][1]).toMatchObject({ coverage_percent: 100 });
|
||||
});
|
||||
|
||||
it('فیلد خالی → null (ارث از قرارداد)', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
const input = await percentInput();
|
||||
fireEvent.change(input, { target: { value: '۴۰' } });
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
|
||||
expect(input.value).toBe('');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
await waitFor(() => expect(put).toHaveBeenCalled());
|
||||
expect(put.mock.calls[0][1]).toMatchObject({ coverage_percent: null });
|
||||
});
|
||||
|
||||
it('حروف نامعتبر وارد نمیشود', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
const input = await percentInput();
|
||||
fireEvent.change(input, { target: { value: 'ابج' } });
|
||||
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ShieldCheckIcon, CheckIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import { digitsOnly, parseUserNumberClamped } from '../lib/utils';
|
||||
import Modal from './ui/Modal';
|
||||
import PriceInput from './ui/PriceInput';
|
||||
import type { ServiceItem } from '../types';
|
||||
@@ -46,6 +47,8 @@ function ContractCard({ contract, item }: { contract: TenantInsurance; item: Ser
|
||||
const existing = rows?.find((r) => r.service_item_uuid === item.uuid);
|
||||
|
||||
const [draft, setDraft] = useState<Draft>({ covered: true, coverage_percent: null, franchise_rials: null, ceiling_rials: null });
|
||||
// متن خام فیلد درصد جدا از مقدار عددی نگه داشته میشود تا کاربر بتواند فیلد را خالی کند.
|
||||
const [percentText, setPercentText] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(existing
|
||||
@@ -56,6 +59,7 @@ function ContractCard({ contract, item }: { contract: TenantInsurance; item: Ser
|
||||
ceiling_rials: existing.ceiling_rials,
|
||||
}
|
||||
: { covered: true, coverage_percent: null, franchise_rials: null, ceiling_rials: null });
|
||||
setPercentText(existing?.coverage_percent == null ? '' : String(existing.coverage_percent));
|
||||
}, [existing]);
|
||||
|
||||
const saveMut = useMutation({
|
||||
@@ -129,9 +133,14 @@ function ContractCard({ contract, item }: { contract: TenantInsurance; item: Ser
|
||||
<input
|
||||
type="text" inputMode="numeric" dir="ltr" className="input"
|
||||
style={{ height: 40, textAlign: 'left' }}
|
||||
value={draft.coverage_percent ?? ''}
|
||||
placeholder="ارث"
|
||||
onChange={(e) => setDraft((d) => ({ ...d, coverage_percent: e.target.value === '' ? null : Number(e.target.value) }))}
|
||||
value={percentText}
|
||||
placeholder="ارث از قرارداد"
|
||||
onChange={(e) => {
|
||||
const digits = digitsOnly(e.target.value, 3);
|
||||
setPercentText(digits);
|
||||
setDraft((d) => ({ ...d, coverage_percent: parseUserNumberClamped(digits, 0, 100) }));
|
||||
}}
|
||||
onBlur={() => setPercentText(draft.coverage_percent == null ? '' : String(draft.coverage_percent))}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ShieldCheckIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import type { ServiceItem, ClinicStaff } from '../types';
|
||||
import { rialToToman, tomanToRial } from '../lib/utils';
|
||||
import { numericField } from '../lib/forms';
|
||||
import Modal from './ui/Modal';
|
||||
import PriceInput from './ui/PriceInput';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
|
||||
const itemSchema = z.object({
|
||||
name: z.string().min(1, 'نام سرویس الزامی است'),
|
||||
price_rials: z.coerce.number().min(0, 'مبلغ نمیتواند منفی باشد'),
|
||||
staff_uuids: z.array(z.string()).optional(),
|
||||
duration_minutes: z.coerce.number().min(0).optional(),
|
||||
bookable: z.boolean().optional(),
|
||||
});
|
||||
type ItemForm = z.infer<typeof itemSchema>;
|
||||
|
||||
const EMPTY_FORM: ItemForm = { name: '', price_rials: 0, staff_uuids: [], duration_minutes: undefined, bookable: false };
|
||||
|
||||
interface Props {
|
||||
/** `'create'` برای سرویس جدید، شیء سرویس برای ویرایش، `null` یعنی بسته. */
|
||||
item: 'create' | ServiceItem | null;
|
||||
/** بخش مقصد؛ برای حالت ایجاد الزامی است. */
|
||||
sectionUuid: string | null;
|
||||
onClose: () => void;
|
||||
/** برای باز کردن مودال پوشش بیمه از داخل فرم (فقط در حالت ویرایش). */
|
||||
onManageInsurance?: (item: ServiceItem) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* فرم ایجاد/ویرایش سرویس — مشترک بین فهرست سرویسها و صفحهی جزئیات سرویس.
|
||||
*
|
||||
* تنظیمات بیمه اینجا نیست: پوشش هر بیمهگر تنها در «پوشش بیمه» مدیریت میشود و
|
||||
* پرچم `insurance_covered` سمت سرور از همانجا همگام میشود.
|
||||
*/
|
||||
export default function ServiceItemFormModal({ item, sectionUuid, onClose, onManageInsurance }: Props) {
|
||||
const qc = useQueryClient();
|
||||
const editing = item !== null && typeof item === 'object' ? item : null;
|
||||
|
||||
const { data: staffData } = useQuery<ApiResponse<ClinicStaff[]>>({
|
||||
queryKey: ['staff'],
|
||||
queryFn: () => api.get('/api/v1/staff'),
|
||||
enabled: item !== null,
|
||||
});
|
||||
const allStaff = staffData?.data ?? [];
|
||||
|
||||
const form = useForm<ItemForm>({ resolver: zodResolver(itemSchema), defaultValues: EMPTY_FORM });
|
||||
|
||||
useEffect(() => {
|
||||
if (item === null) return;
|
||||
form.reset(editing
|
||||
? {
|
||||
name: editing.name,
|
||||
price_rials: rialToToman(editing.price_rials),
|
||||
staff_uuids: (editing.staff_members ?? (editing.staff ? [editing.staff] : [])).map((s) => s.uuid),
|
||||
duration_minutes: editing.duration_minutes ?? undefined,
|
||||
bookable: editing.bookable ?? false,
|
||||
}
|
||||
: EMPTY_FORM);
|
||||
}, [item]);
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['service-items'] });
|
||||
qc.invalidateQueries({ queryKey: ['service-sections'] });
|
||||
if (editing) qc.invalidateQueries({ queryKey: ['service-item', editing.uuid] });
|
||||
};
|
||||
|
||||
const createItem = useMutation({
|
||||
mutationFn: (body: ItemForm) => api.post('/api/v1/service-item', {
|
||||
...body,
|
||||
section_uuid: sectionUuid,
|
||||
price_rials: tomanToRial(body.price_rials),
|
||||
}),
|
||||
onSuccess: () => { invalidate(); onClose(); toast.success('سرویس ایجاد شد'); },
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const editItem = useMutation({
|
||||
mutationFn: (body: ItemForm) => api.patch(`/api/v1/service-item/${editing!.uuid}`, {
|
||||
...body,
|
||||
price_rials: tomanToRial(body.price_rials),
|
||||
}),
|
||||
onSuccess: () => { invalidate(); onClose(); toast.success('سرویس ویرایش شد'); },
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const saving = createItem.isPending || editItem.isPending;
|
||||
|
||||
const selectedStaffUuids = form.watch('staff_uuids') ?? [];
|
||||
const editingMembers = editing ? (editing.staff_members ?? (editing.staff ? [editing.staff] : [])) : [];
|
||||
const staffOptions = allStaff
|
||||
.filter((s) => s.active || editingMembers.some((m) => m.uuid === s.uuid))
|
||||
.filter((s) => !selectedStaffUuids.includes(s.uuid))
|
||||
.map((s) => ({ value: s.uuid, label: s.active ? s.full_name : `${s.full_name} (غیرفعال)` }));
|
||||
const staffNameOf = (uuid: string) =>
|
||||
allStaff.find((s) => s.uuid === uuid)?.full_name
|
||||
?? editingMembers.find((m) => m.uuid === uuid)?.full_name
|
||||
?? uuid;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={item !== null}
|
||||
onClose={onClose}
|
||||
title={editing ? 'ویرایش سرویس' : 'سرویس جدید'}
|
||||
size="md"
|
||||
footer={
|
||||
<>
|
||||
<button type="button" className="btn" onClick={onClose}>انصراف</button>
|
||||
<button type="submit" form="service-item-form" className="btn primary" disabled={saving}>
|
||||
{saving ? 'در حال ذخیره...' : 'ذخیره سرویس'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="service-item-form"
|
||||
onSubmit={form.handleSubmit((d) => (editing ? editItem : createItem).mutate(d))}
|
||||
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
<div>
|
||||
<label className="field-label">نام سرویس *</label>
|
||||
<div className="field" style={form.formState.errors.name ? { borderColor: 'var(--danger)' } : undefined}>
|
||||
<input {...form.register('name')} placeholder="مثلاً: سرم ۵۰۰cc" autoFocus />
|
||||
</div>
|
||||
{form.formState.errors.name && (
|
||||
<span className="field-error">{form.formState.errors.name.message}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<div>
|
||||
<label className="field-label">قیمت پایه (تومان) *</label>
|
||||
<div className="field">
|
||||
<PriceInput
|
||||
value={form.watch('price_rials') ?? 0}
|
||||
onChange={(v) => form.setValue('price_rials', v)}
|
||||
placeholder="۸۵,۰۰۰"
|
||||
min={0}
|
||||
suffix="تومان"
|
||||
/>
|
||||
</div>
|
||||
{form.formState.errors.price_rials && (
|
||||
<span className="field-error">{form.formState.errors.price_rials.message}</span>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">پرسنل مسئول</label>
|
||||
<SearchableSelect
|
||||
options={staffOptions}
|
||||
value={''}
|
||||
onChange={(v) => { if (v != null) form.setValue('staff_uuids', [...selectedStaffUuids, String(v)]); }}
|
||||
placeholder="افزودن پرسنل (اختیاری)"
|
||||
noOptionsMessage="پرسنلی باقی نمانده"
|
||||
height={42}
|
||||
/>
|
||||
{selectedStaffUuids.length > 0 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
|
||||
{selectedStaffUuids.map((uuid) => (
|
||||
<span key={uuid} style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
fontSize: 12.5, color: 'var(--text-2)', background: 'var(--surface-2)',
|
||||
border: '1px solid var(--border)', borderRadius: 999, padding: '4px 6px 4px 10px',
|
||||
}}>
|
||||
{staffNameOf(uuid)}
|
||||
<button
|
||||
type="button" aria-label={`حذف ${staffNameOf(uuid)}`}
|
||||
onClick={() => form.setValue('staff_uuids', selectedStaffUuids.filter((u) => u !== uuid))}
|
||||
style={{ display: 'grid', placeItems: 'center', width: 16, height: 16, border: 'none', cursor: 'pointer', borderRadius: '50%', background: 'var(--surface-3)', color: 'var(--text-3)' }}
|
||||
>
|
||||
<XMarkIcon style={{ width: 11 }} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'end' }}>
|
||||
<div>
|
||||
<label className="field-label">زمان متوسط (دقیقه)</label>
|
||||
<div className="field">
|
||||
<input {...numericField(form.register('duration_minutes'))} placeholder="مثلاً: 50" />
|
||||
</div>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', padding: '9px 0' }}>
|
||||
<span className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.watch('bookable') ?? false}
|
||||
onChange={(e) => form.setValue('bookable', e.target.checked)}
|
||||
/>
|
||||
<span className="switch-track"><span className="switch-thumb" /></span>
|
||||
</span>
|
||||
<span style={{ fontSize: 13 }}>نمایش در نوبتدهی</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* بیمه — تنظیمات فقط در «پوشش بیمه» مدیریت میشود تا دادهی تکراری ساخته نشود. */}
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px',
|
||||
borderRadius: 'var(--r-sm)', background: 'var(--primary-soft)',
|
||||
}}>
|
||||
<ShieldCheckIcon style={{ width: 16, flexShrink: 0, color: 'var(--primary)' }} />
|
||||
<span style={{ flex: 1, minWidth: 0, fontSize: 12, color: 'var(--text-2)', lineHeight: 1.7 }}>
|
||||
پوشش بیمهی این خدمت — درصد، فرانشیز و سقف هر بیمهگر — در بخش «پوشش بیمه» تنظیم میشود.
|
||||
</span>
|
||||
{editing && onManageInsurance && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn sm"
|
||||
style={{ flexShrink: 0 }}
|
||||
onClick={() => { const it = editing; onClose(); onManageInsurance(it); }}
|
||||
>
|
||||
پوشش بیمه
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { PencilIcon, CheckIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import { formatRial, formatNumber, rialToToman, tomanToRial } from '../lib/utils';
|
||||
import { formatRial, formatYear, rialToToman, tomanToRial } from '../lib/utils';
|
||||
import Modal from './ui/Modal';
|
||||
import PriceInput from './ui/PriceInput';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
@@ -46,7 +46,7 @@ export default function ServiceTariffModal({ item, onClose }: { item: ServiceIte
|
||||
const opts: { value: number; label: string }[] = [];
|
||||
for (let y = currentYear + 2; y >= currentYear - 5; y--) {
|
||||
if (used.has(y)) continue;
|
||||
opts.push({ value: y, label: y === currentYear ? `${formatNumber(y)} (سال جاری)` : formatNumber(y) });
|
||||
opts.push({ value: y, label: y === currentYear ? `${formatYear(y)} (سال جاری)` : formatYear(y) });
|
||||
}
|
||||
return opts;
|
||||
}, [currentYear, tariffs]);
|
||||
@@ -85,7 +85,7 @@ export default function ServiceTariffModal({ item, onClose }: { item: ServiceIte
|
||||
display: 'flex', gap: 8, padding: '11px 13px', borderRadius: 'var(--r-sm)',
|
||||
background: 'var(--primary-subtle)', fontSize: 12, color: 'var(--text-2)', lineHeight: 1.7,
|
||||
}}>
|
||||
<span>قیمت پایهی سرویس همان تعرفهی سال جاری ({currentYear ? formatNumber(currentYear) : '—'}) است و همهجا از همین استفاده میشود. تعرفهی سالهای دیگر فقط برای صورتحساب همان سال بهکار میرود.</span>
|
||||
<span>قیمت پایهی سرویس همان تعرفهی سال جاری ({currentYear ? formatYear(currentYear) : '—'}) است و همهجا از همین استفاده میشود. تعرفهی سالهای دیگر فقط برای صورتحساب همان سال بهکار میرود.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -131,7 +131,7 @@ export default function ServiceTariffModal({ item, onClose }: { item: ServiceIte
|
||||
background: isCurrent ? 'var(--primary-subtle)' : 'var(--bg)',
|
||||
}}>
|
||||
<span style={{ fontWeight: 700, fontSize: 13, minWidth: 70 }}>
|
||||
سال {formatNumber(t.year)}
|
||||
سال {formatYear(t.year)}
|
||||
{isCurrent && <span className="badge green" style={{ fontSize: 9.5, marginInlineStart: 6 }}><span className="bdot" />جاری</span>}
|
||||
</span>
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
import { useBankAccounts, usePosDevices } from '../hooks/usePaymentMethods';
|
||||
import { formatRial, formatNumber, tomanToRial } from '../lib/utils';
|
||||
import { formatRial, formatNumber, tomanToRial, digitsOnly } from '../lib/utils';
|
||||
|
||||
export type WalletMode = 'charge' | 'withdraw';
|
||||
|
||||
@@ -154,7 +154,7 @@ export default function WalletTransactionModal({ open, balanceRials, submitting,
|
||||
inputMode="numeric"
|
||||
value={amountToman > 0 ? formatNumber(amountToman) : ''}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value.replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06f0)).replace(/[^\d]/g, '');
|
||||
const raw = digitsOnly(e.target.value);
|
||||
setAmountToman(raw ? parseInt(raw, 10) : 0);
|
||||
}}
|
||||
placeholder="مبلغ دلخواه (تومان)"
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { TrashIcon } from '@heroicons/react/24/outline';
|
||||
import Modal from '../ui/Modal';
|
||||
import SearchableSelect from '../ui/SearchableSelect';
|
||||
import { formatRial } from '../../lib/utils';
|
||||
import { formatRial, digitsOnly } from '../../lib/utils';
|
||||
import type { InventoryItem, InventoryPackage, PackagePayload } from '../../hooks/useInventory';
|
||||
|
||||
interface Props {
|
||||
@@ -89,7 +89,7 @@ export default function AddPackageModal({ open, editing, items, saving, onClose,
|
||||
<div>
|
||||
<label className="field-label">مقدار</label>
|
||||
<div className="field">
|
||||
<input value={amount} inputMode="numeric" onChange={(e) => setAmount(e.target.value.replace(/[^0-9]/g, ''))} placeholder="1" />
|
||||
<input value={amount} inputMode="numeric" onChange={(e) => setAmount(digitsOnly(e.target.value))} placeholder="1" />
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn ghost" style={{ justifyContent: 'center', height: 46 }} onClick={addLine} disabled={items.length === 0}>
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import Modal from '../ui/Modal';
|
||||
import SearchableSelect from '../ui/SearchableSelect';
|
||||
import DigitInput from '../ui/DigitInput';
|
||||
import { BANK_OPTIONS } from './banks';
|
||||
import {
|
||||
useCreatePos,
|
||||
@@ -85,11 +86,11 @@ export default function PosFormModal({
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">شماره ترمینال</label>
|
||||
<input className="input" value={terminalNumber} onChange={(e) => setTerminalNumber(e.target.value)} placeholder="شماره ترمینال" />
|
||||
<DigitInput className="input" value={terminalNumber} onChange={setTerminalNumber} placeholder="شماره ترمینال" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">شماره حساب</label>
|
||||
<input className="input" value={accountNumber} onChange={(e) => setAccountNumber(e.target.value)} placeholder="شماره حساب" />
|
||||
<DigitInput className="input" value={accountNumber} onChange={setAccountNumber} placeholder="شماره حساب" />
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { useState } from 'react';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import PriceInput from './PriceInput';
|
||||
|
||||
/** پوشش حالت واقعی: مقدار توسط والد نگه داشته میشود (controlled). */
|
||||
function Controlled({ initial = 0, ...rest }: { initial?: number } & Record<string, unknown>) {
|
||||
const [value, setValue] = useState(initial);
|
||||
return (
|
||||
<>
|
||||
<PriceInput value={value} onChange={setValue} {...rest} />
|
||||
<span data-testid="value">{value}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const input = () => screen.getByRole('textbox') as HTMLInputElement;
|
||||
const emitted = () => screen.getByTestId('value').textContent;
|
||||
|
||||
describe('PriceInput', () => {
|
||||
it('رقم فارسی را میپذیرد و عدد لاتین میدهد', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '۸۵۰۰۰' } });
|
||||
|
||||
expect(emitted()).toBe('85000');
|
||||
expect(input().value).toBe('۸۵٬۰۰۰');
|
||||
});
|
||||
|
||||
it('رقم عربی را میپذیرد', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '٢٥٠' } });
|
||||
|
||||
expect(emitted()).toBe('250');
|
||||
});
|
||||
|
||||
it('پیست با واحد و جداکننده پاکسازی میشود', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '۸۵,۰۰۰ تومان' } });
|
||||
|
||||
expect(emitted()).toBe('85000');
|
||||
});
|
||||
|
||||
it('صفرِ تایپشده حفظ میشود و به خالی تبدیل نمیشود', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '۰' } });
|
||||
|
||||
expect(input().value).toBe('۰');
|
||||
expect(emitted()).toBe('0');
|
||||
});
|
||||
|
||||
it('پاککردن فیلد ⇒ خالی و مقدار صفر', () => {
|
||||
render(<Controlled initial={5000} />);
|
||||
fireEvent.change(input(), { target: { value: '' } });
|
||||
|
||||
expect(input().value).toBe('');
|
||||
expect(emitted()).toBe('0');
|
||||
});
|
||||
|
||||
it('مقدار اولیه صفر ⇒ فیلد خالی (نه ۰)', () => {
|
||||
render(<Controlled initial={0} />);
|
||||
expect(input().value).toBe('');
|
||||
});
|
||||
|
||||
it('min حین تایپ اعمال نمیشود ولی روی blur اعمال میشود', () => {
|
||||
render(<Controlled min={100} />);
|
||||
fireEvent.change(input(), { target: { value: '۵' } });
|
||||
expect(emitted()).toBe('5');
|
||||
|
||||
fireEvent.blur(input());
|
||||
expect(emitted()).toBe('100');
|
||||
expect(input().value).toBe('۱۰۰');
|
||||
});
|
||||
|
||||
it('max روی blur اعمال میشود', () => {
|
||||
render(<Controlled max={1000} />);
|
||||
fireEvent.change(input(), { target: { value: '۵۰۰۰' } });
|
||||
fireEvent.blur(input());
|
||||
|
||||
expect(emitted()).toBe('1000');
|
||||
});
|
||||
|
||||
it('فیلد خالی روی blur به min پرت نمیشود', () => {
|
||||
render(<Controlled min={100} />);
|
||||
fireEvent.blur(input());
|
||||
|
||||
expect(input().value).toBe('');
|
||||
expect(emitted()).toBe('0');
|
||||
});
|
||||
|
||||
it('حروف نامعتبر حذف میشوند و هرگز NaN نمیدهد', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: 'ابج' } });
|
||||
|
||||
expect(input().value).toBe('');
|
||||
expect(emitted()).toBe('0');
|
||||
expect(emitted()).not.toContain('NaN');
|
||||
});
|
||||
|
||||
it('latin ارقام لاتین با کاما نمایش میدهد', () => {
|
||||
render(<Controlled latin />);
|
||||
fireEvent.change(input(), { target: { value: '۱۲۰۰' } });
|
||||
|
||||
expect(input().value).toBe('1,200');
|
||||
});
|
||||
|
||||
it('suffix واحد را کنار فیلد نشان میدهد', () => {
|
||||
render(<Controlled suffix="تومان" />);
|
||||
expect(screen.getByText('تومان')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('تغییر مقدار از بیرون متن فیلد را همگام میکند', () => {
|
||||
const { rerender } = render(<PriceInput value={1000} onChange={vi.fn()} />);
|
||||
expect(input().value).toBe('۱٬۰۰۰');
|
||||
|
||||
rerender(<PriceInput value={0} onChange={vi.fn()} />);
|
||||
expect(input().value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { toEnglishDigits } from '../../lib/utils';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { digitsOnly, parseUserNumber } from '../../lib/utils';
|
||||
|
||||
interface PriceInputProps {
|
||||
value: number | '';
|
||||
@@ -9,15 +9,30 @@ interface PriceInputProps {
|
||||
style?: React.CSSProperties;
|
||||
disabled?: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
/** نمایش ارقام لاتین با جداکنندهٔ کاما (پیشفرض: فارسی). */
|
||||
latin?: boolean;
|
||||
/** واحد نمایشی داخل فیلد، مثلاً «تومان». */
|
||||
suffix?: string;
|
||||
}
|
||||
|
||||
function formatDisplay(num: number, latin: boolean): string {
|
||||
if (num === 0) return '';
|
||||
return new Intl.NumberFormat(latin ? 'en-US' : 'fa-IR').format(num);
|
||||
}
|
||||
|
||||
/** مقدار prop را به متن نمایشی تبدیل میکند؛ صفر و خالی هر دو فیلد خالی هستند. */
|
||||
function textFromValue(value: number | '', latin: boolean): string {
|
||||
const num = value === '' ? 0 : Number(value);
|
||||
return Number.isFinite(num) && num !== 0 ? formatDisplay(num, latin) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* ورودی مبلغ: ارقام فارسی/عربی، جداکننده و واحد چسبیده به عدد را میپذیرد (پیست
|
||||
* «۸۵,۰۰۰ تومان» ⇒ 85000) و همیشه یک عدد معتبر — هرگز NaN — به بالا میدهد.
|
||||
*
|
||||
* متن فیلد state مستقل است تا «۰ تایپشده» از «خالی» تفکیک شود؛ محدودکردن به بازهٔ
|
||||
* min/max فقط روی blur اعمال میشود تا رقم اول تایپ به مرز نپرد.
|
||||
*/
|
||||
export default function PriceInput({
|
||||
value,
|
||||
onChange,
|
||||
@@ -26,31 +41,58 @@ export default function PriceInput({
|
||||
style,
|
||||
disabled,
|
||||
min = 0,
|
||||
max,
|
||||
latin = false,
|
||||
suffix,
|
||||
}: PriceInputProps) {
|
||||
const [display, setDisplay] = useState(() => (value !== '' && value > 0 ? formatDisplay(value, latin) : ''));
|
||||
const [text, setText] = useState(() => textFromValue(value, latin));
|
||||
const textRef = useRef(text);
|
||||
textRef.current = text;
|
||||
|
||||
// فقط وقتی مقدار از بیرون عوض شده باشد (reset فرم، بارگذاری داده) متن را بازنویسی کن.
|
||||
useEffect(() => {
|
||||
setDisplay(value !== '' && Number(value) > 0 ? formatDisplay(Number(value), latin) : '');
|
||||
const shown = parseUserNumber(textRef.current) ?? 0;
|
||||
const incoming = value === '' ? 0 : Number(value);
|
||||
if (shown !== incoming) setText(textFromValue(value, latin));
|
||||
}, [value, latin]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const raw = toEnglishDigits(e.target.value).replace(/[^0-9]/g, '');
|
||||
const num = raw === '' ? 0 : Math.max(min, parseInt(raw, 10));
|
||||
const raw = digitsOnly(e.target.value);
|
||||
const num = parseUserNumber(raw) ?? 0;
|
||||
setText(raw === '' ? '' : formatDisplay(num, latin));
|
||||
onChange(num);
|
||||
setDisplay(num > 0 ? formatDisplay(num, latin) : '');
|
||||
};
|
||||
|
||||
return (
|
||||
const handleBlur = () => {
|
||||
if (text === '') return;
|
||||
const num = parseUserNumber(text) ?? 0;
|
||||
const clamped = Math.min(max ?? Infinity, Math.max(min, num));
|
||||
if (clamped !== num) {
|
||||
setText(formatDisplay(clamped, latin));
|
||||
onChange(clamped);
|
||||
}
|
||||
};
|
||||
|
||||
const input = (
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
value={display}
|
||||
value={text}
|
||||
onChange={handleChange}
|
||||
onBlur={handleBlur}
|
||||
placeholder={placeholder}
|
||||
className={className}
|
||||
style={{ textAlign: 'left', direction: 'ltr', ...style }}
|
||||
style={suffix ? { textAlign: 'left', direction: 'ltr', border: 'none', background: 'transparent', outline: 'none', flex: 1, minWidth: 0, padding: 0, ...style } : { textAlign: 'left', direction: 'ltr', ...style }}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
|
||||
if (!suffix) return input;
|
||||
|
||||
return (
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6, width: '100%' }}>
|
||||
{input}
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)', flexShrink: 0 }}>{suffix}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user