test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -1,10 +1,10 @@
|
||||
import { Suspense, useEffect } from 'react';
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import axios from 'axios';
|
||||
import { Suspense,useEffect } from 'react';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import { router } from './routes/adminRoutes';
|
||||
import { useAdminAuthStore } from './store/adminAuthStore';
|
||||
import { BASE_DOMAIN } from './services/api';
|
||||
import { useAdminAuthStore } from './store/adminAuthStore';
|
||||
|
||||
function SuspenseFallback() {
|
||||
return (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import Sidebar from './Sidebar';
|
||||
import Topbar from './Topbar';
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter,Route,Routes } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
import Layout from './Layout';
|
||||
import Sidebar from './Sidebar';
|
||||
import Topbar from './Topbar';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn().mockResolvedValue({ data: { success: true, data: { newOrders: 5 } } }),
|
||||
post: vi.fn().mockResolvedValue({ data: { success: true } }),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Admin Panel Navigation Components', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useAdminAuthStore.getState().clearAuth();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('Sidebar component', () => {
|
||||
it('renders navigation group headings and sub-menu items', () => {
|
||||
const setIsOpen = vi.fn();
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
// Verify main group titles
|
||||
expect(screen.getByText('داشبورد و تحلیل داده')).toBeInTheDocument();
|
||||
expect(screen.getByText('سفارشات و مالی')).toBeInTheDocument();
|
||||
expect(screen.getByText('محصولات و کاتالوگ')).toBeInTheDocument();
|
||||
|
||||
// Default active group is 'main', check its items
|
||||
expect(screen.getByText('نمای کلی داشبورد')).toBeInTheDocument();
|
||||
expect(screen.getByText('گزارشات و تحلیل فروش')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('highlights the active route based on current path and auto-expands its group', () => {
|
||||
const setIsOpen = vi.fn();
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/orders']}>
|
||||
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
// Group 'سفارشات و مالی' should be open
|
||||
const ordersLink = screen.getByRole('link', { name: /مدیریت سفارشات/i });
|
||||
expect(ordersLink).toBeInTheDocument();
|
||||
expect(ordersLink.className).toContain('bg-purple-600');
|
||||
});
|
||||
|
||||
it('toggles groups when clicking group accordion buttons', () => {
|
||||
const setIsOpen = vi.fn();
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
// Initially products group items are collapsed
|
||||
expect(screen.queryByText('لیست محصولات')).not.toBeInTheDocument();
|
||||
|
||||
// Click group button
|
||||
const productsGroupBtn = screen.getByRole('button', { name: /محصولات و کاتالوگ/i });
|
||||
fireEvent.click(productsGroupBtn);
|
||||
|
||||
// Now items should be visible
|
||||
expect(screen.getByText('لیست محصولات')).toBeInTheDocument();
|
||||
expect(screen.getByText('دستهبندیهای تخصصی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders badges when fetched from stats API', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: { success: true, data: { newOrders: 7 } },
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/orders']}>
|
||||
<Sidebar isOpen={true} setIsOpen={vi.fn()} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('7')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls setIsOpen(false) when clicking an item link', () => {
|
||||
const setIsOpen = vi.fn();
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const dashboardLink = screen.getByRole('link', { name: /نمای کلی داشبورد/i });
|
||||
fireEvent.click(dashboardLink);
|
||||
expect(setIsOpen).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('renders in collapsed mode correctly with tooltip triggers', () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Sidebar isOpen={false} setIsOpen={vi.fn()} isCollapsed={true} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const aside = screen.getByRole('complementary');
|
||||
expect(aside.className).toContain('lg:w-20');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Topbar component', () => {
|
||||
it('displays user profile info, role, and toggle buttons', () => {
|
||||
useAdminAuthStore.getState().setAuth('test-token', {
|
||||
id: '1',
|
||||
mobile: '09123456789',
|
||||
role: 'SUPER_ADMIN',
|
||||
firstName: 'علی',
|
||||
lastName: 'محمدی',
|
||||
});
|
||||
|
||||
const toggleMenu = vi.fn();
|
||||
const toggleCollapse = vi.fn();
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Topbar toggleMenu={toggleMenu} isCollapsed={false} toggleCollapse={toggleCollapse} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByText('علی محمدی')).toBeInTheDocument();
|
||||
expect(screen.getByText('SUPER_ADMIN')).toBeInTheDocument();
|
||||
|
||||
// Collapse toggle button
|
||||
const collapseBtn = screen.getByRole('button', { name: /کوچک کردن سایدبار/i });
|
||||
fireEvent.click(collapseBtn);
|
||||
expect(toggleCollapse).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Mobile menu button
|
||||
const mobileBtn = screen.getByRole('button', { name: /باز کردن منو/i });
|
||||
fireEvent.click(mobileBtn);
|
||||
expect(toggleMenu).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('filters searchable pages with live autocomplete dropdown', async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Topbar toggleMenu={vi.fn()} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('جستجوی سریع در بخشهای پنل...');
|
||||
fireEvent.change(searchInput, { target: { value: 'سفارش' } });
|
||||
|
||||
expect(await screen.findByText('مدیریت سفارشات مشتریان')).toBeInTheDocument();
|
||||
|
||||
// Click the search result item
|
||||
fireEvent.click(screen.getByText('مدیریت سفارشات مشتریان'));
|
||||
expect(screen.queryByText('مدیریت سفارشات مشتریان')).not.toBeInTheDocument();
|
||||
expect(searchInput).toHaveValue('');
|
||||
});
|
||||
|
||||
it('handles user menu dropdown and logout trigger', async () => {
|
||||
useAdminAuthStore.getState().setAuth('test-token', {
|
||||
id: 'admin-1',
|
||||
mobile: '09123456789',
|
||||
role: 'ADMIN',
|
||||
firstName: 'مدیر',
|
||||
lastName: 'سیستم',
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Topbar toggleMenu={vi.fn()} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
// Click profile button to open dropdown
|
||||
const profileBtn = screen.getByText('مدیر سیستم').closest('button');
|
||||
expect(profileBtn).not.toBeNull();
|
||||
fireEvent.click(profileBtn!);
|
||||
|
||||
expect(screen.getByText('مرکز مانیتورینگ')).toBeInTheDocument();
|
||||
expect(screen.getByText('خروج از حساب')).toBeInTheDocument();
|
||||
|
||||
// Click logout
|
||||
const logoutBtn = screen.getByText('خروج از حساب');
|
||||
fireEvent.click(logoutBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/logout');
|
||||
expect(useAdminAuthStore.getState().isAuthenticated).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Layout integration', () => {
|
||||
it('integrates Sidebar, Topbar and Outlet with collapse toggling and persistence', () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/test']}>
|
||||
<Routes>
|
||||
<Route path="/" element={<Layout />}>
|
||||
<Route path="test" element={<div>Nested Content View</div>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Nested Content View')).toBeInTheDocument();
|
||||
expect(screen.getByRole('complementary')).toBeInTheDocument();
|
||||
|
||||
// Toggle sidebar collapse
|
||||
const collapseBtn = screen.getByRole('button', { name: /کوچک کردن سایدبار/i });
|
||||
fireEvent.click(collapseBtn);
|
||||
expect(localStorage.getItem('canina_admin_sidebar_collapsed')).toBe('true');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { render,screen,waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter,Route,Routes } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
import type { AdminUser } from '../types/admin';
|
||||
import ProtectedRoute from './ProtectedRoute';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('ProtectedRoute Guard Component', () => {
|
||||
const superAdminUser: AdminUser = {
|
||||
id: 'user-1',
|
||||
mobile: '09120000000',
|
||||
role: 'SUPER_ADMIN',
|
||||
};
|
||||
|
||||
const regularAdminUser: AdminUser = {
|
||||
id: 'user-2',
|
||||
mobile: '09121111111',
|
||||
role: 'ADMIN',
|
||||
};
|
||||
|
||||
const customerUser: AdminUser = {
|
||||
id: 'user-3',
|
||||
mobile: '09122222222',
|
||||
role: 'CUSTOMER',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useAdminAuthStore.getState().clearAuth();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
const renderWithRouter = () => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/admin/dashboard']}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login Page</div>} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/admin/dashboard" element={<div>Admin Dashboard Content</div>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders protected child content immediately when already authenticated with ADMIN role', async () => {
|
||||
useAdminAuthStore.getState().setAuth('valid-token', regularAdminUser);
|
||||
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders protected child content immediately when authenticated with SUPER_ADMIN role', async () => {
|
||||
useAdminAuthStore.getState().setAuth('valid-token', superAdminUser);
|
||||
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('redirects to /login if user is authenticated but does not have ADMIN or SUPER_ADMIN role', async () => {
|
||||
useAdminAuthStore.getState().setAuth('valid-token', customerUser);
|
||||
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Login Page')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Admin Dashboard Content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('redirects to /login when completely unauthenticated (no token, no user)', async () => {
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Login Page')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Admin Dashboard Content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('refreshes token successfully via /auth/refresh when accessToken exists but state is unauthenticated', async () => {
|
||||
useAdminAuthStore.setState({
|
||||
accessToken: 'stale-token',
|
||||
isAuthenticated: false,
|
||||
adminUser: null,
|
||||
});
|
||||
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
accessToken: 'fresh-token',
|
||||
user: regularAdminUser,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/refresh');
|
||||
expect(useAdminAuthStore.getState().accessToken).toBe('fresh-token');
|
||||
expect(useAdminAuthStore.getState().isAuthenticated).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to /users/profile when /auth/refresh fails, and succeeds if profile is valid', async () => {
|
||||
useAdminAuthStore.setState({
|
||||
accessToken: 'persisted-token',
|
||||
isAuthenticated: false,
|
||||
adminUser: null,
|
||||
});
|
||||
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('Refresh failed'));
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: superAdminUser,
|
||||
},
|
||||
});
|
||||
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
|
||||
expect(api.get).toHaveBeenCalledWith('/users/profile');
|
||||
expect(useAdminAuthStore.getState().isAuthenticated).toBe(true);
|
||||
});
|
||||
|
||||
it('clears auth and redirects to /login when both refresh and profile validation fail', async () => {
|
||||
useAdminAuthStore.setState({
|
||||
accessToken: 'invalid-token',
|
||||
isAuthenticated: false,
|
||||
adminUser: null,
|
||||
});
|
||||
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('Refresh failed'));
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error('Profile failed'));
|
||||
|
||||
renderWithRouter();
|
||||
|
||||
expect(await screen.findByText('Login Page')).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(useAdminAuthStore.getState().isAuthenticated).toBe(false);
|
||||
expect(useAdminAuthStore.getState().accessToken).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { Navigate,Outlet } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
import type { ApiResponse, AuthResponseData, AdminUser } from '../types/admin';
|
||||
import type { AdminUser,ApiResponse,AuthResponseData } from '../types/admin';
|
||||
|
||||
export default function ProtectedRoute() {
|
||||
const { isAuthenticated, accessToken, setAuth, clearAuth } = useAdminAuthStore();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, ReactNode, ErrorInfo } from 'react';
|
||||
import { AlertCircle, RefreshCw, Home } from 'lucide-react';
|
||||
import { AlertCircle,Home,RefreshCw } from 'lucide-react';
|
||||
import { Component,type ErrorInfo,type ReactNode } from 'react';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
|
||||
@@ -1,43 +1,43 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
LayoutDashboard,
|
||||
TrendingUp,
|
||||
ShoppingCart,
|
||||
Receipt,
|
||||
Package,
|
||||
FolderTree,
|
||||
Tag,
|
||||
Sparkles,
|
||||
FileText,
|
||||
Users,
|
||||
Heart,
|
||||
MessageSquare,
|
||||
Building2,
|
||||
PhoneCall,
|
||||
Image,
|
||||
FlaskConical,
|
||||
MessageSquareQuote,
|
||||
BookOpen,
|
||||
Video,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
Languages,
|
||||
UserCheck,
|
||||
DollarSign,
|
||||
CreditCard,
|
||||
Truck,
|
||||
Sliders,
|
||||
Globe,
|
||||
ChevronDown,
|
||||
Star,
|
||||
Layers,
|
||||
HelpCircle,
|
||||
Menu,
|
||||
RotateCcw,
|
||||
Activity,
|
||||
Key,
|
||||
Activity,
|
||||
BookOpen,
|
||||
Building2,
|
||||
ChevronDown,
|
||||
CreditCard,
|
||||
DollarSign,
|
||||
FileText,
|
||||
FlaskConical,
|
||||
FolderTree,
|
||||
Globe,
|
||||
Heart,
|
||||
HelpCircle,
|
||||
Image,
|
||||
Key,
|
||||
Languages,
|
||||
Layers,
|
||||
LayoutDashboard,
|
||||
Menu,
|
||||
MessageSquare,
|
||||
MessageSquareQuote,
|
||||
Package,
|
||||
PhoneCall,
|
||||
Receipt,
|
||||
RotateCcw,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
ShoppingCart,
|
||||
Sliders,
|
||||
Sparkles,
|
||||
Star,
|
||||
Tag,
|
||||
TrendingUp,
|
||||
Truck,
|
||||
UserCheck,
|
||||
Users,
|
||||
Video,
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useRef,useState } from 'react';
|
||||
import { Link,useLocation } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
|
||||
interface SubMenuItem {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { Search, UserCircle, Menu, Activity, ShieldCheck, MessageSquare, Calendar, Clock, RefreshCw, PanelRightClose, PanelRightOpen } from 'lucide-react';
|
||||
import { Activity,Clock,Menu,PanelRightClose,PanelRightOpen,Search,UserCircle } from 'lucide-react';
|
||||
import { useEffect,useRef,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { Link,useNavigate } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React from 'react';
|
||||
import { Printer, X, CheckCircle2, ShieldCheck, Copy } from 'lucide-react';
|
||||
import { Copy,Printer,ShieldCheck,X } from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import Button from './ui/Button';
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { fireEvent,render,screen } from '@testing-library/react';
|
||||
import { describe,expect,it,vi } from 'vitest';
|
||||
import Button from './Button';
|
||||
|
||||
describe('Button Component', () => {
|
||||
it('renders children correctly', () => {
|
||||
render(<Button>کلیک کنید</Button>);
|
||||
expect(screen.getByRole('button', { name: 'کلیک کنید' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with different variants and size styling classes', () => {
|
||||
const { rerender } = render(<Button variant="danger" size="sm">حذف</Button>);
|
||||
let btn = screen.getByRole('button');
|
||||
expect(btn.className).toContain('bg-rose-600');
|
||||
expect(btn.className).toContain('px-3');
|
||||
|
||||
rerender(<Button variant="success" size="lg">تایید</Button>);
|
||||
btn = screen.getByRole('button');
|
||||
expect(btn.className).toContain('bg-emerald-600');
|
||||
expect(btn.className).toContain('px-5');
|
||||
});
|
||||
|
||||
it('handles click events when enabled', () => {
|
||||
const handleClick = vi.fn();
|
||||
render(<Button onClick={handleClick}>کلیک</Button>);
|
||||
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('shows spinner and disables button when isLoading is true', () => {
|
||||
const handleClick = vi.fn();
|
||||
render(<Button isLoading onClick={handleClick}>ارسال</Button>);
|
||||
|
||||
const btn = screen.getByRole('button');
|
||||
expect(btn).toBeDisabled();
|
||||
expect(screen.queryByText('ارسال')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(btn);
|
||||
expect(handleClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders startIcon, endIcon, badge, and info tooltip correctly', () => {
|
||||
const MockIcon = ({ className }: { className?: string }) => <svg data-testid="mock-icon" className={className} />;
|
||||
|
||||
render(
|
||||
<Button
|
||||
startIcon={MockIcon}
|
||||
endIcon={MockIcon}
|
||||
badge={5}
|
||||
info="اطلاعات کمکی"
|
||||
>
|
||||
آیتم
|
||||
</Button>
|
||||
);
|
||||
|
||||
const icons = screen.getAllByTestId('mock-icon');
|
||||
expect(icons.length).toBe(2);
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('اطلاعات کمکی')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { Info } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import Spinner from './Spinner';
|
||||
|
||||
export type ButtonVariant =
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { fireEvent,render,screen } from '@testing-library/react';
|
||||
import { describe,expect,it,vi } from 'vitest';
|
||||
import ConfirmModal from './ConfirmModal';
|
||||
|
||||
describe('ConfirmModal Component', () => {
|
||||
const defaultProps = {
|
||||
isOpen: true,
|
||||
title: 'حذف آیتم',
|
||||
message: 'آیا از حذف این آیتم اطمینان دارید؟',
|
||||
onConfirm: vi.fn(),
|
||||
onCancel: vi.fn(),
|
||||
};
|
||||
|
||||
it('does not render when isOpen is false', () => {
|
||||
const { container } = render(<ConfirmModal {...defaultProps} isOpen={false} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders title, message, and default button texts when isOpen is true', () => {
|
||||
render(<ConfirmModal {...defaultProps} />);
|
||||
|
||||
expect(screen.getByText('حذف آیتم')).toBeInTheDocument();
|
||||
expect(screen.getByText('آیا از حذف این آیتم اطمینان دارید؟')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'تایید' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'لغو' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onConfirm when confirm button is clicked', () => {
|
||||
const onConfirmMock = vi.fn();
|
||||
render(<ConfirmModal {...defaultProps} onConfirm={onConfirmMock} />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: 'تایید' });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
expect(onConfirmMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onCancel when cancel button or close X is clicked', () => {
|
||||
const onCancelMock = vi.fn();
|
||||
render(<ConfirmModal {...defaultProps} onCancel={onCancelMock} />);
|
||||
|
||||
const cancelButton = screen.getByRole('button', { name: 'لغو' });
|
||||
fireEvent.click(cancelButton);
|
||||
expect(onCancelMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const closeIconButton = buttons[0];
|
||||
fireEvent.click(closeIconButton);
|
||||
expect(onCancelMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('renders custom confirm and cancel texts', () => {
|
||||
render(
|
||||
<ConfirmModal
|
||||
{...defaultProps}
|
||||
confirmText="بله، حذف کن"
|
||||
cancelText="انصراف"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'بله، حذف کن' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'انصراف' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables buttons and shows loading text when isLoading is true', () => {
|
||||
const onConfirmMock = vi.fn();
|
||||
const onCancelMock = vi.fn();
|
||||
|
||||
render(
|
||||
<ConfirmModal
|
||||
{...defaultProps}
|
||||
isLoading={true}
|
||||
onConfirm={onConfirmMock}
|
||||
onCancel={onCancelMock}
|
||||
/>
|
||||
);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: 'در حال پردازش...' });
|
||||
const cancelButton = screen.getByRole('button', { name: 'لغو' });
|
||||
|
||||
expect(confirmButton).toBeDisabled();
|
||||
expect(cancelButton).toBeDisabled();
|
||||
|
||||
fireEvent.click(confirmButton);
|
||||
fireEvent.click(cancelButton);
|
||||
|
||||
expect(onConfirmMock).not.toHaveBeenCalled();
|
||||
expect(onCancelMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies non-destructive styling when isDestructive is false', () => {
|
||||
render(<ConfirmModal {...defaultProps} isDestructive={false} />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: 'تایید' });
|
||||
expect(confirmButton.className).toContain('bg-purple-600');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { X, AlertTriangle } from 'lucide-react';
|
||||
import { AlertTriangle,X } from 'lucide-react';
|
||||
|
||||
interface ConfirmModalProps {
|
||||
isOpen: boolean;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { HelpCircle } from 'lucide-react';
|
||||
import React from 'react';
|
||||
|
||||
export interface FormFieldProps {
|
||||
label?: string;
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import {
|
||||
X,
|
||||
Search,
|
||||
Check,
|
||||
Smile,
|
||||
Pill,
|
||||
ShieldCheck,
|
||||
HeartPulse,
|
||||
Sparkles,
|
||||
ShoppingBag,
|
||||
User,
|
||||
Building2,
|
||||
PhoneCall,
|
||||
Activity,
|
||||
Heart,
|
||||
Dog,
|
||||
BookOpen,
|
||||
FileText,
|
||||
Video,
|
||||
Award,
|
||||
Star,
|
||||
Truck,
|
||||
HelpCircle,
|
||||
MessageSquare,
|
||||
Globe,
|
||||
Settings,
|
||||
Flame,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
ThumbsUp,
|
||||
Package,
|
||||
Layers,
|
||||
Compass,
|
||||
MapPin,
|
||||
Mail,
|
||||
Send,
|
||||
Zap,
|
||||
Tag,
|
||||
Gift,
|
||||
Clock,
|
||||
Activity,
|
||||
AlertCircle,
|
||||
Award,
|
||||
BookOpen,
|
||||
Building2,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Compass,
|
||||
Dog,
|
||||
FileText,
|
||||
Flame,
|
||||
Gift,
|
||||
Globe,
|
||||
Heart,
|
||||
HeartPulse,
|
||||
HelpCircle,
|
||||
Layers,
|
||||
Mail,
|
||||
MapPin,
|
||||
MessageSquare,
|
||||
Package,
|
||||
PhoneCall,
|
||||
Pill,
|
||||
Search,
|
||||
Send,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
ShoppingBag,
|
||||
Smile,
|
||||
Sparkles,
|
||||
Star,
|
||||
Tag,
|
||||
ThumbsUp,
|
||||
Truck,
|
||||
User,
|
||||
Video,
|
||||
X,
|
||||
Zap,
|
||||
} from 'lucide-react';
|
||||
import React,{ useMemo,useState } from 'react';
|
||||
|
||||
interface IconPickerModalProps {
|
||||
isOpen: boolean;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { X, ZoomIn, ZoomOut, Download, ExternalLink } from 'lucide-react';
|
||||
import { ExternalLink,X,ZoomIn,ZoomOut } from 'lucide-react';
|
||||
import React,{ useEffect } from 'react';
|
||||
|
||||
export interface ImagePreviewModalProps {
|
||||
isOpen: boolean;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { forwardRef } from 'react';
|
||||
import React,{ forwardRef } from 'react';
|
||||
|
||||
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
error?: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Eye, EyeOff, Copy, Check } from 'lucide-react';
|
||||
import { Check,Copy,Eye,EyeOff } from 'lucide-react';
|
||||
import React,{ useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
interface MaskableFieldProps {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../../services/api';
|
||||
import MediaSelector from './MediaSelector';
|
||||
|
||||
vi.mock('../../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://test.canina.ir',
|
||||
}));
|
||||
|
||||
describe('MediaSelector Modal Component', () => {
|
||||
const mockMediaData = [
|
||||
{
|
||||
id: 'media-1',
|
||||
url: '/uploads/product-1.jpg',
|
||||
filename: 'product-1.jpg',
|
||||
createdAt: '2025-01-01T10:00:00Z',
|
||||
mimetype: 'image/jpeg',
|
||||
},
|
||||
{
|
||||
id: 'media-2',
|
||||
url: '/uploads/guide-video.mp4',
|
||||
filename: 'guide-video.mp4',
|
||||
createdAt: '2025-01-02T10:00:00Z',
|
||||
mimetype: 'video/mp4',
|
||||
},
|
||||
{
|
||||
id: 'media-3',
|
||||
url: '/uploads/catalog.pdf',
|
||||
filename: 'catalog.pdf',
|
||||
createdAt: '2025-01-03T10:00:00Z',
|
||||
mimetype: 'application/pdf',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: { success: true, data: mockMediaData },
|
||||
});
|
||||
});
|
||||
|
||||
it('renders nothing when isOpen is false', () => {
|
||||
const { container } = render(
|
||||
<MediaSelector isOpen={false} onClose={vi.fn()} onSelect={vi.fn()} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('fetches and displays media items when isOpen is true', async () => {
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
|
||||
);
|
||||
|
||||
expect(await screen.findByText('گالری و مدیریت رسانه')).toBeInTheDocument();
|
||||
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
|
||||
expect(screen.getByText('guide-video.mp4')).toBeInTheDocument();
|
||||
expect(screen.getByText('catalog.pdf')).toBeInTheDocument();
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/media');
|
||||
});
|
||||
|
||||
it('filters media list by file type tabs', async () => {
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
|
||||
);
|
||||
|
||||
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
|
||||
|
||||
// Click 'ویدئوها' tab
|
||||
const videoTab = screen.getByRole('button', { name: 'ویدئوها' });
|
||||
fireEvent.click(videoTab);
|
||||
|
||||
// Only video should remain visible
|
||||
expect(screen.getByText('guide-video.mp4')).toBeInTheDocument();
|
||||
expect(screen.queryByText('product-1.jpg')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('catalog.pdf')).not.toBeInTheDocument();
|
||||
|
||||
// Click 'اسناد PDF' tab
|
||||
const pdfTab = screen.getByRole('button', { name: 'اسناد PDF' });
|
||||
fireEvent.click(pdfTab);
|
||||
|
||||
expect(screen.getByText('catalog.pdf')).toBeInTheDocument();
|
||||
expect(screen.queryByText('guide-video.mp4')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('selects an item on click and confirms selection with the footer button', async () => {
|
||||
const onSelect = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={onClose} onSelect={onSelect} />
|
||||
);
|
||||
|
||||
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /انتخاب و ثبت فایل/i });
|
||||
expect(submitBtn).toBeDisabled();
|
||||
|
||||
// Click on the product card
|
||||
const cardText = screen.getByText('product-1.jpg');
|
||||
fireEvent.click(cardText);
|
||||
|
||||
// Now submit button should be enabled
|
||||
expect(submitBtn).not.toBeDisabled();
|
||||
expect(screen.getByText(/۱ فایل انتخاب شد/i)).toBeInTheDocument();
|
||||
|
||||
// Click submit
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith('https://test.canina.ir/uploads/product-1.jpg');
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('immediately confirms and closes on card double-click', async () => {
|
||||
const onSelect = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={onClose} onSelect={onSelect} />
|
||||
);
|
||||
|
||||
const cardText = await screen.findByText('product-1.jpg');
|
||||
fireEvent.doubleClick(cardText);
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith('https://test.canina.ir/uploads/product-1.jpg');
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens preview modal when eye button is clicked', async () => {
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
|
||||
);
|
||||
|
||||
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
|
||||
|
||||
const eyeButtons = screen.getAllByTitle('مشاهده');
|
||||
expect(eyeButtons.length).toBeGreaterThan(0);
|
||||
fireEvent.click(eyeButtons[0]);
|
||||
|
||||
// Modal or preview image should be triggered
|
||||
await waitFor(() => {
|
||||
const previewImg = document.querySelector('img[src="https://test.canina.ir/uploads/product-1.jpg"]');
|
||||
expect(previewImg).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('triggers delete confirm modal and executes delete on confirmation', async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
|
||||
);
|
||||
|
||||
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
|
||||
|
||||
const deleteButtons = screen.getAllByTitle('حذف فایل');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
expect(await screen.findByText('حذف تصویر')).toBeInTheDocument();
|
||||
expect(screen.getByText(/آیا از حذف این تصویر مطمئن هستید؟/i)).toBeInTheDocument();
|
||||
|
||||
// Confirm deletion
|
||||
const confirmBtn = screen.getByRole('button', { name: /تایید/i });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/admin/media/media-1');
|
||||
expect(screen.queryByText('product-1.jpg')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls onClose when clicking close icon or cancel button', async () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<MediaSelector isOpen={true} onClose={onClose} onSelect={vi.fn()} />
|
||||
);
|
||||
|
||||
await screen.findByText('گالری و مدیریت رسانه');
|
||||
|
||||
const cancelBtn = screen.getByRole('button', { name: 'انصراف' });
|
||||
fireEvent.click(cancelBtn);
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { X, Upload, Image as ImageIcon, Trash2, CheckCircle2, Clipboard, Eye, Video, FileText, Music, Play } from 'lucide-react';
|
||||
import { CheckCircle2,Clipboard,Eye,FileText,Image as ImageIcon,Music,Play,Trash2,Upload,X } from 'lucide-react';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../../services/api';
|
||||
import Spinner from './Spinner';
|
||||
import Pagination from './Pagination';
|
||||
import api,{ BASE_DOMAIN } from '../../services/api';
|
||||
import ConfirmModal from './ConfirmModal';
|
||||
import ImagePreviewModal from './ImagePreviewModal';
|
||||
import Pagination from './Pagination';
|
||||
import Spinner from './Spinner';
|
||||
|
||||
interface Media {
|
||||
id: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import React,{ useEffect } from 'react';
|
||||
|
||||
export interface ModalProps {
|
||||
isOpen: boolean;
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { fireEvent,render,screen } from '@testing-library/react';
|
||||
import { describe,expect,it,vi } from 'vitest';
|
||||
import Pagination from './Pagination';
|
||||
|
||||
describe('Pagination Component', () => {
|
||||
it('renders nothing when totalPages is 1 or less', () => {
|
||||
const { container: c1 } = render(
|
||||
<Pagination currentPage={1} totalPages={1} onPageChange={vi.fn()} />
|
||||
);
|
||||
expect(c1.firstChild).toBeNull();
|
||||
|
||||
const { container: c0 } = render(
|
||||
<Pagination currentPage={1} totalPages={0} onPageChange={vi.fn()} />
|
||||
);
|
||||
expect(c0.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders navigation buttons and page numbers when totalPages > 1', () => {
|
||||
render(
|
||||
<Pagination currentPage={2} totalPages={5} onPageChange={vi.fn()} />
|
||||
);
|
||||
|
||||
expect(screen.getByTitle('صفحه اول')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('صفحه قبلی')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('صفحه بعدی')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('صفحه آخر')).toBeInTheDocument();
|
||||
|
||||
// Check Persian digit representation of current page 2 ('۲')
|
||||
const page2Button = screen.getByRole('button', { name: (2).toLocaleString('fa-IR') });
|
||||
expect(page2Button).toBeInTheDocument();
|
||||
expect(page2Button.className).toContain('bg-purple-600');
|
||||
});
|
||||
|
||||
it('disables first and previous buttons on the first page', () => {
|
||||
render(
|
||||
<Pagination currentPage={1} totalPages={5} onPageChange={vi.fn()} />
|
||||
);
|
||||
|
||||
const firstBtn = screen.getByTitle('صفحه اول');
|
||||
const prevBtn = screen.getByTitle('صفحه قبلی');
|
||||
const nextBtn = screen.getByTitle('صفحه بعدی');
|
||||
const lastBtn = screen.getByTitle('صفحه آخر');
|
||||
|
||||
expect(firstBtn).toBeDisabled();
|
||||
expect(prevBtn).toBeDisabled();
|
||||
expect(nextBtn).not.toBeDisabled();
|
||||
expect(lastBtn).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables next and last buttons on the last page', () => {
|
||||
render(
|
||||
<Pagination currentPage={5} totalPages={5} onPageChange={vi.fn()} />
|
||||
);
|
||||
|
||||
const firstBtn = screen.getByTitle('صفحه اول');
|
||||
const prevBtn = screen.getByTitle('صفحه قبلی');
|
||||
const nextBtn = screen.getByTitle('صفحه بعدی');
|
||||
const lastBtn = screen.getByTitle('صفحه آخر');
|
||||
|
||||
expect(firstBtn).not.toBeDisabled();
|
||||
expect(prevBtn).not.toBeDisabled();
|
||||
expect(nextBtn).toBeDisabled();
|
||||
expect(lastBtn).toBeDisabled();
|
||||
});
|
||||
|
||||
it('calls onPageChange with correct page numbers when navigation buttons are clicked', () => {
|
||||
const handlePageChange = vi.fn();
|
||||
render(
|
||||
<Pagination currentPage={3} totalPages={10} onPageChange={handlePageChange} />
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByTitle('صفحه اول'));
|
||||
expect(handlePageChange).toHaveBeenCalledWith(1);
|
||||
|
||||
fireEvent.click(screen.getByTitle('صفحه قبلی'));
|
||||
expect(handlePageChange).toHaveBeenCalledWith(2);
|
||||
|
||||
fireEvent.click(screen.getByTitle('صفحه بعدی'));
|
||||
expect(handlePageChange).toHaveBeenCalledWith(4);
|
||||
|
||||
fireEvent.click(screen.getByTitle('صفحه آخر'));
|
||||
expect(handlePageChange).toHaveBeenCalledWith(10);
|
||||
});
|
||||
|
||||
it('navigates directly via jump input form', () => {
|
||||
const handlePageChange = vi.fn();
|
||||
render(
|
||||
<Pagination currentPage={2} totalPages={10} onPageChange={handlePageChange} />
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('2');
|
||||
const submitBtn = screen.getByRole('button', { name: /برو/ });
|
||||
|
||||
// Valid jump
|
||||
fireEvent.change(input, { target: { value: '7' } });
|
||||
fireEvent.click(submitBtn);
|
||||
expect(handlePageChange).toHaveBeenCalledWith(7);
|
||||
|
||||
// Invalid jump (out of range > totalPages)
|
||||
handlePageChange.mockClear();
|
||||
fireEvent.change(input, { target: { value: '15' } });
|
||||
fireEvent.click(submitBtn);
|
||||
expect(handlePageChange).not.toHaveBeenCalled();
|
||||
|
||||
// Invalid jump (<= 0)
|
||||
handlePageChange.mockClear();
|
||||
fireEvent.change(input, { target: { value: '0' } });
|
||||
fireEvent.click(submitBtn);
|
||||
expect(handlePageChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
|
||||
import { ChevronLeft,ChevronRight,ChevronsLeft,ChevronsRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface PaginationProps {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React,{ useEffect,useState } from 'react';
|
||||
|
||||
interface PriceInputProps {
|
||||
value: number | string;
|
||||
@@ -38,7 +38,6 @@ export default function PriceInput({
|
||||
suffix = 'تومان',
|
||||
disabled = false,
|
||||
required = false,
|
||||
min,
|
||||
max,
|
||||
name,
|
||||
id,
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
import React, { useRef, useEffect, useState, useCallback } from 'react';
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Heading3,
|
||||
Heading4,
|
||||
List,
|
||||
ListOrdered,
|
||||
Link as LinkIcon,
|
||||
AlignRight,
|
||||
AlignCenter,
|
||||
AlignLeft,
|
||||
Palette,
|
||||
PaintBucket,
|
||||
Undo,
|
||||
Redo,
|
||||
Code,
|
||||
RemoveFormatting,
|
||||
Image as ImageIcon,
|
||||
Video,
|
||||
Music,
|
||||
Table as TableIcon,
|
||||
Quote,
|
||||
Minus,
|
||||
Maximize2,
|
||||
Minimize2,
|
||||
AlignCenter,
|
||||
AlignLeft,
|
||||
AlignRight,
|
||||
Bold,
|
||||
Code,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Heading3,
|
||||
Heading4,
|
||||
Image as ImageIcon,
|
||||
Italic,
|
||||
Link as LinkIcon,
|
||||
List,
|
||||
ListOrdered,
|
||||
Maximize2,
|
||||
Minimize2,
|
||||
Minus,
|
||||
Music,
|
||||
PaintBucket,
|
||||
Palette,
|
||||
Quote,
|
||||
Redo,
|
||||
RemoveFormatting,
|
||||
Table as TableIcon,
|
||||
Underline,
|
||||
Undo,
|
||||
Video,
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import MediaSelector from './MediaSelector';
|
||||
|
||||
interface RichTextEditorProps {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { forwardRef } from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import React,{ forwardRef } from 'react';
|
||||
|
||||
export interface SelectOption {
|
||||
value: string | number;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { forwardRef } from 'react';
|
||||
import React,{ forwardRef } from 'react';
|
||||
|
||||
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
|
||||
error?: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ArrowDown,ArrowUp,ArrowUpDown } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
|
||||
|
||||
export interface ThSortProps {
|
||||
column: string;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react';
|
||||
|
||||
export interface ToggleSwitchProps {
|
||||
checked: boolean;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
|
||||
// Handle Vite dynamic import chunk mismatch after fresh deployment
|
||||
window.addEventListener('vite:preloadError', (event) => {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ApiKeysPage from './ApiKeysPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const key = { id: 'k1', name: 'Warehouse', keyPrefix: 'test_prefix', scopes: ['orders:read'], status: 'ACTIVE', isExpired: false };
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { success: true, data: [key] } });
|
||||
vi.mocked(api.post).mockResolvedValue({ data: { success: true, data: { rawKey: 'synthetic-test-key' } } });
|
||||
vi.mocked(api.patch).mockResolvedValue({ data: { success: true } }); vi.mocked(api.delete).mockResolvedValue({ data: { success: true } });
|
||||
});
|
||||
async function open() { render(<ApiKeysPage />); await screen.findByText('Warehouse'); fireEvent.click(screen.getByRole('button', { name: 'ساخت API Key جدید' })); }
|
||||
function submit() { fireEvent.submit(document.querySelector('form')!); }
|
||||
describe('ApiKeysPage', () => {
|
||||
it('shows only the prefix, scopes and active status', async () => { render(<ApiKeysPage />); await screen.findByText('Warehouse'); expect(screen.getByText('test_prefix')).toBeInTheDocument(); expect(screen.getByText('orders:read')).toBeInTheDocument(); expect(screen.getByText('فعال')).toBeInTheDocument(); });
|
||||
it('rejects whitespace names without making a request', async () => { await open(); fireEvent.change(screen.getByPlaceholderText('مثلاً: ورکفلو n8n یا اتصال انبار'), { target: { value: ' ' } }); submit(); expect(toast.error).toHaveBeenCalledWith('لطفاً عنوان کلید را وارد کنید'); expect(api.post).not.toHaveBeenCalled(); });
|
||||
it('creates restricted expiring key and displays raw key only until dismissed', async () => {
|
||||
await open(); fireEvent.change(screen.getByPlaceholderText('مثلاً: ورکفلو n8n یا اتصال انبار'), { target: { value: ' Automation ' } });
|
||||
fireEvent.change(screen.getByPlaceholderText('کاربرد این کلید در کجاست؟'), { target: { value: ' Orders ' } });
|
||||
fireEvent.click(screen.getByText('مشاهده سفارشات')); fireEvent.click(screen.getByRole('button', { name: '۳۰ روزه' }));
|
||||
const before = Date.now(); submit(); await screen.findByDisplayValue('synthetic-test-key');
|
||||
const payload = vi.mocked(api.post).mock.calls[0][1] as { name: string; description: string; scopes: string[]; expiresAt: string };
|
||||
expect(payload).toEqual({ name: 'Automation', description: 'Orders', scopes: ['orders:read'], expiresAt: expect.any(String) });
|
||||
expect(new Date(payload.expiresAt).getTime() - before).toBeGreaterThan(29 * 86400000);
|
||||
expect(new Date(payload.expiresAt).getTime() - before).toBeLessThan(31 * 86400000);
|
||||
const copy = vi.fn().mockResolvedValue(undefined); Object.defineProperty(navigator, 'clipboard', { value: { writeText: copy }, configurable: true });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'کپی کلید' })); expect(copy).toHaveBeenCalledWith('synthetic-test-key');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'کلید را ذخیره کردم، بستن پنجره' })); expect(screen.queryByDisplayValue('synthetic-test-key')).not.toBeInTheDocument();
|
||||
});
|
||||
it('retains creation form on rejection', async () => { vi.mocked(api.post).mockRejectedValue(new Error('offline')); await open(); fireEvent.change(screen.getByPlaceholderText('مثلاً: ورکفلو n8n یا اتصال انبار'), { target: { value: 'Draft' } }); submit(); await waitFor(() => expect(api.post).toHaveBeenCalled()); expect(screen.getByDisplayValue('Draft')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); });
|
||||
it('toggles key status and reloads', async () => { render(<ApiKeysPage />); fireEvent.click(await screen.findByTitle('غیرفعال کردن کلید')); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/admin/api-keys/k1/toggle')); await waitFor(() => expect(api.get).toHaveBeenCalledTimes(2)); });
|
||||
it('requires confirmation before deleting and removes the row after success', async () => {
|
||||
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false); render(<ApiKeysPage />); fireEvent.click(await screen.findByTitle('حذف دائمی کلید')); expect(api.delete).not.toHaveBeenCalled();
|
||||
confirm.mockReturnValue(true); fireEvent.click(screen.getByTitle('حذف دائمی کلید')); await waitFor(() => expect(api.delete).toHaveBeenCalledWith('/admin/api-keys/k1')); await screen.findByText('هیچ کلید دسترسی تعریف نشده است'); confirm.mockRestore();
|
||||
});
|
||||
it('retains key on rejected delete or status mutation', async () => {
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true); vi.mocked(api.delete).mockRejectedValue(new Error('offline')); vi.mocked(api.patch).mockRejectedValue(new Error('offline'));
|
||||
render(<ApiKeysPage />); fireEvent.click(await screen.findByTitle('حذف دائمی کلید')); fireEvent.click(screen.getByTitle('غیرفعال کردن کلید')); await waitFor(() => expect(api.patch).toHaveBeenCalled()); expect(screen.getByText('Warehouse')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); vi.mocked(window.confirm).mockRestore();
|
||||
});
|
||||
it('reports load failures and clears loading', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(<ApiKeysPage />); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بارگذاری کلیدهای دسترسی')); expect(screen.getByText('هیچ کلید دسترسی تعریف نشده است')).toBeInTheDocument(); });
|
||||
});
|
||||
@@ -1,23 +1,22 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Key,
|
||||
Plus,
|
||||
Trash2,
|
||||
Copy,
|
||||
Check,
|
||||
Shield,
|
||||
Clock,
|
||||
AlertTriangle,
|
||||
RefreshCw,
|
||||
Power,
|
||||
ExternalLink,
|
||||
Lock,
|
||||
AlertTriangle,
|
||||
Check,
|
||||
Clock,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
Key,
|
||||
Plus,
|
||||
Power,
|
||||
RefreshCw,
|
||||
Shield,
|
||||
Trash2
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import type { ApiKeyItem, CreateApiKeyPayload } from '../types/admin';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
import type { ApiKeyItem,CreateApiKeyPayload } from '../types/admin';
|
||||
|
||||
export default function ApiKeysPage() {
|
||||
const [keys, setKeys] = useState<ApiKeyItem[]>([]);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import B2BManager from './B2BManager';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
|
||||
describe('B2BManager',()=>{
|
||||
const inquiry = { id: 'i1', companyName: 'Clinic Alpha', contactName: 'Doctor A', phone: '09120000000', email: 'a@example.test', businessType: 'clinic', message: 'Bulk request', status: 'PENDING' };
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => ({ data: url === '/b2b/inquiries' ? [inquiry] : { data: [] } })); vi.mocked(api.patch).mockResolvedValue({ data: {} }); });
|
||||
it('filters inquiries by status without losing the loaded list', async () => { render(<B2BManager />); await screen.findByText('Clinic Alpha'); fireEvent.click(screen.getByRole('button', { name: 'رد شده' })); expect(screen.queryByText('Clinic Alpha')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'همه' })); expect(screen.getByText('Clinic Alpha')).toBeInTheDocument(); });
|
||||
it('reviews an inquiry with trimmed notes and refreshes the list', async () => { render(<B2BManager />); fireEvent.click(await screen.findByRole('button', { name: 'تغییر وضعیت' })); fireEvent.change(document.querySelector('#inquiryForm select')!, { target: { value: 'APPROVED' } }); fireEvent.change(screen.getByRole('textbox'), { target: { value: ' approved after review ' } }); fireEvent.submit(document.querySelector('#inquiryForm')!); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/b2b/inquiries/i1', { status: 'APPROVED', adminNotes: 'approved after review' })); await waitFor(() => expect(api.get).toHaveBeenCalledTimes(2)); });
|
||||
it('keeps failed review open and reports failure', async () => { vi.mocked(api.patch).mockRejectedValue(new Error('denied')); render(<B2BManager />); fireEvent.click(await screen.findByRole('button', { name: 'تغییر وضعیت' })); fireEvent.submit(document.querySelector('#inquiryForm')!); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بروزرسانی وضعیت درخواست B2B')); expect(document.querySelector('#inquiryForm')).toBeInTheDocument(); });
|
||||
it('blocks whitespace-only partner identity before posting', async () => { render(<B2BManager />); await screen.findByText('Clinic Alpha'); fireEvent.click(screen.getByTestId('b2b-partners-tab')); fireEvent.click(await screen.findByRole('button', { name: 'افزودن همکار B2B جدید' })); fireEvent.change(screen.getByPlaceholderText('uuid-string-of-user'), { target: { value: ' ' } }); fireEvent.submit(document.querySelector('#partnerForm')!); expect(api.post).not.toHaveBeenCalled(); expect(toast.error).toHaveBeenCalledWith('شناسه کاربر و نام شرکت اجباری هستند'); });
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Building2, CheckCircle2, XCircle, Clock, PhoneCall, Filter, X, Plus, ShieldCheck } from 'lucide-react';
|
||||
import { Building2,CheckCircle2,Clock,Filter,PhoneCall,Plus,ShieldCheck,XCircle } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import type { B2BInquiry, PartnerAccount } from '../types/admin';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
import type { B2BInquiry,PartnerAccount } from '../types/admin';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
import { fireEvent,render,screen,waitFor } from "@testing-library/react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { beforeEach,describe,expect,it,vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import BannersManager from "./BannersManager";
|
||||
|
||||
vi.mock("../services/api", () => {
|
||||
return {
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: "https://canina.ir",
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock MediaSelector
|
||||
vi.mock("../components/ui/MediaSelector", () => ({
|
||||
default: ({ isOpen, onSelect, onClose }: any) => {
|
||||
if (!isOpen) return null;
|
||||
return (
|
||||
<div data-testid="media-selector-modal">
|
||||
<button
|
||||
onClick={() => {
|
||||
onSelect("/uploads/media-selected.png");
|
||||
}}
|
||||
>
|
||||
Select Media Sample
|
||||
</button>
|
||||
<button onClick={onClose}>Close Media</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe("BannersManager", () => {
|
||||
const mockBanners = [
|
||||
{
|
||||
id: "b-1",
|
||||
title: "Banner 1",
|
||||
subtitle: "Subtitle 1",
|
||||
imageUrl: "/uploads/banner1.jpg",
|
||||
linkUrl: "/products/promo1",
|
||||
position: "home_hero",
|
||||
isActive: true,
|
||||
order: 0,
|
||||
},
|
||||
{
|
||||
id: "b-2",
|
||||
title: "Banner 2",
|
||||
subtitle: "Subtitle 2",
|
||||
imageUrl: "https://external.com/banner2.png",
|
||||
linkUrl: "/products/promo2",
|
||||
position: "home_promo",
|
||||
isActive: false,
|
||||
order: 1,
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders banners list successfully", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
expect(screen.getByText("مدیریت بنرها و اسلایدرها")).toBeInTheDocument();
|
||||
|
||||
// Wait for banners to load
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Banner 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("Banner 2")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText("Subtitle 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("اسلایدر اصلی")).toBeInTheDocument();
|
||||
expect(screen.getByText("بنر تبلیغاتی میانی")).toBeInTheDocument();
|
||||
expect(screen.getByText("/products/promo1")).toBeInTheDocument();
|
||||
expect(screen.getByText("فعال")).toBeInTheDocument();
|
||||
expect(screen.getByText("غیرفعال")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("handles empty state when no banners found", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("هیچ بنری یافت نشد")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a new banner via modal", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); // for refresh
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Banner 1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click Add New Banner button
|
||||
const addButton = screen.getByRole("button", { name: /افزودن بنر جدید/i });
|
||||
fireEvent.click(addButton);
|
||||
|
||||
// Modal should be open
|
||||
expect(screen.getByText("افزودن بنر جدید", { selector: "h3" })).toBeInTheDocument();
|
||||
|
||||
// Fill in form fields
|
||||
const titleInput = screen.getByPlaceholderText(/مثال: تخفیف ویژه مکملهای غذایی/i);
|
||||
const subtitleInput = screen.getByPlaceholderText(/مثال: تا ۳۰٪ تخفیف برای مدت محدود/i);
|
||||
const imageInput = screen.getByPlaceholderText(/آدرس تصویر یا انتخاب از رسانهها\.\.\./i);
|
||||
const linkInput = screen.getByPlaceholderText(/\/shop یا https:\/\/\.\.\./i);
|
||||
|
||||
fireEvent.change(titleInput, { target: { value: "New Campaign Banner" } });
|
||||
fireEvent.change(subtitleInput, { target: { value: "Save 20%" } });
|
||||
fireEvent.change(imageInput, { target: { value: "/uploads/new-camp.jpg" } });
|
||||
fireEvent.change(linkInput, { target: { value: "/camp" } });
|
||||
|
||||
// Save banner
|
||||
const saveButton = screen.getByRole("button", { name: /ذخیره تغییرات/i });
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/banners", expect.objectContaining({
|
||||
title: "New Campaign Banner",
|
||||
subtitle: "Save 20%",
|
||||
imageUrl: "/uploads/new-camp.jpg",
|
||||
linkUrl: "/camp",
|
||||
position: "home_hero",
|
||||
isActive: true,
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith("بنر جدید با موفقیت ایجاد شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("selects image from MediaSelector", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("هیچ بنری یافت نشد")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /افزودن بنر جدید/i }));
|
||||
|
||||
// Open media selector
|
||||
const chooseMediaButton = screen.getByRole("button", { name: /انتخاب تصویر/i });
|
||||
fireEvent.click(chooseMediaButton);
|
||||
|
||||
expect(screen.getByTestId("media-selector-modal")).toBeInTheDocument();
|
||||
|
||||
// Select media
|
||||
fireEvent.click(screen.getByText("Select Media Sample"));
|
||||
|
||||
const imageInput = screen.getByPlaceholderText(/آدرس تصویر یا انتخاب از رسانهها\.\.\./i) as HTMLInputElement;
|
||||
expect(imageInput.value).toBe("/uploads/media-selected.png");
|
||||
});
|
||||
|
||||
it("edits an existing banner", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Banner 1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole("row");
|
||||
const editButton = rows[1].querySelectorAll("button")[3];
|
||||
fireEvent.click(editButton);
|
||||
|
||||
expect(screen.getByText("ویرایش بنر", { selector: "h3" })).toBeInTheDocument();
|
||||
|
||||
const titleInput = screen.getByPlaceholderText(/مثال: تخفیف ویژه مکملهای غذایی/i);
|
||||
expect(titleInput).toHaveValue("Banner 1");
|
||||
|
||||
fireEvent.change(titleInput, { target: { value: "Updated Banner 1" } });
|
||||
|
||||
const saveButton = screen.getByRole("button", { name: /ذخیره تغییرات/i });
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith("/banners/b-1", expect.objectContaining({
|
||||
title: "Updated Banner 1",
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith("بنر با موفقیت بروزرسانی شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles active state of a banner", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Banner 1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const activeToggle = screen.getByText("فعال");
|
||||
fireEvent.click(activeToggle);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith("/banners/b-1", { isActive: false });
|
||||
expect(toast.success).toHaveBeenCalledWith("وضعیت بنر تغییر کرد");
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes a banner via confirmation modal", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Banner 1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole("row");
|
||||
const deleteButton = rows[1].querySelectorAll("button")[4];
|
||||
fireEvent.click(deleteButton);
|
||||
|
||||
expect(screen.getByText(/آیا از حذف این بنر اطمینان دارید؟/i)).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole("button", { name: /تایید/i });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/banners/b-1");
|
||||
expect(toast.success).toHaveBeenCalledWith("بنر با موفقیت حذف شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("moves banner order down and calls reorder API", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners });
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<BannersManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Banner 1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole("row");
|
||||
const moveDownButton = rows[1].querySelectorAll("button")[1];
|
||||
fireEvent.click(moveDownButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith("/banners/reorder", [
|
||||
{ id: "b-2", order: 0 },
|
||||
{ id: "b-1", order: 1 },
|
||||
]);
|
||||
expect(toast.success).toHaveBeenCalledWith("ترتیب بنرها به روز شد");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Image as ImageIcon, Plus, Edit2, Trash2, X, MoveUp, MoveDown, CheckCircle2, XCircle } from 'lucide-react';
|
||||
import { CheckCircle2,Edit2,Image as ImageIcon,MoveDown,MoveUp,Plus,Trash2,XCircle } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
import type { Banner } from '../types/admin';
|
||||
|
||||
|
||||
@@ -153,6 +153,17 @@ export default function BannersManager() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleActive = async (banner: Banner) => {
|
||||
try {
|
||||
await api.patch('/banners/' + banner.id, { isActive: !banner.isActive });
|
||||
toast.success('وضعیت بنر تغییر کرد');
|
||||
fetchBanners();
|
||||
} catch (err) {
|
||||
console.error('Failed to toggle banner status:', err);
|
||||
toast.error('خطا در تغییر وضعیت بنر');
|
||||
}
|
||||
};
|
||||
|
||||
const getImageFullUrl = (url: string) => {
|
||||
if (!url) return '';
|
||||
if (url.startsWith('http')) return url;
|
||||
@@ -211,14 +222,14 @@ export default function BannersManager() {
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
disabled={index === 0}
|
||||
onClick={() => handleReorder(index, 'up')}
|
||||
onClick={() => handleMoveOrder(index, 'up')}
|
||||
className="p-1 text-gray-400 hover:text-purple-600 disabled:opacity-30 disabled:hover:text-gray-400 cursor-pointer"
|
||||
>
|
||||
<MoveUp className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
disabled={index === banners.length - 1}
|
||||
onClick={() => handleReorder(index, 'down')}
|
||||
onClick={() => handleMoveOrder(index, 'down')}
|
||||
className="p-1 text-gray-400 hover:text-purple-600 disabled:opacity-30 disabled:hover:text-gray-400 cursor-pointer"
|
||||
>
|
||||
<MoveDown className="w-4 h-4" />
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
import { fireEvent,render,screen,waitFor } from "@testing-library/react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { beforeEach,describe,expect,it,vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import Blogs from "./Blogs";
|
||||
|
||||
vi.mock("../services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: "https://canina.ir",
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock MediaSelector
|
||||
vi.mock("../components/ui/MediaSelector", () => ({
|
||||
default: ({ isOpen, onSelect, onClose }: any) => {
|
||||
if (!isOpen) return null;
|
||||
return (
|
||||
<div data-testid="media-selector-modal">
|
||||
<button onClick={() => onSelect("/uploads/blog-image.jpg")}>
|
||||
Select Media
|
||||
</button>
|
||||
<button onClick={onClose}>Close Media</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock RichTextEditor
|
||||
vi.mock("../components/ui/RichTextEditor", () => ({
|
||||
default: ({ value, onChange }: any) => (
|
||||
<textarea
|
||||
data-testid="rich-text-editor"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="متن مقاله را بنویسید..."
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
describe("Blogs Page Component", () => {
|
||||
const mockBlogs = [
|
||||
{
|
||||
id: "blog-1",
|
||||
title: "راهنمای جامع نگهداری سگ پامرانین",
|
||||
slug: "pomeranian-care-guide",
|
||||
content: "<p>محتوای جامع راهنما</p>",
|
||||
excerpt: "خلاصه مقاله درباره نگهداری پامرانین",
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: "2025-01-01T10:00:00Z",
|
||||
readingTime: 5,
|
||||
viewCount: 120,
|
||||
featured: true,
|
||||
allowComments: true,
|
||||
showOnHome: true,
|
||||
category: { id: "cat-1", name: "آموزش و نگهداری", slug: "care" },
|
||||
categoryId: "cat-1",
|
||||
tags: [{ id: "tag-1", name: "سگ" }],
|
||||
author: { id: "user-1", firstName: "علی", lastName: "محمدی" },
|
||||
relatedProductIds: [],
|
||||
relatedBlogIds: [],
|
||||
},
|
||||
{
|
||||
id: "blog-2",
|
||||
title: "بهترین رژیم غذایی گربه",
|
||||
slug: "cat-diet-guide",
|
||||
content: "<p>محتوای رژیم گربه</p>",
|
||||
excerpt: "رژیم غذایی اصولی برای گربه",
|
||||
status: "DRAFT",
|
||||
isPublished: false,
|
||||
readingTime: 3,
|
||||
viewCount: 15,
|
||||
featured: false,
|
||||
allowComments: false,
|
||||
showOnHome: false,
|
||||
category: { id: "cat-2", name: "تغذیه", slug: "nutrition" },
|
||||
categoryId: "cat-2",
|
||||
tags: [],
|
||||
author: { id: "user-2", firstName: "سارا", lastName: "احمدی" },
|
||||
relatedProductIds: [],
|
||||
relatedBlogIds: [],
|
||||
},
|
||||
];
|
||||
|
||||
const mockCategories = [
|
||||
{ id: "cat-1", name: "آموزش و نگهداری", slug: "care" },
|
||||
{ id: "cat-2", name: "تغذیه", slug: "nutrition" },
|
||||
];
|
||||
|
||||
const mockTags = [
|
||||
{ id: "tag-1", name: "سگ", slug: "dog" },
|
||||
{ id: "tag-2", name: "گربه", slug: "cat" },
|
||||
];
|
||||
|
||||
const mockAuthors = [
|
||||
{ id: "user-1", firstName: "علی", lastName: "محمدی" },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === "/admin/blogs") {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
data: mockBlogs,
|
||||
meta: { total: 2, page: 1, lastPage: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url === "/admin/blogs/categories") {
|
||||
return Promise.resolve({ data: { data: mockCategories } });
|
||||
}
|
||||
if (url === "/admin/blogs/tags") {
|
||||
return Promise.resolve({ data: { data: mockTags } });
|
||||
}
|
||||
if (url === "/admin/blogs/authors") {
|
||||
return Promise.resolve({ data: { data: mockAuthors } });
|
||||
}
|
||||
if (url === "/admin/products") {
|
||||
return Promise.resolve({ data: { data: [] } });
|
||||
}
|
||||
return Promise.resolve({ data: {} });
|
||||
});
|
||||
});
|
||||
|
||||
const renderComponent = () =>
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Blogs />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
it("renders blogs list table and categories properly", async () => {
|
||||
renderComponent();
|
||||
|
||||
expect(screen.getByText("مدیریت جامع وبلاگ و دانشنامه سلامت")).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("راهنمای جامع نگهداری سگ پامرانین")).toBeInTheDocument();
|
||||
expect(screen.getByText("بهترین رژیم غذایی گربه")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getAllByText("آموزش و نگهداری").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("تغذیه").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("علی محمدی")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("منتشر شده").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("پیشنویس").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("filters blogs by search term and status", async () => {
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("راهنمای جامع نگهداری سگ پامرانین")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/جستجو در عنوان، چکیده و اسلاگ مقالات\.\.\./i);
|
||||
fireEvent.change(searchInput, { target: { value: "پامرانین" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith("/admin/blogs", expect.objectContaining({
|
||||
params: expect.objectContaining({ search: "پامرانین" }),
|
||||
}));
|
||||
});
|
||||
|
||||
const selects = screen.getAllByRole("combobox");
|
||||
fireEvent.change(selects[0], { target: { value: "PUBLISHED" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith("/admin/blogs", expect.objectContaining({
|
||||
params: expect.objectContaining({ status: "PUBLISHED" }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it("opens modal and creates a new blog article", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("راهنمای جامع نگهداری سگ پامرانین")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const createButton = screen.getByRole("button", { name: /مقاله جدید/i });
|
||||
fireEvent.click(createButton);
|
||||
|
||||
expect(screen.getByText("افزودن مقاله جدید", { selector: "h3" })).toBeInTheDocument();
|
||||
|
||||
const titleInput = screen.getByTestId("blog-title-input");
|
||||
fireEvent.change(titleInput, { target: { value: "مقاله تست جدید" } });
|
||||
|
||||
const editor = screen.getByTestId("rich-text-editor");
|
||||
fireEvent.change(editor, { target: { value: "این متن تستی مقاله است برای سنجش ایجاد." } });
|
||||
|
||||
const submitButton = screen.getByTestId("blog-save-btn");
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/blogs", expect.objectContaining({
|
||||
title: "مقاله تست جدید",
|
||||
content: "این متن تستی مقاله است برای سنجش ایجاد.",
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith("مقاله جدید با موفقیت ذخیره شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("opens edit modal for an existing blog post and saves changes", async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("راهنمای جامع نگهداری سگ پامرانین")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editButtons = screen.getAllByTitle("ویرایش مقاله");
|
||||
fireEvent.click(editButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/ویرایش مقاله:/i, { selector: "h3" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const titleInput = screen.getByTestId("blog-title-input");
|
||||
expect(titleInput).toHaveValue("راهنمای جامع نگهداری سگ پامرانین");
|
||||
|
||||
fireEvent.change(titleInput, { target: { value: "راهنمای جامع نگهداری سگ پامرانین ویرایش شده" } });
|
||||
|
||||
const saveButton = screen.getByTestId("blog-save-btn");
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith("/admin/blogs/blog-1", expect.objectContaining({
|
||||
title: "راهنمای جامع نگهداری سگ پامرانین ویرایش شده",
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith("مقاله با موفقیت ویرایش و بروزرسانی شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows delete confirmation and deletes blog article", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("راهنمای جامع نگهداری سگ پامرانین")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const deleteButtons = screen.getAllByTitle("حذف مقاله");
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
expect(screen.getByText(/آیا از حذف این مقاله مطمئن هستید؟/i)).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole("button", { name: /تایید/i });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/admin/blogs/blog-1");
|
||||
expect(toast.success).toHaveBeenCalledWith("مقاله با موفقیت حذف شد");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,40 +1,36 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Search,
|
||||
Plus,
|
||||
Edit2,
|
||||
Trash2,
|
||||
FileText,
|
||||
Image as ImageIcon,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Eye,
|
||||
Clock,
|
||||
Tag,
|
||||
FolderTree,
|
||||
Calendar,
|
||||
Globe,
|
||||
Share2,
|
||||
MessageSquare,
|
||||
Sparkles,
|
||||
Layers,
|
||||
X,
|
||||
ExternalLink,
|
||||
ShoppingBag,
|
||||
HelpCircle,
|
||||
Pin,
|
||||
Send,
|
||||
Calendar,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Edit2,
|
||||
Eye,
|
||||
FileText,
|
||||
FolderTree,
|
||||
Globe,
|
||||
Image as ImageIcon,
|
||||
Layers,
|
||||
Pin,
|
||||
Plus,
|
||||
Search,
|
||||
Share2,
|
||||
ShoppingBag,
|
||||
Sparkles,
|
||||
Tag,
|
||||
Trash2,
|
||||
X,
|
||||
XCircle
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import RichTextEditor from '../components/ui/RichTextEditor';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import RichTextEditor from '../components/ui/RichTextEditor';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
|
||||
export interface BlogCategory {
|
||||
id: string;
|
||||
@@ -556,7 +552,7 @@ export default function Blogs() {
|
||||
};
|
||||
|
||||
// Helper status badge
|
||||
const renderStatusBadge = (status: string, isPublished: boolean, scheduledAt?: string | null) => {
|
||||
const renderStatusBadge = (status: string, _isPublished: boolean, scheduledAt?: string | null) => {
|
||||
switch (status) {
|
||||
case 'PUBLISHED':
|
||||
return (
|
||||
@@ -1216,13 +1212,11 @@ export default function Blogs() {
|
||||
const content = formData.content || '';
|
||||
const title = formData.title || '';
|
||||
const metaTitle = formData.metaTitle || '';
|
||||
const metaDesc = formData.metaDescription || '';
|
||||
const focusKey = formData.focusKeywords ? formData.focusKeywords.toLowerCase().trim() : '';
|
||||
|
||||
const textOnly = content.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
const wordsCount = textOnly ? textOnly.split(' ').length : 0;
|
||||
|
||||
const hasH1InContent = /<h1[^>]*>/i.test(content);
|
||||
const h2Matches = (content.match(/<h2[^>]*>/gi) || []).length;
|
||||
const h3Matches = (content.match(/<h3[^>]*>/gi) || []).length;
|
||||
|
||||
@@ -1231,20 +1225,15 @@ export default function Blogs() {
|
||||
const imgsWithoutAlt = imgTags.filter(img => !/alt=["'][^"']+["']/i.test(img)).length + (!formData.imageAlt && formData.imageUrl ? 1 : 0);
|
||||
|
||||
const hasInternalLinks = /href=["'](\/|https?:\/\/(www\.)?canina\.ir)[^"']*["']/i.test(content);
|
||||
const hasExternalLinks = /href=["']https?:\/\/(?!(www\.)?canina\.ir)[^"']+["']/i.test(content);
|
||||
|
||||
let keyDensity = 0;
|
||||
let keywordFoundInTitle = false;
|
||||
let keywordFoundInDesc = false;
|
||||
let keywordFoundInContent = false;
|
||||
|
||||
if (focusKey) {
|
||||
const regex = new RegExp(focusKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
|
||||
const occurrences = (textOnly.match(regex) || []).length;
|
||||
keyDensity = wordsCount > 0 ? Number(((occurrences / wordsCount) * 100).toFixed(1)) : 0;
|
||||
keywordFoundInTitle = (title + ' ' + metaTitle).toLowerCase().includes(focusKey);
|
||||
keywordFoundInDesc = metaDesc.toLowerCase().includes(focusKey);
|
||||
keywordFoundInContent = occurrences > 0;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { fireEvent,render,screen,waitFor } from "@testing-library/react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { beforeEach,describe,expect,it,vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import CMS from "./CMS";
|
||||
|
||||
vi.mock("../services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("CMS Page Component", () => {
|
||||
const mockBanners = [
|
||||
{
|
||||
id: "banner-1",
|
||||
title: "مکملهای مفاصل و استخوان",
|
||||
subtitle: "تضمین سلامت حرکتی سگ و گربه شما با فرمولاسیون آلمانی کنینا",
|
||||
imageUrl: "/assets/images/joint-banner.png",
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: "banner-2",
|
||||
title: "تغذیه تخصصی و ویتامینها",
|
||||
subtitle: "کاملترین سبد مکملهای ویتامینه",
|
||||
imageUrl: "/assets/images/vitamins.png",
|
||||
isActive: true,
|
||||
},
|
||||
];
|
||||
|
||||
const mockTestimonials = [
|
||||
{
|
||||
id: "testi-1",
|
||||
vetName: "دکتر امیر رضایی",
|
||||
clinicName: "بیمارستان دامپزشکی پایتخت",
|
||||
quote: "اثربخشی کانهیدروکس گگ در سگهای مبتلا به دیسپلازی لگن بینظیر است.",
|
||||
},
|
||||
{
|
||||
id: "testi-2",
|
||||
vetName: "دکتر مریم کاظمی",
|
||||
clinicName: "کلینیک مرکزی البرز",
|
||||
quote: "بهترین انتخاب برای مکملهای مفاصل در نژادهای درشت.",
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === "/admin/cms/hero-banners") {
|
||||
return Promise.resolve({ data: mockBanners });
|
||||
}
|
||||
if (url === "/admin/cms/vet-testimonials") {
|
||||
return Promise.resolve({ data: mockTestimonials });
|
||||
}
|
||||
return Promise.resolve({ data: [] });
|
||||
});
|
||||
});
|
||||
|
||||
const renderComponent = (initialEntries = ["/cms"]) =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<CMS />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
it("renders CMS page title, tabs, and hero banners by default", async () => {
|
||||
renderComponent();
|
||||
|
||||
expect(screen.getByText(/مدیریت محتوای پویا \(CMS\)/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "بنرهای هیرو" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "نظرات دامپزشکان" })).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("مکملهای مفاصل و استخوان")).toBeInTheDocument();
|
||||
expect(screen.getByText("تغذیه تخصصی و ویتامینها")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText("تضمین سلامت حرکتی سگ و گربه شما با فرمولاسیون آلمانی کنینا")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("switches to vet testimonials tab and renders testimonials list", async () => {
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("مکملهای مفاصل و استخوان")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const testimonialsTab = screen.getByRole("button", { name: "نظرات دامپزشکان" });
|
||||
fireEvent.click(testimonialsTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/دکتر امیر رضایی/i)).toBeInTheDocument();
|
||||
expect(screen.getByText("بیمارستان دامپزشکی پایتخت")).toBeInTheDocument();
|
||||
expect(screen.getByText(/"اثربخشی کانهیدروکس گگ در سگهای مبتلا به دیسپلازی لگن بینظیر است."/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.queryByText("مکملهای مفاصل و استخوان")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates a new hero banner successfully", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("مکملهای مفاصل و استخوان")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const titleInput = screen.getByPlaceholderText("تخصص آلمانی در خدمت سلامت پت...");
|
||||
const subtitleInput = screen.getByPlaceholderText("توضیحات بنر...");
|
||||
const imageInput = screen.getByPlaceholderText("/assets/images/...");
|
||||
|
||||
fireEvent.change(titleInput, { target: { value: "جشنواره فروش پاییزه" } });
|
||||
fireEvent.change(subtitleInput, { target: { value: "تا ۲۰٪ تخفیف روی تمامی مکملها" } });
|
||||
fireEvent.change(imageInput, { target: { value: "/assets/images/autumn-sale.png" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: "ثبت بنر جدید" });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/cms/hero-banners", {
|
||||
title: "جشنواره فروش پاییزه",
|
||||
subtitle: "تا ۲۰٪ تخفیف روی تمامی مکملها",
|
||||
imageUrl: "/assets/images/autumn-sale.png",
|
||||
isActive: true,
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith("بنر با موفقیت ایجاد شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("handles hero banner creation error", async () => {
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error("Server error"));
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("مکملهای مفاصل و استخوان")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const titleInput = screen.getByPlaceholderText("تخصص آلمانی در خدمت سلامت پت...");
|
||||
fireEvent.change(titleInput, { target: { value: "بنر ناموفق" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: "ثبت بنر جدید" });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith("خطا در ایجاد بنر");
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes a hero banner after confirmation", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("مکملهای مفاصل و استخوان")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const deleteButtons = screen.getAllByRole("button", { name: "حذف" });
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
expect(screen.getByText("حذف بنر")).toBeInTheDocument();
|
||||
expect(screen.getByText("آیا از حذف این بنر مطمئن هستید؟")).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole("button", { name: "تایید" });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/admin/cms/hero-banners/banner-1");
|
||||
expect(toast.success).toHaveBeenCalledWith("بنر با موفقیت حذف شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a new vet testimonial successfully", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
const testimonialsTab = screen.getByRole("button", { name: "نظرات دامپزشکان" });
|
||||
fireEvent.click(testimonialsTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/دکتر امیر رضایی/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const vetInput = screen.getByPlaceholderText("دکتر علی محمدی");
|
||||
const clinicInput = screen.getByPlaceholderText("کلینیک دامپزشکی پایتخت");
|
||||
const quoteInput = screen.getByPlaceholderText("تجربه استفاده از Canhydrox GAG...");
|
||||
|
||||
fireEvent.change(vetInput, { target: { value: "دکتر سارا نوری" } });
|
||||
fireEvent.change(clinicInput, { target: { value: "کلینیک مهر" } });
|
||||
fireEvent.change(quoteInput, { target: { value: "تجربه بسیار عالی از مکملهای کلسیم و مالت کنینا." } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: "ثبت نظر جدید" });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/cms/vet-testimonials", {
|
||||
vetName: "دکتر سارا نوری",
|
||||
clinicName: "کلینیک مهر",
|
||||
quote: "تجربه بسیار عالی از مکملهای کلسیم و مالت کنینا.",
|
||||
rating: 5,
|
||||
isActive: true,
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith("نظر دامپزشک ثبت شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes a vet testimonial after confirmation", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
const testimonialsTab = screen.getByRole("button", { name: "نظرات دامپزشکان" });
|
||||
fireEvent.click(testimonialsTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/دکتر امیر رضایی/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const deleteButtons = screen.getAllByRole("button", { name: "حذف" });
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
expect(screen.getByText("حذف نظر دامپزشک")).toBeInTheDocument();
|
||||
expect(screen.getByText("آیا از حذف این نظر مطمئن هستید؟")).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole("button", { name: "تایید" });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/admin/cms/vet-testimonials/testi-1");
|
||||
expect(toast.success).toHaveBeenCalledWith("نظر با موفقیت حذف شد");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React,{ useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
export interface HeroBanner {
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Categories from './Categories';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://canina.ir',
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../components/ui/MediaSelector', () => ({
|
||||
default: ({ isOpen, onSelect }: { isOpen: boolean; onSelect: (url: string) => void }) => {
|
||||
if (!isOpen) return null;
|
||||
return (
|
||||
<div data-testid="media-selector-mock">
|
||||
<button onClick={() => onSelect('/uploads/selected-category.png')}>
|
||||
تایید انتخاب تصویر
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Categories Page', () => {
|
||||
const mockCategories = [
|
||||
{
|
||||
id: 'cat-1',
|
||||
name: 'مکملهای غذایی',
|
||||
slug: 'food-supplements',
|
||||
description: 'انواع مکملهای تقویتی و درمانی',
|
||||
metaTitle: 'خرید مکمل غذایی سگ و گربه',
|
||||
metaDescription: 'بهترین مکملهای غذایی با قیمت مناسب',
|
||||
imageUrl: '/images/cat-1.png',
|
||||
},
|
||||
{
|
||||
id: 'cat-2',
|
||||
name: 'محصولات بهداشتی',
|
||||
slug: 'hygiene-products',
|
||||
description: 'شامپو و لوسیون',
|
||||
metaTitle: '',
|
||||
metaDescription: '',
|
||||
imageUrl: '',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
data: mockCategories,
|
||||
meta: { lastPage: 2, total: 15 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const renderCategories = (initialEntries = ['/categories']) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<Categories />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders category list and page header correctly', async () => {
|
||||
renderCategories();
|
||||
|
||||
expect(screen.getByText('مدیریت دستهبندیها')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /دستهبندی جدید/i })).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مکملهای غذایی')).toBeInTheDocument();
|
||||
expect(screen.getByText('food-supplements')).toBeInTheDocument();
|
||||
expect(screen.getByText('محصولات بهداشتی')).toBeInTheDocument();
|
||||
expect(screen.getByText('hygiene-products')).toBeInTheDocument();
|
||||
expect(screen.getByText('تکمیل')).toBeInTheDocument();
|
||||
expect(screen.getByText('ناقص')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('filters categories when typing in search input', async () => {
|
||||
renderCategories();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مکملهای غذایی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('جستجو در نام و اسلاگ...');
|
||||
fireEvent.change(searchInput, { target: { value: 'بهداشتی' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/categories', {
|
||||
params: expect.objectContaining({
|
||||
search: 'بهداشتی',
|
||||
page: 1,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('opens add category modal and creates a new category', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCategories();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مکملهای غذایی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const addBtn = screen.getByRole('button', { name: /دستهبندی جدید/i });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(screen.getByText('افزودن دستهبندی جدید')).toBeInTheDocument();
|
||||
|
||||
const nameLabel = screen.getByText(/نام دستهبندی \*/i);
|
||||
const nameInput = nameLabel.parentElement!.querySelector('input')!;
|
||||
const slugLabel = screen.getByText(/اسلاگ \(Slug\) \*/i);
|
||||
const slugInput = slugLabel.parentElement!.querySelector('input')!;
|
||||
const descLabel = screen.getByText(/توضیحات دستهبندی/i);
|
||||
const descInput = descLabel.parentElement!.querySelector('textarea')!;
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'ویتامینها' } });
|
||||
fireEvent.change(slugInput, { target: { value: 'vitamins' } });
|
||||
fireEvent.change(descInput, { target: { value: 'قرص و قطره ویتامین' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /ذخیره دستهبندی/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/categories', expect.objectContaining({
|
||||
name: 'ویتامینها',
|
||||
slug: 'vitamins',
|
||||
description: 'قرص و قطره ویتامین',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('دستهبندی جدید با موفقیت ایجاد شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens edit modal and updates existing category', async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCategories();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مکملهای غذایی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('مکملهای غذایی').closest('tr');
|
||||
const actionBtns = firstRow?.querySelectorAll('button');
|
||||
expect(actionBtns && actionBtns.length >= 1).toBe(true);
|
||||
if (actionBtns && actionBtns[0]) {
|
||||
fireEvent.click(actionBtns[0]);
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('ویرایش دستهبندی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const nameLabel = screen.getByText(/نام دستهبندی \*/i);
|
||||
const nameInput = nameLabel.parentElement?.querySelector('input') as HTMLInputElement;
|
||||
expect(nameInput.value).toBe('مکملهای غذایی');
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'مکملهای درمانی سگ' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /ذخیره دستهبندی/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
'/admin/categories/cat-1',
|
||||
expect.objectContaining({
|
||||
name: 'مکملهای درمانی سگ',
|
||||
slug: 'food-supplements',
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith('دستهبندی با موفقیت ویرایش شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens delete confirm modal and deletes a category', async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCategories();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مکملهای غذایی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('مکملهای غذایی').closest('tr');
|
||||
const actionBtns = firstRow?.querySelectorAll('button');
|
||||
expect(actionBtns && actionBtns.length >= 2).toBe(true);
|
||||
|
||||
if (actionBtns) {
|
||||
fireEvent.click(actionBtns[1]);
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('حذف دستهبندی')).toBeInTheDocument();
|
||||
expect(screen.getByText(/آیا از حذف این دستهبندی مطمئن هستید؟/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: /تایید|حذف/i });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/admin/categories/cat-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('دستهبندی با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('displays empty state when no categories are returned', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
data: [],
|
||||
meta: { lastPage: 1, total: 0 },
|
||||
},
|
||||
});
|
||||
|
||||
renderCategories();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('هیچ دستهبندی یافت نشد')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Search, Plus, Edit2, Trash2, FolderTree, Image as ImageIcon, X } from 'lucide-react';
|
||||
import { Edit2,FolderTree,Image as ImageIcon,Plus,Search,Trash2 } from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ContactSubmissions from './ContactSubmissions';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), put: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
|
||||
const submission = { id: 's1', name: 'Sender', phone: '09120000000', email: 'sender@example.com', subject: 'Question', message: 'Full message', status: 'PENDING', adminNotes: 'Existing note', createdAt: '2026-03-01' };
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(api.get).mockImplementation(async url => ({ data: url === '/contact/submissions' ? { items: [submission] } : [{ key: 'office', title: 'Office', value: 'Address', icon: 'map', order: 1 }] }));
|
||||
vi.mocked(api.put).mockResolvedValue({ data: {} });
|
||||
});
|
||||
async function open() { render(<ContactSubmissions />); fireEvent.click(await screen.findByRole('button', { name: 'مشاهده & تغییر وضعیت' })); }
|
||||
describe('ContactSubmissions', () => {
|
||||
it('shows sender, full message and saved notes', async () => {
|
||||
await open(); expect(screen.getByText('Full message')).toBeInTheDocument(); expect(screen.getByText(/sender@example.com/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('textbox')).toHaveValue('Existing note'); expect(screen.getByRole('combobox')).toHaveValue('PENDING');
|
||||
});
|
||||
it.each(['IN_PROGRESS', 'RESOLVED'])('updates status %s and refreshes submissions', async status => {
|
||||
await open(); fireEvent.change(screen.getByRole('combobox'), { target: { value: status } });
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Followed up' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalledWith('/contact/submissions/s1', { status, adminNotes: 'Followed up' }));
|
||||
await waitFor(() => expect(screen.queryByText('Full message')).not.toBeInTheDocument()); expect(api.get).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it('keeps failed update editable without claiming success', async () => {
|
||||
vi.mocked(api.put).mockRejectedValue(new Error('offline')); await open(); fireEvent.click(screen.getByRole('button', { name: 'ثبت تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalled()); expect(screen.getByRole('textbox')).toHaveValue('Existing note'); expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
it('cancels without mutating', async () => { await open(); fireEvent.click(screen.getByRole('button', { name: 'انصراف' })); expect(screen.queryByText('Full message')).not.toBeInTheDocument(); expect(api.put).not.toHaveBeenCalled(); });
|
||||
it('edits contact info preserving item identifiers', async () => {
|
||||
render(<ContactSubmissions />); await screen.findByText('Sender'); fireEvent.click(screen.getByRole('button', { name: 'اطلاعات نمایندگی & آدرسها' }));
|
||||
fireEvent.change(screen.getByDisplayValue('Office'), { target: { value: 'New office' } }); fireEvent.change(screen.getByDisplayValue('Address'), { target: { value: 'New address' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات اطلاعات نمایندگی' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalledWith('/contact/info', { items: [{ key: 'office', title: 'New office', value: 'New address', icon: 'map', order: 1 }] })); expect(toast.success).toHaveBeenCalled();
|
||||
});
|
||||
it('handles failed initial requests with empty state', async () => {
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(<ContactSubmissions />);
|
||||
await waitFor(() => expect(api.get).toHaveBeenCalledTimes(2)); expect(screen.getByText('هیچ پیامی ثبت نشده است.')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
it('does not report successful info save on rejection', async () => {
|
||||
vi.mocked(api.put).mockRejectedValue(new Error('offline')); render(<ContactSubmissions />); await screen.findByText('Sender'); fireEvent.click(screen.getByRole('button', { name: 'اطلاعات نمایندگی & آدرسها' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات اطلاعات نمایندگی' })); await waitFor(() => expect(api.put).toHaveBeenCalled()); expect(toast.success).not.toHaveBeenCalled(); expect(screen.getByDisplayValue('Address')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Mail, MessageSquare } from 'lucide-react';
|
||||
import { Mail } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
interface ContactSubmission {
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Coupons from './Coupons';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Coupons Page Component', () => {
|
||||
const mockCoupons = [
|
||||
{
|
||||
id: 'cpn-1',
|
||||
code: 'WELCOME20',
|
||||
type: 'percent',
|
||||
value: 20,
|
||||
minCartValue: 200000,
|
||||
maxCartValue: 50000,
|
||||
maxUses: 100,
|
||||
usedCount: 25,
|
||||
expiresAt: '2026-12-31T23:59:59Z',
|
||||
isActive: true,
|
||||
targets: [
|
||||
{
|
||||
targetType: 'ROLE',
|
||||
targetId: 'User_PetOwner',
|
||||
modifierType: 'override',
|
||||
modifierValue: 25,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'cpn-2',
|
||||
code: 'FLAT50K',
|
||||
type: 'fixed',
|
||||
value: 50000,
|
||||
minCartValue: 500000,
|
||||
maxCartValue: null,
|
||||
maxUses: 50,
|
||||
usedCount: 50,
|
||||
expiresAt: '2026-06-30T23:59:59Z',
|
||||
isActive: false,
|
||||
targets: [],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockCoupons,
|
||||
meta: { lastPage: 1, total: 2 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const renderCoupons = (initialEntries = ['/coupons']) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<Coupons />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders coupons table, headers, codes, and target badges', async () => {
|
||||
renderCoupons();
|
||||
|
||||
expect(screen.getByText(/تخفیفهای پلیمورفیک/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /کد تخفیف جدید/i })).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('WELCOME20')).toBeInTheDocument();
|
||||
expect(screen.getByText('20٪')).toBeInTheDocument();
|
||||
expect(screen.getByText('1 هدف')).toBeInTheDocument();
|
||||
expect(screen.getByText('FLAT50K')).toBeInTheDocument();
|
||||
expect(screen.getByText(/50,000|۵۰,۰۰۰/)).toBeInTheDocument();
|
||||
expect(screen.getByText('0 هدف')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('filters coupons by search term and requests API with debounce', async () => {
|
||||
renderCoupons();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('WELCOME20')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('جستجوی کد...');
|
||||
fireEvent.change(searchInput, { target: { value: 'WELCOME' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/coupons', {
|
||||
params: expect.objectContaining({
|
||||
search: 'WELCOME',
|
||||
page: 1,
|
||||
limit: 10,
|
||||
}),
|
||||
});
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('toggles coupon active status via status button', async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCoupons();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('WELCOME20')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const activeButtons = screen.getAllByRole('button', { name: /فعال/i });
|
||||
expect(activeButtons.length).toBeGreaterThan(0);
|
||||
|
||||
// Toggle active coupon to inactive
|
||||
fireEvent.click(activeButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/coupons/cpn-1/toggle', {
|
||||
isActive: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('opens modal and creates a new percentage coupon', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCoupons();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('WELCOME20')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const createBtn = screen.getByRole('button', { name: /کد تخفیف جدید/i });
|
||||
fireEvent.click(createBtn);
|
||||
|
||||
expect(screen.getByText('ساخت تخفیف جدید')).toBeInTheDocument();
|
||||
|
||||
const labelCode = screen.getByText(/کد تخفیف \*/);
|
||||
const codeInput = labelCode.closest('.space-y-2')?.querySelector('input');
|
||||
expect(codeInput).toBeTruthy();
|
||||
if (codeInput) {
|
||||
fireEvent.change(codeInput, { target: { value: 'SUMMER30' } });
|
||||
}
|
||||
|
||||
const percentInput = screen.getByPlaceholderText('مثال: ۲۰');
|
||||
fireEvent.change(percentInput, { target: { value: '30' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: 'ثبت تخفیف' });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/coupons', expect.objectContaining({
|
||||
code: 'SUMMER30',
|
||||
type: 'percent',
|
||||
value: 30,
|
||||
isActive: true,
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('کد تخفیف با موفقیت ایجاد شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens modal in edit mode and updates existing coupon', async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCoupons();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('WELCOME20')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('WELCOME20').closest('tr');
|
||||
const actionButtons = firstRow?.querySelectorAll('button');
|
||||
// Button order in table row: toggle status (0), edit (1), trash (2)
|
||||
expect(actionButtons && actionButtons.length >= 3).toBe(true);
|
||||
|
||||
if (actionButtons) {
|
||||
fireEvent.click(actionButtons[1]);
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('ویرایش تخفیف')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const labelCode = screen.getByText(/کد تخفیف \*/);
|
||||
const codeInput = labelCode.closest('.space-y-2')?.querySelector('input') as HTMLInputElement;
|
||||
expect(codeInput).toBeTruthy();
|
||||
expect(codeInput.value).toBe('WELCOME20');
|
||||
|
||||
fireEvent.change(codeInput, { target: { value: 'WELCOME25' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: 'ثبت تخفیف' });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/coupons/cpn-1', expect.objectContaining({
|
||||
code: 'WELCOME25',
|
||||
type: 'percent',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('کد تخفیف با موفقیت ویرایش شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens confirmation modal and deletes coupon', async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderCoupons();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('WELCOME20')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('WELCOME20').closest('tr');
|
||||
const actionButtons = firstRow?.querySelectorAll('button');
|
||||
expect(actionButtons && actionButtons.length >= 3).toBe(true);
|
||||
|
||||
if (actionButtons) {
|
||||
fireEvent.click(actionButtons[2]); // delete button
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('حذف کد تخفیف')).toBeInTheDocument();
|
||||
expect(screen.getByText(/آیا از حذف این کد تخفیف مطمئن هستید؟/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: 'تایید' });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/admin/coupons/cpn-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('کد تخفیف با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('renders empty table message when no coupons found', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { lastPage: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
renderCoupons();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('هیچ کدی یافت نشد')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Tag, Plus, Edit2, Trash2, Search, XCircle, CheckCircle2, User, Heart, ShoppingBag, FolderTree, Shield, HelpCircle } from 'lucide-react';
|
||||
import { CheckCircle2,Edit2,FolderTree,Heart,HelpCircle,Plus,Search,Shield,ShoppingBag,Tag,Trash2,User,XCircle } from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Input from '../components/ui/Input';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
export interface CouponTarget {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import { render,screen,waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Dashboard from './Dashboard';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock recharts to avoid JSDOM SVG / ResizeObserver dimensions issues
|
||||
vi.mock('recharts', () => ({
|
||||
ResponsiveContainer: ({ children }: any) => <div data-testid="responsive-container">{children}</div>,
|
||||
LineChart: ({ children, data }: any) => (
|
||||
<div data-testid="line-chart" data-chart-len={data?.length}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
Line: () => <div data-testid="line" />,
|
||||
XAxis: () => <div data-testid="x-axis" />,
|
||||
YAxis: () => <div data-testid="y-axis" />,
|
||||
CartesianGrid: () => <div data-testid="cartesian-grid" />,
|
||||
Tooltip: () => <div data-testid="tooltip" />,
|
||||
PieChart: ({ children }: any) => <div data-testid="pie-chart">{children}</div>,
|
||||
Pie: ({ children }: any) => <div data-testid="pie">{children}</div>,
|
||||
Cell: () => <div data-testid="cell" />,
|
||||
}));
|
||||
|
||||
describe('Dashboard Page Component', () => {
|
||||
const mockStats = {
|
||||
revenue: 45000000,
|
||||
newOrders: 18,
|
||||
users: 124,
|
||||
todayVisits: 850,
|
||||
categoriesDistribution: [
|
||||
{ name: 'مکمل سگ', value: 15 },
|
||||
{ name: 'مکمل گربه', value: 10 },
|
||||
{ name: 'بهداشتی', value: 7 },
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockStats,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const renderDashboard = () => {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<Dashboard />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders dashboard headers and initial zero or placeholder stats', async () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(screen.getByText('داشبورد')).toBeInTheDocument();
|
||||
expect(screen.getByText('خلاصهای از وضعیت فروشگاه کنینا')).toBeInTheDocument();
|
||||
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
|
||||
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
|
||||
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
|
||||
expect(screen.getByText('بازدید امروز')).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/dashboard/stats');
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches dashboard stats from API and renders calculated values', async () => {
|
||||
renderDashboard();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/dashboard/stats');
|
||||
});
|
||||
|
||||
// Verify formatted values in cards
|
||||
expect(await screen.findByText(`${(45000000).toLocaleString()} تومان`)).toBeInTheDocument();
|
||||
expect(screen.getByText('18')).toBeInTheDocument();
|
||||
expect(screen.getByText('124')).toBeInTheDocument();
|
||||
expect(screen.getByText('850')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders quick action navigation links with appropriate routes', async () => {
|
||||
renderDashboard();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('18')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const ordersLink = screen.getByText('سفارشات جدید').closest('a');
|
||||
expect(ordersLink).toHaveAttribute('href', '/orders');
|
||||
|
||||
const usersLink = screen.getByText('کاربران فعال').closest('a');
|
||||
expect(usersLink).toHaveAttribute('href', '/users');
|
||||
|
||||
const revenueCard = screen.getByText('درآمد کل').closest('a');
|
||||
expect(revenueCard).toHaveAttribute('href', '/reports');
|
||||
});
|
||||
|
||||
it('renders sales chart and category distribution sections', async () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(screen.getByText('روند بازدید و فروش (۷ روز گذشته)')).toBeInTheDocument();
|
||||
expect(screen.getByText('دستهبندی محصولات')).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مکمل سگ')).toBeInTheDocument();
|
||||
expect(screen.getByText('مکمل گربه')).toBeInTheDocument();
|
||||
expect(screen.getByText('بهداشتی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('line-chart')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('pie-chart')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back gracefully when API returns error', async () => {
|
||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
renderDashboard();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/dashboard/stats');
|
||||
});
|
||||
|
||||
// Default zero state should remain rendered
|
||||
expect(screen.getByText('0 تومان')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('0').length).toBeGreaterThan(0);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Activity,DollarSign,ShoppingCart,Users } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { DollarSign, ShoppingCart, Users, Activity } from 'lucide-react';
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
|
||||
import { CartesianGrid,Cell,Line,LineChart,Pie,PieChart,ResponsiveContainer,Tooltip,XAxis,YAxis } from 'recharts';
|
||||
import api from '../services/api';
|
||||
|
||||
interface CategoryDist {
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import DoctorsManager from './DoctorsManager';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://canina.ir',
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../components/ui/MediaSelector', () => ({
|
||||
default: ({ isOpen, onSelect, onClose }: any) => {
|
||||
if (!isOpen) return null;
|
||||
return (
|
||||
<div data-testid="media-selector-modal">
|
||||
<button onClick={() => onSelect('/uploads/doctors/avatar-sample.jpg')}>
|
||||
Select Avatar Media
|
||||
</button>
|
||||
<button onClick={onClose}>Close Media</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('DoctorsManager Component', () => {
|
||||
const mockDoctors = [
|
||||
{
|
||||
id: 'doc-1',
|
||||
name: 'دکتر سارا صادقی',
|
||||
title: 'متخصص تغذیه و جراحی دامپزشکی',
|
||||
clinicName: 'کلینیک دامپزشکی مهر',
|
||||
avatarUrl: '/uploads/doctors/doc1.jpg',
|
||||
bio: 'فارغالتحصیل دانشکده دامپزشکی با ۱۰ سال سابقه تخصصی.',
|
||||
cv: 'رزومه کامل: ۱۰ مقاله علمی در زمینه فیزیولوژی گوارش سگ و گربه.',
|
||||
phone: '02188888888',
|
||||
email: 'dr.sadeghi@canina.ir',
|
||||
instagram: '@dr.sadeghi',
|
||||
isActive: true,
|
||||
order: 1,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'doc-2',
|
||||
name: 'دکتر کامران احمدی',
|
||||
title: 'دامپزشک ارشد',
|
||||
clinicName: 'بیمارستان مرکزی',
|
||||
avatarUrl: 'https://cdn.example.com/doc2.png',
|
||||
bio: 'پژوهشگر مکملهای تغذیهای حیوانات خانگی.',
|
||||
cv: 'مدرس دانشگاه و محقق ارشد فارماکولوژی.',
|
||||
phone: '02199999999',
|
||||
email: 'dr.ahmadi@canina.ir',
|
||||
instagram: '@dr.ahmadi',
|
||||
isActive: false,
|
||||
order: 2,
|
||||
createdAt: '2026-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders doctors list with names, titles, clinics, and contact details', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
expect(screen.getByText('مدیریت پزشکان و کادر علمی')).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر سارا صادقی')).toBeInTheDocument();
|
||||
expect(screen.getByText('دکتر کامران احمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('متخصص تغذیه و جراحی دامپزشکی')).toBeInTheDocument();
|
||||
expect(screen.getByText('دامپزشک ارشد')).toBeInTheDocument();
|
||||
expect(screen.getByText('کلینیک دامپزشکی مهر')).toBeInTheDocument();
|
||||
expect(screen.getByText('بیمارستان مرکزی')).toBeInTheDocument();
|
||||
expect(screen.getByText('02188888888')).toBeInTheDocument();
|
||||
expect(screen.getByText('@dr.sadeghi')).toBeInTheDocument();
|
||||
expect(screen.getByText('فعال')).toBeInTheDocument();
|
||||
expect(screen.getByText('غیرفعال')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters doctors list via search input', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر سارا صادقی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: { doctors: [mockDoctors[0]] },
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/جستجو بر اساس نام، تخصص، کلینیک، رزومه/i);
|
||||
fireEvent.change(searchInput, { target: { value: 'سارا' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/doctors', {
|
||||
params: { search: 'سارا', limit: 100 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('displays empty state when no doctors found', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: [] } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پزشکی یافت نشد')).toBeInTheDocument();
|
||||
expect(screen.getByText('افزودن اولین پزشک')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('opens CV details modal and shows full curriculum vitae', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر سارا صادقی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const cvButtons = screen.getAllByRole('button', { name: /مشاهده رزومه/i });
|
||||
fireEvent.click(cvButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/رزومه علمی — دکتر سارا صادقی/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/رزومه کامل: ۱۰ مقاله علمی در زمینه فیزیولوژی گوارش سگ و گربه/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const closeButtons = screen.getAllByRole('button', { name: /بستن/i });
|
||||
fireEvent.click(closeButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText(/رزومه علمی — دکتر سارا صادقی/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a new doctor via modal with avatar selector', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر سارا صادقی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const addBtn = screen.getByRole('button', { name: /افزودن پزشک جدید/i });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(screen.getByText('افزودن پزشک جدید به کادر علمی', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText(/مثال: دکتر سارا صادقی/i);
|
||||
const clinicInput = screen.getByPlaceholderText(/مثال: بیمارستان دامپزشکی تهران/i);
|
||||
const bioInput = screen.getByPlaceholderText(/خلاصهای از سوابق و حوزه کاری.../i);
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'دکتر نیما مرادی' } });
|
||||
fireEvent.change(clinicInput, { target: { value: 'کلینیک پارس' } });
|
||||
fireEvent.change(bioInput, { target: { value: 'متخصص غدد و متابولیسم سگها' } });
|
||||
|
||||
// Open media selector
|
||||
const mediaBtn = screen.getByRole('button', { name: /گالری رسانه/i });
|
||||
fireEvent.click(mediaBtn);
|
||||
|
||||
expect(screen.getByTestId('media-selector-modal')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('Select Avatar Media'));
|
||||
|
||||
const avatarInput = screen.getByPlaceholderText(/آدرس تصویر یا انتخاب از رسانهها.../i) as HTMLInputElement;
|
||||
expect(avatarInput.value).toBe('/uploads/doctors/avatar-sample.jpg');
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: 'افزودن پزشک' });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/doctors', expect.objectContaining({
|
||||
name: 'دکتر نیما مرادی',
|
||||
clinicName: 'کلینیک پارس',
|
||||
bio: 'متخصص غدد و متابولیسم سگها',
|
||||
avatarUrl: '/uploads/doctors/avatar-sample.jpg',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('پزشک جدید با موفقیت افزوده شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('edits an existing doctor', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر سارا صادقی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editBtns = screen.getAllByTitle('ویرایش اطلاعات');
|
||||
fireEvent.click(editBtns[0]);
|
||||
|
||||
expect(screen.getByText('ویرایش اطلاعات پزشک', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText(/مثال: دکتر سارا صادقی/i);
|
||||
expect(nameInput).toHaveValue('دکتر سارا صادقی');
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'دکتر سارا صادقی نیا' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: 'ذخیره تغییرات' });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith('/doctors/doc-1', expect.objectContaining({
|
||||
name: 'دکتر سارا صادقی نیا',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('اطلاعات پزشک با موفقیت بروزرسانی شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes a doctor via confirm modal', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { doctors: mockDoctors } });
|
||||
|
||||
render(<DoctorsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر سارا صادقی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const deleteBtns = screen.getAllByTitle('حذف پزشک');
|
||||
fireEvent.click(deleteBtns[0]);
|
||||
|
||||
expect(screen.getByText(/آیا از حذف این پزشک از سامانه مطمئن هستید؟/i)).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: /تایید/i });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/doctors/doc-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('پزشک با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { Plus, Search, Edit2, Trash2, UserCheck, Star, X, ImageIcon, Phone, Mail, FileText, CheckCircle2, ShieldCheck, Globe } from 'lucide-react';
|
||||
import { Edit2,FileText,Globe,ImageIcon,Phone,Plus,Search,ShieldCheck,Trash2,UserCheck } from 'lucide-react';
|
||||
import React,{ useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
|
||||
|
||||
export interface Doctor {
|
||||
@@ -544,7 +544,7 @@ export default function DoctorsManager() {
|
||||
{/* Confirm Delete Modal */}
|
||||
<ConfirmModal
|
||||
isOpen={!!deleteTargetId}
|
||||
onClose={() => setDeleteTargetId(null)}
|
||||
onCancel={() => setDeleteTargetId(null)}
|
||||
onConfirm={handleDelete}
|
||||
title="حذف پزشک"
|
||||
message="آیا از حذف این پزشک از سامانه مطمئن هستید؟ ویدئوهای مرتبط با این پزشک بدون تغییر باقی خواهند ماند."
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import FAQManager from './FAQManager';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('FAQManager Component', () => {
|
||||
const mockFaqs = [
|
||||
{
|
||||
id: 'faq-1',
|
||||
question: 'آیا محصولات کنینا اصل هستند؟',
|
||||
answer: 'بله تمامی محصولات مستقیماً از شرکت Canina Pharma آلمان وارد میشوند.',
|
||||
order: 1,
|
||||
isActive: true,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'faq-2',
|
||||
question: 'زمان ارسال سفارشات چقدر است؟',
|
||||
answer: 'سفارشات تهران ۲۴ ساعته و شهرستانها بین ۲ الی ۳ روز کاری تحویل میشوند.',
|
||||
order: 2,
|
||||
isActive: false,
|
||||
createdAt: '2026-01-02T00:00:00Z',
|
||||
updatedAt: '2026-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders FAQs list with question, answer, and status', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
expect(screen.getByText('سوالات متداول (FAQ)')).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('آیا محصولات کنینا اصل هستند؟')).toBeInTheDocument();
|
||||
expect(screen.getByText('زمان ارسال سفارشات چقدر است؟')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText(/تمامی محصولات مستقیماً از شرکت Canina Pharma آلمان/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/سفارشات تهران ۲۴ ساعته/)).toBeInTheDocument();
|
||||
expect(screen.getByText('ترتیب: 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('ترتیب: 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('فعال')).toBeInTheDocument();
|
||||
expect(screen.getByText('غیرفعال')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays empty state when no FAQs exist', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('هیچ سوالی ثبت نشده است')).toBeInTheDocument();
|
||||
expect(screen.getByText('اولین سوال را اضافه کنید')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a new FAQ via modal', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('آیا محصولات کنینا اصل هستند؟')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const addBtn = screen.getByRole('button', { name: /افزودن سوال جدید/i });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(screen.getByText('افزودن سوال جدید', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const questionInput = screen.getByPlaceholderText(/مثال: آیا محصولات کنینا برای سگهای حساس مناسب است؟/i);
|
||||
const answerInput = screen.getByPlaceholderText(/پاسخ کامل، واضح و مفید.../i);
|
||||
|
||||
fireEvent.change(questionInput, { target: { value: 'نحوه نگهداری مکملها چیست؟' } });
|
||||
fireEvent.change(answerInput, { target: { value: 'در جای خشک و خنک نگهداری شود.' } });
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره سوال/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/faq', expect.objectContaining({
|
||||
question: 'نحوه نگهداری مکملها چیست؟',
|
||||
answer: 'در جای خشک و خنک نگهداری شود.',
|
||||
order: 2,
|
||||
isActive: true,
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('سوال جدید اضافه شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('validates empty question and answer on save', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('هیچ سوالی ثبت نشده است')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('اولین سوال را اضافه کنید'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره سوال/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
// native required or toast error
|
||||
// In handleSave: if (!formData.question.trim() || !formData.answer.trim()) toast.error('سوال و جواب اجباری هستند')
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('edits an existing FAQ', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('آیا محصولات کنینا اصل هستند؟')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Each FAQ row has toggle button, edit button, delete button
|
||||
// Or find buttons next to questions
|
||||
const faqContainer = screen.getByText('آیا محصولات کنینا اصل هستند؟').closest('.space-y-2')?.parentElement?.parentElement;
|
||||
const buttons = faqContainer?.querySelectorAll('button') || [];
|
||||
const editBtn = buttons[1]; // 0: toggle, 1: edit, 2: delete
|
||||
fireEvent.click(editBtn);
|
||||
|
||||
expect(screen.getByText('ویرایش سوال متداول', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const questionInput = screen.getByPlaceholderText(/مثال: آیا محصولات کنینا برای سگهای حساس مناسب است؟/i);
|
||||
expect(questionInput).toHaveValue('آیا محصولات کنینا اصل هستند؟');
|
||||
|
||||
fireEvent.change(questionInput, { target: { value: 'آیا محصولات کنینا اصل و اورجینال هستند؟' } });
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره سوال/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith('/faq/faq-1', expect.objectContaining({
|
||||
question: 'آیا محصولات کنینا اصل و اورجینال هستند؟',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('سوال با موفقیت بروزرسانی شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('toggles active status of an FAQ', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('آیا محصولات کنینا اصل هستند؟')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const toggleBtn = screen.getByTitle('غیرفعالسازی');
|
||||
fireEvent.click(toggleBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith('/faq/faq-1', { isActive: false });
|
||||
expect(toast.success).toHaveBeenCalledWith('غیرفعال شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes an FAQ via confirm modal', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
|
||||
render(<FAQManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('آیا محصولات کنینا اصل هستند؟')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const faqContainer = screen.getByText('آیا محصولات کنینا اصل هستند؟').closest('.space-y-2')?.parentElement?.parentElement;
|
||||
const buttons = faqContainer?.querySelectorAll('button') || [];
|
||||
const deleteBtn = buttons[2];
|
||||
fireEvent.click(deleteBtn);
|
||||
|
||||
expect(screen.getByText('آیا از حذف این سوال متداول اطمینان دارید؟')).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: /تایید/i });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/faq/faq-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('سوال حذف شد');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { HelpCircle, Plus, Edit2, Trash2, X, GripVertical, ToggleLeft, ToggleRight } from 'lucide-react';
|
||||
import { Edit2,HelpCircle,Plus,ToggleLeft,ToggleRight,Trash2 } from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
interface FAQ {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import FinancialSettingsPage from './FinancialSettingsPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const submit = () => fireEvent.submit(document.querySelector('form')!);
|
||||
describe('FinancialSettingsPage', () => {
|
||||
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/settings/financial' ? { data: { taxPercentage: '9', charityDonationOptions: ['10000', '50000'], walletWithdrawalEnabled: false } } : url === '/admin/settings' ? { success: true, data: { CHARITY_ROUND_STEP: '20000', REFILL_REWARD_PERCENT: '7' } } : { success: true, data: { roundingStep: '1000', roundingMode: 'DOWN', defaultRetailMarginPercent: '20', defaultWholesaleMarginPercent: '10' } } })); vi.mocked(api.patch).mockResolvedValue({ data: {} }); vi.mocked(api.put).mockResolvedValue({ data: { message: 'Pricing saved' } }); });
|
||||
const load = async () => { render(<FinancialSettingsPage />); await screen.findByDisplayValue('9'); };
|
||||
it('saves numeric financial/pricing values and string admin settings', async () => { await load(); fireEvent.change(screen.getByDisplayValue('9'), { target: { value: '12' } }); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Pricing saved')); expect(api.patch).toHaveBeenCalledWith('/settings/financial', expect.objectContaining({ taxPercentage: 12, charityDonationOptions: [10000, 50000] })); expect(api.put).toHaveBeenCalledWith('/admin/settings', expect.objectContaining({ TAX_PERCENTAGE: '12', CHARITY_ROUND_STEP: '20000', REFILL_REWARD_PERCENT: '7' })); expect(api.put).toHaveBeenCalledWith('/admin/pricing/settings', expect.objectContaining({ roundingStep: 1000, roundingMode: 'DOWN', defaultRetailMarginPercent: 20, applyToAllProducts: true })); });
|
||||
it('rejects out-of-range VAT through native validation', async () => { await load(); const vat = screen.getByDisplayValue('9') as HTMLInputElement; fireEvent.change(vat, { target: { value: '101' } }); expect(vat.checkValidity()).toBe(false); fireEvent.click(document.querySelector('button[type=submit]')!); expect(api.patch).not.toHaveBeenCalled(); });
|
||||
it('adds unique positive donations in sorted order', async () => { await load(); const input = screen.getByPlaceholderText('مبلغ جدید (مثال: ۱۰۰,۰۰۰)'); const add = input.parentElement!.parentElement!.querySelector('button')!; for (const amount of ['0', '10000', '20000']) { fireEvent.change(input, { target: { value: amount } }); fireEvent.click(add); } submit(); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/settings/financial', expect.objectContaining({ charityDonationOptions: [10000, 20000, 50000] }))); });
|
||||
it('reports partial save rejection without false success and can retry', async () => { await load(); vi.mocked(api.patch).mockRejectedValueOnce(new Error('offline')); submit(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بروزرسانی تنظیمات مالی')); expect(toast.success).not.toHaveBeenCalled(); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); });
|
||||
it('loads defaults after failure without updating products', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(<FinancialSettingsPage />); await screen.findByDisplayValue('10'); expect(api.put).not.toHaveBeenCalled(); });
|
||||
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { DollarSign, Save, Plus, X, Heart, Percent, Wallet, Calculator, ArrowUpRight, ArrowDownRight, Compass } from 'lucide-react';
|
||||
import { ArrowDownRight,ArrowUpRight,Calculator,Compass,DollarSign,Heart,Percent,Plus,Save,Wallet,X } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import Button from '../components/ui/Button';
|
||||
import Input from '../components/ui/Input';
|
||||
import type { FinancialSettings, PricingSettings } from '../types/admin';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
import type { FinancialSettings,PricingSettings } from '../types/admin';
|
||||
import { calculateSellingPrice } from '../utils/pricing';
|
||||
|
||||
export default function FinancialSettingsPage() {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import IngredientsManager from './IngredientsManager';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://canina.ir',
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../components/ui/MediaSelector', () => ({
|
||||
default: ({ isOpen, onSelect, onClose }: any) => {
|
||||
if (!isOpen) return null;
|
||||
return (
|
||||
<div data-testid="media-selector-modal">
|
||||
<button onClick={() => onSelect('/uploads/ingredients/mussel.png')}>
|
||||
Select Ingredient Image
|
||||
</button>
|
||||
<button onClick={onClose}>Close Media</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('IngredientsManager Component', () => {
|
||||
const mockIngredients = [
|
||||
{
|
||||
id: 'ing-1',
|
||||
nameFa: 'صدف لبسبز',
|
||||
nameEn: 'Green-Lipped Mussel',
|
||||
slug: 'green-lipped-mussel',
|
||||
scientificName: 'Perna canaliculus',
|
||||
description: 'حاوی گلیکوزآمینوگلیکان طبیعی و اسیدهای چرب امگا ۳ برای تقویت مفاصل.',
|
||||
imageUrl: '/uploads/ingredients/mussel.png',
|
||||
benefits: ['ترمیم غضروف', 'ضد التهاب مفاصل', 'تسکین درد'],
|
||||
},
|
||||
{
|
||||
id: 'ing-2',
|
||||
nameFa: 'روغن ماهی سالمون',
|
||||
nameEn: 'Salmon Oil',
|
||||
slug: 'salmon-oil',
|
||||
scientificName: 'Salmo salar oil',
|
||||
description: 'غنی از EPA و DHA جهت درخشش مو و سلامت پوست.',
|
||||
imageUrl: '',
|
||||
benefits: ['سلامت پوست و مو', 'تقویت قلب'],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders ingredients list with names, scientific name, and benefits tags', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
|
||||
render(<IngredientsManager />);
|
||||
|
||||
expect(screen.getByText(/مدیریت ترکیبات و دانشنامه علمی/i)).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('صدف لبسبز')).toBeInTheDocument();
|
||||
expect(screen.getByText('Green-Lipped Mussel')).toBeInTheDocument();
|
||||
expect(screen.getByText('روغن ماهی سالمون')).toBeInTheDocument();
|
||||
expect(screen.getByText('Salmon Oil')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Perna canaliculus')).toBeInTheDocument();
|
||||
expect(screen.getByText('Salmo salar oil')).toBeInTheDocument();
|
||||
expect(screen.getByText('ترمیم غضروف')).toBeInTheDocument();
|
||||
expect(screen.getByText('ضد التهاب مفاصل')).toBeInTheDocument();
|
||||
expect(screen.getByText('تسکین درد')).toBeInTheDocument();
|
||||
expect(screen.getByText('سلامت پوست و مو')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays empty state when no ingredients exist', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(<IngredientsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('هیچ ترکیبی ثبت نشده است')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a new ingredient with benefits tags and media selection', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
|
||||
render(<IngredientsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('صدف لبسبز')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const addBtn = screen.getByRole('button', { name: /افزودن ترکیب جدید/i });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(screen.getByText('افزودن ترکیب جدید', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const nameFaInput = screen.getByPlaceholderText(/مثال: صدف لبسبز/i);
|
||||
const nameEnInput = screen.getByPlaceholderText('Green-Lipped Mussel');
|
||||
const slugInput = screen.getByPlaceholderText('green-lipped-mussel');
|
||||
const scientificInput = screen.getByPlaceholderText('Perna canaliculus');
|
||||
const descInput = screen.getByPlaceholderText(/توضیحات بیوشیمیایی و خواص بالینی ماده را وارد کنید.../i);
|
||||
|
||||
fireEvent.change(nameFaInput, { target: { value: 'کلسیم کربنات' } });
|
||||
fireEvent.change(nameEnInput, { target: { value: 'Calcium Carbonate' } });
|
||||
fireEvent.change(slugInput, { target: { value: 'calcium-carbonate' } });
|
||||
fireEvent.change(scientificInput, { target: { value: 'CaCO3' } });
|
||||
fireEvent.change(descInput, { target: { value: 'منبع معدنی غنی کلسیم برای استحکام دندان و استخوان.' } });
|
||||
|
||||
// Open media selector
|
||||
const mediaBtn = screen.getByRole('button', { name: /انتخاب از رسانه/i });
|
||||
fireEvent.click(mediaBtn);
|
||||
|
||||
expect(screen.getByTestId('media-selector-modal')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('Select Ingredient Image'));
|
||||
|
||||
// Add benefit tag
|
||||
const benefitInput = screen.getByPlaceholderText(/تایپ کنید و اینتر بزنید/i);
|
||||
fireEvent.change(benefitInput, { target: { value: 'استحکام استخوان' } });
|
||||
const addBenefitBtn = screen.getByRole('button', { name: 'افزودن' });
|
||||
fireEvent.click(addBenefitBtn);
|
||||
|
||||
expect(screen.getByText('استحکام استخوان')).toBeInTheDocument();
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره تغییرات/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/ingredients', expect.objectContaining({
|
||||
nameFa: 'کلسیم کربنات',
|
||||
nameEn: 'Calcium Carbonate',
|
||||
slug: 'calcium-carbonate',
|
||||
scientificName: 'CaCO3',
|
||||
description: 'منبع معدنی غنی کلسیم برای استحکام دندان و استخوان.',
|
||||
imageUrl: '/uploads/ingredients/mussel.png',
|
||||
benefits: ['استحکام استخوان'],
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('ترکیب جدید با موفقیت ایجاد شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('edits an existing ingredient and removes a benefit tag', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
|
||||
render(<IngredientsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('صدف لبسبز')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole('row');
|
||||
// Row 0 is header, Row 1 is first ingredient
|
||||
const editBtn = rows[1].querySelectorAll('button')[0];
|
||||
fireEvent.click(editBtn);
|
||||
|
||||
expect(screen.getByText('ویرایش ترکیب دانشنامه', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const nameFaInput = screen.getByPlaceholderText(/مثال: صدف لبسبز/i);
|
||||
expect(nameFaInput).toHaveValue('صدف لبسبز');
|
||||
|
||||
// Remove first tag 'ترمیم غضروف' inside modal
|
||||
const tagSpan = screen.getAllByText('ترمیم غضروف')[1]; // One in table, one in modal
|
||||
const removeTagBtn = tagSpan.querySelector('button');
|
||||
if (removeTagBtn) {
|
||||
fireEvent.click(removeTagBtn);
|
||||
}
|
||||
|
||||
fireEvent.change(nameFaInput, { target: { value: 'عصاره صدف لبسبز' } });
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره تغییرات/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith('/ingredients/ing-1', expect.objectContaining({
|
||||
nameFa: 'عصاره صدف لبسبز',
|
||||
benefits: ['ضد التهاب مفاصل', 'تسکین درد'],
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('ترکیب با موفقیت بروزرسانی شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes an ingredient via confirm modal', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockIngredients });
|
||||
|
||||
render(<IngredientsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('صدف لبسبز')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole('row');
|
||||
const deleteBtn = rows[1].querySelectorAll('button')[1];
|
||||
fireEvent.click(deleteBtn);
|
||||
|
||||
expect(screen.getByText(/آیا از حذف این ترکیب دانشنامه اطمینان دارید؟/i)).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: /تایید/i });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/ingredients/ing-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('ترکیب با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { FlaskConical, Plus, Edit2, Trash2, X, Tag } from 'lucide-react';
|
||||
import { Edit2,FlaskConical,Plus,Tag,Trash2,X } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
import type { Ingredient } from '../types/admin';
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
import Login from './Login';
|
||||
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Login Page', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useAdminAuthStore.getState().clearAuth();
|
||||
});
|
||||
|
||||
const renderLogin = () => {
|
||||
return render(
|
||||
<BrowserRouter>
|
||||
<Login />
|
||||
</BrowserRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders password login form initially with all essential elements', () => {
|
||||
renderLogin();
|
||||
|
||||
expect(screen.getByText('ورود به پنل مدیریت')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('admin@canina.ir')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /ورود به سیستم/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switches between password and phone (OTP) tabs', () => {
|
||||
renderLogin();
|
||||
|
||||
const otpTab = screen.getByRole('button', { name: /ورود با پیامک \(OTP\)/i });
|
||||
fireEvent.click(otpTab);
|
||||
|
||||
expect(screen.getByPlaceholderText('09123456789')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /ارسال کد تایید پیامکی/i })).toBeInTheDocument();
|
||||
|
||||
const passTab = screen.getByRole('button', { name: /ورود با رمز عبور/i });
|
||||
fireEvent.click(passTab);
|
||||
|
||||
expect(screen.getByPlaceholderText('admin@canina.ir')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('validates phone number on OTP tab when requesting code with invalid input', async () => {
|
||||
renderLogin();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود با پیامک \(OTP\)/i }));
|
||||
|
||||
const phoneInput = screen.getByPlaceholderText('09123456789');
|
||||
fireEvent.change(phoneInput, { target: { value: '0912' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /ارسال کد تایید پیامکی/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('شماره موبایل معتبر وارد کنید');
|
||||
});
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits valid phone number and advances to OTP code step', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true, message: 'کد ارسال شد' },
|
||||
});
|
||||
|
||||
renderLogin();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود با پیامک \(OTP\)/i }));
|
||||
|
||||
const phoneInput = screen.getByPlaceholderText('09123456789');
|
||||
fireEvent.change(phoneInput, { target: { value: '09123456789' } });
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ارسال کد تایید پیامکی/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/send-otp', {
|
||||
phoneNumber: '09123456789',
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('کد ارسال شد');
|
||||
expect(screen.getByPlaceholderText('12345')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /تایید و ورود به پنل/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('allows user to go back and change phone number from OTP step', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderLogin();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود با پیامک \(OTP\)/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText('09123456789'), {
|
||||
target: { value: '09123456789' },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: /ارسال کد تایید پیامکی/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText('12345')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /تغییر شماره/i }));
|
||||
|
||||
expect(screen.getByPlaceholderText('09123456789')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('validates short OTP code', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderLogin();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود با پیامک \(OTP\)/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText('09123456789'), {
|
||||
target: { value: '09123456789' },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: /ارسال کد تایید پیامکی/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText('12345')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('12345'), { target: { value: '12' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /تایید و ورود به پنل/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('کد تایید معتبر وارد کنید');
|
||||
});
|
||||
});
|
||||
|
||||
it('submits OTP code, updates auth store, and navigates on success', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderLogin();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود با پیامک \(OTP\)/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText('09123456789'), {
|
||||
target: { value: '09123456789' },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: /ارسال کد تایید پیامکی/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText('12345')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const fakeAdmin = {
|
||||
id: 'admin-1',
|
||||
fullName: 'مدیر تستی',
|
||||
email: 'admin@canina.ir',
|
||||
role: 'ADMIN' as const,
|
||||
status: 'ACTIVE' as const,
|
||||
createdAt: '2026-01-01',
|
||||
};
|
||||
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
accessToken: 'jwt-otp-token',
|
||||
user: fakeAdmin,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('12345'), { target: { value: '12345' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /تایید و ورود به پنل/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/verify-otp', {
|
||||
phoneNumber: '09123456789',
|
||||
code: '12345',
|
||||
});
|
||||
const state = useAdminAuthStore.getState();
|
||||
expect(state.accessToken).toBe('jwt-otp-token');
|
||||
expect(state.adminUser).toEqual(fakeAdmin);
|
||||
expect(state.isAuthenticated).toBe(true);
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/');
|
||||
});
|
||||
});
|
||||
|
||||
it('handles password login success by setting auth store and navigating', async () => {
|
||||
const fakeAdmin = {
|
||||
id: 'admin-2',
|
||||
fullName: 'مدیر اصلی',
|
||||
email: 'admin@canina.ir',
|
||||
role: 'SUPER_ADMIN' as const,
|
||||
status: 'ACTIVE' as const,
|
||||
createdAt: '2026-01-01',
|
||||
};
|
||||
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
accessToken: 'jwt-admin-token',
|
||||
user: fakeAdmin,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
renderLogin();
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('admin@canina.ir'), {
|
||||
target: { value: 'admin@canina.ir' },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText('••••••••'), {
|
||||
target: { value: 'Secret123!' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود به سیستم/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/admin-login', {
|
||||
email: 'admin@canina.ir',
|
||||
password: 'Secret123!',
|
||||
});
|
||||
const state = useAdminAuthStore.getState();
|
||||
expect(state.accessToken).toBe('jwt-admin-token');
|
||||
expect(state.adminUser).toEqual(fakeAdmin);
|
||||
expect(state.isAuthenticated).toBe(true);
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/');
|
||||
});
|
||||
});
|
||||
|
||||
it('shows error toast when password login returns unsuccessful status', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: false,
|
||||
},
|
||||
});
|
||||
|
||||
renderLogin();
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('admin@canina.ir'), {
|
||||
target: { value: 'admin@canina.ir' },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText('••••••••'), {
|
||||
target: { value: 'WrongPassword' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /ورود به سیستم/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('اطلاعات ورود نامعتبر است');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ChevronLeft,KeyRound,Lock,Mail,Phone } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Lock, Mail, Phone, ChevronLeft, KeyRound } from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
import type { ApiResponse, AuthResponseData } from '../types/admin';
|
||||
import type { ApiResponse,AuthResponseData } from '../types/admin';
|
||||
|
||||
export default function Login() {
|
||||
const [loginMode, setLoginMode] = useState<'password' | 'otp'>('password');
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import { fireEvent,render,screen,waitFor } from "@testing-library/react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { beforeEach,describe,expect,it,vi } from "vitest";
|
||||
import api,{ BASE_DOMAIN } from "../services/api";
|
||||
import MediaManager from "./Media";
|
||||
|
||||
vi.mock("../services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: "https://canina.ir",
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("MediaManager Page Component", () => {
|
||||
const mockMediaList = [
|
||||
{
|
||||
id: "media-1",
|
||||
url: "/uploads/canina-dog-food.png",
|
||||
filename: "canina-dog-food.png",
|
||||
mimetype: "image/png",
|
||||
size: 1024 * 500, // 500 KB
|
||||
altText: "عکس غذای سگ کنینا",
|
||||
title: "غذای سگ",
|
||||
description: "توضیحات عکس غذای سگ",
|
||||
caption: "کپشن عکس",
|
||||
createdAt: "2025-01-01T12:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "media-2",
|
||||
url: "/uploads/cat-guide-video.mp4",
|
||||
filename: "cat-guide-video.mp4",
|
||||
mimetype: "video/mp4",
|
||||
size: 1024 * 1024 * 5, // 5 MB
|
||||
createdAt: "2025-01-02T14:30:00Z",
|
||||
},
|
||||
{
|
||||
id: "media-3",
|
||||
url: "/uploads/care-podcast.mp3",
|
||||
filename: "care-podcast.mp3",
|
||||
mimetype: "audio/mp3",
|
||||
size: 1024 * 1024 * 2, // 2 MB
|
||||
createdAt: "2025-01-03T09:15:00Z",
|
||||
},
|
||||
{
|
||||
id: "media-4",
|
||||
url: "/uploads/canina-catalog.pdf",
|
||||
filename: "canina-catalog.pdf",
|
||||
mimetype: "application/pdf",
|
||||
size: 1024 * 800, // 800 KB
|
||||
createdAt: "2025-01-04T16:45:00Z",
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.assign(navigator, {
|
||||
clipboard: {
|
||||
writeText: vi.fn().mockImplementation(() => Promise.resolve()),
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === "/admin/media") {
|
||||
return Promise.resolve({ data: { data: mockMediaList } });
|
||||
}
|
||||
return Promise.resolve({ data: [] });
|
||||
});
|
||||
});
|
||||
|
||||
it("renders media gallery grid with files correctly", async () => {
|
||||
render(<MediaManager />);
|
||||
|
||||
expect(screen.getByText("مدیریت رسانه و فایلها")).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
expect(screen.getByText("cat-guide-video.mp4")).toBeInTheDocument();
|
||||
expect(screen.getByText("care-podcast.mp3")).toBeInTheDocument();
|
||||
expect(screen.getByText("canina-catalog.pdf")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText("4 فایل · 8.3 MB فضا اشغال شده")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters media items by search input and file type tabs", async () => {
|
||||
render(<MediaManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Search filter
|
||||
const searchInput = screen.getByPlaceholderText("جستجو در نام فایلها...");
|
||||
fireEvent.change(searchInput, { target: { value: "cat-guide" } });
|
||||
|
||||
expect(screen.getByText("cat-guide-video.mp4")).toBeInTheDocument();
|
||||
expect(screen.queryByText("canina-dog-food.png")).not.toBeInTheDocument();
|
||||
|
||||
// Clear search
|
||||
fireEvent.change(searchInput, { target: { value: "" } });
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
|
||||
// Filter by type: تصاویر
|
||||
const imagesTab = screen.getByRole("button", { name: "تصاویر" });
|
||||
fireEvent.click(imagesTab);
|
||||
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
expect(screen.queryByText("cat-guide-video.mp4")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("care-podcast.mp3")).not.toBeInTheDocument();
|
||||
|
||||
// Filter by type: اسناد PDF
|
||||
const pdfTab = screen.getByRole("button", { name: "اسناد PDF" });
|
||||
fireEvent.click(pdfTab);
|
||||
|
||||
expect(screen.getByText("canina-catalog.pdf")).toBeInTheDocument();
|
||||
expect(screen.queryByText("canina-dog-food.png")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("triggers file upload and sends multipart post request", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
const { container } = render(<MediaManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const fileInput = container.querySelector("input[type=\"file\"]") as HTMLInputElement;
|
||||
expect(fileInput).not.toBeNull();
|
||||
|
||||
const file = new File(["dummy image content"], "new-uploaded-banner.jpg", {
|
||||
type: "image/jpeg",
|
||||
});
|
||||
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/admin/media/upload",
|
||||
expect.any(FormData),
|
||||
expect.objectContaining({
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith("1 فایل با موفقیت آپلود شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("copies media URL to clipboard", async () => {
|
||||
render(<MediaManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const copyButtons = screen.getAllByTitle("کپی لینک");
|
||||
expect(copyButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(copyButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
|
||||
`${BASE_DOMAIN}/uploads/canina-dog-food.png`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("opens delete confirmation modal and deletes single media file", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<MediaManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const deleteButtons = screen.getAllByTitle("حذف");
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
expect(screen.getByText("آیا از حذف این تصویر مطمئن هستید؟ این عملیات قابل بازگشت نیست.")).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole("button", { name: "تایید" });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/admin/media/media-1");
|
||||
expect(toast.success).toHaveBeenCalledWith("فایل با موفقیت حذف شد");
|
||||
});
|
||||
|
||||
// Item should be removed from view
|
||||
expect(screen.queryByText("canina-dog-food.png")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("edits image SEO attributes and updates via PUT", async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<MediaManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const seoButtons = screen.getAllByTitle("تنظیمات سئو");
|
||||
fireEvent.click(seoButtons[0]);
|
||||
|
||||
expect(screen.getByText("تنظیمات سئوی تصویر")).toBeInTheDocument();
|
||||
|
||||
const altInput = screen.getByPlaceholderText("مثال: عکس مکمل کانیدروکس گپ کنینا");
|
||||
expect(altInput).toHaveValue("عکس غذای سگ کنینا");
|
||||
|
||||
fireEvent.change(altInput, { target: { value: "عکس جدید غذای سگ کنینا اصل آلمان" } });
|
||||
|
||||
const saveButton = screen.getByRole("button", { name: "ذخیره سئو" });
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith("/admin/media/media-1", expect.objectContaining({
|
||||
altText: "عکس جدید غذای سگ کنینا اصل آلمان",
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith("تنظیمات سئوی تصویر با موفقیت ذخیره شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("supports multi-selection and bulk deletion", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<MediaManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("canina-dog-food.png")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const selectAllBtn = screen.getByRole("button", { name: /انتخاب همه در این صفحه/i });
|
||||
fireEvent.click(selectAllBtn);
|
||||
|
||||
expect(screen.getByText("4 مورد انتخاب شده")).toBeInTheDocument();
|
||||
|
||||
const bulkDeleteBtn = screen.getByRole("button", { name: /حذف موارد انتخابشده/i });
|
||||
fireEvent.click(bulkDeleteBtn);
|
||||
|
||||
expect(screen.getByText("حذف گروهی تصاویر")).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole("button", { name: "تایید" });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/admin/media/bulk", {
|
||||
data: { ids: ["media-1", "media-2", "media-3", "media-4"] },
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith("4 فایل با موفقیت حذف شد");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { Upload, Image as ImageIcon, Trash2, Copy, CheckCircle2, Search, X, FolderOpen, FileText, Music, Play } from 'lucide-react';
|
||||
import { CheckCircle2,Copy,FileText,FolderOpen,Image as ImageIcon,Music,Play,Search,Trash2,Upload,X } from 'lucide-react';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import ImagePreviewModal from '../components/ui/ImagePreviewModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { fireEvent,render,screen,waitFor } from "@testing-library/react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { beforeEach,describe,expect,it,vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import MenuManager from "./MenuManager";
|
||||
|
||||
vi.mock("../services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("MenuManager Page Component", () => {
|
||||
const mockMenuItems = [
|
||||
{
|
||||
id: "menu-1",
|
||||
menuType: "HEADER",
|
||||
label: "فروشگاه تخصصی",
|
||||
href: "/shop",
|
||||
parentId: null,
|
||||
order: 1,
|
||||
isActive: true,
|
||||
isExternal: false,
|
||||
icon: "🛒",
|
||||
badge: "جدید",
|
||||
children: [
|
||||
{
|
||||
id: "menu-1-sub",
|
||||
menuType: "HEADER",
|
||||
label: "مکملهای سگ",
|
||||
href: "/shop/dog-supplements",
|
||||
parentId: "menu-1",
|
||||
order: 1,
|
||||
isActive: true,
|
||||
isExternal: false,
|
||||
icon: null,
|
||||
badge: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "menu-2",
|
||||
menuType: "HEADER",
|
||||
label: "مقالات و دانشنامه",
|
||||
href: "/wiki",
|
||||
parentId: null,
|
||||
order: 2,
|
||||
isActive: false,
|
||||
isExternal: false,
|
||||
icon: "📚",
|
||||
badge: null,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: "menu-3",
|
||||
menuType: "FOOTER_COL1",
|
||||
label: "درباره کنینا",
|
||||
href: "/about-us",
|
||||
parentId: null,
|
||||
order: 1,
|
||||
isActive: true,
|
||||
isExternal: false,
|
||||
icon: null,
|
||||
badge: null,
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({ data: mockMenuItems });
|
||||
});
|
||||
|
||||
const renderComponent = (initialEntries = ["/menu"]) =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<MenuManager />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
it("renders menu tabs and current items for HEADER by default", async () => {
|
||||
renderComponent();
|
||||
|
||||
expect(screen.getByText("مدیریت منو")).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
expect(screen.getByText("مقالات و دانشنامه")).toBeInTheDocument();
|
||||
expect(screen.getByText("مکملهای سگ")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText("/shop")).toBeInTheDocument();
|
||||
expect(screen.getByText("جدید")).toBeInTheDocument();
|
||||
expect(screen.getByText("🛒")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("switches tabs and displays items corresponding to selected tab", async () => {
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const footerTabBtn = screen.getByRole("button", { name: "🔗 فوتر — ستون ۱" });
|
||||
fireEvent.click(footerTabBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("درباره کنینا")).toBeInTheDocument();
|
||||
expect(screen.getByText("/about-us")).toBeInTheDocument();
|
||||
expect(screen.queryByText("فروشگاه تخصصی")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows empty state when a menu category has no items", async () => {
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const footerCol3Tab = screen.getByRole("button", { name: "🔗 فوتر — ستون ۳" });
|
||||
fireEvent.click(footerCol3Tab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("هیچ آیتمی در این منو وجود ندارد")).toBeInTheDocument();
|
||||
expect(screen.getByText("اولین آیتم را اضافه کنید")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles item active status successfully", async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const hideButtons = screen.getAllByTitle("مخفی کردن");
|
||||
fireEvent.click(hideButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith("/menu/menu-1", { isActive: false });
|
||||
expect(toast.success).toHaveBeenCalledWith("مخفی شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a new menu item via modal submission", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const createButton = screen.getByRole("button", { name: "آیتم جدید" });
|
||||
fireEvent.click(createButton);
|
||||
|
||||
expect(screen.getByText("افزودن آیتم جدید")).toBeInTheDocument();
|
||||
|
||||
const titleInput = screen.getByPlaceholderText("مثال: فروشگاه تخصصی");
|
||||
const hrefInput = screen.getByPlaceholderText("مثال: /shop یا https://...");
|
||||
|
||||
fireEvent.change(titleInput, { target: { value: "تماس با ما" } });
|
||||
fireEvent.change(hrefInput, { target: { value: "/contact" } });
|
||||
|
||||
const saveButton = screen.getByRole("button", { name: "ذخیره" });
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/menu",
|
||||
expect.objectContaining({
|
||||
menuType: "HEADER",
|
||||
label: "تماس با ما",
|
||||
href: "/contact",
|
||||
parentId: null,
|
||||
isActive: true,
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith("آیتم جدید اضافه شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("validates required fields before submitting form", async () => {
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const createButton = screen.getByRole("button", { name: "آیتم جدید" });
|
||||
fireEvent.click(createButton);
|
||||
|
||||
const form = document.querySelector("#menuForm");
|
||||
expect(form).toBeInTheDocument();
|
||||
fireEvent.submit(form!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith("عنوان و لینک اجباری هستند");
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("edits an existing menu item via modal", async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editBtn = document.querySelector(".text-blue-600.hover\\:bg-blue-50");
|
||||
expect(editBtn).toBeInTheDocument();
|
||||
fireEvent.click(editBtn!);
|
||||
|
||||
expect(screen.getByText("ویرایش آیتم منو")).toBeInTheDocument();
|
||||
|
||||
const titleInput = screen.getByPlaceholderText("مثال: فروشگاه تخصصی");
|
||||
expect(titleInput).toHaveValue("فروشگاه تخصصی");
|
||||
|
||||
fireEvent.change(titleInput, { target: { value: "فروشگاه محصولات اورجینال" } });
|
||||
|
||||
const saveButton = screen.getByRole("button", { name: "ذخیره" });
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
"/menu/menu-1",
|
||||
expect.objectContaining({
|
||||
label: "فروشگاه محصولات اورجینال",
|
||||
href: "/shop",
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith("آیتم منو بروزرسانی شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes a menu item after modal confirmation", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("فروشگاه تخصصی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const deleteBtn = document.querySelector(".text-red-500.hover\\:bg-red-50");
|
||||
expect(deleteBtn).toBeInTheDocument();
|
||||
fireEvent.click(deleteBtn!);
|
||||
|
||||
expect(screen.getByText("حذف آیتم منو")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("آیا از حذف این آیتم اطمینان دارید؟ آیتمهای زیرمجموعه نیز حذف خواهند شد.")
|
||||
).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole("button", { name: "تایید" });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith("/menu/menu-1");
|
||||
expect(toast.success).toHaveBeenCalledWith("آیتم حذف شد");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,18 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Menu, Plus, Edit2, Trash2, X, ExternalLink,
|
||||
Eye, EyeOff, ChevronDown, ChevronRight
|
||||
ChevronDown,ChevronRight,
|
||||
Edit2,
|
||||
ExternalLink,
|
||||
Eye,EyeOff,
|
||||
Menu,Plus,
|
||||
Trash2
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { act,fireEvent,render,screen } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import MonitoringPage from './MonitoringPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
describe('MonitoringPage', () => {
|
||||
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/payment/admin/stats' ? { todayVolume: '125000', todayVerified: 4, successRate: 0 } : url === '/payment/admin/health' ? { status: 'ONLINE', latencyMs: 250 } : { credit: 0 } })); });
|
||||
afterEach(() => vi.useRealTimers());
|
||||
const load = async () => { render(<MonitoringPage />); await screen.findByText('1 رویداد ثبت شده'); };
|
||||
it('renders real volume and preserves zero success rate and SMS balance', async () => { await load(); expect(screen.getByText('۱۲۵٬۰۰۰ تومان')).toBeInTheDocument(); expect(screen.getByText('0%')).toBeInTheDocument(); expect(screen.getAllByText(/۰ پیامک/).length).toBeGreaterThan(0); });
|
||||
it('shows offline gateway and SMS on rejected endpoints instead of false healthy states', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); await load(); expect(screen.getAllByText('غیرفعال / قطعی')).toHaveLength(2); expect(screen.queryByText('98.4%')).not.toBeInTheDocument(); });
|
||||
it('honors explicit offline health response even when latency is low', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { status: 'OFFLINE', latencyMs: 10 } : { credit: 12 } })); await load(); expect(screen.getByText('غیرفعال / قطعی')).toBeInTheDocument(); });
|
||||
it('shows slow gateway warning and refreshes all three read-only endpoints', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { latencyMs: 2000 } : { credit: 12 } })); await load(); expect(screen.getByText('کاهش سرعت / هشدار')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /بروزرسانی زنده/ })); await screen.findByText('2 رویداد ثبت شده'); expect(api.get).toHaveBeenCalledTimes(6); expect(api.post).not.toHaveBeenCalled(); });
|
||||
it('polls after 30 seconds and cleans timer on unmount', async () => { vi.useFakeTimers(); const view = render(<MonitoringPage />); await act(async () => { await Promise.resolve(); }); expect(api.get).toHaveBeenCalledTimes(3); for (let i=0; i<30; i++) await act(async () => { vi.advanceTimersByTime(1000); }); expect(api.get).toHaveBeenCalledTimes(6); view.unmount(); await act(async () => { vi.advanceTimersByTime(60000); }); expect(api.get).toHaveBeenCalledTimes(6); });
|
||||
|
||||
});
|
||||
@@ -1,29 +1,20 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Activity,
|
||||
Server,
|
||||
CreditCard,
|
||||
MessageSquare,
|
||||
Truck,
|
||||
Database,
|
||||
RefreshCw,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
XCircle,
|
||||
Clock,
|
||||
Zap,
|
||||
HardDrive,
|
||||
Cpu,
|
||||
ExternalLink,
|
||||
ShieldCheck,
|
||||
TrendingUp,
|
||||
FileText
|
||||
import {
|
||||
Activity,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
CreditCard,
|
||||
Database,
|
||||
FileText,
|
||||
MessageSquare,
|
||||
RefreshCw,
|
||||
Truck
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Button from '../components/ui/Button';
|
||||
import Badge from '../components/ui/Badge';
|
||||
import Button from '../components/ui/Button';
|
||||
import Skeleton from '../components/ui/Skeleton';
|
||||
import api from '../services/api';
|
||||
|
||||
interface MonitoringStats {
|
||||
timestamp: string;
|
||||
@@ -58,10 +49,10 @@ interface MonitoringStats {
|
||||
|
||||
export default function MonitoringPage() {
|
||||
const [stats, setStats] = useState<MonitoringStats | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [, setIsLoading] = useState(true);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [autoRefresh, setAutoRefresh] = useState(true);
|
||||
const [refreshInterval, setRefreshInterval] = useState(30); // seconds
|
||||
const [autoRefresh] = useState(true);
|
||||
const [refreshInterval] = useState(30); // seconds
|
||||
const [countdown, setCountdown] = useState(30);
|
||||
const [logs, setLogs] = useState<any[]>([]);
|
||||
|
||||
@@ -83,21 +74,21 @@ export default function MonitoringPage() {
|
||||
const txStats = txStatsRes.status === 'fulfilled' ? txStatsRes.value?.data : null;
|
||||
const health = healthRes.status === 'fulfilled' ? healthRes.value?.data : null;
|
||||
const sms = smsRes.status === 'fulfilled' ? smsRes.value?.data : null;
|
||||
const smsCreditVal = typeof sms === 'object' && sms !== null ? sms.credit || sms.balance || sms.data : sms;
|
||||
const smsCreditVal = typeof sms === 'object' && sms !== null ? sms.credit ?? sms.balance ?? sms.data : sms;
|
||||
|
||||
const newStats: MonitoringStats = {
|
||||
timestamp: new Date().toLocaleTimeString('fa-IR'),
|
||||
zibal: {
|
||||
status: health?.status === 'ONLINE' ? 'ONLINE' : health?.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
|
||||
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
|
||||
latencyMs: health?.latencyMs || Math.floor(Math.random() * 80) + 120,
|
||||
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
|
||||
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
|
||||
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
|
||||
successRate: txStats?.successRate || 98.4,
|
||||
successRate: txStats?.successRate ?? 0,
|
||||
},
|
||||
melipayamak: {
|
||||
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'ONLINE',
|
||||
credit: smsCreditVal ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'در دسترس',
|
||||
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
|
||||
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
|
||||
latencyMs: Math.floor(Math.random() * 60) + 95,
|
||||
todaySmsSent: 48,
|
||||
patternActive: true,
|
||||
@@ -159,7 +150,7 @@ export default function MonitoringPage() {
|
||||
return () => clearInterval(interval);
|
||||
}, [autoRefresh, refreshInterval, fetchMonitoringData]);
|
||||
|
||||
const getStatusBadge = (status: 'ONLINE' | 'DEGRADED' | 'OFFLINE' | 'HEALTHY' | 'CONNECTED') => {
|
||||
const getStatusBadge = (status: 'ONLINE' | 'DEGRADED' | 'OFFLINE' | 'HEALTHY' | 'CONNECTED' | 'DISCONNECTED') => {
|
||||
switch (status) {
|
||||
case 'ONLINE':
|
||||
case 'HEALTHY':
|
||||
@@ -168,6 +159,7 @@ export default function MonitoringPage() {
|
||||
case 'DEGRADED':
|
||||
return <Badge variant="warning" size="sm">کاهش سرعت / هشدار</Badge>;
|
||||
case 'OFFLINE':
|
||||
case 'DISCONNECTED':
|
||||
return <Badge variant="danger" size="sm">غیرفعال / قطعی</Badge>;
|
||||
default:
|
||||
return <Badge variant="slate" size="sm">نامشخص</Badge>;
|
||||
@@ -238,7 +230,7 @@ export default function MonitoringPage() {
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">درصد موفقیت (Success Rate):</span>
|
||||
<span className="font-mono font-bold text-emerald-600">{stats?.zibal.successRate || 98.4}%</span>
|
||||
<span className="font-mono font-bold text-emerald-600">{stats?.zibal.successRate ?? 0}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Orders from './Orders';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
post: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Orders Page Component', () => {
|
||||
const mockOrders = [
|
||||
{
|
||||
id: 'ord-101',
|
||||
trackingNumber: '1001',
|
||||
createdAt: '2025-02-01T12:00:00Z',
|
||||
status: 'processing',
|
||||
totalAmount: 1250000,
|
||||
paymentMethod: 'zibal',
|
||||
user: {
|
||||
firstName: 'سارا',
|
||||
lastName: 'کریمی',
|
||||
mobile: '09121112233',
|
||||
},
|
||||
orderItems: [
|
||||
{
|
||||
id: 'item-1',
|
||||
productTitle: 'غذای خشک سگ رویال کنین',
|
||||
quantity: 2,
|
||||
price: 500000,
|
||||
},
|
||||
],
|
||||
shippingAddress: 'تهران، خیابان ولیعصر',
|
||||
},
|
||||
{
|
||||
id: 'ord-102',
|
||||
trackingNumber: '1002',
|
||||
createdAt: '2025-02-02T15:30:00Z',
|
||||
status: 'delivered',
|
||||
totalAmount: 480000,
|
||||
paymentMethod: 'wallet',
|
||||
user: {
|
||||
firstName: 'رضا',
|
||||
lastName: 'اکبری',
|
||||
phone: '09359998877',
|
||||
},
|
||||
orderItems: [
|
||||
{
|
||||
id: 'item-2',
|
||||
productTitle: 'شامپو ضد کک گربه',
|
||||
quantity: 1,
|
||||
price: 480000,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockOrders,
|
||||
meta: { lastPage: 1 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders order list with customer name, items count, and status badge', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Orders />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('سارا کریمی')).toBeInTheDocument();
|
||||
expect(screen.getByText('رضا اکبری')).toBeInTheDocument();
|
||||
expect(screen.getByText('سفارش جدید')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles search input change and fires debounced query', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Orders />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('سارا کریمی');
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/جستجو \(شماره سفارش، خریدار، تلفن\)...|جستجو/i);
|
||||
fireEvent.change(searchInput, { target: { value: 'سارا' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith(expect.stringContaining('search=%D8%B3%D8%A7%D8%B1%D8%A7'));
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('filters orders by clicking status filter buttons', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Orders />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('سارا کریمی');
|
||||
|
||||
// Click 'تحویل شده' tab button
|
||||
const deliveredTab = screen.getByRole('button', { name: 'تحویل شده' });
|
||||
fireEvent.click(deliveredTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith(expect.stringContaining('status=delivered'));
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('opens order details view modal when view button is clicked', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Orders />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('سارا کریمی');
|
||||
|
||||
// Click first 'جزئیات' button
|
||||
const viewButtons = screen.getAllByRole('button', { name: /جزئیات/i });
|
||||
fireEvent.click(viewButtons[0]);
|
||||
|
||||
// Modal should show order details modal title
|
||||
expect(await screen.findByText(/جزئیات سفارش #1001/i)).toBeInTheDocument();
|
||||
expect(screen.getByText('تهران، خیابان ولیعصر')).toBeInTheDocument();
|
||||
|
||||
// Close modal by clicking cancel/close button
|
||||
const closeButtons = screen.getAllByRole('button', { name: 'بستن' });
|
||||
fireEvent.click(closeButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText(/جزئیات سفارش #1001/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('updates order status via table select change', async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Orders />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('سارا کریمی');
|
||||
|
||||
// Selects in order rows
|
||||
const statusSelects = screen.getAllByTestId('order-status-select');
|
||||
expect(statusSelects.length).toBeGreaterThan(0);
|
||||
|
||||
// Change status of first order to packaged
|
||||
fireEvent.change(statusSelects[0], { target: { value: 'packaged' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orders/ord-101/status', {
|
||||
status: 'packaged',
|
||||
trackingNumber: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('shows empty state when no orders match criteria', async () => {
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { lastPage: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Orders />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('هیچ سفارشی یافت نشد.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,38 +1,33 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
ShoppingCart,
|
||||
Eye,
|
||||
Search,
|
||||
X,
|
||||
Printer,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Truck,
|
||||
XCircle,
|
||||
MapPin,
|
||||
User,
|
||||
Phone,
|
||||
Mail,
|
||||
Package,
|
||||
Save,
|
||||
Download,
|
||||
PackageCheck,
|
||||
Heart,
|
||||
CreditCard,
|
||||
ArrowUpDown,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
Undo2,
|
||||
Wallet,
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpDown,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
CreditCard,
|
||||
Download,
|
||||
Eye,
|
||||
Heart,
|
||||
PackageCheck,
|
||||
Printer,
|
||||
Save,
|
||||
Search,
|
||||
ShoppingCart,
|
||||
Truck,
|
||||
Undo2,
|
||||
User,
|
||||
Wallet,
|
||||
XCircle
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Skeleton from '../components/ui/Skeleton';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Skeleton from '../components/ui/Skeleton';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
export interface OrderItem {
|
||||
@@ -118,34 +113,7 @@ export const ORDER_STATUS_MAP: Record<string, { label: string; color: string; ic
|
||||
cancelled: { label: 'لغو شده', color: 'bg-red-50 text-red-700 border-red-200', icon: XCircle },
|
||||
};
|
||||
|
||||
const getPaymentStatusBadge = (status: string) => {
|
||||
switch (status?.toLowerCase()) {
|
||||
case 'success':
|
||||
case 'paid':
|
||||
case 'completed':
|
||||
return { label: 'پرداخت موفق', color: 'bg-emerald-50 text-emerald-700 border-emerald-200' };
|
||||
case 'pending':
|
||||
case 'in_progress':
|
||||
return { label: 'در انتظار پرداخت', color: 'bg-amber-50 text-amber-700 border-amber-200' };
|
||||
case 'failed':
|
||||
case 'error':
|
||||
return { label: 'ناموفق', color: 'bg-red-50 text-red-700 border-red-200' };
|
||||
default:
|
||||
return { label: 'نامشخص', color: 'bg-gray-50 text-gray-700 border-gray-200' };
|
||||
}
|
||||
};
|
||||
|
||||
const getShippingMethodLabel = (method?: string) => {
|
||||
switch (method?.toLowerCase()) {
|
||||
case 'express':
|
||||
case 'tipax': return { label: 'تیپاکس (اکسپرس)', color: 'bg-purple-50 text-purple-700 border-purple-200' };
|
||||
case 'post':
|
||||
case 'pishtaz': return { label: 'پست پیشتاز', color: 'bg-blue-50 text-blue-700 border-blue-200' };
|
||||
case 'courier':
|
||||
case 'peyk': return { label: 'پیک اختصاصی فوری', color: 'bg-amber-50 text-amber-700 border-amber-200' };
|
||||
default: return { label: method || 'پست پیشتاز', color: 'bg-gray-50 text-gray-700 border-gray-200' };
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const getPaymentMethodLabel = (method?: string) => {
|
||||
@@ -505,7 +473,7 @@ export default function Orders() {
|
||||
<span style="font-weight: 700; color: #111827;">${pName}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: center; font-weight: 700;">${toPersianDigits(item.quantity)}</td>
|
||||
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: center; font-weight: 700;">${toPersianDigits(item.quantity ?? 0)}</td>
|
||||
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: left; font-weight: 700;">${toPersianDigits(pPrice.toLocaleString())} تومان</td>
|
||||
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: left; font-weight: 900; color: #0055FF;">${toPersianDigits(rowTotal.toLocaleString())} تومان</td>
|
||||
</tr>
|
||||
@@ -1273,7 +1241,7 @@ export default function Orders() {
|
||||
}
|
||||
}}
|
||||
title={`ثبت ارسال مرسوله - سفارش #${shippingModalOrder.trackingNumber || shippingModalOrder.id.slice(0, 8)}`}
|
||||
size="md"
|
||||
maxWidth="md"
|
||||
footer={
|
||||
<div className="flex items-center justify-end gap-3 w-full">
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import PaymentGatewaysPage from './PaymentGatewaysPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
|
||||
describe('PaymentGatewaysPage',()=>{
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => ({ data: url === '/admin/settings' ? { success: true, data: { ZIBAL_MERCHANT: 'merchant-test', PAY_GATEWAY_ONLINE_ENABLE: 'false' } } : { data: [] } })); vi.mocked(api.put).mockResolvedValue({ data: {} }); vi.mocked(api.post).mockResolvedValue({ data: { result: 1 } }); });
|
||||
const load = async () => { render(<PaymentGatewaysPage />); await screen.findByDisplayValue('merchant-test'); };
|
||||
it('hydrates disabled online payment and saves exact string flags', async () => { await load(); expect(screen.getAllByRole('checkbox')[0]).not.toBeChecked(); fireEvent.submit(document.querySelector('form')!); await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/settings', expect.objectContaining({ ZIBAL_MERCHANT: 'merchant-test', PAY_GATEWAY_ONLINE_ENABLE: 'false' }))); });
|
||||
it('reports rejected settings writes without a success toast', async () => { vi.mocked(api.put).mockRejectedValue(new Error('denied')); await load(); fireEvent.submit(document.querySelector('form')!); await waitFor(() => expect(toast.error).toHaveBeenCalled()); expect(toast.success).not.toHaveBeenCalled(); });
|
||||
it('converts refund tomans to rials and omits optional fields', async () => { await load(); fireEvent.click(screen.getByRole('button', { name: 'کیفپولهای زیبال و ریفاند' })); fireEvent.change(screen.getByPlaceholderText('مثال: 2808993485'), { target: { value: 'track-test' } }); fireEvent.change(screen.getByPlaceholderText('کل مبلغ تراکنش'), { target: { value: '250' } }); fireEvent.submit(document.querySelector('form')!); await waitFor(() => expect(api.post).toHaveBeenCalledWith('/payment/admin/refund', { trackId: 'track-test', amount: 2500, tryReverse: false, cardNumber: undefined, description: undefined })); });
|
||||
it('does not send refunds without track ID', async () => { await load(); fireEvent.click(screen.getByRole('button', { name: 'کیفپولهای زیبال و ریفاند' })); fireEvent.submit(document.querySelector('form')!); expect(api.post).not.toHaveBeenCalled(); expect(toast.error).toHaveBeenCalledWith('شناسه تراکنش (Track ID) الزامی است'); });
|
||||
});
|
||||
@@ -1,21 +1,20 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
CreditCard,
|
||||
Save,
|
||||
ShieldCheck,
|
||||
Wallet,
|
||||
ArrowLeftRight,
|
||||
CheckCircle2,
|
||||
Building2,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
Users,
|
||||
Search,
|
||||
ArrowLeftRight,
|
||||
Building2,
|
||||
CheckCircle2,
|
||||
CreditCard,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
Save,
|
||||
ShieldCheck,
|
||||
Users,
|
||||
Wallet
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Pets from './Pets';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), delete: vi.fn() }, BASE_DOMAIN: 'https://api.example.com' }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const pet = { id: 'p1', name: 'Milo', type: 'گربه', breed: 'Persian', age: 2, weight: 3, imageUrl: '/uploads/milo.jpg', user: { firstName: 'Owner', lastName: 'One', mobile: '09120000000' }, medicalConditions: [{ condition: 'Allergy' }], reminders: [{ id: 'r1', title: 'Daily pill', time: '08:00', frequency: 'daily' }], healthLogs: [{ id: 'h1', appetite: 'good', energy: 'normal', digestion: 'normal', note: 'Improved today', loggedDate: '2026-03-01', createdAt: '2026-03-01' }], prescriptions: [{ id: 'rx-12345678', status: 'APPROVED', notes: 'Patient note', adminNotes: 'Clinical note', createdAt: '2026-03-01' }] };
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { data: [pet], meta: { lastPage: 2 } } }); vi.mocked(api.delete).mockResolvedValue({ data: {} }); });
|
||||
async function load() { render(<Pets />); await screen.findByText('Milo'); }
|
||||
describe('Pets', () => {
|
||||
it('loads paginated pets with owner data and relative image URL', async () => { await load(); expect(api.get).toHaveBeenCalledWith('/admin/pets', { params: { page: 1, limit: 10, search: '' } }); expect(screen.getByText('Owner One')).toBeInTheDocument(); expect(screen.getByAltText('Milo')).toHaveAttribute('src', 'https://api.example.com/uploads/milo.jpg'); expect(screen.getByText('1 یادآور • 1 گزارش')).toBeInTheDocument(); });
|
||||
it('opens complete health dossier and closes without mutation', async () => { await load(); fireEvent.click(screen.getByTitle('مشاهده پرونده کامل سلامت')); for (const text of ['Allergy', 'Daily pill', 'Improved today', 'APPROVED']) expect(screen.getByText(text)).toBeInTheDocument(); expect(screen.getByText(/Clinical note/)).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'بستن پرونده' })); expect(screen.queryByText('Allergy')).not.toBeInTheDocument(); expect(api.delete).not.toHaveBeenCalled(); });
|
||||
it('changes pages then resets page on debounced search', async () => {
|
||||
await load(); fireEvent.click(screen.getByRole('button', { name: '۲' }));
|
||||
await waitFor(() => expect(api.get).toHaveBeenCalledWith('/admin/pets', { params: { page: 2, limit: 10, search: '' } }), { timeout: 2000 });
|
||||
fireEvent.change(screen.getByPlaceholderText('جستجو در نام همدم...'), { target: { value: 'Milo' } });
|
||||
await waitFor(() => expect(api.get).toHaveBeenCalledWith('/admin/pets', { params: { page: 1, limit: 10, search: 'Milo' } }), { timeout: 2000 });
|
||||
});
|
||||
it('cancels delete without contacting API', async () => { await load(); fireEvent.click(screen.getByTitle('حذف پت')); fireEvent.click(screen.getByRole('button', { name: 'لغو' })); expect(api.delete).not.toHaveBeenCalled(); });
|
||||
it('deletes only after confirmation and refreshes the list', async () => { await load(); fireEvent.click(screen.getByTitle('حذف پت')); vi.mocked(api.get).mockResolvedValue({ data: { data: [], meta: { lastPage: 1 } } }); fireEvent.click(screen.getByRole('button', { name: 'تایید' })); await waitFor(() => expect(api.delete).toHaveBeenCalledWith('/admin/pets/p1')); expect(await screen.findByText('هیچ حیوانی یافت نشد')).toBeInTheDocument(); expect(toast.success).toHaveBeenCalledWith('پروفایل حیوان خانگی با موفقیت حذف شد'); });
|
||||
it('reports rejected deletion and retains profile', async () => { vi.mocked(api.delete).mockRejectedValue(new Error('offline')); await load(); fireEvent.click(screen.getByTitle('حذف پت')); fireEvent.click(screen.getByRole('button', { name: 'تایید' })); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در حذف پروفایل')); expect(screen.getByText('Milo')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); });
|
||||
it('clears loading after failed initial fetch', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(<Pets />); expect(await screen.findByText('هیچ حیوانی یافت نشد')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); });
|
||||
it('renders missing optional dossier sections safely', async () => { vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'p2', name: 'Minimal' }] } }); render(<Pets />); await screen.findByText('Minimal'); expect(screen.getByText('نژاد نامشخص')).toBeInTheDocument(); fireEvent.click(screen.getByTitle('مشاهده پرونده کامل سلامت')); for (const text of ['مورد پزشکی خاصی ثبت نشده است.', 'یادآوری فعالی ثبت نشده است.', 'گزارش سلامتی ثبت نشده است.', 'نسخهای برای این پت ثبت نشده است.']) expect(screen.getByText(text)).toBeInTheDocument(); });
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Search, Trash2, Heart, Image as ImageIcon, Eye, Clock, Activity, FileText, X, Dog, Cat, ShieldCheck } from 'lucide-react';
|
||||
import { Activity,Cat,Clock,Dog,Eye,FileText,Heart,Search,ShieldCheck,Trash2 } from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
|
||||
|
||||
export interface Pet {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import PrescriptionsManager from './PrescriptionsManager';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn() }, BASE_DOMAIN: 'https://api.example.com' }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const rx = { id: 'rx-12345678', status: 'PENDING', fileUrl: '/uploads/rx.jpg', notes: 'Patient note', adminNotes: 'Prior note\n__PRESCRIBED_PRODUCTS__:["p1"]', createdAt: '2026-03-01', user: { firstName: 'Owner', lastName: 'One', mobile: '09120000000' }, pet: { name: 'Milo', type: 'گربه', breed: 'Persian', age: 2, weight: 3 } };
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(api.get).mockImplementation(async url => ({ data: url === '/prescriptions' ? { data: [rx] } : { data: [{ id: 'p1', name: 'Supplement', price: 100 }] } }));
|
||||
vi.mocked(api.patch).mockResolvedValue({ data: {} });
|
||||
});
|
||||
async function open() { render(<PrescriptionsManager />); fireEvent.click(await screen.findByRole('button', { name: 'بررسی و تجویز' })); }
|
||||
function submit() { fireEvent.submit(document.getElementById('prescriptionForm')!); }
|
||||
describe('PrescriptionsManager', () => {
|
||||
it('renders owner and pet data and filters by clinical status', async () => {
|
||||
render(<PrescriptionsManager />);
|
||||
expect(await screen.findByText('Owner One')).toBeInTheDocument();
|
||||
expect(screen.getByText('Milo (Persian)')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'رد شده' }));
|
||||
expect(screen.getByText('هیچ نسخهای با این فیلتر یافت نشد')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'همه' }));
|
||||
expect(screen.getByText('Patient note')).toBeInTheDocument();
|
||||
});
|
||||
it('restores encoded products and trims clinical notes on approval', async () => {
|
||||
await open();
|
||||
expect(screen.getByRole('textbox')).toHaveValue('Prior note');
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: ' Take daily ' } });
|
||||
submit();
|
||||
await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/prescriptions/rx-12345678/review', { status: 'APPROVED', adminNotes: 'Take daily\n__PRESCRIBED_PRODUCTS__:["p1"]' }));
|
||||
await waitFor(() => expect(document.getElementById('prescriptionForm')).not.toBeInTheDocument());
|
||||
expect(api.get).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it.each([['عدم تایید / ناخوانا', 'REJECTED'], ['در انتظار پیگیری بیمار', 'PENDING']])('submits decision %s without deselected products', async (label, status) => {
|
||||
await open(); fireEvent.click(screen.getByRole('button', { name: label }));
|
||||
fireEvent.click(screen.getByText('Supplement'));
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: ' ' } }); submit();
|
||||
await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/prescriptions/rx-12345678/review', { status, adminNotes: undefined }));
|
||||
});
|
||||
it('retains review and notes when update fails', async () => {
|
||||
vi.mocked(api.patch).mockRejectedValue(new Error('offline')); await open(); submit();
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در تغییر وضعیت نسخه پزشکی'));
|
||||
expect(screen.getByRole('textbox')).toHaveValue('Prior note'); expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
it('handles initial prescription failure', async () => {
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(<PrescriptionsManager />);
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بارگذاری اطلاعات'));
|
||||
expect(await screen.findByText('هیچ نسخهای با این فیلتر یافت نشد')).toBeInTheDocument();
|
||||
});
|
||||
it('allows review when optional products fail', async () => {
|
||||
vi.mocked(api.get).mockImplementation(async url => { if (url !== '/prescriptions') throw new Error('products offline'); return { data: [rx] }; });
|
||||
await open(); expect(screen.getByRole('textbox')).toHaveValue('Prior note'); expect(toast.error).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'انصراف' })); expect(api.patch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { FileText, Eye, CheckCircle2, XCircle, Clock, Filter, X, Package, User, Dog, Cat } from 'lucide-react';
|
||||
import { Cat,CheckCircle2,Clock,Dog,Eye,FileText,Filter,Package,User,XCircle } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ImagePreviewModal from '../components/ui/ImagePreviewModal';
|
||||
import Badge from '../components/ui/Badge';
|
||||
import Button from '../components/ui/Button';
|
||||
import ImagePreviewModal from '../components/ui/ImagePreviewModal';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
import type { Prescription } from '../types/admin';
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Products from './Products';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://canina.ir',
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../components/ui/MediaSelector', () => ({
|
||||
default: () => <div data-testid="media-selector-stub">MediaSelector Stub</div>,
|
||||
}));
|
||||
|
||||
vi.mock('../components/ui/RichTextEditor', () => ({
|
||||
default: ({ value, onChange, placeholder }: any) => (
|
||||
<textarea
|
||||
data-testid="rich-text-editor"
|
||||
placeholder={placeholder}
|
||||
value={value || ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('Products Page', () => {
|
||||
const mockCategories = [
|
||||
{ id: 'cat-1', nameFa: 'مکمل مفاصل و استخوان', slug: 'joints' },
|
||||
{ id: 'cat-2', nameFa: 'پوست و مو', slug: 'skin-coat' },
|
||||
];
|
||||
|
||||
const mockProducts = [
|
||||
{
|
||||
id: 'prod-1',
|
||||
artNo: 'CAN-101',
|
||||
nameFa: 'پتهیدروکس پودر کنینا',
|
||||
nameEn: 'Canina Petvital Canhydrox GAG',
|
||||
slug: 'canina-petvital-canhydrox-gag',
|
||||
priceValue: 850000,
|
||||
wholesalePrice: 720000,
|
||||
buyPrice: 600000,
|
||||
stock: 15,
|
||||
stockStatus: 'IN_STOCK',
|
||||
category: { id: 'cat-1', nameFa: 'مکمل مفاصل و استخوان' },
|
||||
packageSize: 600,
|
||||
unit: 'گرم',
|
||||
imageUrl: '/images/canhydrox.png',
|
||||
totalSold: 28,
|
||||
},
|
||||
{
|
||||
id: 'prod-2',
|
||||
artNo: 'CAN-102',
|
||||
nameFa: 'بیوتین فورت سگ',
|
||||
nameEn: 'Canina Biotin Forte Tablets',
|
||||
slug: 'canina-biotin-forte-tablets',
|
||||
priceValue: 420000,
|
||||
wholesalePrice: 350000,
|
||||
buyPrice: 300000,
|
||||
stock: 0,
|
||||
stockStatus: 'OUT_OF_STOCK',
|
||||
category: { id: 'cat-2', nameFa: 'پوست و مو' },
|
||||
packageSize: 200,
|
||||
unit: 'عدد قرص',
|
||||
imageUrl: '/images/biotin.png',
|
||||
totalSold: 5,
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === '/admin/products') {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
data: mockProducts,
|
||||
meta: { lastPage: 2, total: 2 },
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url === '/admin/categories/all' || url === '/admin/categories') {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
data: mockCategories,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url === '/admin/pricing/settings') {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
data: {
|
||||
roundingStep: 5000,
|
||||
roundingMode: 'UP',
|
||||
defaultRetailMarginPercent: 30,
|
||||
defaultWholesaleMarginPercent: 15,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve({ data: {} });
|
||||
});
|
||||
});
|
||||
|
||||
const renderProducts = (initialEntries = ['/products']) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<Products />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders products table, pricing, and stock status correctly', async () => {
|
||||
renderProducts();
|
||||
|
||||
expect(screen.getByText('مدیریت محصولات')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /محصول جدید/i })).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پتهیدروکس پودر کنینا')).toBeInTheDocument();
|
||||
expect(screen.getByText('CAN-101')).toBeInTheDocument();
|
||||
expect(screen.getByText('850,000 تومان')).toBeInTheDocument();
|
||||
expect(screen.getByText('15 عدد موجود')).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText('بیوتین فورت سگ')).toBeInTheDocument();
|
||||
expect(screen.getByText('CAN-102')).toBeInTheDocument();
|
||||
expect(screen.getByText('420,000 تومان')).toBeInTheDocument();
|
||||
expect(screen.getByText('0 عدد موجود')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('filters product catalog using search input', async () => {
|
||||
renderProducts();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پتهیدروکس پودر کنینا')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/جستجو حرفهای در نام فارسی/i);
|
||||
fireEvent.change(searchInput, { target: { value: 'بیوتین' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/products', {
|
||||
params: expect.objectContaining({
|
||||
search: 'بیوتین',
|
||||
page: 1,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('filters products by category dropdown', async () => {
|
||||
renderProducts();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پتهیدروکس پودر کنینا')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
const categorySelect = selects[0];
|
||||
fireEvent.change(categorySelect, { target: { value: 'cat-2' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/products', {
|
||||
params: expect.objectContaining({
|
||||
categoryId: 'cat-2',
|
||||
page: 1,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('opens create modal and displays form fields', async () => {
|
||||
renderProducts();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پتهیدروکس پودر کنینا')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const newProdBtn = screen.getByRole('button', { name: /محصول جدید/i });
|
||||
fireEvent.click(newProdBtn);
|
||||
|
||||
expect(screen.getByText('افزودن محصول جدید')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'ذخیره محصول' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens edit modal and modifies existing product', async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({
|
||||
data: {
|
||||
id: 'prod-1',
|
||||
artNo: 'CAN-101',
|
||||
nameFa: 'پتهیدروکس پودر کنینا اصلاح شده',
|
||||
priceValue: 890000,
|
||||
},
|
||||
});
|
||||
|
||||
renderProducts();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پتهیدروکس پودر کنینا')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('پتهیدروکس پودر کنینا').closest('tr');
|
||||
const editBtn = firstRow!.querySelector('button.text-blue-600')!;
|
||||
expect(editBtn).toBeDefined();
|
||||
fireEvent.click(editBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('ویرایش پیشرفته محصول')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const form = document.querySelector('form#productForm')!;
|
||||
const inputs = form.querySelectorAll('input');
|
||||
// nameFa is inputs[1]
|
||||
expect(inputs[1].value).toBe('پتهیدروکس پودر کنینا');
|
||||
|
||||
fireEvent.change(inputs[1], { target: { value: 'پتهیدروکس پودر کنینا اصلاح شده' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: 'ذخیره محصول' });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
'/admin/products/prod-1',
|
||||
expect.objectContaining({
|
||||
artNo: 'CAN-101',
|
||||
nameFa: 'پتهیدروکس پودر کنینا اصلاح شده',
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith('محصول با موفقیت ویرایش شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('triggers delete confirmation and deletes product', async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderProducts();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پتهیدروکس پودر کنینا')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('پتهیدروکس پودر کنینا').closest('tr');
|
||||
const deleteBtn = firstRow!.querySelector('button.text-red-600')!;
|
||||
expect(deleteBtn).toBeDefined();
|
||||
fireEvent.click(deleteBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('حذف محصول')).toBeInTheDocument();
|
||||
expect(screen.getByText(/آیا از حذف این محصول مطمئن هستید؟/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: 'تایید' });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/admin/products/prod-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('محصول با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('displays empty state when catalog is empty', async () => {
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === '/admin/products') {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
data: [],
|
||||
meta: { lastPage: 1, total: 0 },
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve({ data: { data: [] } });
|
||||
});
|
||||
|
||||
renderProducts();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('محصولی یافت نشد')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,65 +1,59 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Search,
|
||||
Filter,
|
||||
Box,
|
||||
Plus,
|
||||
Edit2,
|
||||
Trash2,
|
||||
Image as ImageIcon,
|
||||
X,
|
||||
HelpCircle,
|
||||
ArrowUpDown,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
GripVertical,
|
||||
Film,
|
||||
Play,
|
||||
ChevronRight,
|
||||
ChevronLeft,
|
||||
Link2,
|
||||
Calculator,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
DollarSign,
|
||||
Percent,
|
||||
Layers,
|
||||
RotateCcw,
|
||||
CheckCircle2,
|
||||
Compass,
|
||||
Maximize2,
|
||||
ExternalLink,
|
||||
Thermometer,
|
||||
AlertTriangle,
|
||||
Sparkles,
|
||||
Star,
|
||||
FlaskConical,
|
||||
Shield,
|
||||
Heart,
|
||||
Zap,
|
||||
Clock,
|
||||
Tag,
|
||||
Activity,
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpDown,
|
||||
Box,
|
||||
Calculator,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Compass,
|
||||
DollarSign,
|
||||
Edit2,
|
||||
ExternalLink,
|
||||
Film,
|
||||
Filter,
|
||||
FlaskConical,
|
||||
GripVertical,
|
||||
HelpCircle,
|
||||
Image as ImageIcon,
|
||||
Link2,
|
||||
Maximize2,
|
||||
Percent,
|
||||
Play,
|
||||
Plus,
|
||||
Search,
|
||||
Shield,
|
||||
Sparkles,
|
||||
Star,
|
||||
Thermometer,
|
||||
Trash2,
|
||||
TrendingDown,
|
||||
TrendingUp,
|
||||
X
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Input from '../components/ui/Input';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import RichTextEditor from '../components/ui/RichTextEditor';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
import type { PricingSettings } from '../types/admin';
|
||||
import {
|
||||
DEFAULT_PRICING_SETTINGS,
|
||||
calculateSellingPrice,
|
||||
applyRounding,
|
||||
DEFAULT_PRICING_SETTINGS,
|
||||
calculateSellingPrice
|
||||
} from '../utils/pricing';
|
||||
|
||||
export interface Category {
|
||||
slug?: string;
|
||||
id: string;
|
||||
nameFa: string;
|
||||
nameEn?: string;
|
||||
@@ -644,7 +638,7 @@ export default function Products() {
|
||||
const prodIdParam = searchParams.get('productId');
|
||||
const tabParam = searchParams.get('tab');
|
||||
if (modalParam === 'create') {
|
||||
openModal(null);
|
||||
openModal();
|
||||
if (tabParam) setActiveTab(tabParam);
|
||||
} else if (modalParam === 'edit' && prodIdParam) {
|
||||
const found = prodList.find((p: Product) => p.id === prodIdParam);
|
||||
@@ -1268,7 +1262,7 @@ export default function Products() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPreviewImage({
|
||||
url: getProductImageUrl(product.imageUrl),
|
||||
url: getProductImageUrl(product.imageUrl ?? ''),
|
||||
title: product.nameFa || product.name || '',
|
||||
subtitle: product.nameEn,
|
||||
artNo: product.artNo
|
||||
@@ -4282,7 +4276,7 @@ export default function Products() {
|
||||
isOpen={isMediaSelectorOpen}
|
||||
onClose={() => setIsMediaSelectorOpen(false)}
|
||||
onSelect={(url) => {
|
||||
if ((mediaTargetField as string) === 'gallery') {
|
||||
if (mediaTargetField === 'gallery') {
|
||||
if (!formData.images.includes(url)) {
|
||||
setFormData({ ...formData, images: [...formData.images, url] });
|
||||
}
|
||||
@@ -4300,7 +4294,7 @@ export default function Products() {
|
||||
}
|
||||
}}
|
||||
selectedUrl={
|
||||
(mediaTargetField as string) === 'gallery'
|
||||
mediaTargetField === 'gallery'
|
||||
? undefined
|
||||
: mediaTargetField === 'specialistImage'
|
||||
? (formData.specialist?.image?.startsWith('http') ? formData.specialist?.image : formData.specialist?.image ? `${BASE_DOMAIN}${formData.specialist?.image}` : undefined)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Reports from './Reports';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
|
||||
vi.mock('recharts', () => { const Box=({children}:{children?: import('react').ReactNode})=><div>{children}</div>; return { AreaChart:Box, Area:()=>null, XAxis:()=>null, YAxis:()=>null, CartesianGrid:()=>null, Tooltip:()=>null, ResponsiveContainer:Box, BarChart:Box, Bar:()=>null, PieChart:Box, Pie:Box, Cell:()=>null, Legend:()=>null }; });
|
||||
describe('Reports',()=>{
|
||||
const report={overview:{totalRevenue:1000,totalCharity:0,productSalesRevenue:1000,totalCostOfGoods:600,totalTax:0,totalDiscounts:0,netProfit:400,totalOrders:2,b2bRevenue:0,b2cRevenue:1000},salesTimeline:[],bestSellers:[],categoryDistribution:[],topCoupons:[]};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{success:true,data:report}});});
|
||||
const load=async()=>{render(<Reports/>);await screen.findByText('گزارشات و تحلیلهای مالی پیشرفته');};
|
||||
it('requests a bounded default date range and renders revenue',async()=>{await load();expect(api.get).toHaveBeenCalledWith('/admin/reports',{params:{startDate:expect.any(String)}});expect(screen.getAllByText('1,000').length).toBeGreaterThan(0);});
|
||||
it('clears date bounds for all history and sends B2B role filter',async()=>{await load();fireEvent.click(screen.getByRole('button',{name:'کل تاریخچه'}));await waitFor(()=>expect(api.get).toHaveBeenLastCalledWith('/admin/reports',{params:{}}));fireEvent.change(screen.getByRole('combobox'),{target:{value:'B2B'}});await waitFor(()=>expect(api.get).toHaveBeenLastCalledWith('/admin/reports',{params:{role:'B2B'}}));});
|
||||
it('sends custom date bounds rather than the default range',async()=>{await load();fireEvent.click(screen.getByRole('button',{name:'بازه سفارشی'}));const dates=document.querySelectorAll('input[type=date]');fireEvent.change(dates[0],{target:{value:'2026-01-01'}});fireEvent.change(dates[1],{target:{value:'2026-01-31'}});await waitFor(()=>expect(api.get).toHaveBeenLastCalledWith('/admin/reports',{params:{startDate:'2026-01-01',endDate:'2026-01-31'}}));});
|
||||
});
|
||||
@@ -1,25 +1,28 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
TrendingUp,
|
||||
DollarSign,
|
||||
ShoppingBag,
|
||||
Users,
|
||||
HeartHandshake,
|
||||
Download,
|
||||
Calendar,
|
||||
Filter,
|
||||
Receipt,
|
||||
Percent,
|
||||
Package,
|
||||
ShieldCheck
|
||||
import {
|
||||
DollarSign,
|
||||
Download,
|
||||
Filter,
|
||||
HeartHandshake,
|
||||
Receipt,
|
||||
ShoppingBag,
|
||||
TrendingUp
|
||||
} from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Cell,Legend,
|
||||
Pie,
|
||||
PieChart,
|
||||
Tooltip as RechartsTooltip,ResponsiveContainer,
|
||||
XAxis,YAxis
|
||||
} from 'recharts';
|
||||
import Button from '../components/ui/Button';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import {
|
||||
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer,
|
||||
BarChart, Bar, PieChart, Pie, Cell, Legend
|
||||
} from 'recharts';
|
||||
import api from '../services/api';
|
||||
|
||||
const COLORS = ['#8B5CF6', '#EC4899', '#3B82F6', '#10B981', '#F59E0B'];
|
||||
|
||||
@@ -443,8 +446,8 @@ export default function Reports() {
|
||||
/>
|
||||
<RechartsTooltip
|
||||
cursor={{ fill: '#fdf2f8' }}
|
||||
formatter={(val: number) => [`${val.toLocaleString('fa-IR')} عدد`, 'تعداد فروش']}
|
||||
labelFormatter={(lbl: string) => `محصول: ${lbl}`}
|
||||
formatter={(val) => [`${(val ?? 0).toLocaleString('fa-IR')} عدد`, 'تعداد فروش']}
|
||||
labelFormatter={(lbl) => `محصول: ${lbl}`}
|
||||
/>
|
||||
<Bar dataKey="quantity" fill="#EC4899" radius={[0, 6, 6, 0]} barSize={18} />
|
||||
</BarChart>
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Reviews from './Reviews';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Reviews Page Component', () => {
|
||||
const mockProductReviews = [
|
||||
{
|
||||
id: 'rev-1',
|
||||
productId: 'prod-1',
|
||||
userName: 'علی رضایی',
|
||||
userPhone: '09121111111',
|
||||
rating: 5,
|
||||
comment: 'محصول بسیار باکیفیت و موثر بود، سگ من عاشق طعمش شد.',
|
||||
status: 'PENDING',
|
||||
adminReply: '',
|
||||
createdAt: '2026-04-10T10:00:00Z',
|
||||
product: {
|
||||
id: 'prod-1',
|
||||
nameFa: 'قرص مولتی ویتامین سگ',
|
||||
nameEn: 'Dog Multi-Vitamin',
|
||||
slug: 'dog-multi-vitamin',
|
||||
imageUrl: '/images/products/vit.jpg',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'rev-2',
|
||||
productId: 'prod-2',
|
||||
userName: 'مریم احمدی',
|
||||
userPhone: '09122222222',
|
||||
rating: 3,
|
||||
comment: 'بستهبندی کمی آسیب دیده بود.',
|
||||
status: 'APPROVED',
|
||||
adminReply: 'با سلام، پوزش بابت مشکل ارسال؛ تیم پشتیبانی پیگیری خواهد کرد.',
|
||||
createdAt: '2026-04-09T08:00:00Z',
|
||||
product: {
|
||||
id: 'prod-2',
|
||||
nameFa: 'خمیر مالت گربه',
|
||||
nameEn: 'Cat Malt Paste',
|
||||
slug: 'cat-malt-paste',
|
||||
imageUrl: '',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const mockBlogComments = [
|
||||
{
|
||||
id: 'comm-1',
|
||||
blogId: 'blog-1',
|
||||
userName: 'سارا کاظمی',
|
||||
email: 'sara@example.com',
|
||||
content: 'مقاله بسیار آموزندهای در مورد نگهداری پاپی بود، سپاسگزارم.',
|
||||
status: 'PENDING',
|
||||
createdAt: '2026-04-08T12:00:00Z',
|
||||
blog: {
|
||||
title: 'راهنمای تغذیه توله سگ',
|
||||
slug: 'puppy-feeding-guide',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url.startsWith('/admin/reviews')) {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockProductReviews,
|
||||
pagination: { totalPages: 1, total: 2 },
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url.startsWith('/admin/blogs/comments')) {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockBlogComments,
|
||||
meta: { lastPage: 1, total: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.reject(new Error('Unknown url: ' + url));
|
||||
});
|
||||
});
|
||||
|
||||
const renderReviews = () => {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<Reviews />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders reviews list, product names, ratings, and comments', async () => {
|
||||
renderReviews();
|
||||
|
||||
expect(screen.getByText('مدیریت نظرات و دیدگاهها')).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
expect(screen.getByText('علی رضایی')).toBeInTheDocument();
|
||||
expect(screen.getByText('محصول بسیار باکیفیت و موثر بود، سگ من عاشق طعمش شد.')).toBeInTheDocument();
|
||||
|
||||
// Look inside the table body for status badges
|
||||
const statusBadges = screen.getAllByText('در انتظار بررسی');
|
||||
expect(statusBadges.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
expect(screen.getByText('خمیر مالت گربه')).toBeInTheDocument();
|
||||
expect(screen.getByText('مریم احمدی')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('تایید شده').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText(/با سلام، پوزش بابت مشکل ارسال/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('switches to blog comments tab and displays blog article comments', async () => {
|
||||
renderReviews();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const blogTab = screen.getByText('نظرات مقالات وبلاگ و دانشنامه');
|
||||
fireEvent.click(blogTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith(expect.stringContaining('/admin/blogs/comments'));
|
||||
expect(screen.getByText('راهنمای تغذیه توله سگ')).toBeInTheDocument();
|
||||
expect(screen.getByText('سارا کاظمی')).toBeInTheDocument();
|
||||
expect(screen.getByText('مقاله بسیار آموزندهای در مورد نگهداری پاپی بود، سپاسگزارم.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('filters reviews by status filter button', async () => {
|
||||
renderReviews();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const pendingFilterBtn = screen.getByRole('button', { name: 'در انتظار بررسی' });
|
||||
fireEvent.click(pendingFilterBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith(expect.stringContaining('status=PENDING'));
|
||||
});
|
||||
});
|
||||
|
||||
it('approves a pending product review via checkmark action button', async () => {
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderReviews();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// The first review (rev-1) is PENDING and has approve button
|
||||
const approveBtn = screen.getByTitle('تایید دیدگاه');
|
||||
fireEvent.click(approveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith('/admin/reviews/rev-1', {
|
||||
status: 'APPROVED',
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('دیدگاه تایید شد و در سایت نمایش مییابد.');
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a review via cross action button', async () => {
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderReviews();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rejectBtns = screen.getAllByTitle('رد دیدگاه');
|
||||
expect(rejectBtns.length).toBeGreaterThan(0);
|
||||
fireEvent.click(rejectBtns[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith('/admin/reviews/rev-1', {
|
||||
status: 'REJECTED',
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('دیدگاه رد شد.');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens reply modal and saves admin reply', async () => {
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderReviews();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const replyBtns = screen.getAllByTitle('پاسخ به دیدگاه');
|
||||
fireEvent.click(replyBtns[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('پاسخ به دیدگاه علی رضایی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const textarea = screen.getByPlaceholderText('پاسخ و توضیحات رسمی برای نمایش در زیر نظر...');
|
||||
fireEvent.change(textarea, { target: { value: 'خیلی ممنون از اعتماد و نظر مثبت شما!' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: 'ثبت و انتشار پاسخ' });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith('/admin/reviews/rev-1', {
|
||||
adminReply: 'خیلی ممنون از اعتماد و نظر مثبت شما!',
|
||||
status: 'APPROVED',
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('پاسخ با موفقیت ثبت شد.');
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes review after window confirmation', async () => {
|
||||
vi.spyOn(window, 'confirm').mockReturnValueOnce(true);
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderReviews();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('قرص مولتی ویتامین سگ')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const trashBtns = screen.getAllByTitle('حذف دیدگاه');
|
||||
fireEvent.click(trashBtns[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(window.confirm).toHaveBeenCalledWith('آیا از حذف دائمی این دیدگاه اطمینان دارید؟');
|
||||
expect(api.delete).toHaveBeenCalledWith('/admin/reviews/rev-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('دیدگاه با موفقیت حذف شد.');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,23 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
MessageSquare,
|
||||
Search,
|
||||
Star,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Trash2,
|
||||
Reply,
|
||||
Loader2,
|
||||
ExternalLink,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Clock,
|
||||
User,
|
||||
Package,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Clock,
|
||||
MessageSquare,
|
||||
Package,
|
||||
Reply,
|
||||
Search,
|
||||
Star,
|
||||
Trash2,
|
||||
User,
|
||||
XCircle
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import SeoSettingsPage from './SeoSettingsPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const submit = () => fireEvent.submit(document.querySelector('form')!);
|
||||
describe('SeoSettingsPage', () => {
|
||||
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { data: { brand_name_fa: 'Test Brand', brand_name_en: 'Brand EN', title_separator: '-', title_position: 'prefix', ga_measurement_id: 'G-TEST', enableGoogleAnalytics: false } } }); vi.mocked(api.patch).mockResolvedValue({ data: {} }); });
|
||||
const load = async () => { render(<SeoSettingsPage />); await screen.findByDisplayValue('Test Brand'); };
|
||||
it('hydrates legacy keys and updates title preview with position and separator', async () => { await load(); expect(screen.getByText('Test Brand - فروشگاه مکملهای تخصصی سگ و گربه')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: '•' })); expect(screen.getByText('Test Brand • فروشگاه مکملهای تخصصی سگ و گربه')).toBeInTheDocument(); fireEvent.change(screen.getByRole('combobox'), { target: { value: 'none' } }); expect(screen.getByText('فروشگاه مکملهای تخصصی سگ و گربه')).toBeInTheDocument(); });
|
||||
it('saves edited title configuration and disabled analytics', async () => { await load(); fireEvent.change(screen.getByDisplayValue('Test Brand'), { target: { value: 'New Brand' } }); submit(); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/settings/seo', expect.objectContaining({ brandNameFa: 'New Brand', googleAnalyticsId: 'G-TEST', enableGoogleAnalytics: false }))); expect(toast.success).toHaveBeenCalled(); });
|
||||
it('requires brand before native submit', async () => { await load(); const brand = screen.getByDisplayValue('Test Brand') as HTMLInputElement; fireEvent.change(brand, { target: { value: '' } }); expect(brand.checkValidity()).toBe(false); fireEvent.click(document.querySelector('button[type=submit]')!); expect(api.patch).not.toHaveBeenCalled(); });
|
||||
it('retains edits and reports rejected save', async () => { await load(); vi.mocked(api.patch).mockRejectedValueOnce(new Error('offline')); submit(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بروزرسانی تنظیمات سئو')); expect(screen.getByDisplayValue('Test Brand')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); });
|
||||
it('uses default editable SEO after fetch rejection', async () => { vi.mocked(api.get).mockRejectedValueOnce(new Error('offline')); render(<SeoSettingsPage />); await screen.findByDisplayValue('کنینا ایران'); expect(api.patch).not.toHaveBeenCalled(); });
|
||||
|
||||
});
|
||||
@@ -1,14 +1,22 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Globe, Save, Sliders, Sparkles, Search, BarChart3, Code2,
|
||||
CheckCircle2, Activity, ExternalLink, Copy, Check, Rss,
|
||||
FileCode, Bot, ShoppingBag, Layers, Info
|
||||
import {
|
||||
Activity,
|
||||
BarChart3,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
Code2,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
FileCode,
|
||||
Globe,Save,
|
||||
Search,
|
||||
Sliders,Sparkles
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Button from '../components/ui/Button';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
import type { SeoSettings } from '../types/admin';
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Settings from './Settings';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
|
||||
describe('Settings',()=>{
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { success: true, data: { site_logo_text_en: 'Legacy Brand', contact_email: 'legacy@example.test' } } }); vi.mocked(api.put).mockResolvedValue({ data: {} }); });
|
||||
const load = async () => { render(<MemoryRouter><Settings /></MemoryRouter>); await screen.findByDisplayValue('Legacy Brand'); };
|
||||
it('hydrates legacy branding and saves edited values in canonical fields', async () => { await load(); fireEvent.change(screen.getByDisplayValue('Legacy Brand'), { target: { value: 'New Brand' } }); fireEvent.submit(document.querySelector('form')!); await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/settings', expect.objectContaining({ BRAND_LOGO_TEXT_EN: 'New Brand', CONTACT_EMAIL: 'legacy@example.test' }))); });
|
||||
it('reports failed save without claiming success', async () => { vi.mocked(api.put).mockRejectedValue(new Error('denied')); await load(); fireEvent.submit(document.querySelector('form')!); await waitFor(() => expect(toast.error).toHaveBeenCalled()); expect(toast.success).not.toHaveBeenCalled(); });
|
||||
it('renders contact settings on a deep link', async () => { render(<MemoryRouter initialEntries={['/?tab=contact']}><Settings /></MemoryRouter>); expect(await screen.findByDisplayValue('legacy@example.test')).toBeInTheDocument(); });
|
||||
});
|
||||
@@ -1,26 +1,25 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Settings as SettingsIcon,
|
||||
Save,
|
||||
Share2,
|
||||
Palette,
|
||||
CreditCard,
|
||||
Truck,
|
||||
DollarSign,
|
||||
Globe,
|
||||
Sliders,
|
||||
ShieldCheck,
|
||||
MessageSquare,
|
||||
Building2,
|
||||
ExternalLink,
|
||||
ChevronLeft,
|
||||
Sparkles,
|
||||
Building2,
|
||||
ChevronLeft,
|
||||
CreditCard,
|
||||
DollarSign,
|
||||
Globe,
|
||||
MessageSquare,
|
||||
Palette,
|
||||
Save,
|
||||
Settings as SettingsIcon,
|
||||
Share2,
|
||||
ShieldCheck,
|
||||
Sliders,
|
||||
Sparkles,
|
||||
Truck
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import { Link } from 'react-router-dom';
|
||||
import Button from '../components/ui/Button';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ShippingSettingsPage from './ShippingSettingsPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), put: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const submit = () => fireEvent.submit(document.querySelector('form')!);
|
||||
describe('Shipping settings', () => {
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { success: true, data: { shipping_fee: 72000, free_shipping_threshold: 300000, min_order_amount: 1000, SHIPPING_NOTICE: 'Delivery notice' } } }); vi.mocked(api.put).mockResolvedValue({ data: {} }); });
|
||||
const load = async () => { render(<ShippingSettingsPage />); await screen.findByDisplayValue('Delivery notice'); };
|
||||
it('loads legacy keys and saves normalized prices and announcement', async () => { await load(); fireEvent.change(screen.getByPlaceholderText('مثال: ۸۵,۰۰۰'), { target: { value: '۹۰,۰۰۰' } }); fireEvent.change(screen.getByDisplayValue('Delivery notice'), { target: { value: 'Updated delivery' } }); submit(); await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/settings', { SHIPPING_FEE: '90000', FREE_SHIPPING_THRESHOLD: '300000', MIN_ORDER_AMOUNT: '1000', shipping_notice: 'Updated delivery' })); expect(toast.success).toHaveBeenCalled(); });
|
||||
it('preserves numeric zero shipping prices', async () => { vi.mocked(api.get).mockResolvedValue({ data: { success: true, data: { SHIPPING_FEE: 0, FREE_SHIPPING_THRESHOLD: 0, MIN_ORDER_AMOUNT: 0, shipping_notice: 'Free delivery' } } }); render(<ShippingSettingsPage />); await screen.findByDisplayValue('Free delivery'); submit(); await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/settings', expect.objectContaining({ SHIPPING_FEE: '0', FREE_SHIPPING_THRESHOLD: '0' }))); });
|
||||
it('keeps draft and permits retry after rejected save', async () => { await load(); vi.mocked(api.put).mockRejectedValueOnce(new Error('offline')); submit(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در ذخیره تنظیمات ارسال')); expect(screen.getByDisplayValue('Delivery notice')).toBeInTheDocument(); expect(screen.getByRole('button', { name: /ذخیره تغییرات ارسال/ })).toBeEnabled(); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); });
|
||||
it('renders defaults after failed fetch without mutating', async () => { vi.mocked(api.get).mockRejectedValueOnce(new Error('offline')); render(<ShippingSettingsPage />); await screen.findByRole('button', { name: /ذخیره تغییرات ارسال/ }); expect(api.put).not.toHaveBeenCalled(); });
|
||||
});
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Truck, Save, Gift, ShieldAlert } from 'lucide-react';
|
||||
import { Save,Truck } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import Button from '../components/ui/Button';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
|
||||
@@ -28,9 +28,9 @@ export default function ShippingSettingsPage() {
|
||||
if (res.data?.success) {
|
||||
const d = res.data.data;
|
||||
setShipping({
|
||||
SHIPPING_FEE: String(d.SHIPPING_FEE || d.shipping_fee || d.standardShippingFee || '85000'),
|
||||
FREE_SHIPPING_THRESHOLD: String(d.FREE_SHIPPING_THRESHOLD || d.free_shipping_threshold || d.freeShippingThreshold || '2000000'),
|
||||
MIN_ORDER_AMOUNT: String(d.MIN_ORDER_AMOUNT || d.min_order_amount || d.minOrderAmount || '0'),
|
||||
SHIPPING_FEE: String(d.SHIPPING_FEE ?? d.shipping_fee ?? d.standardShippingFee ?? '85000'),
|
||||
FREE_SHIPPING_THRESHOLD: String(d.FREE_SHIPPING_THRESHOLD ?? d.free_shipping_threshold ?? d.freeShippingThreshold ?? '2000000'),
|
||||
MIN_ORDER_AMOUNT: String(d.MIN_ORDER_AMOUNT ?? d.min_order_amount ?? d.minOrderAmount ?? '0'),
|
||||
shipping_notice: d.shipping_notice || d.SHIPPING_NOTICE || 'ارسال رایگان برای سفارشهای بالای ۱۵۰ هزار تومان — گارانتی اصالت کنینا آلمان',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import SmartAdvisorManager from './SmartAdvisorManager';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('SmartAdvisorManager Component', () => {
|
||||
const mockRules = [
|
||||
{
|
||||
id: 'rule-1',
|
||||
condition: 'مشکلات مفصلی و لنگش',
|
||||
targetPetType: 'سگ',
|
||||
recommendedProduct: 'prod-1',
|
||||
reason: 'حاوی ۲۵٪ پودر صدف لبسبز جهت بازسازی غضروفها و روانسازی مفاصل.',
|
||||
product: {
|
||||
id: 'prod-1',
|
||||
nameFa: 'پودر مفاصل کانین هیدروپت',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'rule-2',
|
||||
condition: 'ریزش موی شدید و خارش پوستی',
|
||||
targetPetType: 'هر دو',
|
||||
recommendedProduct: 'prod-2',
|
||||
reason: 'ترکیب بیوتین و اسیدهای چرب امگا ۳ و ۶ برای توقف ریزش مو.',
|
||||
product: {
|
||||
id: 'prod-2',
|
||||
nameFa: 'روغن سالمون کنینا',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const mockProducts = [
|
||||
{
|
||||
id: 'prod-1',
|
||||
nameFa: 'پودر مفاصل کانین هیدروپت',
|
||||
nameEn: 'GAG Forte',
|
||||
artNo: 'CN-101',
|
||||
},
|
||||
{
|
||||
id: 'prod-2',
|
||||
nameFa: 'روغن سالمون کنینا',
|
||||
nameEn: 'Salmon Oil',
|
||||
artNo: 'CN-102',
|
||||
},
|
||||
{
|
||||
id: 'prod-3',
|
||||
nameFa: 'خمیر ویتامین گربه',
|
||||
nameEn: 'Cat Vitamin Paste',
|
||||
artNo: 'CN-103',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const setupDefaultMocks = () => {
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === '/smart-advisor/rules') {
|
||||
return Promise.resolve({ data: mockRules });
|
||||
}
|
||||
if (url === '/admin/products') {
|
||||
return Promise.resolve({ data: { data: mockProducts } });
|
||||
}
|
||||
return Promise.reject(new Error('Unknown url: ' + url));
|
||||
});
|
||||
};
|
||||
|
||||
it('renders rules list with condition, target pet, recommended product, and reason', async () => {
|
||||
setupDefaultMocks();
|
||||
|
||||
render(<SmartAdvisorManager />);
|
||||
|
||||
expect(screen.getByText(/مدیریت موتور مشاور هوشمند \(Smart Advisor\)/i)).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مشکلات مفصلی و لنگش')).toBeInTheDocument();
|
||||
expect(screen.getByText('ریزش موی شدید و خارش پوستی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('پودر مفاصل کانین هیدروپت')).toBeInTheDocument();
|
||||
expect(screen.getByText('روغن سالمون کنینا')).toBeInTheDocument();
|
||||
expect(screen.getByText('سگ')).toBeInTheDocument();
|
||||
expect(screen.getByText('هر دو')).toBeInTheDocument();
|
||||
expect(screen.getByText(/حاوی ۲۵٪ پودر صدف لبسبز/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays empty state when no rules exist', async () => {
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === '/smart-advisor/rules') {
|
||||
return Promise.resolve({ data: [] });
|
||||
}
|
||||
if (url === '/admin/products') {
|
||||
return Promise.resolve({ data: { data: [] } });
|
||||
}
|
||||
return Promise.reject(new Error('Unknown url: ' + url));
|
||||
});
|
||||
|
||||
render(<SmartAdvisorManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('هیچ قانونی ثبت نشده است')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a new rule with product search and selection', async () => {
|
||||
setupDefaultMocks();
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<SmartAdvisorManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مشکلات مفصلی و لنگش')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const addBtn = screen.getByRole('button', { name: /تعریف قانون جدید/i });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(screen.getByText('تعریف قانون جدید', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const conditionInput = screen.getByPlaceholderText(/مثال: مشکلات مفصلی و لنگش/i);
|
||||
const reasonInput = screen.getByPlaceholderText(/مثال: حاوی ۱۰٪ پودر صدف لبسبز/i);
|
||||
|
||||
fireEvent.change(conditionInput, { target: { value: 'کمبود کلسیم و نرمی استخوان' } });
|
||||
fireEvent.change(reasonInput, { target: { value: 'کلسیم سیترات برای جذب سریع بدون ایجاد رسوب کلیوی.' } });
|
||||
|
||||
// Filter product search in modal dropdown
|
||||
const productSearchInput = screen.getByPlaceholderText(/جستجو در نام محصولات.../i);
|
||||
fireEvent.change(productSearchInput, { target: { value: 'خمیر' } });
|
||||
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
// selects[0] is targetPetType, selects[1] is recommendedProduct
|
||||
const productSelect = selects[1];
|
||||
fireEvent.change(productSelect, { target: { value: 'prod-3' } });
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره قانون/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/smart-advisor/rules', expect.objectContaining({
|
||||
condition: 'کمبود کلسیم و نرمی استخوان',
|
||||
targetPetType: 'سگ',
|
||||
recommendedProduct: 'prod-3',
|
||||
reason: 'کلسیم سیترات برای جذب سریع بدون ایجاد رسوب کلیوی.',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('قانون جدید با موفقیت ایجاد شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('edits an existing advisor rule', async () => {
|
||||
setupDefaultMocks();
|
||||
vi.mocked(api.patch).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<SmartAdvisorManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مشکلات مفصلی و لنگش')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole('row');
|
||||
const editBtn = rows[1].querySelectorAll('button')[0];
|
||||
fireEvent.click(editBtn);
|
||||
|
||||
expect(screen.getByText('ویرایش قانون مشاور هوشمند', { selector: 'h3' })).toBeInTheDocument();
|
||||
|
||||
const conditionInput = screen.getByPlaceholderText(/مثال: مشکلات مفصلی و لنگش/i);
|
||||
expect(conditionInput).toHaveValue('مشکلات مفصلی و لنگش');
|
||||
|
||||
fireEvent.change(conditionInput, { target: { value: 'مشکلات مفصلی حاد و آرتروز' } });
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /ذخیره قانون/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith('/smart-advisor/rules/rule-1', expect.objectContaining({
|
||||
condition: 'مشکلات مفصلی حاد و آرتروز',
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('قانون مشاور هوشمند بروزرسانی شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes an advisor rule via confirm modal', async () => {
|
||||
setupDefaultMocks();
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<SmartAdvisorManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مشکلات مفصلی و لنگش')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole('row');
|
||||
const deleteBtn = rows[1].querySelectorAll('button')[1];
|
||||
fireEvent.click(deleteBtn);
|
||||
|
||||
expect(screen.getByText(/آیا از حذف این قانون مشاور هوشمند اطمینان دارید؟/i)).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: /تایید/i });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/smart-advisor/rules/rule-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('قانون با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Edit2, Trash2, X, Search, Sparkles } from 'lucide-react';
|
||||
import { Edit2,Plus,Search,Sparkles,Trash2 } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import type { SmartAdvisorRule, Product } from '../types/admin';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
import type { Product,SmartAdvisorRule } from '../types/admin';
|
||||
|
||||
|
||||
export default function SmartAdvisorManager() {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import SmsSettingsPage from './SmsSettingsPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const submit = () => fireEvent.submit(document.querySelector('form')!);
|
||||
describe('SmsSettingsPage', () => {
|
||||
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: { data: url === '/settings/sms' ? { enabled: false, username: 'demo-user', otpBodyId: '123', adminPhone: '' } : url.includes('credit') ? { success: true, credit: 0 } : url.includes('logs') ? { logs: [], totalPages: 1 } : [] } })); vi.mocked(api.patch).mockResolvedValue({ data: {} }); vi.mocked(api.post).mockResolvedValue({ data: { success: true, message: 'Mock accepted' } }); });
|
||||
const load = async (path='/settings/sms') => { render(<MemoryRouter initialEntries={[path]}><SmsSettingsPage /></MemoryRouter>); await screen.findByDisplayValue('demo-user'); };
|
||||
it('trims config and converts IDs before save without dispatching SMS', async () => { await load(); fireEvent.change(screen.getByDisplayValue('demo-user'), { target: { value: ' edited-user ' } }); submit(); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/settings/sms', expect.objectContaining({ username: 'edited-user', otpBodyId: 123, enabled: false, rules: [] }))); expect(api.post).not.toHaveBeenCalled(); expect(toast.success).toHaveBeenCalledWith('تنظیمات درگاه پیامک با موفقیت در دیتابیس ذخیره شد'); });
|
||||
it('retains config after rejected save and permits retry', async () => { await load(); vi.mocked(api.patch).mockRejectedValueOnce(new Error('offline')); submit(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در ذخیرهسازی تنظیمات پیامک')); expect(screen.getByDisplayValue('demo-user')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); });
|
||||
it('validates destination before test dispatch', async () => { await load(); const form=screen.getByPlaceholderText('0912...').closest('form')!; fireEvent.submit(form); expect(toast.error).toHaveBeenCalledWith('لطفاً شماره موبایل مقصد برای تست را وارد کنید'); expect(api.post).not.toHaveBeenCalled(); });
|
||||
it('builds OTP dispatch payload using mocked API only', async () => { await load(); const phone=screen.getByPlaceholderText('0912...'); fireEvent.change(phone, { target: { value: '09120000000' } }); fireEvent.submit(phone.closest('form')!); await waitFor(() => expect(api.post).toHaveBeenCalledWith('/settings/sms/test', { phone: '09120000000', patternId: 123, args: ['123456'] })); await screen.findByText('Mock accepted'); });
|
||||
it('displays backend dispatch error without false success', async () => { await load(); vi.mocked(api.post).mockRejectedValueOnce({ response: { data: { message: 'Insufficient credit' } } }); const phone=screen.getByPlaceholderText('0912...'); fireEvent.change(phone, { target: { value: '09120000000' } }); fireEvent.submit(phone.closest('form')!); await screen.findByText('Insufficient credit'); expect(toast.error).toHaveBeenCalledWith('Insufficient credit'); expect(toast.success).not.toHaveBeenCalled(); });
|
||||
it('invalid tab falls back to settings without fetching logs', async () => { await load('/settings/sms?tab=invalid'); expect(api.get).not.toHaveBeenCalledWith('/settings/sms/logs', expect.anything()); });
|
||||
it('deep-linked logs handles failure independently of settings hydration', async () => { vi.mocked(api.get).mockImplementation(async (url) => { if (url.includes('logs')) throw new Error('offline'); return { data: { data: [] } }; }); render(<MemoryRouter initialEntries={['/settings/sms?tab=logs']}><SmsSettingsPage /></MemoryRouter>); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در دریافت لاگهای پیامک')); expect(api.get).toHaveBeenCalledWith('/settings/sms/logs', { params: { page: 1, limit: 15, sortOrder: 'desc' } }); });
|
||||
|
||||
});
|
||||
@@ -1,50 +1,50 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
MessageSquare,
|
||||
Save,
|
||||
Send,
|
||||
ShieldCheck,
|
||||
KeyRound,
|
||||
Coins,
|
||||
User,
|
||||
Hash,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Smartphone,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Edit3,
|
||||
Copy,
|
||||
Check,
|
||||
Layers,
|
||||
SlidersHorizontal,
|
||||
Clock,
|
||||
AlertTriangle,
|
||||
X,
|
||||
ArrowUpRight,
|
||||
History,
|
||||
Search,
|
||||
Trash2,
|
||||
TrendingUp,
|
||||
Info,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Filter,
|
||||
Zap,
|
||||
CheckSquare,
|
||||
Square,
|
||||
Users,
|
||||
Play,
|
||||
FileText,
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
ArrowUpRight,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
CheckSquare,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Clock,
|
||||
Coins,
|
||||
Copy,
|
||||
Edit3,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FileText,
|
||||
Filter,
|
||||
Hash,
|
||||
History,
|
||||
Info,
|
||||
KeyRound,
|
||||
Layers,
|
||||
MessageSquare,
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Save,
|
||||
Search,
|
||||
Send,
|
||||
ShieldCheck,
|
||||
SlidersHorizontal,
|
||||
Smartphone,
|
||||
Square,
|
||||
Trash2,
|
||||
TrendingUp,
|
||||
User,
|
||||
Users,
|
||||
X,
|
||||
Zap,
|
||||
} from 'lucide-react';
|
||||
import React,{ useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
export interface SmsRule {
|
||||
id: string;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import SslSettingsPage from './SslSettingsPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
|
||||
describe('SslSettingsPage',()=>{
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { data: { exists: false } } }); vi.mocked(api.post).mockResolvedValue({ data: { message: 'Mock certificate accepted' } }); });
|
||||
const load = async () => { render(<SslSettingsPage />); await waitFor(() => expect(api.get).toHaveBeenCalledWith('/admin/ssl/status')); await screen.findByRole('button', { name: 'ورود متن (PEM Content)' }); };
|
||||
it('prevents installing an incomplete file pair', async () => { await load(); expect(screen.getByRole('button', { name: 'نصب و فعالسازی گواهی جدید' })).toBeDisabled(); fireEvent.submit(document.querySelector('form')!); expect(api.post).not.toHaveBeenCalled(); expect(toast.error).toHaveBeenCalled(); });
|
||||
it('posts both PEM fields and clears them after mocked acceptance', async () => { await load(); fireEvent.click(screen.getByRole('button', { name: 'ورود متن (PEM Content)' })); const fields=screen.getAllByRole('textbox').filter(x=>x.tagName==='TEXTAREA'); fireEvent.change(fields[0], { target: { value: 'TEST CERTIFICATE CONTENT' } }); fireEvent.change(fields[1], { target: { value: 'TEST KEY CONTENT NOT A REAL KEY' } }); fireEvent.submit(document.querySelector('form')!); await waitFor(() => expect(api.post).toHaveBeenCalledWith('/admin/ssl/update-text', { certificate: 'TEST CERTIFICATE CONTENT', privateKey: 'TEST KEY CONTENT NOT A REAL KEY' })); await waitFor(() => expect(fields[0]).toHaveValue('')); });
|
||||
it('surfaces backend certificate rejection and preserves entered text', async () => { vi.mocked(api.post).mockRejectedValue({ response: { data: { message: 'certificate mismatch' } } }); await load(); fireEvent.click(screen.getByRole('button', { name: 'ورود متن (PEM Content)' })); const fields=document.querySelectorAll('textarea'); fields.forEach((x)=>fireEvent.change(x,{target:{value:'invalid fixture'}})); fireEvent.submit(document.querySelector('form')!); await waitFor(()=>expect(toast.error).toHaveBeenCalledWith('certificate mismatch')); expect(fields[0]).toHaveValue('invalid fixture'); });
|
||||
it('trims online domain checks and never writes TLS configuration', async () => { await load(); vi.mocked(api.get).mockResolvedValue({ data: { onlineCheck: false, message: 'untrusted' } }); fireEvent.change(screen.getByDisplayValue('canina.ir'), { target: { value: ' example.test ' } }); fireEvent.click(screen.getByRole('button', { name: 'تست زنده پورت ۴۴۳ دامنه' })); await waitFor(()=>expect(api.get).toHaveBeenCalledWith('/admin/ssl/test-domain', {params:{domain:'example.test'}})); await waitFor(()=>expect(toast.error).toHaveBeenCalledWith('untrusted')); expect(api.post).not.toHaveBeenCalled(); });
|
||||
});
|
||||
@@ -1,25 +1,25 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import {
|
||||
ShieldCheck,
|
||||
ShieldAlert,
|
||||
Upload,
|
||||
FileCode,
|
||||
Key,
|
||||
RefreshCw,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
Globe,
|
||||
Calendar,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
Lock,
|
||||
Clock,
|
||||
Sparkles
|
||||
import {
|
||||
AlertTriangle,
|
||||
Calendar,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
FileCode,
|
||||
Globe,
|
||||
Key,
|
||||
Lock,
|
||||
RefreshCw,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
Sparkles,
|
||||
Upload
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useRef,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import SystemSettingsPage from './SystemSettingsPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
const submit = () => fireEvent.submit(document.querySelector('form')!);
|
||||
describe('SystemSettingsPage', () => {
|
||||
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/settings/system' ? { data: { maintenanceMode: false, supportPhone: '02100000000', catalogOnlyMode: '1', catalogShowPrices: 'false', catalogAllowCart: 1 } } : {} })); vi.mocked(api.patch).mockResolvedValue({ data: {} }); vi.mocked(api.put).mockResolvedValue({ data: {} }); });
|
||||
const load = async () => { render(<MemoryRouter><SystemSettingsPage /></MemoryRouter>); await screen.findByText('نمایش قیمت محصولات در حالت کاتالوگ'); };
|
||||
it('normalizes catalog flags and links to security and SMS', async () => { await load(); expect(screen.getByLabelText('نمایش قیمت محصولات در حالت کاتالوگ')).not.toBeChecked(); expect(screen.getByRole('link', { name: /SSL/ })).toHaveAttribute('href', '/settings/ssl'); expect(screen.getByRole('link', { name: /MeliPayamak/ })).toHaveAttribute('href', '/settings/sms'); });
|
||||
it('synchronizes maintenance and catalog flags to both endpoints', async () => { await load(); fireEvent.click(screen.getAllByRole('checkbox')[0]); fireEvent.click(screen.getByLabelText('نمایش قیمت محصولات در حالت کاتالوگ')); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); expect(api.patch).toHaveBeenCalledWith('/settings/system', expect.objectContaining({ maintenanceMode: true, CATALOG_SHOW_PRICES: 'true', CATALOG_ALLOW_CART: 'true' })); expect(api.put).toHaveBeenCalledWith('/settings/ui-texts', expect.objectContaining({ MAINTENANCE_MODE: 'true', CATALOG_ONLY_MODE: 'true' })); });
|
||||
it('does not announce success if one synchronization fails and retains edits', async () => { await load(); vi.mocked(api.put).mockRejectedValueOnce(new Error('offline')); submit(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بروزرسانی تنظیمات سیستمی')); expect(toast.success).not.toHaveBeenCalled(); expect(screen.getByLabelText('نمایش قیمت محصولات در حالت کاتالوگ')).not.toBeChecked(); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); });
|
||||
it('falls back to defaults on failed loading', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(<MemoryRouter><SystemSettingsPage /></MemoryRouter>); await waitFor(() => expect(document.querySelector('form')).not.toBeNull()); expect(screen.getAllByRole('checkbox')[0]).not.toBeChecked(); expect(api.patch).not.toHaveBeenCalled(); });
|
||||
|
||||
});
|
||||
@@ -1,20 +1,19 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Sliders,
|
||||
Save,
|
||||
AlertTriangle,
|
||||
ShieldAlert,
|
||||
MessageSquare,
|
||||
BookOpen,
|
||||
ShoppingBag,
|
||||
Info,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
BookOpen,
|
||||
CheckCircle2,
|
||||
MessageSquare,
|
||||
Save,
|
||||
ShieldAlert,
|
||||
ShoppingBag,
|
||||
Sliders
|
||||
} from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import { Link } from 'react-router-dom';
|
||||
import Button from '../components/ui/Button';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api from '../services/api';
|
||||
import type { SystemSettings } from '../types/admin';
|
||||
|
||||
|
||||
@@ -51,7 +50,7 @@ export default function SystemSettingsPage() {
|
||||
api.get('/settings/system'),
|
||||
api.get('/settings/ui-texts'),
|
||||
])
|
||||
.then(([resSys, resUi]) => {
|
||||
.then(([resSys]) => {
|
||||
if (!isSubscribed) return;
|
||||
const data = resSys.data?.data || resSys.data;
|
||||
if (data) {
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import TestimonialsManager from './TestimonialsManager';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://api.example.com',
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../components/ui/MediaSelector', () => ({
|
||||
default: ({ isOpen, onClose, onSelect }: any) => {
|
||||
if (!isOpen) return null;
|
||||
return (
|
||||
<div data-testid="media-selector-modal">
|
||||
<button onClick={() => { onSelect('/uploads/selected-avatar.jpg'); onClose(); }}>
|
||||
انتخاب عکس از گالری
|
||||
</button>
|
||||
<button onClick={onClose}>بستن مدال رسانه</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('TestimonialsManager Component', () => {
|
||||
const mockTestimonials = [
|
||||
{
|
||||
id: 't-1',
|
||||
authorName: 'سارا احمدی',
|
||||
roleTitle: 'سرپرست سگ ژرمن شپرد',
|
||||
avatarUrl: '/uploads/sara.jpg',
|
||||
content: 'مکمل مفصلساز کانیهیدروکس معجزه کرد و سگ من دوباره راحت راه میرود.',
|
||||
rating: 5,
|
||||
isFeatured: true,
|
||||
isActive: true,
|
||||
showOnHome: true,
|
||||
order: 1,
|
||||
createdAt: '2026-03-01T12:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 't-2',
|
||||
authorName: 'دکتر علیرضا کاظمی',
|
||||
roleTitle: 'دامپزشک جراح',
|
||||
avatarUrl: '',
|
||||
content: 'توصیه همیشگی کلینیک ما برای تقویت سیستم ایمنی استفاده از محصولات کنینا است.',
|
||||
rating: 4,
|
||||
isFeatured: false,
|
||||
isActive: false,
|
||||
showOnHome: false,
|
||||
order: 2,
|
||||
createdAt: '2026-03-05T15:30:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(api.get as any).mockResolvedValue({ data: mockTestimonials });
|
||||
});
|
||||
|
||||
it('renders testimonials list correctly', async () => {
|
||||
render(<TestimonialsManager />);
|
||||
|
||||
expect(api.get).toHaveBeenCalledWith('/testimonials');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('سارا احمدی')).toBeInTheDocument();
|
||||
expect(screen.getByText('دکتر علیرضا کاظمی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('سرپرست سگ ژرمن شپرد')).toBeInTheDocument();
|
||||
expect(screen.getByText(/مکمل مفصلساز کانیهیدروکس/)).toBeInTheDocument();
|
||||
expect(screen.getByText('فعال')).toBeInTheDocument();
|
||||
expect(screen.getByText('غیرفعال')).toBeInTheDocument();
|
||||
expect(screen.getByText('خانه')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('toggles active status of a testimonial', async () => {
|
||||
(api.patch as any).mockResolvedValue({ data: { success: true } });
|
||||
|
||||
render(<TestimonialsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('سارا احمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const activeBadge = screen.getByText('فعال');
|
||||
fireEvent.click(activeBadge);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith('/testimonials/t-1', { isActive: false });
|
||||
expect(toast.success).toHaveBeenCalledWith('وضعیت نظر تغییر کرد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens modal to create a new testimonial and submits successfully', async () => {
|
||||
(api.post as any).mockResolvedValue({ data: { success: true } });
|
||||
|
||||
render(<TestimonialsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('سارا احمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const addBtn = screen.getByRole('button', { name: /افزودن نظر جدید/ });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'افزودن نظر جدید' })).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText('مثال: دکتر علیرضا رضایی');
|
||||
const roleInput = screen.getByPlaceholderText('مثال: متخصص جراحی دامپزشکی');
|
||||
const contentInput = screen.getByPlaceholderText('متن کامل نظر و تجربه همکاری با محصولات کنینا...');
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'کامران شریفی' } });
|
||||
fireEvent.change(roleInput, { target: { value: 'سرپرست هاسکی' } });
|
||||
fireEvent.change(contentInput, { target: { value: 'عالی بود و تأثیر سریع داشت.' } });
|
||||
|
||||
const form = document.getElementById('testimonialForm') as HTMLFormElement;
|
||||
fireEvent.submit(form);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
'/testimonials',
|
||||
expect.objectContaining({
|
||||
authorName: 'کامران شریفی',
|
||||
roleTitle: 'سرپرست هاسکی',
|
||||
content: 'عالی بود و تأثیر سریع داشت.',
|
||||
rating: 5,
|
||||
isFeatured: true,
|
||||
isActive: true,
|
||||
showOnHome: false,
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith('نظر جدید با موفقیت ایجاد شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens modal to edit an existing testimonial and saves changes', async () => {
|
||||
(api.patch as any).mockResolvedValue({ data: { success: true } });
|
||||
|
||||
render(<TestimonialsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('سارا احمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole('row');
|
||||
const firstRowButtons = rows[1].querySelectorAll('button');
|
||||
// Button 1 is edit
|
||||
fireEvent.click(firstRowButtons[1]);
|
||||
|
||||
expect(screen.getByText('ویرایش نظر')).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText('مثال: دکتر علیرضا رضایی');
|
||||
expect(nameInput).toHaveValue('سارا احمدی');
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'سارا احمدی پور' } });
|
||||
|
||||
const form = document.getElementById('testimonialForm') as HTMLFormElement;
|
||||
fireEvent.submit(form);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.patch).toHaveBeenCalledWith(
|
||||
'/testimonials/t-1',
|
||||
expect.objectContaining({
|
||||
authorName: 'سارا احمدی پور',
|
||||
roleTitle: 'سرپرست سگ ژرمن شپرد',
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith('نظر با موفقیت بروزرسانی شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes a testimonial after confirming modal', async () => {
|
||||
(api.delete as any).mockResolvedValue({ data: { success: true } });
|
||||
|
||||
render(<TestimonialsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('سارا احمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const rows = screen.getAllByRole('row');
|
||||
const firstRowButtons = rows[1].querySelectorAll('button');
|
||||
// Delete is buttons[2]
|
||||
fireEvent.click(firstRowButtons[2]);
|
||||
|
||||
expect(screen.getByText('حذف نظر')).toBeInTheDocument();
|
||||
expect(screen.getByText('آیا از حذف این نظر اطمینان دارید؟')).toBeInTheDocument();
|
||||
|
||||
const confirmBtn = screen.getByRole('button', { name: 'تایید' });
|
||||
fireEvent.click(confirmBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.delete).toHaveBeenCalledWith('/testimonials/t-1');
|
||||
expect(toast.success).toHaveBeenCalledWith('نظر با موفقیت حذف شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('validates required fields on submission', async () => {
|
||||
render(<TestimonialsManager />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /افزودن نظر جدید/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /افزودن نظر جدید/ }));
|
||||
|
||||
// Empty fields
|
||||
const nameInput = screen.getByPlaceholderText('مثال: دکتر علیرضا رضایی');
|
||||
const contentInput = screen.getByPlaceholderText('متن کامل نظر و تجربه همکاری با محصولات کنینا...');
|
||||
fireEvent.change(nameInput, { target: { value: ' ' } });
|
||||
fireEvent.change(contentInput, { target: { value: ' ' } });
|
||||
|
||||
const form = document.getElementById('testimonialForm') as HTMLFormElement;
|
||||
fireEvent.submit(form);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('نام نویسنده و متن نظر اجباری هستند');
|
||||
});
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports failed initial fetch', async () => {
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error('offline'));
|
||||
render(<TestimonialsManager />);
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در دریافت لیست نظرات و گواهیها'));
|
||||
});
|
||||
|
||||
it('does not report success or refresh when status toggle fails', async () => {
|
||||
vi.mocked(api.patch).mockRejectedValueOnce(new Error('offline'));
|
||||
render(<TestimonialsManager />);
|
||||
fireEvent.click(await screen.findByText('فعال'));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در تغییر وضعیت نظر'));
|
||||
expect(api.get).toHaveBeenCalledTimes(1);
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retains edited content when saving fails', async () => {
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('offline'));
|
||||
render(<TestimonialsManager />); await screen.findByText('سارا احمدی');
|
||||
fireEvent.click(screen.getByRole('button', { name: /افزودن نظر جدید/ }));
|
||||
fireEvent.change(screen.getByPlaceholderText('مثال: دکتر علیرضا رضایی'), { target: { value: 'Draft author' } });
|
||||
fireEvent.change(screen.getByPlaceholderText('متن کامل نظر و تجربه همکاری با محصولات کنینا...'), { target: { value: 'Draft content' } });
|
||||
fireEvent.submit(document.getElementById('testimonialForm')!);
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در ذخیره نظر'));
|
||||
expect(screen.getByDisplayValue('Draft content')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { MessageSquareQuote, Plus, Edit2, Trash2, X, Star, CheckCircle2, XCircle } from 'lucide-react';
|
||||
import { CheckCircle2,Edit2,MessageSquareQuote,Plus,Star,Trash2,XCircle } from 'lucide-react';
|
||||
import { useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Button from '../components/ui/Button';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
import type { Testimonial } from '../types/admin';
|
||||
|
||||
|
||||
@@ -95,6 +95,17 @@ export default function TestimonialsManager() {
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleToggleActive = async (item: Testimonial) => {
|
||||
try {
|
||||
await api.patch('/testimonials/' + item.id, { isActive: !item.isActive });
|
||||
toast.success('وضعیت نظر تغییر کرد');
|
||||
fetchTestimonials();
|
||||
} catch (err) {
|
||||
console.error('Failed to toggle testimonial status:', err);
|
||||
toast.error('خطا در تغییر وضعیت نظر');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!formData.authorName.trim() || !formData.content.trim()) {
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { fireEvent,render,screen,waitFor } from "@testing-library/react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { beforeEach,describe,expect,it,vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import Tickets from "./Tickets";
|
||||
|
||||
vi.mock("../services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("Tickets Page Component", () => {
|
||||
const mockTicketsList = [
|
||||
{
|
||||
id: "ticket-1",
|
||||
ticketNumber: "TK-1001",
|
||||
subject: "مشاوره در مورد دوز کلسیم پامرانین",
|
||||
category: "VET_CONSULTATION",
|
||||
priority: "HIGH",
|
||||
status: "OPEN",
|
||||
createdAt: "2025-01-01T10:00:00Z",
|
||||
updatedAt: "2025-01-01T12:00:00Z",
|
||||
user: {
|
||||
id: "user-1",
|
||||
firstName: "مهدی",
|
||||
lastName: "رضایی",
|
||||
mobile: "09121112233",
|
||||
},
|
||||
pet: {
|
||||
id: "pet-1",
|
||||
name: "تدی",
|
||||
type: "DOG",
|
||||
breed: "پامرانین",
|
||||
},
|
||||
messages: [],
|
||||
},
|
||||
{
|
||||
id: "ticket-2",
|
||||
ticketNumber: "TK-1002",
|
||||
subject: "پیگیری سفارش مکمل و زمان ارسال",
|
||||
category: "ORDER_SUPPORT",
|
||||
priority: "MEDIUM",
|
||||
status: "ANSWERED",
|
||||
createdAt: "2025-01-02T08:30:00Z",
|
||||
updatedAt: "2025-01-02T09:45:00Z",
|
||||
user: {
|
||||
id: "user-2",
|
||||
firstName: "سارا",
|
||||
lastName: "کمالی",
|
||||
mobile: "09359998877",
|
||||
},
|
||||
messages: [],
|
||||
},
|
||||
];
|
||||
|
||||
const mockTicketDetail = {
|
||||
id: "ticket-1",
|
||||
ticketNumber: "TK-1001",
|
||||
subject: "مشاوره در مورد دوز کلسیم پامرانین",
|
||||
category: "VET_CONSULTATION",
|
||||
priority: "HIGH",
|
||||
status: "OPEN",
|
||||
createdAt: "2025-01-01T10:00:00Z",
|
||||
updatedAt: "2025-01-01T12:00:00Z",
|
||||
user: {
|
||||
id: "user-1",
|
||||
firstName: "مهدی",
|
||||
lastName: "رضایی",
|
||||
mobile: "09121112233",
|
||||
},
|
||||
pet: {
|
||||
id: "pet-1",
|
||||
name: "تدی",
|
||||
type: "DOG",
|
||||
breed: "پامرانین",
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: "msg-1",
|
||||
senderRole: "USER",
|
||||
senderName: "مهدی رضایی",
|
||||
message: "سلام آقای دکتر، سگ من روزی ۲ قرص کلسیم میخوره، آیا زیاده؟",
|
||||
createdAt: "2025-01-01T10:00:00Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === "/tickets/admin/all") {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
data: mockTicketsList,
|
||||
meta: { total: 2, page: 1, lastPage: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url === "/tickets/ticket-1") {
|
||||
return Promise.resolve({
|
||||
data: { data: mockTicketDetail },
|
||||
});
|
||||
}
|
||||
return Promise.resolve({ data: {} });
|
||||
});
|
||||
});
|
||||
|
||||
it("renders tickets list table with badges and details properly", async () => {
|
||||
render(<Tickets />);
|
||||
|
||||
expect(screen.getByText("پشتیبانی، تیکتینگ و مشاوره دامپزشکی")).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("TK-1001")).toBeInTheDocument();
|
||||
expect(screen.getByText("TK-1002")).toBeInTheDocument();
|
||||
expect(screen.getByText("مشاوره در مورد دوز کلسیم پامرانین")).toBeInTheDocument();
|
||||
expect(screen.getByText("پیگیری سفارش مکمل و زمان ارسال")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText("مهدی رضایی")).toBeInTheDocument();
|
||||
expect(screen.getByText("سارا کمالی")).toBeInTheDocument();
|
||||
expect(screen.getByText("09121112233")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("مشاوره دامپزشک").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("پشتیبانی سفارش").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("در انتظار پاسخ").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("پاسخ داده شد").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText(/تدی \(پامرانین\)/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters tickets by search query, status and category", async () => {
|
||||
render(<Tickets />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("TK-1001")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/جستجو در موضوع، شماره تیکت، نام کاربر یا شماره موبایل\.\.\./i);
|
||||
fireEvent.change(searchInput, { target: { value: "TK-1001" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith("/tickets/admin/all", expect.objectContaining({
|
||||
params: expect.objectContaining({ search: "TK-1001" }),
|
||||
}));
|
||||
});
|
||||
|
||||
const selects = screen.getAllByRole("combobox");
|
||||
const statusSelect = selects[0];
|
||||
const categorySelect = selects[1];
|
||||
|
||||
fireEvent.change(statusSelect, { target: { value: "OPEN" } });
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith("/tickets/admin/all", expect.objectContaining({
|
||||
params: expect.objectContaining({ status: "OPEN" }),
|
||||
}));
|
||||
});
|
||||
|
||||
fireEvent.change(categorySelect, { target: { value: "VET_CONSULTATION" } });
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith("/tickets/admin/all", expect.objectContaining({
|
||||
params: expect.objectContaining({ category: "VET_CONSULTATION" }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it("opens ticket detail modal, views message history, and submits admin reply", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<Tickets />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("TK-1001")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const viewButtons = screen.getAllByRole("button", { name: "مشاهده و پاسخ" });
|
||||
fireEvent.click(viewButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith("/tickets/ticket-1");
|
||||
expect(screen.getByText("سلام آقای دکتر، سگ من روزی ۲ قرص کلسیم میخوره، آیا زیاده؟")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const replyTextarea = screen.getByPlaceholderText("متن پاسخ تخصصی به کاربر را وارد کنید...");
|
||||
fireEvent.change(replyTextarea, {
|
||||
target: { value: "سلام وقت بخیر، دوز کلسیم بر اساس وزن پت محاسبه میشود. لطفا وزن دقیق را بفرمایید." },
|
||||
});
|
||||
|
||||
const submitReplyBtn = screen.getByRole("button", { name: /ارسال پاسخ به کاربر/i });
|
||||
fireEvent.click(submitReplyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/tickets/ticket-1/messages",
|
||||
expect.objectContaining({
|
||||
message: "سلام وقت بخیر، دوز کلسیم بر اساس وزن پت محاسبه میشود. لطفا وزن دقیق را بفرمایید.",
|
||||
status: "ANSWERED",
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith("پاسخ با موفقیت برای کاربر ارسال شد");
|
||||
});
|
||||
});
|
||||
|
||||
it("updates ticket status directly from inside the details modal", async () => {
|
||||
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<Tickets />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("TK-1001")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const viewButtons = screen.getAllByRole("button", { name: "مشاهده و پاسخ" });
|
||||
fireEvent.click(viewButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("سلام آقای دکتر، سگ من روزی ۲ قرص کلسیم میخوره، آیا زیاده؟")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Inside modal header there is a status select
|
||||
const statusSelects = screen.getAllByRole("combobox");
|
||||
const modalStatusSelect = statusSelects.find((s) => (s as HTMLSelectElement).value === "OPEN");
|
||||
expect(modalStatusSelect).toBeDefined();
|
||||
|
||||
fireEvent.change(modalStatusSelect!, { target: { value: "CLOSED" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith("/tickets/admin/ticket-1/status", {
|
||||
status: "CLOSED",
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith("وضعیت تیکت تغییر یافت");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,27 +1,20 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
MessageSquare,
|
||||
Search,
|
||||
Filter,
|
||||
Stethoscope,
|
||||
FileText,
|
||||
User,
|
||||
Clock,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
XCircle,
|
||||
Send,
|
||||
RefreshCw,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ShieldCheck,
|
||||
Building2,
|
||||
Calendar,
|
||||
Building2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
FileText,
|
||||
MessageSquare,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Send,
|
||||
Stethoscope,
|
||||
User
|
||||
} from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import api from '../services/api';
|
||||
|
||||
interface TicketMessage {
|
||||
id: string;
|
||||
@@ -68,7 +61,7 @@ export default function Tickets() {
|
||||
|
||||
// Detail / Reply Modal
|
||||
const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
|
||||
const [fetchingDetail, setFetchingDetail] = useState(false);
|
||||
const [, setFetchingDetail] = useState(false);
|
||||
const [replyMessage, setReplyMessage] = useState('');
|
||||
const [replyStatus, setReplyStatus] = useState<string>('ANSWERED');
|
||||
const [sendingReply, setSendingReply] = useState(false);
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Transactions from './Transactions';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Transactions Page Component', () => {
|
||||
const mockTransactions = [
|
||||
{
|
||||
id: 'tx-1',
|
||||
userId: 'usr-1',
|
||||
orderId: 'ord-12345678',
|
||||
amount: 1500000,
|
||||
amountRials: 15000000,
|
||||
gateway: 'zibal',
|
||||
trackId: '123456789',
|
||||
refNumber: '987654321',
|
||||
cardNumber: '603799******1234',
|
||||
status: 'VERIFIED',
|
||||
type: 'ORDER',
|
||||
createdAt: '2026-04-10T12:00:00Z',
|
||||
user: {
|
||||
id: 'usr-1',
|
||||
firstName: 'رضا',
|
||||
lastName: 'محمدی',
|
||||
mobile: '09123456789',
|
||||
},
|
||||
order: {
|
||||
id: 'ord-12345678',
|
||||
orderNumber: 'CN-1001',
|
||||
trackingNumber: 'CANINA-ORD-1001',
|
||||
totalAmount: 1500000,
|
||||
status: 'PROCESSING',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tx-2',
|
||||
userId: 'usr-2',
|
||||
orderId: null,
|
||||
amount: 500000,
|
||||
amountRials: 5000000,
|
||||
gateway: 'wallet',
|
||||
trackId: '555666777',
|
||||
refNumber: null,
|
||||
cardNumber: null,
|
||||
status: 'PENDING',
|
||||
type: 'WALLET_TOPUP',
|
||||
createdAt: '2026-04-11T14:30:00Z',
|
||||
user: {
|
||||
id: 'usr-2',
|
||||
firstName: 'مهدی',
|
||||
lastName: 'کریمی',
|
||||
mobile: '09198765432',
|
||||
},
|
||||
order: null,
|
||||
},
|
||||
];
|
||||
|
||||
const mockStats = {
|
||||
totalCount: 45,
|
||||
verifiedCount: 38,
|
||||
pendingCount: 4,
|
||||
failedCount: 3,
|
||||
totalVolume: 85000000,
|
||||
todayVolume: 12000000,
|
||||
successRate: 84.4,
|
||||
};
|
||||
|
||||
const mockHealth = {
|
||||
gatewayName: 'زیبال (Zibal Payment Gateway)',
|
||||
status: 'ONLINE',
|
||||
latencyMs: 72,
|
||||
checkedAt: '2026-04-11T14:40:00Z',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url.startsWith('/payment/admin/stats')) {
|
||||
return Promise.resolve({ data: mockStats });
|
||||
}
|
||||
if (url.startsWith('/payment/admin/health')) {
|
||||
return Promise.resolve({ data: mockHealth });
|
||||
}
|
||||
if (url.startsWith('/payment/admin/transactions')) {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
success: true,
|
||||
transactions: mockTransactions,
|
||||
totalPages: 1,
|
||||
totalCount: 2,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.reject(new Error('Unknown url: ' + url));
|
||||
});
|
||||
});
|
||||
|
||||
const renderTransactions = (initialEntries = ['/transactions']) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<Transactions />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders transactions page with header, health banner, stats, and table', async () => {
|
||||
renderTransactions();
|
||||
|
||||
expect(screen.getByText('لاگها و مدیریت تراکنشهای مالی')).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
// Gateway health banner
|
||||
expect(screen.getByText('زیبال (Zibal Payment Gateway)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Latency: 72ms')).toBeInTheDocument();
|
||||
|
||||
// Stats
|
||||
expect(screen.getByText('حجم کل تراکنشهای موفق')).toBeInTheDocument();
|
||||
expect(screen.getByText('پرداختهای موفق امروز')).toBeInTheDocument();
|
||||
|
||||
// Transactions rows
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
expect(screen.getByText('09123456789')).toBeInTheDocument();
|
||||
expect(screen.getByText('CANINA-ORD-1001')).toBeInTheDocument();
|
||||
expect(screen.getByText('زیبال (Zibal)')).toBeInTheDocument();
|
||||
expect(screen.getByText('پرداخت تایید شده')).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText('مهدی کریمی')).toBeInTheDocument();
|
||||
expect(screen.getByText('شارژ کیف پول')).toBeInTheDocument();
|
||||
expect(screen.getByText('در انتظار تایید')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('filters transactions by search and status select', async () => {
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('جستجو بر اساس نام، موبایل، Track ID، شماره مرجع...');
|
||||
fireEvent.change(searchInput, { target: { value: '09123456789' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith(expect.stringContaining('search=09123456789'));
|
||||
});
|
||||
|
||||
const statusSelect = screen.getByDisplayValue('همه وضعیتها');
|
||||
fireEvent.change(statusSelect, { target: { value: 'VERIFIED' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.get).toHaveBeenCalledWith(expect.stringContaining('status=VERIFIED'));
|
||||
});
|
||||
});
|
||||
|
||||
it('opens details modal when clicking details eye button and triggers live inquiry', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
status: 1,
|
||||
message: 'موفق',
|
||||
paidAt: '2026-04-10T12:00:00Z',
|
||||
},
|
||||
});
|
||||
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const detailBtns = screen.getAllByTitle('مشاهده جزئیات کامل و استعلام زنده');
|
||||
fireEvent.click(detailBtns[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/جزئیات تراکنش #123456789/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// In modal, there's button for live inquiry ("استعلام مجدد")
|
||||
const inquiryBtn = screen.getByRole('button', { name: /استعلام مجدد/i });
|
||||
fireEvent.click(inquiryBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/payment/admin/inquiry', {
|
||||
trackId: '123456789',
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('استعلام تراکنش با موفقیت دریافت شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('triggers manual reconcile batch action', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
verified: 2,
|
||||
failed: 0,
|
||||
},
|
||||
});
|
||||
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const reconcileBtn = screen.getByRole('button', { name: /انطباق خودکار تراکنشها/i });
|
||||
fireEvent.click(reconcileBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/payment/admin/reconcile');
|
||||
expect(toast.success).toHaveBeenCalledWith('انطباق انجام شد: 2 تایید شده، 0 ناموفق');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens refund modal for verified transaction and executes refund to wallet', async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const refundBtn = screen.getByTitle('استرداد وجه تراکنش (کیف پول یا درگاه زیبال)');
|
||||
fireEvent.click(refundBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/استرداد وجه تراکنش/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Execute refund button in modal: "تایید و افزایش اعتبار کیف پول"
|
||||
const executeBtn = screen.getByRole('button', { name: /تایید و افزایش اعتبار کیف پول/i });
|
||||
fireEvent.click(executeBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/users/usr-1/wallet-adjust', expect.objectContaining({
|
||||
type: 'refund',
|
||||
amount: 1500000,
|
||||
}));
|
||||
expect(toast.success).toHaveBeenCalledWith('مبلغ با موفقیت به کیف پول کاربر عودت داده شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('opens digital receipt modal when clicking printer button', async () => {
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const receiptBtns = screen.getAllByTitle('مشاهده رسید دیجیتال تراکنش');
|
||||
fireEvent.click(receiptBtns[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/رسید تراکنش 123456789/)).toBeInTheDocument();
|
||||
expect(screen.getByText('شماره تراکنش')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('handles manual verification for pending transaction in details modal', async () => {
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { message: 'تراکنش با موفقیت تایید شد' },
|
||||
});
|
||||
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مهدی کریمی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const detailBtns = screen.getAllByTitle('مشاهده جزئیات کامل و استعلام زنده');
|
||||
// Second transaction is PENDING
|
||||
fireEvent.click(detailBtns[1]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/جزئیات تراکنش #555666777/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const verifyBtn = screen.getByRole('button', { name: /تایید دستی/i });
|
||||
fireEvent.click(verifyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith('/payment/admin/manual-verify/tx-2', {
|
||||
adminNote: 'تایید دستی فیش واریزی توسط مدیر سیستم',
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('تراکنش با موفقیت تایید شد');
|
||||
});
|
||||
});
|
||||
|
||||
it('copies trackId to clipboard when copy button clicked', async () => {
|
||||
Object.assign(navigator, {
|
||||
clipboard: {
|
||||
writeText: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
});
|
||||
|
||||
renderTransactions();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('رضا محمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText('رضا محمدی').closest('tr');
|
||||
const copyBtns = firstRow?.querySelectorAll('button');
|
||||
const trackCopyBtn = copyBtns?.[0];
|
||||
if (trackCopyBtn) {
|
||||
fireEvent.click(trackCopyBtn);
|
||||
expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('با موفقیت کپی شد'));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,31 +1,31 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
CreditCard,
|
||||
Search,
|
||||
Eye,
|
||||
Copy,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Clock,
|
||||
DollarSign,
|
||||
TrendingUp,
|
||||
Receipt,
|
||||
ShieldCheck,
|
||||
RotateCcw,
|
||||
Activity,
|
||||
Undo2,
|
||||
Printer,
|
||||
Wallet,
|
||||
Activity,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Copy,
|
||||
CreditCard,
|
||||
DollarSign,
|
||||
Eye,
|
||||
Printer,
|
||||
Receipt,
|
||||
RotateCcw,
|
||||
Search,
|
||||
ShieldCheck,
|
||||
TrendingUp,
|
||||
Undo2,
|
||||
Wallet,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Button from '../components/ui/Button';
|
||||
import TransactionReceiptModal,{ type TransactionReceiptData } from '../components/TransactionReceiptModal';
|
||||
import Badge from '../components/ui/Badge';
|
||||
import ThSort from '../components/ui/ThSort';
|
||||
import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import TransactionReceiptModal, { type TransactionReceiptData } from '../components/TransactionReceiptModal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ThSort from '../components/ui/ThSort';
|
||||
import api from '../services/api';
|
||||
import { useTableParams } from '../utils/useTableParams';
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ export default function Transactions() {
|
||||
const [selectedTx, setSelectedTx] = useState<Transaction | null>(null);
|
||||
const [liveInquiryLoading, setLiveInquiryLoading] = useState(false);
|
||||
const [liveInquiryData, setLiveInquiryData] = useState<any>(null);
|
||||
const [showRawLogs, setShowRawLogs] = useState(false);
|
||||
const [, setShowRawLogs] = useState(false);
|
||||
|
||||
// Receipt Modal State
|
||||
const [receiptModalOpen, setReceiptModalOpen] = useState(false);
|
||||
@@ -447,7 +447,7 @@ export default function Transactions() {
|
||||
<div className="flex items-center gap-4 text-xs font-mono font-bold text-gray-300 mt-1">
|
||||
<span>Latency: {health.latencyMs}ms</span>
|
||||
<span>•</span>
|
||||
<span>Updated: {health.checkedAt || health.lastChecked ? new Date(health.checkedAt || health.lastChecked).toLocaleTimeString('fa-IR') : 'الان'}</span>
|
||||
<span>Updated: {health.checkedAt || health.lastChecked ? new Date((health.checkedAt || health.lastChecked) ?? '').toLocaleTimeString('fa-IR') : 'الان'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import UITexts from './UITexts';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
|
||||
describe('UITexts',()=>{
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{}});vi.mocked(api.put).mockResolvedValue({data:{}});});
|
||||
const load=async()=>{render(<MemoryRouter><UITexts/></MemoryRouter>);await screen.findByRole('button',{name:/ذخیره تمامی تغییرات/});};
|
||||
it('disables bulk save until a field is changed',async()=>{await load();expect(screen.getByRole('button',{name:/ذخیره تمامی تغییرات/})).toBeDisabled();});
|
||||
it('saves only the edited key in a bulk update',async()=>{await load();const field=document.querySelector('input[type=text],textarea')!;const card=field.closest('.space-y-3')!;const key=card.querySelector('code')!.textContent!;fireEvent.change(field,{target:{value:'Edited content'}});fireEvent.click(screen.getByRole('button',{name:/ذخیره تمامی تغییرات/}));await waitFor(()=>expect(api.put).toHaveBeenCalledWith('/settings/ui-texts',{[key]:'Edited content'}));await waitFor(()=>expect(screen.getByRole('button',{name:/ذخیره تمامی تغییرات/})).toBeDisabled());});
|
||||
it('falls back to PATCH for individual fields',async()=>{await load();vi.mocked(api.put).mockRejectedValue(new Error('method unavailable'));vi.mocked(api.patch).mockResolvedValue({data:{}});const field=document.querySelector('input[type=text],textarea')!;const card=field.closest('.space-y-3')!;const key=card.querySelector('code')!.textContent!;fireEvent.change(field,{target:{value:'Fallback content'}});fireEvent.click(card.querySelector('button:last-child')!);await waitFor(()=>expect(api.patch).toHaveBeenCalledWith('/settings/ui-texts/'+encodeURIComponent(key),{value:'Fallback content'}));});
|
||||
});
|
||||
@@ -1,54 +1,46 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Languages,
|
||||
Save,
|
||||
Search,
|
||||
Loader2,
|
||||
Layout,
|
||||
Sliders,
|
||||
Link as LinkIcon,
|
||||
FileText,
|
||||
Check,
|
||||
Upload,
|
||||
HelpCircle,
|
||||
Eye,
|
||||
Layers,
|
||||
ChevronDown,
|
||||
Sparkles,
|
||||
Home,
|
||||
ShoppingBag,
|
||||
BookOpen,
|
||||
PhoneCall,
|
||||
Building2,
|
||||
Heart,
|
||||
Smile,
|
||||
Globe,
|
||||
Settings,
|
||||
Pill,
|
||||
ShieldCheck,
|
||||
HeartPulse,
|
||||
Activity,
|
||||
Award,
|
||||
Video,
|
||||
Info,
|
||||
Truck,
|
||||
CreditCard,
|
||||
User,
|
||||
Shield,
|
||||
Smartphone,
|
||||
Monitor,
|
||||
Sparkle,
|
||||
Award,
|
||||
BookOpen,
|
||||
Building2,
|
||||
Check,
|
||||
ChevronDown,
|
||||
CreditCard,
|
||||
Eye,
|
||||
FileText,
|
||||
Globe,
|
||||
Heart,
|
||||
HelpCircle,
|
||||
Home,
|
||||
Languages,
|
||||
Layout,
|
||||
Link as LinkIcon,
|
||||
Monitor,
|
||||
PhoneCall,
|
||||
Pill,
|
||||
Save,
|
||||
Search,
|
||||
Shield,
|
||||
ShieldCheck,
|
||||
ShoppingBag,
|
||||
Sliders,
|
||||
Smartphone,
|
||||
Sparkles,
|
||||
Truck,
|
||||
Upload,
|
||||
User,
|
||||
Video
|
||||
} from 'lucide-react';
|
||||
import React,{ useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api, { BASE_DOMAIN } from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ToggleSwitch from '../components/ui/ToggleSwitch';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import Button from '../components/ui/Button';
|
||||
import IconPickerModal,{ ICON_REGISTRY } from '../components/ui/IconPickerModal';
|
||||
import ImagePreviewModal from '../components/ui/ImagePreviewModal';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
import RichTextEditor from '../components/ui/RichTextEditor';
|
||||
import IconPickerModal, { ICON_REGISTRY } from '../components/ui/IconPickerModal';
|
||||
import Button from '../components/ui/Button';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ToggleSwitch from '../components/ui/ToggleSwitch';
|
||||
import api,{ BASE_DOMAIN } from '../services/api';
|
||||
|
||||
// Structured Page Builder Definitions
|
||||
interface SectionField {
|
||||
@@ -720,7 +712,6 @@ export default function UITexts() {
|
||||
}
|
||||
};
|
||||
|
||||
const isImageKey = (k: string) => k.includes('image') || k.includes('logo') || k.includes('img') || k.includes('avatar') || k.includes('url');
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
|
||||
Loaded 100 of 439 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user