Spaces:
Runtime error
Runtime error
feat: add accounting system with expenses, revenue summary, and monthly history
Browse filesFiles changed (5)
205 unmodified lines206207208209210211212213214215216217218219220221222223224205 unmodified lines @@index([createdAt]) @@map("notifications")}
model Expense { id String @id @default(cuid()) description String @db.VarChar(300) amount Decimal @db.Decimal(10, 2) category String @db.VarChar(50) date DateTime @default(now()) notes String? @db.Text createdBy String @db.VarChar(100) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt
@@index([date]) @@index([category]) @@map("expenses")}426 unmodified lines427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577426 unmodified linesrouter.get('/contact', contactCtrl.adminList)router.get('/contact/:id', contactCtrl.adminGetById)router.post('/contact/:id/reply', validate(z.object({ content: z.string().min(1, 'محتوى الرد مطلوب') })), contactCtrl.adminReply)
// Accountingrouter.get('/accounts/summary', async (req, res, next) => { try { const now = new Date() const firstDay = new Date(now.getFullYear(), now.getMonth(), 1) const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1)
const [paidOrders, pendingOrders, totalExpenses, monthExpenses, lastMonthOrders] = await Promise.all([ prisma.order.aggregate({ _sum: { totalAmount: true }, where: { status: 'COMPLETED' } }), prisma.order.aggregate({ _sum: { totalAmount: true }, where: { status: { in: ['PENDING', 'ACCEPTED', 'IN_PROGRESS'] } } }), prisma.expense.aggregate({ _sum: { amount: true } }), prisma.expense.aggregate({ _sum: { amount: true }, where: { date: { gte: firstDay } } }), prisma.order.aggregate({ _sum: { totalAmount: true }, where: { status: 'COMPLETED', createdAt: { gte: lastMonth, lt: firstDay } } }), ])
const totalRevenue = Number(paidOrders._sum.totalAmount || 0) const pendingRevenue = Number(pendingOrders._sum.totalAmount || 0) const totalExpense = Number(totalExpenses._sum.amount || 0)
res.json({ totalRevenue, totalExpenses: totalExpense, netProfit: totalRevenue - totalExpense, pendingRevenue, monthExpenses: Number(monthExpenses._sum.amount || 0), lastMonthRevenue: Number(lastMonthOrders._sum.totalAmount || 0), orderCounts: { completed: await prisma.order.count({ where: { status: 'COMPLETED' } }), pending: await prisma.order.count({ where: { status: 'PENDING' } }), inProgress: await prisma.order.count({ where: { status: 'IN_PROGRESS' } }), cancelled: await prisma.order.count({ where: { status: 'CANCELLED' } }), }, }) } catch (err) { next(err) }})
router.get('/accounts/expenses', async (req, res, next) => { try { const { page, limit } = getPagination(req.query) const category = req.query.category const from = req.query.from ? new Date(req.query.from) : null const to = req.query.to ? new Date(req.query.to) : null
const where = {} if (category) where.category = category if (from || to) { where.date = {} if (from) where.date.gte = from if (to) where.date.lte = to }
const [expenses, total] = await Promise.all([ prisma.expense.findMany({ where, orderBy: { date: 'desc' }, take: limit, skip: (page - 1) * limit, }), prisma.expense.count({ where }), ])
const totalAmount = await prisma.expense.aggregate({ _sum: { amount: true }, where })
res.json({ expenses: expenses.map(e => ({ ...e, amount: Number(e.amount) })), total, page, totalPages: Math.ceil(total / limit), totalAmount: Number(totalAmount._sum.amount || 0), }) } catch (err) { next(err) }})
router.post('/accounts/expenses', validate(z.object({ description: z.string().min(1).max(300), amount: z.number().positive(), category: z.string().min(1).max(50), date: z.string().optional(), notes: z.string().max(500).optional(),})), async (req, res, next) => { try { const d = req.validatedData const expense = await prisma.expense.create({ data: { description: d.description, amount: d.amount, category: d.category, date: d.date ? new Date(d.date) : new Date(), notes: d.notes || null, createdBy: req.user.firstName + ' ' + req.user.lastName, }, }) res.json({ ...expense, amount: Number(expense.amount) }) } catch (err) { next(err) }})
router.put('/accounts/expenses/:id', validate(z.object({ description: z.string().min(1).max(300).optional(), amount: z.number().positive().optional(), category: z.string().min(1).max(50).optional(), date: z.string().optional(), notes: z.string().max(500).optional().nullable(),})), async (req, res, next) => { try { const d = req.validatedData const updateData = {} if (d.description !== undefined) updateData.description = d.description if (d.amount !== undefined) updateData.amount = d.amount if (d.category !== undefined) updateData.category = d.category if (d.date !== undefined) updateData.date = new Date(d.date) if (d.notes !== undefined) updateData.notes = d.notes
const expense = await prisma.expense.update({ where: { id: req.params.id }, data: updateData, }) res.json({ ...expense, amount: Number(expense.amount) }) } catch (err) { next(err) }})
router.delete('/accounts/expenses/:id', async (req, res, next) => { try { await prisma.expense.delete({ where: { id: req.params.id } }) res.json({ message: 'تم حذف المصروف' }) } catch (err) { next(err) }})
// Revenue breakdown by monthrouter.get('/accounts/revenue-history', async (req, res, next) => { try { const months = await prisma.$queryRaw` SELECT TO_CHAR(DATE_TRUNC('month', "createdAt"), 'YYYY-MM') as month, SUM("totalAmount")::float as revenue, COUNT(*)::int as orders FROM orders WHERE status = 'COMPLETED' GROUP BY DATE_TRUNC('month', "createdAt") ORDER BY month DESC LIMIT 12 ` res.json(months) } catch (err) { next(err) }})router.patch('/contact/:id/read', contactCtrl.adminToggleRead)router.patch('/contact/:id/status', contactCtrl.adminToggleStatus)router.delete('/contact/:id', contactCtrl.adminDelete)1223459 unmodified lines15161718192021import { NavLink, useNavigate } from 'react-router-dom'import { LayoutDashboard, ShoppingBag, Palette, Monitor, MessageCircle, Mail, LogOut, X, Users, UserCog, Shield } from 'lucide-react'import { LayoutDashboard, ShoppingBag, Palette, Monitor, MessageCircle, Mail, LogOut, X, Users, UserCog, Shield, DollarSign } from 'lucide-react'import { useAuthStore } from '../../store/authStore'import { cn } from '../../utils/cn'
9 unmodified lines
const accounts = [ { to: '/x9k2-manage/panel/accounts', icon: UserCog, label: 'الحسابات' }, { to: '/x9k2-manage/panel/accounting', icon: DollarSign, label: 'المحاسبة' },]
export function AdminSidebar({ open, onClose }) {123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261import { useState } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { DollarSign, TrendingUp, TrendingDown, Wallet, Plus, Trash2, Loader, Pencil, X, Calendar, Search } from 'lucide-react'import { PageHeader } from '../../components/shared/PageHeader'import { EmptyState } from '../../components/shared/EmptyState'import { api } from '../../lib/axios'import toast from 'react-hot-toast'
const categories = ['سيرفرات', 'استضافة', 'نطاقات', 'تسويق', 'برمجيات', 'مرتبات', 'ضرائب', 'أخرى']
const categoryColors = { سيرفرات: 'bg-red-100 text-red-700', استضافة: 'bg-blue-100 text-blue-700', نطاقات: 'bg-purple-100 text-purple-700', تسويق: 'bg-yellow-100 text-yellow-700', برمجيات: 'bg-indigo-100 text-indigo-700', مرتبات: 'bg-green-100 text-green-700', ضرائب: 'bg-orange-100 text-orange-700', أخرى: 'bg-gray-100 text-gray-700',}
export default function AdminAccountingPage() { const queryClient = useQueryClient() const [showAdd, setShowAdd] = useState(false) const [editing, setEditing] = useState(null) const [filterCat, setFilterCat] = useState('') const [form, setForm] = useState({ description: '', amount: '', category: 'أخرى', date: '', notes: '' })
const { data: summary, isLoading: summaryLoading } = useQuery({ queryKey: ['admin-accounting-summary'], queryFn: () => api.get('/admin/accounts/summary').then(r => r.data), refetchInterval: 30000, })
const { data: expensesData, isLoading: expLoading } = useQuery({ queryKey: ['admin-accounting-expenses', filterCat], queryFn: () => api.get('/admin/accounts/expenses', { params: { category: filterCat || undefined, limit: 100 } }).then(r => r.data), })
const { data: revenueHistory } = useQuery({ queryKey: ['admin-revenue-history'], queryFn: () => api.get('/admin/accounts/revenue-history').then(r => r.data), })
const createMut = useMutation({ mutationFn: (d) => api.post('/admin/accounts/expenses', d), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin-accounting'] }) setShowAdd(false) resetForm() toast.success('تم إضافة المصروف') }, onError: () => toast.error('فشل إضافة المصروف'), })
const updateMut = useMutation({ mutationFn: ({ id, ...d }) => api.put(`/admin/accounts/expenses/${id}`, d), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin-accounting'] }) setEditing(null) resetForm() toast.success('تم تحديث المصروف') }, onError: () => toast.error('فشل تحديث المصروف'), })
const deleteMut = useMutation({ mutationFn: (id) => api.delete(`/admin/accounts/expenses/${id}`), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin-accounting'] }) toast.success('تم حذف المصروف') }, onError: () => toast.error('فشل حذف المصروف'), })
const resetForm = () => setForm({ description: '', amount: '', category: 'أخرى', date: '', notes: '' })
const handleSubmit = (e) => { e.preventDefault() const payload = { description: form.description, amount: parseFloat(form.amount), category: form.category, notes: form.notes || undefined } if (form.date) payload.date = form.date if (editing) updateMut.mutate({ id: editing, ...payload }) else createMut.mutate(payload) }
const startEdit = (exp) => { setEditing(exp.id) setForm({ description: exp.description, amount: String(exp.amount), category: exp.category, date: exp.date?.slice(0, 10) || '', notes: exp.notes || '' }) setShowAdd(true) }
if (summaryLoading) { return <div className="flex items-center justify-center py-16"><Loader className="w-6 h-6 animate-spin text-brand-500" /></div> }
const expenses = expensesData?.expenses || [] const revHistory = revenueHistory || []
return ( <div> <PageHeader title="المحاسبة" description="إدارة الإيرادات والمصروفات" />
{/* Summary Cards */} <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6"> <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5"> <div className="flex items-center justify-between mb-2"> <span className="text-sm text-gray-500 font-medium">إجمالي الإيرادات</span> <div className="w-9 h-9 rounded-lg bg-green-100 flex items-center justify-center"><TrendingUp className="w-5 h-5 text-green-600" /></div> </div> <p className="text-2xl font-bold text-gray-900">{summary?.totalRevenue?.toLocaleString() || 0} <span className="text-sm font-normal text-gray-500">ج.م</span></p> </div> <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5"> <div className="flex items-center justify-between mb-2"> <span className="text-sm text-gray-500 font-medium">إجمالي المصروفات</span> <div className="w-9 h-9 rounded-lg bg-red-100 flex items-center justify-center"><TrendingDown className="w-5 h-5 text-red-600" /></div> </div> <p className="text-2xl font-bold text-gray-900">{summary?.totalExpenses?.toLocaleString() || 0} <span className="text-sm font-normal text-gray-500">ج.م</span></p> </div> <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5"> <div className="flex items-center justify-between mb-2"> <span className="text-sm text-gray-500 font-medium">صافي الربح</span> <div className="w-9 h-9 rounded-lg bg-brand-100 flex items-center justify-center"><DollarSign className="w-5 h-5 text-brand-600" /></div> </div> <p className={`text-2xl font-bold ${(summary?.netProfit || 0) >= 0 ? 'text-green-600' : 'text-red-600'}`}> {summary?.netProfit?.toLocaleString() || 0} <span className="text-sm font-normal text-gray-500">ج.م</span> </p> </div> <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5"> <div className="flex items-center justify-between mb-2"> <span className="text-sm text-gray-500 font-medium">إيرادات معلقة</span> <div className="w-9 h-9 rounded-lg bg-yellow-100 flex items-center justify-center"><Wallet className="w-5 h-5 text-yellow-600" /></div> </div> <p className="text-2xl font-bold text-gray-900">{summary?.pendingRevenue?.toLocaleString() || 0} <span className="text-sm font-normal text-gray-500">ج.م</span></p> </div> </div>
{/* Revenue History */} {revHistory.length > 0 && ( <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-6"> <h3 className="font-bold text-gray-900 mb-3">الإيرادات الشهرية</h3> <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3"> {revHistory.map(m => ( <div key={m.month} className="bg-gray-50 rounded-xl p-3 text-center"> <p className="text-xs text-gray-500 mb-1">{m.month}</p> <p className="font-bold text-sm">{Number(m.revenue).toLocaleString()}</p> <p className="text-xs text-gray-400">{m.orders} طلب</p> </div> ))} </div> </div> )}
{/* Expenses Section */} <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5"> <div className="flex items-center justify-between mb-4"> <h3 className="font-bold text-gray-900">المصروفات</h3> <div className="flex items-center gap-3"> <select value={filterCat} onChange={e => setFilterCat(e.target.value)} className="text-sm border border-gray-200 rounded-xl px-3 py-1.5"> <option value="">كل التصنيفات</option> {categories.map(c => <option key={c} value={c}>{c}</option>)} </select> <button onClick={() => { setEditing(null); resetForm(); setShowAdd(true) }} className="flex items-center gap-2 bg-brand-600 hover:bg-brand-700 text-white px-4 py-2 rounded-xl text-sm font-medium transition-colors"> <Plus className="w-4 h-4" /> مصروف جديد </button> </div> </div>
{expLoading ? ( <div className="flex items-center justify-center py-12"><Loader className="w-6 h-6 animate-spin text-brand-500" /></div> ) : expenses.length === 0 ? ( <EmptyState icon={TrendingDown} title="لا توجد مصروفات" description="لم يتم تسجيل أي مصروفات بعد" /> ) : ( <div className="overflow-x-auto"> <table className="w-full text-sm"> <thead> <tr className="border-b border-gray-100 bg-gray-50/50"> <th className="text-right px-4 py-3 font-medium text-gray-600">الوصف</th> <th className="text-right px-4 py-3 font-medium text-gray-600">التصنيف</th> <th className="text-right px-4 py-3 font-medium text-gray-600">المبلغ</th> <th className="text-right px-4 py-3 font-medium text-gray-600">التاريخ</th> <th className="text-right px-4 py-3 font-medium text-gray-600">بواسطة</th> <th className="text-left px-4 py-3 font-medium text-gray-600">إجراءات</th> </tr> </thead> <tbody> {expenses.map(exp => ( <tr key={exp.id} className="border-b border-gray-50 hover:bg-gray-50/50 transition-colors"> <td className="px-4 py-3 font-medium">{exp.description}</td> <td className="px-4 py-3"> <span className={`inline-block px-2.5 py-1 rounded-lg text-xs font-medium ${categoryColors[exp.category] || 'bg-gray-100 text-gray-700'}`}> {exp.category} </span> </td> <td className="px-4 py-3 font-medium text-red-600">-{Number(exp.amount).toLocaleString()}</td> <td className="px-4 py-3 text-gray-500 text-xs">{new Date(exp.date).toLocaleDateString('ar-EG')}</td> <td className="px-4 py-3 text-gray-500 text-xs">{exp.createdBy}</td> <td className="px-4 py-3 text-left"> <div className="flex items-center gap-2"> <button onClick={() => startEdit(exp)} className="text-gray-400 hover:text-brand-600 p-1"><Pencil className="w-4 h-4" /></button> <button onClick={() => { if (confirm('حذف هذا المصروف؟')) deleteMut.mutate(exp.id) }} className="text-gray-400 hover:text-red-600 p-1"><Trash2 className="w-4 h-4" /></button> </div> </td> </tr> ))} </tbody> </table> </div> )}
{expensesData?.totalAmount > 0 && ( <div className="flex justify-end mt-4 pt-4 border-t border-gray-100"> <p className="text-sm font-medium text-gray-700"> إجمالي المصروفات المعروضة: <span className="text-red-600 font-bold">{Number(expensesData.totalAmount).toLocaleString()} ج.م</span> </p> </div> )} </div>
{/* Add/Edit Modal */} {showAdd && ( <div className="fixed inset-0 bg-black/30 z-50 flex items-center justify-center p-4" onClick={() => { setShowAdd(false); setEditing(null) }}> <div className="bg-white rounded-2xl w-full max-w-md p-6 shadow-xl" onClick={e => e.stopPropagation()}> <div className="flex items-center justify-between mb-4"> <h2 className="font-bold text-lg">{editing ? 'تعديل مصروف' : 'مصروف جديد'}</h2> <button onClick={() => { setShowAdd(false); setEditing(null) }} className="p-1 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5" /></button> </div> <form onSubmit={handleSubmit} className="space-y-3"> <div> <label className="block text-xs font-medium text-gray-700 mb-1">الوصف</label> <input value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500" required /> </div> <div className="grid grid-cols-2 gap-3"> <div> <label className="block text-xs font-medium text-gray-700 mb-1">المبلغ</label> <input type="number" step="0.01" min="0.01" value={form.amount} onChange={e => setForm({ ...form, amount: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500" required /> </div> <div> <label className="block text-xs font-medium text-gray-700 mb-1">التصنيف</label> <select value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500"> {categories.map(c => <option key={c} value={c}>{c}</option>)} </select> </div> </div> <div> <label className="block text-xs font-medium text-gray-700 mb-1">التاريخ</label> <input type="date" value={form.date} onChange={e => setForm({ ...form, date: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500" /> </div> <div> <label className="block text-xs font-medium text-gray-700 mb-1">ملاحظات</label> <textarea value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} rows={2} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500" /> </div> <button type="submit" disabled={createMut.isPending || updateMut.isPending} className="w-full bg-brand-600 hover:bg-brand-700 text-white py-2.5 rounded-xl text-sm font-medium transition-colors disabled:opacity-50"> {createMut.isPending || updateMut.isPending ? 'جاري...' : editing ? 'تحديث' : 'إضافة'} </button> </form> </div> </div> )} </div> )}33 unmodified lines3435363738394058 unmodified lines9910010110210310410533 unmodified linesconst AdminContactPage = lazy(() => import('../pages/admin/AdminContactPage'))const AdminUsersPage = lazy(() => import('../pages/admin/AdminUsersPage'))const AdminAccountsPage = lazy(() => import('../pages/admin/AdminAccountsPage'))const AdminAccountingPage = lazy(() => import('../pages/admin/AdminAccountingPage'))
const router = createBrowserRouter([ {58 unmodified lines { path: 'users', element: <PageTransition><AdminUsersPage /></PageTransition> }, { path: 'contact', element: <PageTransition><AdminContactPage /></PageTransition> }, { path: 'accounts', element: <PageTransition><AdminAccountsPage /></PageTransition> }, { path: 'accounting', element: <PageTransition><AdminAccountingPage /></PageTransition> }, ] },
apps/server/prisma/schema.prisma+16
apps/server/src/modules/admin/admin.routes.js+145
client/src/components/layout/AdminSidebar.jsx+2-1
client/src/pages/admin/AdminAccountingPage.jsxAdded+261
client/src/router/index.jsx+2