780 lines
45 KiB
TypeScript
780 lines
45 KiB
TypeScript
"use client";
|
||
|
||
import Image from "next/image";
|
||
import { useCallback, useEffect, useRef, useState } from "react";
|
||
import { useRouter } from "next/navigation";
|
||
import {
|
||
Activity,
|
||
AlertTriangle,
|
||
ArrowLeft,
|
||
BarChart3,
|
||
Bell,
|
||
Boxes,
|
||
Building2,
|
||
CircleDollarSign,
|
||
CheckCircle2,
|
||
ChevronLeft,
|
||
Eye,
|
||
Heart,
|
||
LayoutDashboard,
|
||
LoaderCircle,
|
||
LogOut,
|
||
MapPin,
|
||
Menu,
|
||
MessageCircle,
|
||
PackagePlus,
|
||
ReceiptText,
|
||
PenLine,
|
||
RefreshCcw,
|
||
Search,
|
||
ShoppingBag,
|
||
Sparkles,
|
||
Store,
|
||
TrendingUp,
|
||
UsersRound,
|
||
Wrench,
|
||
} from "lucide-react";
|
||
|
||
import { ConnectionIndicator } from "@/components/dashboard/connection-indicator";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Drawer } from "@/components/ui/drawer";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import { Textarea } from "@/components/ui/textarea";
|
||
import { useToast } from "@/components/ui/toast";
|
||
import { companyFetch, logoutCompany } from "@/lib/auth/company-client";
|
||
import { cn } from "@/lib/utils";
|
||
import { isHttpError } from "@/lib/api/response";
|
||
|
||
type DashboardData = {
|
||
profile?: {
|
||
_id?: string;
|
||
avatar?: string;
|
||
name?: string;
|
||
stageName?: string;
|
||
bio?: string;
|
||
isVerified?: boolean;
|
||
};
|
||
stats?: Record<string, number>;
|
||
audience?: Record<string, number>;
|
||
topContent?: Array<{
|
||
_id: string;
|
||
content?: string;
|
||
postType?: string;
|
||
displayUrl?: string;
|
||
viewCount?: number;
|
||
likesCount?: number;
|
||
commentsCount?: number;
|
||
engagementScore?: number;
|
||
}>;
|
||
recentActivity?: Array<{
|
||
_id: string;
|
||
title?: string;
|
||
previewText?: string;
|
||
type?: string;
|
||
createdAt?: string;
|
||
}>;
|
||
};
|
||
|
||
type ShopProfile = {
|
||
adminId?: string;
|
||
shopName?: string;
|
||
shopDescription?: string;
|
||
shopImageUrls?: string[];
|
||
shopLocation?: string;
|
||
shopLatitude?: number | null;
|
||
shopLongitude?: number | null;
|
||
};
|
||
|
||
type Listing = {
|
||
_id: string;
|
||
title: string;
|
||
description?: string;
|
||
price?: number;
|
||
currency?: string;
|
||
quantity?: number;
|
||
imageUrls?: string[];
|
||
isActive?: boolean;
|
||
condition?: string;
|
||
instrumentType?: string;
|
||
listingCategory?: string;
|
||
createdAt?: string;
|
||
};
|
||
|
||
type RepairShop = {
|
||
_id: string;
|
||
name: string;
|
||
location?: string;
|
||
services?: string[];
|
||
isActive?: boolean;
|
||
};
|
||
|
||
type CompanyOrder = {
|
||
_id: string;
|
||
orderNumber: string;
|
||
itemTitle: string;
|
||
items?: Array<{ listingId: string; title: string; quantity: number; unitPrice: number; total: number }>;
|
||
fulfillmentMethod?: "delivery" | "pickup";
|
||
city?: string;
|
||
address?: string;
|
||
note?: string;
|
||
quantity: number;
|
||
total: number;
|
||
currency: string;
|
||
customerName: string;
|
||
customerPhone: string;
|
||
status: "pending" | "confirmed" | "processing" | "ready" | "completed" | "cancelled";
|
||
createdAt?: string;
|
||
};
|
||
|
||
type CompanyOrderSummary = {
|
||
total: number;
|
||
pending: number;
|
||
confirmed: number;
|
||
processing: number;
|
||
ready: number;
|
||
completed: number;
|
||
cancelled: number;
|
||
revenue: number;
|
||
completedSales: number;
|
||
lowStock: number;
|
||
};
|
||
|
||
type Paginated<T> = {
|
||
items?: T[];
|
||
data?: T[];
|
||
meta?: { total?: number };
|
||
total?: number;
|
||
totalPages?: number;
|
||
};
|
||
|
||
const navItems = [
|
||
{ href: "#overview", label: "نظرة عامة", icon: LayoutDashboard },
|
||
{ href: "#store", label: "هوية الشركة", icon: Building2 },
|
||
{ href: "#products", label: "المنتجات", icon: ShoppingBag },
|
||
{ href: "#orders", label: "الطلبات والمبيعات", icon: ReceiptText },
|
||
{ href: "#audience", label: "الجمهور", icon: UsersRound },
|
||
{ href: "#content", label: "أفضل المحتوى", icon: BarChart3 },
|
||
{ href: "#activity", label: "آخر النشاطات", icon: Activity },
|
||
];
|
||
|
||
function compactNumber(value: number | undefined) {
|
||
return new Intl.NumberFormat("ar-SA", { notation: "compact", maximumFractionDigits: 1 }).format(value ?? 0);
|
||
}
|
||
|
||
function money(value: number | undefined, currency = "SAR") {
|
||
return new Intl.NumberFormat("ar-SA", { style: "currency", currency }).format(value ?? 0);
|
||
}
|
||
|
||
function getItems<T>(response: Paginated<T>) {
|
||
return response.items ?? response.data ?? [];
|
||
}
|
||
|
||
export default function CompanyDashboardPage() {
|
||
const router = useRouter();
|
||
const { toast } = useToast();
|
||
const [dashboard, setDashboard] = useState<DashboardData | null>(null);
|
||
const [shop, setShop] = useState<ShopProfile | null>(null);
|
||
const [listings, setListings] = useState<Listing[]>([]);
|
||
const [repairShops, setRepairShops] = useState<RepairShop[]>([]);
|
||
const [orders, setOrders] = useState<CompanyOrder[]>([]);
|
||
const [orderSummary, setOrderSummary] = useState<CompanyOrderSummary | null>(null);
|
||
const [orderStatus, setOrderStatus] = useState("all");
|
||
const [orderPage, setOrderPage] = useState(1);
|
||
const [orderPages, setOrderPages] = useState(1);
|
||
const [listingPage, setListingPage] = useState(1);
|
||
const [listingPages, setListingPages] = useState(1);
|
||
const loadSequence = useRef(0);
|
||
const [updatingOrderId, setUpdatingOrderId] = useState<string | null>(null);
|
||
const [unread, setUnread] = useState(0);
|
||
const [loading, setLoading] = useState(true);
|
||
const [refreshing, setRefreshing] = useState(false);
|
||
const [loadError, setLoadError] = useState<string | null>(null);
|
||
const [mobileMenu, setMobileMenu] = useState(false);
|
||
const [listingDrawer, setListingDrawer] = useState(false);
|
||
const [profileDrawer, setProfileDrawer] = useState(false);
|
||
const [search, setSearch] = useState("");
|
||
const [searchQuery, setSearchQuery] = useState("");
|
||
const [saving, setSaving] = useState(false);
|
||
const [listingForm, setListingForm] = useState({
|
||
title: "",
|
||
description: "",
|
||
price: "",
|
||
quantity: "1",
|
||
instrumentType: "",
|
||
isActive: true,
|
||
});
|
||
const [profileForm, setProfileForm] = useState({
|
||
shopName: "",
|
||
shopDescription: "",
|
||
shopLocation: "",
|
||
});
|
||
|
||
const load = useCallback(async (background = false) => {
|
||
const sequence = ++loadSequence.current;
|
||
setLoadError(null);
|
||
if (background) {
|
||
setRefreshing(true);
|
||
} else {
|
||
setLoading(true);
|
||
}
|
||
try {
|
||
const [
|
||
dashboardResponse,
|
||
shopResponse,
|
||
listingsResponse,
|
||
repairsResponse,
|
||
unreadResponse,
|
||
ordersResponse,
|
||
orderSummaryResponse,
|
||
] =
|
||
await Promise.all([
|
||
companyFetch<DashboardData>("/users/me/dashboard"),
|
||
companyFetch<ShopProfile>("/marketplace/admin/shop-profile/me"),
|
||
companyFetch<Paginated<Listing>>(`/marketplace/admin/listings/me?page=${listingPage}&limit=8&sortOrder=desc&q=${encodeURIComponent(searchQuery)}`),
|
||
companyFetch<Paginated<RepairShop>>("/marketplace/admin/repair-shops/me?page=1&limit=10"),
|
||
companyFetch<{ count?: number; unreadCount?: number }>("/notifications/unread-count")
|
||
.catch((): { count?: number; unreadCount?: number } => ({ count: 0 })),
|
||
companyFetch<Paginated<CompanyOrder>>(`/orders/admin?page=${orderPage}&limit=20${orderStatus === "all" ? "" : `&status=${orderStatus}`}`),
|
||
companyFetch<CompanyOrderSummary>("/orders/admin/summary"),
|
||
]);
|
||
|
||
if (sequence !== loadSequence.current) return;
|
||
setDashboard(dashboardResponse);
|
||
setShop(shopResponse);
|
||
setListings(getItems(listingsResponse));
|
||
setListingPages(listingsResponse.totalPages ?? 1);
|
||
setRepairShops(getItems(repairsResponse));
|
||
setOrders(getItems(ordersResponse));
|
||
setOrderPages(ordersResponse.totalPages ?? 1);
|
||
setOrderSummary(orderSummaryResponse);
|
||
setUnread(unreadResponse.unreadCount ?? unreadResponse.count ?? 0);
|
||
setProfileForm({
|
||
shopName: shopResponse.shopName ?? "",
|
||
shopDescription: shopResponse.shopDescription ?? "",
|
||
shopLocation: shopResponse.shopLocation ?? "",
|
||
});
|
||
} catch (error) {
|
||
if (sequence !== loadSequence.current) return;
|
||
if (isHttpError(error, 401, 403)) {
|
||
router.replace("/company/login");
|
||
return;
|
||
}
|
||
toast({ title: "تعذر تحميل مساحة العمل", description: String(error), variant: "danger" });
|
||
setLoadError(String(error));
|
||
} finally {
|
||
if (sequence === loadSequence.current) {
|
||
setLoading(false);
|
||
setRefreshing(false);
|
||
}
|
||
}
|
||
}, [router, toast, listingPage, searchQuery, orderPage, orderStatus]);
|
||
|
||
useEffect(() => {
|
||
void load(true);
|
||
return () => { loadSequence.current += 1; };
|
||
}, [load]);
|
||
|
||
useEffect(() => {
|
||
const timer = window.setTimeout(() => {
|
||
setListingPage(1);
|
||
setSearchQuery(search.trim());
|
||
}, 250);
|
||
return () => window.clearTimeout(timer);
|
||
}, [search]);
|
||
|
||
const activeListings = listings.filter((item) => item.isActive).length;
|
||
const profileCompletion = [
|
||
shop?.shopName,
|
||
shop?.shopDescription,
|
||
shop?.shopLocation,
|
||
shop?.shopImageUrls?.length,
|
||
].filter(Boolean).length * 25;
|
||
|
||
const createListing = async (event: React.FormEvent) => {
|
||
event.preventDefault();
|
||
setSaving(true);
|
||
try {
|
||
await companyFetch("/marketplace/admin/listings", {
|
||
method: "POST",
|
||
body: JSON.stringify({
|
||
title: listingForm.title.trim(),
|
||
description: listingForm.description.trim(),
|
||
price: Number(listingForm.price),
|
||
quantity: Number(listingForm.quantity),
|
||
currency: "SAR",
|
||
instrumentType: listingForm.instrumentType.trim(),
|
||
listingCategory: "musical_instrument",
|
||
isActive: listingForm.isActive,
|
||
}),
|
||
});
|
||
toast({ title: "تم إنشاء المنتج", description: "أصبح المنتج ظاهرًا في مساحة الشركة.", variant: "success" });
|
||
setListingDrawer(false);
|
||
setListingForm({ title: "", description: "", price: "", quantity: "1", instrumentType: "", isActive: true });
|
||
await load(true);
|
||
} catch (error) {
|
||
toast({ title: "تعذر إنشاء المنتج", description: String(error), variant: "danger" });
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const updateProfile = async (event: React.FormEvent) => {
|
||
event.preventDefault();
|
||
setSaving(true);
|
||
try {
|
||
await companyFetch("/marketplace/admin/shop-profile", {
|
||
method: "PATCH",
|
||
body: JSON.stringify(profileForm),
|
||
});
|
||
toast({ title: "تم تحديث هوية الشركة", variant: "success" });
|
||
setProfileDrawer(false);
|
||
await load(true);
|
||
} catch (error) {
|
||
toast({ title: "تعذر تحديث الملف", description: String(error), variant: "danger" });
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const toggleListing = async (listing: Listing, nextValue: boolean) => {
|
||
setListings((current) =>
|
||
current.map((item) => item._id === listing._id ? { ...item, isActive: nextValue } : item),
|
||
);
|
||
try {
|
||
await companyFetch(`/marketplace/admin/listings/${listing._id}`, {
|
||
method: "PATCH",
|
||
body: JSON.stringify({ isActive: nextValue }),
|
||
});
|
||
toast({ title: nextValue ? "تم نشر المنتج" : "تم إيقاف المنتج", variant: "success" });
|
||
} catch (error) {
|
||
setListings((current) =>
|
||
current.map((item) => item._id === listing._id ? { ...item, isActive: !nextValue } : item),
|
||
);
|
||
toast({ title: "تعذر تحديث المنتج", description: String(error), variant: "danger" });
|
||
}
|
||
};
|
||
|
||
const updateOrderStatus = async (order: CompanyOrder, status: CompanyOrder["status"]) => {
|
||
setUpdatingOrderId(order._id);
|
||
try {
|
||
await companyFetch(`/orders/admin/${order._id}/status`, {
|
||
method: "PATCH",
|
||
body: JSON.stringify({ status }),
|
||
});
|
||
toast({ title: "تم تحديث الطلب", description: order.orderNumber, variant: "success" });
|
||
await load(true);
|
||
} catch (error) {
|
||
toast({ title: "تعذر تحديث الطلب", description: String(error), variant: "danger" });
|
||
} finally {
|
||
setUpdatingOrderId(null);
|
||
}
|
||
};
|
||
|
||
const filteredOrders = orders;
|
||
|
||
const orderLabels: Record<CompanyOrder["status"], string> = {
|
||
pending: "جديد",
|
||
confirmed: "مؤكد",
|
||
processing: "قيد التجهيز",
|
||
ready: "جاهز",
|
||
completed: "مكتمل",
|
||
cancelled: "ملغي",
|
||
};
|
||
|
||
const nextOrderStatus: Partial<Record<CompanyOrder["status"], CompanyOrder["status"]>> = {
|
||
pending: "confirmed",
|
||
confirmed: "processing",
|
||
processing: "ready",
|
||
ready: "completed",
|
||
};
|
||
|
||
if (!loading && loadError && !dashboard) {
|
||
return (
|
||
<main dir="rtl" className="grid min-h-screen place-items-center p-6">
|
||
<div role="alert" className="space-y-4 text-center">
|
||
<h1 className="text-xl font-bold">تعذر تحميل بيانات المتجر</h1>
|
||
<p className="max-w-xl break-words text-sm text-muted-foreground">{loadError}</p>
|
||
<Button onClick={() => void load()}>إعادة المحاولة</Button>
|
||
</div>
|
||
</main>
|
||
);
|
||
}
|
||
|
||
if (loading) {
|
||
return (
|
||
<main role="status" aria-live="polite" className="grid min-h-screen place-items-center bg-[#080c14] text-white">
|
||
<div className="text-center">
|
||
<LoaderCircle className="mx-auto h-9 w-9 animate-spin text-cyan-300" />
|
||
<p className="mt-4 text-sm text-white/55">جارٍ تجهيز مساحة الشركة...</p>
|
||
</div>
|
||
</main>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div className="min-h-screen bg-[#080c14] text-slate-100">
|
||
<a href="#company-main" className="skip-link">انتقل إلى المحتوى</a>
|
||
<div aria-hidden="true" className="fixed inset-0 bg-[radial-gradient(circle_at_85%_0%,rgba(34,211,238,.09),transparent_30%),radial-gradient(circle_at_10%_90%,rgba(139,92,246,.08),transparent_32%)]" />
|
||
<div className="relative mx-auto flex max-w-[1720px] gap-4 p-3 sm:p-4">
|
||
<aside className="sticky top-4 hidden h-[calc(100vh-2rem)] w-72 shrink-0 flex-col rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-4 backdrop-blur-2xl lg:flex" aria-label="تنقل لوحة الشركة">
|
||
<div className="flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] p-3">
|
||
<span className="grid h-11 w-11 place-items-center rounded-xl bg-gradient-to-br from-cyan-400 to-violet-500">
|
||
<Image src="/logo.png" alt="" width={38} height={38} />
|
||
</span>
|
||
<div className="min-w-0">
|
||
<p className="truncate font-black">{shop?.shopName || dashboard?.profile?.name || "Oudelaa Business"}</p>
|
||
<p className="text-[11px] text-white/40">مساحة الشركة</p>
|
||
</div>
|
||
</div>
|
||
<nav className="mt-6 flex-1 space-y-1" aria-label="أقسام لوحة الشركة">
|
||
{navItems.map((item, index) => (
|
||
<a key={item.href} href={item.href} className={cn("flex items-center gap-3 rounded-xl border px-3 py-3 text-sm transition", index === 0 ? "border-cyan-300/20 bg-cyan-300/10 text-cyan-200" : "border-transparent text-white/50 hover:border-white/10 hover:bg-white/[0.04] hover:text-white")}>
|
||
<item.icon aria-hidden="true" className="h-4 w-4" /> {item.label}
|
||
</a>
|
||
))}
|
||
</nav>
|
||
<div className="rounded-2xl border border-white/10 bg-white/[0.04] p-4">
|
||
<div className="flex items-center justify-between text-xs">
|
||
<span className="text-white/50">اكتمال الملف</span>
|
||
<span className="font-bold text-cyan-300">{profileCompletion}%</span>
|
||
</div>
|
||
<div className="mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||
<div className="h-full rounded-full bg-gradient-to-l from-cyan-300 to-violet-400" style={{ width: `${profileCompletion}%` }} />
|
||
</div>
|
||
<button onClick={() => setProfileDrawer(true)} className="mt-3 text-xs font-bold text-white/65 hover:text-white">أكمل ملف الشركة</button>
|
||
</div>
|
||
</aside>
|
||
|
||
<main id="company-main" tabIndex={-1} className="min-w-0 flex-1 outline-none">
|
||
<header className="sticky top-3 z-30 mb-4 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-[#0e1420]/85 p-2.5 shadow-2xl backdrop-blur-2xl">
|
||
<div className="flex min-w-0 items-center gap-3">
|
||
<Button variant="ghost" size="icon" aria-label="فتح قائمة التنقل" className="text-white lg:hidden" onClick={() => setMobileMenu(true)}>
|
||
<Menu className="h-5 w-5" />
|
||
</Button>
|
||
<div>
|
||
<div className="flex items-center gap-2 text-xs text-white/40">
|
||
<span>مساحة الشركة</span><ChevronLeft className="h-3 w-3" /><span className="text-white/75">الرئيسية</span>
|
||
</div>
|
||
<p className="mt-0.5 hidden text-[11px] text-white/35 sm:block">آخر تحديث: {new Intl.DateTimeFormat("ar-SA", { hour: "2-digit", minute: "2-digit" }).format(new Date())}</p>
|
||
</div>
|
||
</div>
|
||
<div className="flex items-center gap-1.5">
|
||
<ConnectionIndicator />
|
||
<Button variant="ghost" size="icon" className="text-white" aria-label="تحديث البيانات" aria-busy={refreshing} onClick={() => void load(true)}>
|
||
<RefreshCcw className={cn("h-4 w-4", refreshing && "animate-spin")} />
|
||
</Button>
|
||
<Button variant="ghost" size="icon" className="relative text-white" aria-label={`${unread} إشعارات غير مقروءة`}>
|
||
<Bell className="h-4 w-4" />
|
||
{unread > 0 ? <span aria-hidden="true" className="absolute left-2 top-2 h-2 w-2 rounded-full bg-cyan-300 ring-2 ring-[#0e1420]" /> : null}
|
||
</Button>
|
||
<div className="hidden h-8 w-px bg-white/10 sm:block" />
|
||
<div className="hidden items-center gap-2 px-2 sm:flex">
|
||
<span className="grid h-8 w-8 place-items-center rounded-lg bg-white/10 text-xs font-black">{(dashboard?.profile?.name ?? "ش").slice(0, 1)}</span>
|
||
<div className="max-w-28">
|
||
<p className="truncate text-xs font-bold">{dashboard?.profile?.name || "مدير الشركة"}</p>
|
||
<p className="text-[10px] text-white/35">Company Admin</p>
|
||
</div>
|
||
</div>
|
||
<Button variant="ghost" size="icon" className="text-white" aria-label="تسجيل الخروج" onClick={async () => {
|
||
await logoutCompany().catch(() => {});
|
||
router.replace("/company/login");
|
||
}}>
|
||
<LogOut className="h-4 w-4" />
|
||
</Button>
|
||
</div>
|
||
</header>
|
||
|
||
<section id="overview" className="relative overflow-hidden rounded-[2rem] border border-white/10 bg-gradient-to-l from-cyan-400/[0.12] via-white/[0.045] to-violet-500/[0.10] p-6 sm:p-8">
|
||
<Sparkles aria-hidden="true" className="absolute -left-8 -top-8 h-40 w-40 text-white/[0.025]" />
|
||
<div className="relative flex flex-col justify-between gap-7 xl:flex-row xl:items-end">
|
||
<div>
|
||
<span className="inline-flex items-center gap-2 rounded-full border border-cyan-300/20 bg-cyan-300/10 px-3 py-1.5 text-xs font-bold text-cyan-200">
|
||
<TrendingUp className="h-3.5 w-3.5" /> مركز الأداء المباشر
|
||
</span>
|
||
<h1 className="mt-5 text-3xl font-black leading-tight sm:text-4xl">
|
||
صباح الإنجاز، {shop?.shopName || dashboard?.profile?.name || "فريق الشركة"}
|
||
</h1>
|
||
<p className="mt-3 max-w-2xl text-sm leading-7 text-white/50">تابع أداء علامتك، أدر منتجاتك، وحوّل البيانات المتاحة إلى خطوات عملية واضحة.</p>
|
||
</div>
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button variant="outline" className="border-white/10 bg-white/[0.04] text-white" onClick={() => setProfileDrawer(true)}><PenLine className="h-4 w-4" /> تعديل الهوية</Button>
|
||
<Button className="bg-gradient-to-l from-cyan-400 to-violet-500 text-slate-950" onClick={() => setListingDrawer(true)}><PackagePlus className="h-4 w-4" /> منتج جديد</Button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section aria-label="مؤشرات الأداء" className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||
{[
|
||
{ label: "المنشورة في هذه الصفحة", value: activeListings, note: `من أصل ${listings.length}`, icon: Boxes, color: "text-cyan-300" },
|
||
{ label: "الإيرادات المكتملة", value: money(orderSummary?.revenue), note: `${orderSummary?.completedSales ?? 0} طلبات مكتملة`, icon: CircleDollarSign, color: "text-violet-300" },
|
||
{ label: "إجمالي المشاهدات", value: compactNumber(dashboard?.stats?.viewCount), note: `${dashboard?.stats?.engagementRate ?? 0}% تفاعل`, icon: Eye, color: "text-emerald-300" },
|
||
{ label: "طلبات تحتاج متابعة", value: compactNumber((orderSummary?.pending ?? 0) + (orderSummary?.confirmed ?? 0) + (orderSummary?.processing ?? 0)), note: `${orderSummary?.lowStock ?? 0} منتجات منخفضة المخزون`, icon: ReceiptText, color: "text-amber-300" },
|
||
].map((metric) => (
|
||
<article key={metric.label} className="group rounded-2xl border border-white/10 bg-white/[0.045] p-5 transition hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.065]">
|
||
<div className="flex items-start justify-between">
|
||
<div><p className="text-xs text-white/45">{metric.label}</p><p className="mt-3 text-2xl font-black">{metric.value}</p></div>
|
||
<span className="grid h-10 w-10 place-items-center rounded-xl bg-white/[0.055]"><metric.icon className={cn("h-5 w-5", metric.color)} /></span>
|
||
</div>
|
||
<p className="mt-4 text-xs text-white/35">{metric.note}</p>
|
||
</article>
|
||
))}
|
||
</section>
|
||
|
||
<div className="mt-4 grid gap-4 xl:grid-cols-[1.55fr_0.85fr]">
|
||
<section id="products" className="rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-4 sm:p-6">
|
||
<div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
|
||
<div><h2 className="text-lg font-black">كتالوج الشركة</h2><p className="mt-1 text-xs text-white/40">إدارة حالة النشر والمخزون والأسعار.</p></div>
|
||
<div className="flex gap-2">
|
||
<div className="relative">
|
||
<Search className="pointer-events-none absolute right-3 top-3 h-4 w-4 text-white/35" />
|
||
<Input aria-label="البحث في المنتجات" value={search} onChange={(event) => setSearch(event.target.value)} placeholder="ابحث..." className="w-40 border-white/10 bg-white/[0.04] pr-9 text-white sm:w-52" />
|
||
</div>
|
||
<Button size="icon" aria-label="إضافة منتج" className="bg-cyan-300 text-slate-950" onClick={() => setListingDrawer(true)}><PackagePlus className="h-4 w-4" /></Button>
|
||
</div>
|
||
</div>
|
||
<div className="mt-5 space-y-2">
|
||
{listings.length ? listings.map((listing) => (
|
||
<article key={listing._id} className="flex items-center gap-3 rounded-2xl border border-white/[0.08] bg-black/10 p-3 transition hover:border-white/15 hover:bg-white/[0.035]">
|
||
<div className="grid h-14 w-14 shrink-0 place-items-center overflow-hidden rounded-xl bg-gradient-to-br from-cyan-300/15 to-violet-400/15">
|
||
{listing.imageUrls?.[0] ? <Image src={listing.imageUrls[0]} alt={listing.title} width={56} height={56} unoptimized className="h-full w-full object-cover" /> : <ShoppingBag className="h-5 w-5 text-white/35" />}
|
||
</div>
|
||
<div className="min-w-0 flex-1">
|
||
<div className="flex items-center gap-2">
|
||
<p className="truncate text-sm font-bold">{listing.title}</p>
|
||
<span className={cn("rounded-full px-2 py-0.5 text-[10px] font-bold", listing.isActive ? "bg-emerald-400/10 text-emerald-300" : "bg-white/[0.06] text-white/40")}>{listing.isActive ? "منشور" : "متوقف"}</span>
|
||
</div>
|
||
<p className="mt-1 truncate text-xs text-white/35">{listing.instrumentType || listing.listingCategory || "منتج"} · المخزون {listing.quantity ?? 0}</p>
|
||
</div>
|
||
<p className="hidden text-sm font-black text-cyan-200 sm:block">{money(listing.price, listing.currency)}</p>
|
||
<Switch aria-label={`${listing.isActive ? "إيقاف" : "نشر"} ${listing.title}`} checked={Boolean(listing.isActive)} onCheckedChange={(value) => void toggleListing(listing, value)} />
|
||
</article>
|
||
)) : (
|
||
<div className="rounded-2xl border border-dashed border-white/10 py-12 text-center">
|
||
<ShoppingBag className="mx-auto h-7 w-7 text-white/25" />
|
||
<p className="mt-3 text-sm font-bold">لا توجد منتجات مطابقة</p>
|
||
<p className="mt-1 text-xs text-white/35">أضف منتجًا أو غيّر عبارة البحث.</p>
|
||
</div>
|
||
)}
|
||
</div>
|
||
{listingPages > 1 ? <nav aria-label="صفحات المنتجات" className="mt-4 flex items-center justify-between gap-3 text-xs">
|
||
<Button variant="outline" size="sm" disabled={refreshing || listingPage <= 1} onClick={() => setListingPage((page) => page - 1)}>السابق</Button>
|
||
<span>{listingPage} / {listingPages}</span>
|
||
<Button variant="outline" size="sm" disabled={refreshing || listingPage >= listingPages} onClick={() => setListingPage((page) => page + 1)}>التالي</Button>
|
||
</nav> : null}
|
||
</section>
|
||
|
||
<div className="space-y-4">
|
||
<section id="store" className="overflow-hidden rounded-[1.75rem] border border-white/10 bg-white/[0.045]">
|
||
<div className="relative h-28 bg-gradient-to-l from-cyan-400/25 to-violet-500/25">
|
||
{shop?.shopImageUrls?.[0] ? <Image src={shop.shopImageUrls[0]} alt={shop.shopName ?? ""} fill unoptimized className="object-cover opacity-70" /> : null}
|
||
</div>
|
||
<div className="p-5">
|
||
<div className="-mt-12 mb-4 grid h-16 w-16 place-items-center rounded-2xl border-4 border-[#101621] bg-gradient-to-br from-cyan-400 to-violet-500">
|
||
<Store className="h-7 w-7 text-slate-950" />
|
||
</div>
|
||
<div className="flex items-start justify-between gap-3">
|
||
<div><h2 className="font-black">{shop?.shopName || "اسم الشركة غير مكتمل"}</h2><p className="mt-1 line-clamp-2 text-xs leading-5 text-white/40">{shop?.shopDescription || "أضف وصفًا موجزًا يوضح نشاط الشركة وقيمتها للعملاء."}</p></div>
|
||
{dashboard?.profile?.isVerified ? <CheckCircle2 aria-label="حساب موثق" className="h-5 w-5 shrink-0 text-cyan-300" /> : null}
|
||
</div>
|
||
<div className="mt-4 flex items-center gap-2 text-xs text-white/45"><MapPin className="h-3.5 w-3.5" /> {shop?.shopLocation || "الموقع غير محدد"}</div>
|
||
<Button variant="outline" className="mt-5 w-full border-white/10 bg-white/[0.03] text-white" onClick={() => setProfileDrawer(true)}>تعديل الملف التجاري</Button>
|
||
</div>
|
||
</section>
|
||
|
||
<section className="rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-5">
|
||
<div className="flex items-center justify-between"><div><h2 className="font-black">فروع الصيانة</h2><p className="mt-1 text-xs text-white/35">{repairShops.length} فروع مرتبطة</p></div><Wrench className="h-5 w-5 text-violet-300" /></div>
|
||
<div className="mt-4 space-y-2">
|
||
{repairShops.slice(0, 3).map((repair) => (
|
||
<div key={repair._id} className="rounded-xl border border-white/[0.07] bg-black/10 p-3">
|
||
<div className="flex items-center justify-between"><p className="text-sm font-bold">{repair.name}</p><span className={cn("h-2 w-2 rounded-full", repair.isActive ? "bg-emerald-300" : "bg-white/25")} /></div>
|
||
<p className="mt-1 text-xs text-white/35">{repair.location || "دون موقع"} · {repair.services?.length ?? 0} خدمات</p>
|
||
</div>
|
||
))}
|
||
{!repairShops.length ? <p className="rounded-xl border border-dashed border-white/10 p-4 text-center text-xs text-white/35">لا توجد فروع صيانة بعد.</p> : null}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
</div>
|
||
|
||
<section id="orders" className="mt-4 rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-4 sm:p-6">
|
||
<div className="flex flex-col justify-between gap-4 lg:flex-row lg:items-center">
|
||
<div>
|
||
<div className="flex items-center gap-2">
|
||
<ReceiptText className="h-5 w-5 text-cyan-300" />
|
||
<h2 className="text-lg font-black">الطلبات والمبيعات</h2>
|
||
</div>
|
||
<p className="mt-1 text-xs text-white/40">تابع الطلب من الاستلام حتى الإكمال مع مزامنة المخزون تلقائيًا.</p>
|
||
</div>
|
||
<label className="flex items-center gap-2 text-xs text-white/45">
|
||
حالة الطلب
|
||
<select
|
||
value={orderStatus}
|
||
onChange={(event) => { setOrderStatus(event.target.value); setOrderPage(1); }}
|
||
className="h-10 rounded-xl border border-white/10 bg-[#111824] px-3 text-sm text-white outline-none focus:ring-2 focus:ring-cyan-300"
|
||
>
|
||
<option value="all">كل الحالات</option>
|
||
{Object.entries(orderLabels).map(([value, label]) => (
|
||
<option key={value} value={value}>{label}</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
</div>
|
||
|
||
<div className="mt-5 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
|
||
{[
|
||
{ label: "إجمالي الطلبات", value: orderSummary?.total ?? 0, icon: ReceiptText, color: "text-cyan-300" },
|
||
{ label: "طلبات جديدة", value: orderSummary?.pending ?? 0, icon: Activity, color: "text-amber-300" },
|
||
{ label: "مبيعات مكتملة", value: orderSummary?.completedSales ?? 0, icon: CheckCircle2, color: "text-emerald-300" },
|
||
{ label: "مخزون منخفض", value: orderSummary?.lowStock ?? 0, icon: AlertTriangle, color: "text-rose-300" },
|
||
].map((item) => (
|
||
<div key={item.label} className="flex items-center justify-between rounded-2xl border border-white/[0.07] bg-black/10 p-4">
|
||
<div><p className="text-[11px] text-white/40">{item.label}</p><p className="mt-2 text-xl font-black">{item.value}</p></div>
|
||
<item.icon className={cn("h-5 w-5", item.color)} />
|
||
</div>
|
||
))}
|
||
</div>
|
||
|
||
<div className="mt-5 space-y-2">
|
||
{filteredOrders.length ? filteredOrders.map((order) => {
|
||
const nextStatus = nextOrderStatus[order.status];
|
||
const terminal = order.status === "completed" || order.status === "cancelled";
|
||
return (
|
||
<article key={order._id} className="grid gap-3 rounded-2xl border border-white/[0.07] bg-black/10 p-4 lg:grid-cols-[1fr_0.8fr_0.7fr_auto] lg:items-center">
|
||
<div className="min-w-0">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<p className="font-bold">{order.items && order.items.length > 1 ? `${order.items.length} منتجات` : order.itemTitle}</p>
|
||
<span className="rounded-full bg-white/[0.06] px-2 py-1 text-[10px] font-bold text-white/55">{orderLabels[order.status]}</span>
|
||
</div>
|
||
<p className="mt-1 text-xs text-white/35">{order.orderNumber} · الكمية {order.quantity}</p>
|
||
{order.items?.length ? (
|
||
<ul className="mt-2 space-y-1 text-xs text-white/60">
|
||
{order.items.map((item) => <li key={item.listingId}>{item.title} × {item.quantity} — {money(item.total, order.currency)}</li>)}
|
||
</ul>
|
||
) : null}
|
||
<p className="mt-2 text-xs text-white/50">{order.fulfillmentMethod === "delivery" ? `توصيل: ${order.city ?? ""} ${order.address ?? ""}` : "استلام من المتجر"}</p>
|
||
{order.note ? <p className="mt-1 text-xs text-white/50">{order.note}</p> : null}
|
||
</div>
|
||
<div>
|
||
<p className="text-sm font-bold">{order.customerName}</p>
|
||
<p dir="ltr" className="mt-1 text-right text-xs text-white/35">{order.customerPhone}</p>
|
||
</div>
|
||
<div>
|
||
<p className="font-black text-cyan-200">{money(order.total, order.currency)}</p>
|
||
<p className="mt-1 text-[10px] text-white/30">{order.createdAt ? new Intl.DateTimeFormat("ar-SA", { dateStyle: "medium" }).format(new Date(order.createdAt)) : "-"}</p>
|
||
</div>
|
||
<div className="flex flex-wrap gap-2 lg:justify-end">
|
||
{nextStatus ? (
|
||
<Button size="sm" disabled={updatingOrderId === order._id} onClick={() => void updateOrderStatus(order, nextStatus)}>
|
||
{updatingOrderId === order._id ? <LoaderCircle className="h-3.5 w-3.5 animate-spin" /> : null}
|
||
{orderLabels[nextStatus]}
|
||
</Button>
|
||
) : null}
|
||
{!terminal ? (
|
||
<Button size="sm" variant="danger" disabled={updatingOrderId === order._id} onClick={() => void updateOrderStatus(order, "cancelled")}>إلغاء</Button>
|
||
) : null}
|
||
</div>
|
||
</article>
|
||
);
|
||
}) : (
|
||
<div className="rounded-2xl border border-dashed border-white/10 py-12 text-center">
|
||
<ReceiptText className="mx-auto h-7 w-7 text-white/25" />
|
||
<p className="mt-3 text-sm font-bold">لا توجد طلبات حتى الآن</p>
|
||
<p className="mt-1 text-xs text-white/35">ستظهر الطلبات هنا فور شرائها من السوق.</p>
|
||
</div>
|
||
)}
|
||
</div>
|
||
{orderPages > 1 ? <nav aria-label="صفحات الطلبات" className="mt-4 flex items-center justify-between gap-3 text-xs">
|
||
<Button variant="outline" size="sm" disabled={refreshing || orderPage <= 1} onClick={() => setOrderPage((page) => page - 1)}>السابق</Button>
|
||
<span>{orderPage} / {orderPages}</span>
|
||
<Button variant="outline" size="sm" disabled={refreshing || orderPage >= orderPages} onClick={() => setOrderPage((page) => page + 1)}>التالي</Button>
|
||
</nav> : null}
|
||
</section>
|
||
|
||
<div className="mt-4 grid gap-4 xl:grid-cols-2">
|
||
<section id="audience" className="rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-5 sm:p-6">
|
||
<div className="flex items-center justify-between"><div><h2 className="text-lg font-black">نبض الجمهور</h2><p className="mt-1 text-xs text-white/40">ملخص نمو المجتمع حول علامتك.</p></div><UsersRound className="h-5 w-5 text-cyan-300" /></div>
|
||
<div className="mt-6 grid grid-cols-3 gap-2">
|
||
{[
|
||
["المتابعون", dashboard?.audience?.followers],
|
||
["جدد هذا الأسبوع", dashboard?.audience?.newFollowersThisWeek],
|
||
["جدد هذا الشهر", dashboard?.audience?.newFollowersThisMonth],
|
||
].map(([label, value]) => (
|
||
<div key={String(label)} className="rounded-2xl border border-white/[0.07] bg-black/10 p-4 text-center"><p className="text-xl font-black">{compactNumber(Number(value))}</p><p className="mt-1 text-[11px] text-white/35">{label}</p></div>
|
||
))}
|
||
</div>
|
||
<div className="mt-5 space-y-3">
|
||
{[
|
||
{ label: "الإعجابات", value: dashboard?.stats?.likesCount, icon: Heart, color: "bg-rose-400" },
|
||
{ label: "التعليقات", value: dashboard?.stats?.commentsCount, icon: MessageCircle, color: "bg-violet-400" },
|
||
{ label: "المشاركات", value: dashboard?.stats?.sharesCount, icon: ArrowLeft, color: "bg-cyan-400" },
|
||
].map((row) => {
|
||
const total = Math.max(1, (dashboard?.stats?.likesCount ?? 0) + (dashboard?.stats?.commentsCount ?? 0) + (dashboard?.stats?.sharesCount ?? 0));
|
||
const width = Math.max(4, ((row.value ?? 0) / total) * 100);
|
||
return <div key={row.label}><div className="mb-1.5 flex justify-between text-xs"><span className="flex items-center gap-2 text-white/55"><row.icon className="h-3.5 w-3.5" />{row.label}</span><span className="font-bold">{compactNumber(row.value)}</span></div><div className="h-1.5 overflow-hidden rounded-full bg-white/[0.06]"><div className={cn("h-full rounded-full", row.color)} style={{ width: `${width}%` }} /></div></div>;
|
||
})}
|
||
</div>
|
||
</section>
|
||
|
||
<section id="content" className="rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-5 sm:p-6">
|
||
<div className="flex items-center justify-between"><div><h2 className="text-lg font-black">أفضل المحتوى</h2><p className="mt-1 text-xs text-white/40">المحتوى الأعلى أداءً حسب التفاعل.</p></div><BarChart3 className="h-5 w-5 text-violet-300" /></div>
|
||
<div className="mt-5 space-y-2">
|
||
{dashboard?.topContent?.slice(0, 4).map((content, index) => (
|
||
<article key={content._id} className="flex items-center gap-3 rounded-2xl border border-white/[0.07] bg-black/10 p-3">
|
||
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-white/[0.06] text-sm font-black text-cyan-300">#{index + 1}</span>
|
||
<div className="min-w-0 flex-1"><p className="truncate text-sm font-bold">{content.content || content.postType || "محتوى"}</p><p className="mt-1 text-[11px] text-white/35">{compactNumber(content.viewCount)} مشاهدة · {compactNumber(content.likesCount)} إعجاب</p></div>
|
||
<span className="text-xs font-bold text-violet-300">{compactNumber(content.engagementScore)}</span>
|
||
</article>
|
||
))}
|
||
{!dashboard?.topContent?.length ? <p className="rounded-xl border border-dashed border-white/10 p-8 text-center text-xs text-white/35">ستظهر نتائج المحتوى هنا عند توفرها.</p> : null}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
|
||
<section id="activity" className="my-4 rounded-[1.75rem] border border-white/10 bg-white/[0.045] p-5 sm:p-6">
|
||
<div className="flex items-center justify-between"><div><h2 className="text-lg font-black">آخر النشاطات</h2><p className="mt-1 text-xs text-white/40">أحدث التفاعلات والإشعارات المرتبطة بالحساب.</p></div><Activity className="h-5 w-5 text-emerald-300" /></div>
|
||
<div className="mt-5 grid gap-2 md:grid-cols-2">
|
||
{dashboard?.recentActivity?.slice(0, 6).map((activity) => (
|
||
<article key={activity._id} className="flex gap-3 rounded-2xl border border-white/[0.07] bg-black/10 p-4">
|
||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-emerald-300/10 text-emerald-300"><Activity className="h-4 w-4" /></span>
|
||
<div className="min-w-0"><p className="truncate text-sm font-bold">{activity.title || activity.type || "نشاط جديد"}</p><p className="mt-1 line-clamp-1 text-xs text-white/35">{activity.previewText || "تم تسجيل نشاط جديد في حساب الشركة."}</p></div>
|
||
</article>
|
||
))}
|
||
{!dashboard?.recentActivity?.length ? <p className="col-span-full rounded-xl border border-dashed border-white/10 p-8 text-center text-xs text-white/35">لا توجد نشاطات حديثة.</p> : null}
|
||
</div>
|
||
</section>
|
||
</main>
|
||
</div>
|
||
|
||
<Drawer open={mobileMenu} onClose={() => setMobileMenu(false)} title="مساحة الشركة" description={shop?.shopName || "Oudelaa Business"} side="right">
|
||
<nav className="space-y-2" aria-label="تنقل الشركة للجوال">
|
||
{navItems.map((item) => <a key={item.href} href={item.href} onClick={() => setMobileMenu(false)} className="flex items-center gap-3 rounded-xl border border-border px-3 py-3 text-sm"><item.icon className="h-4 w-4" />{item.label}</a>)}
|
||
</nav>
|
||
</Drawer>
|
||
|
||
<Drawer open={listingDrawer} onClose={() => setListingDrawer(false)} title="إضافة منتج جديد" description="أدخل البيانات الأساسية ويمكن إضافة الصور لاحقًا." side="left">
|
||
<form className="space-y-4" onSubmit={createListing}>
|
||
<div className="space-y-2"><label htmlFor="listing-title" className="text-sm font-bold">اسم المنتج</label><Input id="listing-title" required maxLength={120} value={listingForm.title} onChange={(event) => setListingForm((form) => ({ ...form, title: event.target.value }))} /></div>
|
||
<div className="space-y-2"><label htmlFor="listing-type" className="text-sm font-bold">نوع الآلة</label><Input id="listing-type" maxLength={80} placeholder="عود، كمان، جيتار..." value={listingForm.instrumentType} onChange={(event) => setListingForm((form) => ({ ...form, instrumentType: event.target.value }))} /></div>
|
||
<div className="grid grid-cols-2 gap-3">
|
||
<div className="space-y-2"><label htmlFor="listing-price" className="text-sm font-bold">السعر</label><Input id="listing-price" dir="ltr" type="number" required min="0" step="0.01" value={listingForm.price} onChange={(event) => setListingForm((form) => ({ ...form, price: event.target.value }))} /></div>
|
||
<div className="space-y-2"><label htmlFor="listing-quantity" className="text-sm font-bold">الكمية</label><Input id="listing-quantity" dir="ltr" type="number" required min="0" value={listingForm.quantity} onChange={(event) => setListingForm((form) => ({ ...form, quantity: event.target.value }))} /></div>
|
||
</div>
|
||
<div className="space-y-2"><label htmlFor="listing-description" className="text-sm font-bold">الوصف</label><Textarea id="listing-description" maxLength={2000} value={listingForm.description} onChange={(event) => setListingForm((form) => ({ ...form, description: event.target.value }))} /></div>
|
||
<div className="flex items-center justify-between rounded-xl border border-border p-3"><label htmlFor="listing-active" className="text-sm font-bold">نشر المنتج مباشرة</label><Switch id="listing-active" aria-label="نشر المنتج مباشرة" checked={listingForm.isActive} onCheckedChange={(value) => setListingForm((form) => ({ ...form, isActive: value }))} /></div>
|
||
<Button type="submit" disabled={saving} className="w-full">{saving ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <PackagePlus className="h-4 w-4" />} حفظ المنتج</Button>
|
||
</form>
|
||
</Drawer>
|
||
|
||
<Drawer open={profileDrawer} onClose={() => setProfileDrawer(false)} title="هوية الشركة" description="تظهر هذه المعلومات للعملاء في ملف المتجر." side="left">
|
||
<form className="space-y-4" onSubmit={updateProfile}>
|
||
<div className="space-y-2"><label htmlFor="shop-name" className="text-sm font-bold">اسم الشركة</label><Input id="shop-name" maxLength={120} value={profileForm.shopName} onChange={(event) => setProfileForm((form) => ({ ...form, shopName: event.target.value }))} /></div>
|
||
<div className="space-y-2"><label htmlFor="shop-location" className="text-sm font-bold">الموقع</label><Input id="shop-location" maxLength={160} placeholder="الرياض، المملكة العربية السعودية" value={profileForm.shopLocation} onChange={(event) => setProfileForm((form) => ({ ...form, shopLocation: event.target.value }))} /></div>
|
||
<div className="space-y-2"><label htmlFor="shop-description" className="text-sm font-bold">نبذة عن الشركة</label><Textarea id="shop-description" maxLength={2000} value={profileForm.shopDescription} onChange={(event) => setProfileForm((form) => ({ ...form, shopDescription: event.target.value }))} /></div>
|
||
<Button type="submit" disabled={saving} className="w-full">{saving ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <PenLine className="h-4 w-4" />} حفظ التغييرات</Button>
|
||
</form>
|
||
</Drawer>
|
||
</div>
|
||
);
|
||
}
|