dynomic orders first commit

This commit is contained in:
Mohammadali 2026-09-07 09:30:09 +03:30
parent 464f2b34a2
commit 4e3eb2de9f
6 changed files with 234 additions and 156 deletions

29
package-lock.json generated
View file

@ -292,9 +292,9 @@
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",
"dev": true,
"license": "MIT",
"optional": true,
@ -2996,6 +2996,18 @@
"node": ">=14.0.0"
}
},
"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.1",
"tslib": "^2.4.0"
}
},
"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
@ -3007,6 +3019,17 @@
"tslib": "^2.4.0"
}
},
"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@unrs/resolver-binding-win32-arm64-msvc": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz",

View file

@ -1,76 +1,43 @@
import Link from "next/link";
import { requireSession } from "@/lib/auth/session";
import { getOrderGroups } from "@/lib/api/orders";
import { PAYMENT_STATUS_LABELS_FA } from "@/lib/order-status";
"use client";
import { useOrders } from "@/lib/providers/orders-provider";
import OrderItem from "@/components/orders/order-item";
import OrderEmpty from "@/components/orders/order-empty";
import OrderServerError from "@/components/orders/order-server-error";
import OrdersSkeleton from "@/components/orders/orders-skeleton";
import OrderHeader from "@/components/orders/order-header";
export default async function OrdersPage() {
return <section>
{/* <OrderEmpty /> */}
{/* <OrderServerError /> */}
{
Array.from({ length: 20 }, (_, index) => <OrderItem />)
}
{/* <OrderEmpty />
<OrderServerError />
<OrdersSkeleton /> */}
export default function OrdersPage() {
const { data, error, isLoading } = useOrders();
{/* <OrdersSkeleton /> */}
{/* <OrderServerError /> */}
{/* <OrderEmpty /> */}
{/* */}
{/* <OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem />
<OrderItem /> */}
if (isLoading) {
return (
<section className="p-4">
<OrdersSkeleton />
</section>
// await requireSession("/orders");
// const orderGroups = await getOrderGroups();
);
}
// return (
// <main className="mx-auto flex w-full max-w-2xl flex-1 flex-col gap-4 px-4 py-6">
// <h1 className="text-lg font-bold">سفارش‌های من</h1>
if (error) {
return (
<section className="p-4">
<OrderServerError />
</section>
);
}
// {orderGroups.length === 0 && <p className="text-sm text-muted-foreground">هنوز سفارشی ثبت نکرده‌اید.</p>}
if (!data || data.length === 0) {
return (
<section className="p-4">
<OrderEmpty />
</section>
);
}
// <div className="flex flex-col gap-3">
// {orderGroups.map((group) => (
// <Link
// key={group.uuid}
// href={`/order-groups/${group.uuid}`}
// className="flex flex-col gap-2 rounded-2xl border border-border p-4"
// >
// <div className="flex justify-between text-sm text-muted-foreground">
// <span>{new Date(group.created_at).toLocaleDateString("fa-IR")}</span>
// <span>{PAYMENT_STATUS_LABELS_FA[group.payment_status]}</span>
// </div>
// <div className="flex flex-wrap gap-1 text-sm">
// {group.orders.map((order) => (
// <span key={order.uuid} className="rounded-full bg-muted px-2 py-0.5">
// {order.store.name}
// </span>
// ))}
// </div>
// <div className="flex justify-between font-semibold">
// <span>مجموع</span>
// <span>{group.total_amount.toLocaleString("fa-IR")} تومان</span>
// </div>
// </Link>
// ))}
// </div>
// </main>
// );
return (
<section className="p-4 space-y-3">
{data.map((group) => (
<OrderItem key={group.uuid} orderGroup={group} />
))}
</section>
);
}

View file

@ -1,15 +1,30 @@
import OrderHeader from '@/components/orders/order-header';
import React from 'react'
import { requireSession } from "@/lib/auth/session";
import { getOrderGroups } from "@/lib/api/orders";
import { OrdersProvider } from "@/lib/providers/orders-provider";
interface OrderLayoutInterface {
children: React.ReactNode;
}
const OrderLayout = async ({ children }: OrderLayoutInterface) => {
return <main className='max-w-5xl w-full mx-auto p-0'>
export default async function OrderLayout({ children }: OrderLayoutInterface) {
await requireSession("/login");
let orderGroups: Awaited<ReturnType<typeof getOrderGroups>> | null = null;
let error: string | null = null;
try {
orderGroups = await getOrderGroups();
} catch (e: any) {
error = e?.message ?? "خطا در دریافت سفارش‌ها";
}
return (
<main className="max-w-5xl w-full mx-auto p-0">
<OrdersProvider orderGroups={orderGroups} error={error}>
<OrderHeader />
{children}
</OrdersProvider>
</main>
);
}
export default OrderLayout

View file

@ -1,90 +1,121 @@
'use client';
import { useRouter } from 'next/navigation';
import React from 'react';
import type { OrderGroup } from "@/types/api";
import { PAYMENT_STATUS_LABELS_FA } from "@/lib/order-status"; // اگه داری
const OrderItem = () => {
interface OrderItemProps {
orderGroup: OrderGroup;
}
const OrderItem = ({ orderGroup }: OrderItemProps) => {
const router = useRouter();
const goToOrderDetail = () => router.push(`/orders/uuid`);
const statusClasses: Record<string, string> = {
'ارسال شد': 'bg-teal-bg text-primary-action',
'در حال آماده‌سازی': 'bg-[#E5F3FF] text-[#007BFF]',
'در انتظار تأیید': 'bg-[#FFF4E5] text-[#E67E22]',
'آماده تحویل حضوری': 'bg-[#EBE5FF] text-[#734DBF]',
'لغو شد': 'bg-[#FCE8E8] text-error',
'تحویل داده شد': 'bg-emerald-bg text-success',
const goToOrderDetail = () => {
router.push(`/orders/${orderGroup.uuid}`); // یا مسیر واقعی جزئیات
};
const order = {
id: 1,
restaurant: 'فست‌فود برگر',
description: 'ساندویچ + نوشیدنی',
status: 'آماده تحویل حضوری',
time: 'امروز، 11:30',
itemsCount: 3,
totalPrice: 45000,
images: Array.from({ length: 5 }, (_, i) => ({
id: i,
src: `https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqIof_DOo6I5-oOLJ1V9_HPfSudXfhewy_5C5Ry7YOO-UXSZ1jvK7-0hw&s=10`,
alt: `product-${i}`,
})),
// وضعیت کلی (از اولین سفارش یا payment_status)
const mainOrder = orderGroup.orders[0];
const status = mainOrder?.status ?? "placed";
// مپ وضعیت به فارسی و کلاس
const statusMap: Record<string, { label: string; className: string }> = {
placed: { label: "ثبت شده", className: "bg-[#FFF4E5] text-[#E67E22]" },
preparing: { label: "در حال آماده‌سازی", className: "bg-[#E5F3FF] text-[#007BFF]" },
ready_to_ship: { label: "آماده ارسال", className: "bg-[#EBE5FF] text-[#734DBF]" },
handed_to_courier: { label: "ارسال شد", className: "bg-teal-bg text-primary-action" },
delivered: { label: "تحویل داده شد", className: "bg-emerald-bg text-success" },
cancelled: { label: "لغو شد", className: "bg-[#FCE8E8] text-error" },
};
const currentStatus = statusMap[status] ?? { label: status, className: "bg-gray-100 text-gray-700" };
// نام فروشگاه‌ها
const storeNames = orderGroup.orders.map(o => o.store.name).join(" + ");
// تعداد کل کالاها
const totalItems = orderGroup.orders.reduce((sum, order) => {
return sum + order.items.reduce((s, item) => s + item.quantity, 0);
}, 0);
// تصاویر محصولات (حداکثر ۵ تا)
const images = orderGroup.orders
.flatMap(order => order.items)
.slice(0, 5)
.map((item, index) => ({
id: index,
src: "", // اگر تصویر محصول داری اینجا بذار، فعلاً خالی
alt: item.product_name_snapshot,
}));
// تاریخ و ساعت
const createdDate = new Date(orderGroup.created_at);
const timeText = createdDate.toLocaleDateString("fa-IR", {
weekday: "long",
hour: "2-digit",
minute: "2-digit",
});
return (
<div className="w-full rounded-2xl min-h-32 border border-gray-300 bg-background p-4 mb-2">
{/* هدر */}
<div className="flex items-center justify-between w-full gap-3">
<div className="flex items-center gap-4">
<div className="size-12 rounded-full bg-gradient-to-br from-primary-action to-primary flex items-center justify-center text-primary-foreground font-bold text-lg">
{order.restaurant.charAt(0)}
<div className="size-12 rounded-full bg-gradient-to-br from-primary-action to-primary flex items-center justify-center text-primary-foreground font-bold text-lg overflow-hidden">
{mainOrder?.store.logo_url ? (
<img src={mainOrder.store.logo_url} alt={mainOrder.store.name} className="w-full h-full object-cover" />
) : (
mainOrder?.store.name?.charAt(0) ?? "س"
)}
</div>
<div className="flex flex-col items-start">
<h2 className="text-md font-bold text-gray-800">{order.restaurant}</h2>
<p className="text-sm text-gray-600">{order.description}</p>
<h2 className="text-md font-bold text-gray-800 line-clamp-1">{storeNames}</h2>
<p className="text-sm text-gray-600 line-clamp-1">
{orderGroup.orders.length > 1
? `${orderGroup.orders.length} فروشگاه`
: mainOrder?.items[0]?.product_name_snapshot ?? "سفارش"}
</p>
</div>
</div>
<span
className={`flex items-center justify-center px-3 py-1 rounded-full text-xs font-bold ${statusClasses[order.status]
}`}
>
{order.status}
<span className={`flex items-center justify-center px-3 py-1 rounded-full text-xs font-bold ${currentStatus.className}`}>
{currentStatus.label}
</span>
</div>
<div className="w-full h-px bg-gray-200 my-4" />
{/* پایین کارت */}
<div className="grid grid-cols-3 gap-3 w-full">
<div className="col-span-2 flex items-center gap-1 overflow-x-auto pb-2 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
{order.images.map((img) => (
<div
key={img.id}
className="size-10 flex-shrink-0 rounded-lg bg-gray-200 overflow-hidden"
>
<img
src={img.src}
alt={img.alt}
className="w-full h-full object-cover"
/>
<div className="col-span-2 flex items-center gap-1 overflow-x-auto pb-2">
{images.length > 0 ? (
images.map((img) => (
<div key={img.id} className="size-10 flex-shrink-0 rounded-lg bg-gray-200 overflow-hidden">
{img.src ? (
<img src={img.src} alt={img.alt} className="w-full h-full object-cover" />
) : (
<div className="w-full h-full flex items-center justify-center text-xs text-gray-400">
{img.alt.charAt(0)}
</div>
))}
)}
</div>
))
) : (
<div className="text-sm text-gray-500">بدون تصویر</div>
)}
</div>
<div className="col-span-1 flex flex-col items-end gap-1">
<div className="flex items-center gap-1 text-xs text-gray-600">
<span>{order.time}</span>
</div>
<div className="flex items-center gap-1 text-primary-action text-sm text-left font-bold">
<span>
{order.itemsCount} کالا • {order.totalPrice.toLocaleString('fa-IR')} تومان
</span>
<div className="text-xs text-gray-600">{timeText}</div>
<div className="text-primary-action text-sm font-bold text-left">
{totalItems} کالا • {orderGroup.total_amount.toLocaleString("fa-IR")} تومان
</div>
</div>
</div>
<button
className="w-full mt-8 rounded-xl h-12 bg-primary-action text-primary-foreground cursor-pointer hover:bg-primary-action/90 transition-colors font-medium"
className="w-full mt-6 rounded-xl h-12 bg-primary-action text-primary-foreground cursor-pointer hover:bg-primary-action/90 transition-colors font-medium"
onClick={goToOrderDetail}
>
مشاهده وضعیت

View file

@ -1,7 +1,7 @@
import "server-only";
import { getValidSession } from "@/lib/auth/session";
import { ApiError, type WinofyErrorDetails } from "./errors";
import { logWinofyRequest, logWinofyResponse } from "./dev-logger";
// import { logWinofyRequest, logWinofyResponse } from "./dev-logger";
const BASE_URL = process.env.GOOYAL_ACCOUNTS_BASE_URL!;
@ -35,7 +35,7 @@ export async function gooyalFetch<T>(path: string, options: GooyalFetchOptions =
}
}
logWinofyRequest?.(method, url.toString(), body);
// logWinofyRequest?.(method, url.toString(), body);
const res = await fetch(url.toString(), {
...rest,
@ -45,12 +45,12 @@ export async function gooyalFetch<T>(path: string, options: GooyalFetchOptions =
});
if (res.status === 204) {
logWinofyResponse?.(method, url.toString(), res.status, null);
// logWinofyResponse?.(method, url.toString(), res.status, null);
return undefined as T;
}
const data = await res.json().catch(() => null);
logWinofyResponse?.(method, url.toString(), res.status, data);
// logWinofyResponse?.(method, url.toString(), res.status, data);
if (!res.ok) {
const envelope = data as { status_message?: string; details?: WinofyErrorDetails } | null;

View file

@ -0,0 +1,42 @@
"use client";
import { createContext, useContext, type ReactNode } from "react";
import type { OrderGroup } from "@/types/api";
type OrdersContextValue = {
data: OrderGroup[] | null;
error: string | null;
isLoading: boolean;
};
const OrdersContext = createContext<OrdersContextValue | undefined>(undefined);
export function OrdersProvider({
children,
orderGroups,
error = null,
}: {
children: ReactNode;
orderGroups: OrderGroup[] | null;
error?: string | null;
}) {
return (
<OrdersContext.Provider
value={{
data: orderGroups,
error,
isLoading: false,
}}
>
{children}
</OrdersContext.Provider>
);
}
export function useOrders() {
const ctx = useContext(OrdersContext);
if (ctx === undefined) {
throw new Error("useOrders must be used within OrdersProvider");
}
return ctx;
}