feat(settings): complete remaining settings tabs (account, tags, turns)
Fill the three previously-placeholder settings sections so every menu item is now a real page inside the settings shell: - حساب کاربری: new authenticated POST /api/v1/user/change-password (verifies current password, ≥8 chars, must differ) + account page with a profile summary and change-password form. - برچسبها: new per-tenant TenantTag domain (entity/repo/controller + migration) with tenant-scoped CRUD at /api/v1/tenant-tag(s), plus a tags management page (list + color + add/edit/delete). - مدیریت نوبت دهی: export the existing WeeklyScheduleTab from DoctorDetailPage and reuse it in a standalone AppointmentSettingsPage (current doctor's uuid + addresses). Wire all three menu entries to their routes. Backend covered by PHPUnit (change-password, tenant-tag CRUD + ownership); FE covered by Vitest. API docs updated (auth.md, tag.md). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -50,6 +50,9 @@ import SmsWalletPage from './pages/SmsWalletPage';
|
||||
import MySecretariesPage from './pages/MySecretariesPage';
|
||||
import AdminSubscriptionPage from './pages/AdminSubscriptionPage';
|
||||
import SettingsMenuPage from './pages/SettingsMenuPage';
|
||||
import AccountSettingsPage from './pages/AccountSettingsPage';
|
||||
import TagsSettingsPage from './pages/TagsSettingsPage';
|
||||
import AppointmentSettingsPage from './pages/AppointmentSettingsPage';
|
||||
import PaymentSuccessPage from './pages/PaymentSuccessPage';
|
||||
import PwaInstallBanner from './components/ui/PwaInstallBanner';
|
||||
|
||||
@@ -195,6 +198,9 @@ export default function App() {
|
||||
{/* فاز ۲ — دکتر / کلینیک */}
|
||||
<Route path="staff" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><StaffPage /></RoleRoute>} />
|
||||
<Route path="settings-menu" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><SettingsMenuPage /></RoleRoute>} />
|
||||
<Route path="account-settings" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']}><AccountSettingsPage /></RoleRoute>} />
|
||||
<Route path="tags-settings" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><TagsSettingsPage /></RoleRoute>} />
|
||||
<Route path="appointment-settings" element={<RoleRoute roles={['doctor']} blockClinicScope><AppointmentSettingsPage /></RoleRoute>} />
|
||||
<Route path="subscription" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><SubscriptionPage /></RoleRoute>} />
|
||||
<Route path="subscription/success" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><PaymentSuccessPage /></RoleRoute>} />
|
||||
<Route path="clinic-services" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClinicServicesPage /></RoleRoute>} />
|
||||
|
||||
@@ -26,14 +26,14 @@ describe('SettingsLayout', () => {
|
||||
expect(active).toHaveAttribute('href', '/admin/subscription');
|
||||
});
|
||||
|
||||
it('renders not-yet-implemented items as disabled placeholders', () => {
|
||||
it('renders every menu item as a navigable link', () => {
|
||||
renderWithProviders(
|
||||
<SettingsLayout active="subscription"><div /></SettingsLayout>,
|
||||
);
|
||||
// "حساب کاربری" has no route → disabled button with "بهزودی"
|
||||
const account = screen.getByText('حساب کاربری').closest('button');
|
||||
expect(account).toBeDisabled();
|
||||
expect(screen.getAllByText('بهزودی').length).toBeGreaterThan(0);
|
||||
// all items are now wired to a route
|
||||
expect(screen.getByText('مدیریت نوبت دهی').closest('a')).toHaveAttribute('href', '/admin/appointment-settings');
|
||||
expect(screen.getByText('برچسبها').closest('a')).toHaveAttribute('href', '/admin/tags-settings');
|
||||
expect(screen.queryByText('بهزودی')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters the menu by the search query', () => {
|
||||
|
||||
@@ -20,15 +20,15 @@ export type SettingsMenuItem = {
|
||||
export const SETTINGS_MENU: SettingsMenuItem[] = [
|
||||
{ key: 'subscription', label: 'خرید اشتراک', icon: CreditCardIcon, to: '/admin/subscription' },
|
||||
{ key: 'doctor', label: 'مدیریت پزشک', icon: UserIcon, to: '/admin/profile' },
|
||||
{ key: 'appointment', label: 'مدیریت نوبت دهی', icon: CalendarDaysIcon },
|
||||
{ key: 'appointment', label: 'مدیریت نوبت دهی', icon: CalendarDaysIcon, to: '/admin/appointment-settings' },
|
||||
{ key: 'clinic', label: 'مدیریت مطب', icon: BuildingOffice2Icon, to: '/admin/my-clinic' },
|
||||
{ key: 'services', label: 'خدمات', icon: WrenchScrewdriverIcon, to: '/admin/clinic-services' },
|
||||
{ key: 'payment', label: 'مدیریت پرداخت', icon: BanknotesIcon, to: '/admin/my-financial' },
|
||||
{ key: 'secretary', label: 'مدیریت منشی', icon: UsersIcon, to: '/admin/my-secretaries' },
|
||||
{ key: 'insurance', label: 'مدیریت بیمه', icon: ShieldCheckIcon, to: '/admin/insurance-pricing' },
|
||||
{ key: 'tags', label: 'برچسبها', icon: TagIcon },
|
||||
{ key: 'tags', label: 'برچسبها', icon: TagIcon, to: '/admin/tags-settings' },
|
||||
{ key: 'sms', label: 'پیامکها', icon: ChatBubbleLeftRightIcon, to: '/admin/sms-wallet' },
|
||||
{ key: 'account', label: 'حساب کاربری', icon: UserCircleIcon },
|
||||
{ key: 'account', label: 'حساب کاربری', icon: UserCircleIcon, to: '/admin/account-settings' },
|
||||
];
|
||||
|
||||
// ── Shared item styling ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/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 AccountSettingsPage from './AccountSettingsPage';
|
||||
|
||||
const post = api.post as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
post.mockReset();
|
||||
post.mockResolvedValue({ success: true, data: { message: 'ok' } });
|
||||
useAuthStore.setState({ primaryRole: 'doctor', userName: 'دکتر امینی', context: null });
|
||||
});
|
||||
|
||||
describe('AccountSettingsPage', () => {
|
||||
it('shows the profile summary and change-password form in the settings shell', () => {
|
||||
renderWithProviders(<AccountSettingsPage />, { route: '/admin/account-settings' });
|
||||
expect(screen.getByText('خرید اشتراک')).toBeInTheDocument(); // shell menu
|
||||
expect(screen.getAllByText('دکتر امینی').length).toBeGreaterThan(0); // profile name
|
||||
expect(screen.getAllByText('تغییر رمز عبور').length).toBeGreaterThan(0); // heading + button
|
||||
});
|
||||
|
||||
it('submits the change-password request with current + new password', async () => {
|
||||
renderWithProviders(<AccountSettingsPage />, { route: '/admin/account-settings' });
|
||||
|
||||
fireEvent.change(screen.getByLabelText('رمز فعلی'), { target: { value: 'oldpass12' } });
|
||||
fireEvent.change(screen.getByLabelText('رمز جدید'), { target: { value: 'newpass34' } });
|
||||
fireEvent.change(screen.getByLabelText('تکرار رمز جدید'), { target: { value: 'newpass34' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'تغییر رمز عبور' }));
|
||||
|
||||
await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/user/change-password', {
|
||||
current_password: 'oldpass12', new_password: 'newpass34',
|
||||
}));
|
||||
});
|
||||
|
||||
it('blocks submit when the confirmation does not match', async () => {
|
||||
renderWithProviders(<AccountSettingsPage />, { route: '/admin/account-settings' });
|
||||
|
||||
fireEvent.change(screen.getByLabelText('رمز فعلی'), { target: { value: 'oldpass12' } });
|
||||
fireEvent.change(screen.getByLabelText('رمز جدید'), { target: { value: 'newpass34' } });
|
||||
fireEvent.change(screen.getByLabelText('تکرار رمز جدید'), { target: { value: 'different' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'تغییر رمز عبور' }));
|
||||
|
||||
expect(await screen.findByText('تکرار رمز مطابقت ندارد')).toBeInTheDocument();
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { UserCircleIcon, EyeIcon, EyeSlashIcon, LockClosedIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import SettingsLayout from '../components/layout/SettingsLayout';
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
admin: 'مدیر', clinic: 'کلینیک', doctor: 'پزشک',
|
||||
secretary: 'منشی', representation: 'نماینده', user: 'کاربر',
|
||||
};
|
||||
|
||||
const schema = z.object({
|
||||
current_password: z.string().min(1, 'رمز فعلی الزامی است'),
|
||||
new_password: z.string().min(8, 'رمز جدید باید حداقل ۸ کاراکتر باشد'),
|
||||
confirm: z.string().min(1, 'تکرار رمز الزامی است'),
|
||||
}).refine((d) => d.new_password === d.confirm, { path: ['confirm'], message: 'تکرار رمز مطابقت ندارد' })
|
||||
.refine((d) => d.new_password !== d.current_password, { path: ['new_password'], message: 'رمز جدید نباید با رمز فعلی یکسان باشد' });
|
||||
|
||||
type Form = z.infer<typeof schema>;
|
||||
|
||||
/** حساب کاربری — profile summary + change-password form, inside the settings shell. */
|
||||
export default function AccountSettingsPage() {
|
||||
const { userName, primaryRole, context } = useAuthStore();
|
||||
const [show, setShow] = useState<{ cur: boolean; next: boolean }>({ cur: false, next: false });
|
||||
|
||||
const form = useForm<Form>({ resolver: zodResolver(schema) });
|
||||
|
||||
const changePassword = useMutation({
|
||||
mutationFn: (d: Form) => api.post('/api/v1/user/change-password', {
|
||||
current_password: d.current_password,
|
||||
new_password: d.new_password,
|
||||
}),
|
||||
onSuccess: () => { toast.success('رمز عبور با موفقیت تغییر یافت'); form.reset(); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const rows: [string, string][] = [
|
||||
['نام', userName || '—'],
|
||||
['نقش', primaryRole ? (ROLE_LABELS[primaryRole] ?? primaryRole) : '—'],
|
||||
['محیط فعلی', context?.name || '—'],
|
||||
];
|
||||
|
||||
return (
|
||||
<SettingsLayout active="account">
|
||||
<div className="fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 620 }}>
|
||||
<h1 className="section-title">حساب کاربری</h1>
|
||||
|
||||
{/* Profile summary */}
|
||||
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
|
||||
<div style={{ width: 48, height: 48, borderRadius: '50%', background: 'var(--primary-soft)', display: 'grid', placeItems: 'center' }}>
|
||||
<UserCircleIcon style={{ width: 28, color: 'var(--primary)' }} />
|
||||
</div>
|
||||
<div style={{ fontWeight: 700, fontSize: 16 }}>{userName || 'کاربر'}</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label} style={{ display: 'flex', justifyContent: 'space-between', padding: '9px 0', borderTop: '1px solid var(--border)' }}>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-3)' }}>{label}</span>
|
||||
<span style={{ fontSize: 13.5, color: 'var(--text)', fontWeight: 600 }}>{value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Change password */}
|
||||
<form
|
||||
onSubmit={form.handleSubmit((d) => changePassword.mutate(d))}
|
||||
style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<LockClosedIcon style={{ width: 18, color: 'var(--text-2)' }} />
|
||||
<b style={{ fontSize: 15 }}>تغییر رمز عبور</b>
|
||||
</div>
|
||||
|
||||
<PasswordField
|
||||
label="رمز فعلی" show={show.cur} onToggle={() => setShow((s) => ({ ...s, cur: !s.cur }))}
|
||||
register={form.register('current_password')} error={form.formState.errors.current_password?.message}
|
||||
/>
|
||||
<PasswordField
|
||||
label="رمز جدید" show={show.next} onToggle={() => setShow((s) => ({ ...s, next: !s.next }))}
|
||||
register={form.register('new_password')} error={form.formState.errors.new_password?.message}
|
||||
/>
|
||||
<PasswordField
|
||||
label="تکرار رمز جدید" show={show.next} onToggle={() => setShow((s) => ({ ...s, next: !s.next }))}
|
||||
register={form.register('confirm')} error={form.formState.errors.confirm?.message}
|
||||
/>
|
||||
|
||||
<button type="submit" className="btn primary" style={{ alignSelf: 'flex-start', height: 42 }} disabled={changePassword.isPending}>
|
||||
{changePassword.isPending ? 'در حال ذخیره...' : 'تغییر رمز عبور'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</SettingsLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordField({ label, show, onToggle, register, error }: {
|
||||
label: string; show: boolean; onToggle: () => void;
|
||||
register: ReturnType<ReturnType<typeof useForm>['register']>; error?: string;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<label className="field-label">{label}</label>
|
||||
<div className="field" style={{ display: 'flex', alignItems: 'center', ...(error ? { borderColor: 'var(--danger)' } : {}) }}>
|
||||
<input type={show ? 'text' : 'password'} aria-label={label} autoComplete="off" {...register} style={{ flex: 1 }} />
|
||||
<button type="button" aria-label={show ? 'پنهانکردن رمز' : 'نمایش رمز'} onClick={onToggle} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-3)', display: 'grid', placeItems: 'center' }}>
|
||||
{show ? <EyeSlashIcon style={{ width: 17 }} /> : <EyeIcon style={{ width: 17 }} />}
|
||||
</button>
|
||||
</div>
|
||||
{error && <span className="field-error">{error}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/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 AppointmentSettingsPage from './AppointmentSettingsPage';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
get.mockReset();
|
||||
useAuthStore.setState({ primaryRole: 'doctor', doctorUuid: 'doc-1', dbUuid: 'doc-1' });
|
||||
get.mockImplementation((url: string) => {
|
||||
if (url.includes('/doctor/doc-1')) return Promise.resolve({ success: true, data: { data: { address: [] } } });
|
||||
if (url.includes('/weekly-schedule')) return Promise.resolve({ success: true, data: {} });
|
||||
return Promise.resolve({ success: true, data: {} });
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppointmentSettingsPage', () => {
|
||||
it('renders the weekly-schedule section inside the settings shell', async () => {
|
||||
renderWithProviders(<AppointmentSettingsPage />, { route: '/admin/appointment-settings' });
|
||||
// appears in the shell menu and as the page heading
|
||||
expect((await screen.findAllByText('مدیریت نوبت دهی')).length).toBeGreaterThan(1);
|
||||
expect(screen.getByText('خرید اشتراک')).toBeInTheDocument(); // shell menu
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import SettingsLayout from '../components/layout/SettingsLayout';
|
||||
import { WeeklyScheduleTab, type AddressData } from './DoctorDetailPage';
|
||||
|
||||
/**
|
||||
* مدیریت نوبت دهی — the doctor's weekly booking schedule as a standalone
|
||||
* settings section. Reuses the WeeklyScheduleTab editor (also shown in the
|
||||
* doctor profile) with the current doctor's uuid and addresses.
|
||||
*/
|
||||
export default function AppointmentSettingsPage() {
|
||||
const doctorUuid = useAuthStore((s) => s.doctorUuid);
|
||||
const dbUuid = useAuthStore((s) => s.dbUuid);
|
||||
const uuid = doctorUuid ?? dbUuid ?? undefined;
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['doctor-detail', uuid, 'appointment-settings'],
|
||||
queryFn: () => api.get<ApiResponse<any>>(`/api/v1/doctor/${uuid}`),
|
||||
enabled: !!uuid,
|
||||
});
|
||||
|
||||
const doctor = (data?.data as any)?.data ?? data?.data;
|
||||
const addresses: AddressData[] = doctor?.address ?? [];
|
||||
|
||||
return (
|
||||
<SettingsLayout active="appointment">
|
||||
<div className="fade-in">
|
||||
<h1 className="section-title" style={{ marginBottom: 16 }}>مدیریت نوبت دهی</h1>
|
||||
|
||||
{!uuid ? (
|
||||
<div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>
|
||||
این بخش فقط برای پزشک در دسترس است.
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<div style={{ padding: 16, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : (
|
||||
<WeeklyScheduleTab doctorUuid={uuid} addresses={addresses} />
|
||||
)}
|
||||
</div>
|
||||
</SettingsLayout>
|
||||
);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ interface ProvinceOpt { id: number; uuid: string; name: string; }
|
||||
interface CityOpt { id: number; uuid: string; name: string; }
|
||||
interface ImageFileData { fid: number; uuid: string; url: string; filename: string; filemime: string; filesize: number; }
|
||||
|
||||
interface AddressData {
|
||||
export interface AddressData {
|
||||
id: string; uuid: string;
|
||||
type: 'personal' | 'clinic';
|
||||
clinic_id: string | null;
|
||||
@@ -1228,7 +1228,7 @@ function SessionEditor({ session, onChange, onRemove, addresses }: {
|
||||
|
||||
// ── Weekly Schedule Tab ────────────────────────────────────────────────────
|
||||
|
||||
function WeeklyScheduleTab({ doctorUuid, addresses, readOnly = false }: { doctorUuid: string; addresses: AddressData[]; readOnly?: boolean }) {
|
||||
export function WeeklyScheduleTab({ doctorUuid, addresses, readOnly = false }: { doctorUuid: string; addresses: AddressData[]; readOnly?: boolean }) {
|
||||
const qc = useQueryClient();
|
||||
const [scheduleMap, setScheduleMap] = useState<NewScheduleMap>(EMPTY_NEW_SCHEDULE);
|
||||
const [scheduleUuid, setScheduleUuid] = useState<string | null>(null);
|
||||
|
||||
@@ -12,11 +12,10 @@ describe('SettingsMenuPage', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('links implemented sections and disables the rest', () => {
|
||||
it('links every implemented section', () => {
|
||||
renderWithProviders(<SettingsMenuPage />);
|
||||
// implemented → anchor with href
|
||||
expect(screen.getByText('خرید اشتراک').closest('a')).toHaveAttribute('href', '/admin/subscription');
|
||||
// not implemented → disabled button
|
||||
expect(screen.getByText('مدیریت نوبت دهی').closest('button')).toBeDisabled();
|
||||
expect(screen.getByText('مدیریت نوبت دهی').closest('a')).toHaveAttribute('href', '/admin/appointment-settings');
|
||||
expect(screen.getByText('حساب کاربری').closest('a')).toHaveAttribute('href', '/admin/account-settings');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/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 TagsSettingsPage from './TagsSettingsPage';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
const post = api.post as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
get.mockReset(); post.mockReset();
|
||||
get.mockResolvedValue({ success: true, data: [
|
||||
{ uuid: 't1', name: 'فوری', color: '#FF0000', active: true },
|
||||
{ uuid: 't2', name: 'پیگیری', color: '#00AA00', active: false },
|
||||
] });
|
||||
post.mockResolvedValue({ success: true, data: { uuid: 't3', name: 'جدید', color: '#5559CE', active: true } });
|
||||
});
|
||||
|
||||
describe('TagsSettingsPage', () => {
|
||||
it('lists tenant tags in the settings shell', async () => {
|
||||
renderWithProviders(<TagsSettingsPage />, { route: '/admin/tags-settings' });
|
||||
expect(await screen.findByText('فوری')).toBeInTheDocument();
|
||||
expect(screen.getByText('پیگیری')).toBeInTheDocument();
|
||||
expect(screen.getByText('خرید اشتراک')).toBeInTheDocument(); // shell menu
|
||||
});
|
||||
|
||||
it('creates a tag through the modal', async () => {
|
||||
renderWithProviders(<TagsSettingsPage />, { route: '/admin/tags-settings' });
|
||||
await screen.findByText('فوری');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /برچسب جدید/ }));
|
||||
fireEvent.change(screen.getByPlaceholderText('مثلاً: فوری'), { target: { value: 'اورژانس' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
|
||||
await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/tenant-tag', expect.objectContaining({ name: 'اورژانس' })));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { PlusIcon, PencilIcon, TrashIcon, TagIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import ConfirmDialog from '../components/ui/ConfirmDialog';
|
||||
import SettingsLayout from '../components/layout/SettingsLayout';
|
||||
|
||||
interface TenantTag { uuid: string; name: string; color: string; active: boolean }
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, 'نام برچسب الزامی است'),
|
||||
color: z.string().regex(/^#([0-9a-fA-F]{6})$/, 'رنگ نامعتبر است'),
|
||||
});
|
||||
type Form = z.infer<typeof schema>;
|
||||
|
||||
const EMPTY: TenantTag[] = [];
|
||||
|
||||
/** برچسبها — per-tenant tag management inside the settings shell. */
|
||||
export default function TagsSettingsPage() {
|
||||
const qc = useQueryClient();
|
||||
const [modal, setModal] = useState<'create' | TenantTag | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<TenantTag | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery<ApiResponse<TenantTag[]>>({
|
||||
queryKey: ['tenant-tags'],
|
||||
queryFn: () => api.get('/api/v1/tenant-tags'),
|
||||
});
|
||||
const tags = data?.data ?? EMPTY;
|
||||
|
||||
const form = useForm<Form>({ resolver: zodResolver(schema), defaultValues: { name: '', color: '#5559CE' } });
|
||||
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ['tenant-tags'] });
|
||||
|
||||
const createTag = useMutation({
|
||||
mutationFn: (d: Form) => api.post('/api/v1/tenant-tag', d),
|
||||
onSuccess: () => { invalidate(); setModal(null); form.reset({ name: '', color: '#5559CE' }); toast.success('برچسب ایجاد شد'); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
const editTag = useMutation({
|
||||
mutationFn: ({ uuid, d }: { uuid: string; d: Form }) => api.patch(`/api/v1/tenant-tag/${uuid}`, d),
|
||||
onSuccess: () => { invalidate(); setModal(null); toast.success('برچسب ویرایش شد'); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
const delTag = useMutation({
|
||||
mutationFn: (uuid: string) => api.delete(`/api/v1/tenant-tag/${uuid}`),
|
||||
onSuccess: () => { invalidate(); setDeleteTarget(null); toast.success('برچسب حذف شد'); },
|
||||
onError: (e: any) => { toast.error(e.message); setDeleteTarget(null); },
|
||||
});
|
||||
|
||||
const openCreate = () => { form.reset({ name: '', color: '#5559CE' }); setModal('create'); };
|
||||
const openEdit = (t: TenantTag) => { form.reset({ name: t.name, color: t.color }); setModal(t); };
|
||||
|
||||
return (
|
||||
<SettingsLayout active="tags">
|
||||
<div className="fade-in">
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, gap: 12, flexWrap: 'wrap' }}>
|
||||
<h1 className="section-title">برچسبها</h1>
|
||||
<button className="btn primary" onClick={openCreate}><PlusIcon style={{ width: 16 }} /> برچسب جدید</button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div style={{ padding: 16, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : tags.length === 0 ? (
|
||||
<div className="card" style={{ padding: '56px 0', textAlign: 'center', color: 'var(--text-3)' }}>
|
||||
<TagIcon style={{ width: 48, margin: '0 auto 14px', display: 'block', opacity: 0.3 }} />
|
||||
<div style={{ fontSize: 14, color: 'var(--text-2)' }}>هنوز برچسبی ثبت نشده است.</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
|
||||
{tags.map((t, i) => (
|
||||
<div key={t.uuid} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
|
||||
borderTop: i === 0 ? 'none' : '1px solid var(--border)', opacity: t.active ? 1 : 0.55,
|
||||
}}>
|
||||
<span style={{ width: 14, height: 14, borderRadius: '50%', background: t.color, flexShrink: 0, border: '1px solid var(--border)' }} />
|
||||
<span style={{ flex: 1, fontWeight: 600, fontSize: 14 }}>{t.name}</span>
|
||||
<span className={`badge ${t.active ? 'green' : 'gray'}`} style={{ fontSize: 11 }}><span className="bdot" />{t.active ? 'فعال' : 'غیرفعال'}</span>
|
||||
<button className="btn sm ghost" aria-label="ویرایش" onClick={() => openEdit(t)} style={{ color: 'var(--text-2)' }}><PencilIcon style={{ width: 15 }} /></button>
|
||||
<button className="btn sm ghost" aria-label="حذف" onClick={() => setDeleteTarget(t)} style={{ color: 'var(--danger)' }}><TrashIcon style={{ width: 15 }} /></button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Modal open={modal !== null} onClose={() => setModal(null)} title={modal === 'create' ? 'برچسب جدید' : 'ویرایش برچسب'}>
|
||||
<form onSubmit={form.handleSubmit((d) => {
|
||||
if (modal === 'create') createTag.mutate(d);
|
||||
else if (modal && typeof modal === 'object') editTag.mutate({ uuid: modal.uuid, d });
|
||||
})} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<label className="field-label">نام برچسب *</label>
|
||||
<div className="field"><input {...form.register('name')} placeholder="مثلاً: فوری" autoFocus /></div>
|
||||
{form.formState.errors.name && <span className="field-error">{form.formState.errors.name.message}</span>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">رنگ</label>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<input type="color" aria-label="رنگ برچسب" value={form.watch('color')} onChange={(e) => form.setValue('color', e.target.value)} style={{ width: 44, height: 38, border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', background: 'none', cursor: 'pointer' }} />
|
||||
<span style={{ fontSize: 13, color: 'var(--text-3)' }}>{form.watch('color')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button type="submit" className="btn primary" disabled={createTag.isPending || editTag.isPending}>ذخیره</button>
|
||||
<button type="button" className="btn" onClick={() => setModal(null)}>انصراف</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleteTarget}
|
||||
title="حذف برچسب"
|
||||
message={`آیا از حذف برچسب «${deleteTarget?.name}» مطمئن هستید؟`}
|
||||
confirmLabel="حذف"
|
||||
onConfirm={() => deleteTarget && delTag.mutate(deleteTarget.uuid)}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
loading={delTag.isPending}
|
||||
/>
|
||||
</SettingsLayout>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user