Compare commits
5
Commits
053a9ba361
...
18bf90bbb6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18bf90bbb6 | ||
|
|
10c70359aa | ||
|
|
f0d8276c3e | ||
|
|
0d6e98bf89 | ||
|
|
c53fb99330 |
@@ -0,0 +1,6 @@
|
||||
# Used by `next build` on the websites VM (production).
|
||||
# Local `next dev` still prefers `.env.local`.
|
||||
NEXT_PUBLIC_API_BASE_URL=https://api.meshkee.com/api/v1
|
||||
NEXT_PUBLIC_DOMAIN=sanihome.ir
|
||||
NEXT_PUBLIC_CUSTOMER_ORIGIN=https://customer.sanihome.ir
|
||||
NEXT_PUBLIC_BUSINESS_ORIGIN=https://business.sanihome.ir
|
||||
@@ -0,0 +1,14 @@
|
||||
Build the shopping cart for this Meshkee storefront using the Website API only (https://api.meshkee.com/api/v1).
|
||||
|
||||
Domain: sanihome.ir (replace if different)
|
||||
|
||||
Resolve tenant: GET /tenants/{domain} → save businessId.
|
||||
Add to cart: authenticated POST /businesses/{businessId}/cart/items.
|
||||
Cart popup/drawer: list items, update qty, remove item, show total; header badge with item count.
|
||||
Click on popup cart list Continue button:
|
||||
If logged in → go to /checkout (or /checkout/cart).
|
||||
If not logged in → /login?redirect=/checkout/cart (same-origin path only).
|
||||
After login/register: read redirect from URL and send user back to cart/checkout (not home).
|
||||
Checkout: address + payment; for online pay use payment.type = "e_payment_gate", gatewayType, and absolute returnUrl.
|
||||
Use bearer token for all cart/order calls. Register/login must include "domain": "{domain}".
|
||||
Do not use CMS/dashboard APIs. Keep cart state in API (not only localStorage).
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
allowedDevOrigins: ["sanihome.com", "localhost"],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const res = await meshkeeFetch("/auth/addresses", { token });
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Failed" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body?.province || !body?.city || !body?.address) {
|
||||
return jsonResponse({ error: "آدرس کامل الزامی است" }, 400);
|
||||
}
|
||||
|
||||
const res = await meshkeeFetch("/auth/addresses", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Failed" }, res.status);
|
||||
return jsonResponse(res.data, res.status === 201 ? 201 : 200);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { getBearerToken, jsonResponse, meshkeeFetch, unauthorizedResponse } from "@/lib/meshkee-server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const res = await meshkeeFetch("/auth/handoff", {
|
||||
method: "POST",
|
||||
token,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return jsonResponse(
|
||||
{ error: "امکان باز کردن پنل مدیریت نیست." },
|
||||
res.status,
|
||||
);
|
||||
}
|
||||
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { jsonResponse, meshkeeFetch } from "@/lib/meshkee-server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body?.cellNumber || !body?.password) {
|
||||
return jsonResponse({ error: "شماره موبایل و رمز عبور الزامی است" }, 400);
|
||||
}
|
||||
|
||||
const res = await meshkeeFetch("/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
cellNumber: body.cellNumber,
|
||||
password: body.password,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return jsonResponse(
|
||||
{ error: "ورود ناموفق بود. اطلاعات را بررسی کنید." },
|
||||
res.status,
|
||||
);
|
||||
}
|
||||
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const res = await meshkeeFetch("/auth/me", { token });
|
||||
if (!res.ok) return jsonResponse({ error: "Unauthorized" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { DOMAIN } from "@/lib/meshkee";
|
||||
import { jsonResponse, meshkeeFetch } from "@/lib/meshkee-server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json().catch(() => null);
|
||||
if (
|
||||
!body?.cellNumber ||
|
||||
!body?.password ||
|
||||
!body?.firstName ||
|
||||
!body?.lastName
|
||||
) {
|
||||
return jsonResponse({ error: "لطفاً همه فیلدهای الزامی را پر کنید" }, 400);
|
||||
}
|
||||
|
||||
const res = await meshkeeFetch("/auth/register", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
cellNumber: body.cellNumber,
|
||||
password: body.password,
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
email: body.email,
|
||||
domain: DOMAIN,
|
||||
acknowledgeExistingAccount: body.acknowledgeExistingAccount ?? false,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return jsonResponse(
|
||||
{ error: "ثبتنام ناموفق بود. اطلاعات را بررسی کنید." },
|
||||
res.status,
|
||||
);
|
||||
}
|
||||
|
||||
return jsonResponse(res.data, 201);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
resolveBusinessId,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body?.payment) {
|
||||
return jsonResponse({ error: "payment is required" }, 400);
|
||||
}
|
||||
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/cart/checkout`, {
|
||||
method: "POST",
|
||||
token,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Checkout failed" }, res.status);
|
||||
return jsonResponse(res.data, res.status === 201 ? 201 : 200);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
resolveBusinessId,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
type RouteContext = { params: Promise<{ itemId: string }> };
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const { itemId } = await context.params;
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body?.quantity) return jsonResponse({ error: "quantity is required" }, 400);
|
||||
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/cart/items/${itemId}`, {
|
||||
method: "PATCH",
|
||||
token,
|
||||
body: JSON.stringify({ quantity: body.quantity }),
|
||||
});
|
||||
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Update failed" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: RouteContext) {
|
||||
const token = getBearerToken(_request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const { itemId } = await context.params;
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/cart/items/${itemId}`, {
|
||||
method: "DELETE",
|
||||
token,
|
||||
});
|
||||
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Remove failed" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
resolveBusinessId,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body?.storeItemVariantId) {
|
||||
return jsonResponse({ error: "storeItemVariantId is required" }, 400);
|
||||
}
|
||||
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/cart/items`, {
|
||||
method: "POST",
|
||||
token,
|
||||
body: JSON.stringify({
|
||||
storeItemVariantId: body.storeItemVariantId,
|
||||
quantity: body.quantity ?? 1,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Add to cart failed" }, res.status);
|
||||
return jsonResponse(res.data, res.status === 201 ? 201 : 200);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
resolveBusinessId,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/cart`, { token });
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Cart error" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/cart`, {
|
||||
method: "DELETE",
|
||||
token,
|
||||
});
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Cart error" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import {
|
||||
getBearerToken,
|
||||
jsonResponse,
|
||||
meshkeeFetch,
|
||||
resolveBusinessId,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/meshkee-server";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
if (!token) return unauthorizedResponse();
|
||||
|
||||
const businessId = await resolveBusinessId();
|
||||
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||
|
||||
const res = await meshkeeFetch(`/businesses/${businessId}/payments/methods`, { token });
|
||||
if (!res.ok) return jsonResponse(res.data ?? { error: "Failed" }, res.status);
|
||||
return jsonResponse(res.data);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||
import { CheckoutCartPage } from "@/components/checkout/CheckoutCartPage";
|
||||
|
||||
export default function CheckoutCartRoute() {
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||
<Breadcrumb
|
||||
items={[
|
||||
{ label: "خانه", href: "/" },
|
||||
{ label: "سبد خرید" },
|
||||
]}
|
||||
/>
|
||||
<CheckoutCartPage />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import Link from "next/link";
|
||||
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||
|
||||
export default async function CheckoutCompletePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ status?: string; orderId?: string }>;
|
||||
}) {
|
||||
const { status, orderId } = await searchParams;
|
||||
const failed = status === "failed";
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||
<Breadcrumb items={[{ label: "خانه", href: "/" }, { label: "نتیجه پرداخت" }]} />
|
||||
<div className="mx-auto max-w-lg rounded-2xl border border-border bg-surface p-8 text-center">
|
||||
<h1 className="mb-3 text-2xl font-bold">
|
||||
{failed ? "پرداخت ناموفق بود" : "سفارش شما ثبت شد"}
|
||||
</h1>
|
||||
{orderId && (
|
||||
<p className="mb-4 text-sm text-muted">
|
||||
شماره سفارش: {new Intl.NumberFormat("fa-IR").format(Number(orderId) || 0) || orderId}
|
||||
</p>
|
||||
)}
|
||||
<Link
|
||||
href="/products"
|
||||
className="inline-flex rounded-xl bg-red px-5 py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
بازگشت به فروشگاه
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||
import { CheckoutPage } from "@/components/checkout/CheckoutPage";
|
||||
|
||||
export default function CheckoutRoute() {
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||
<Breadcrumb
|
||||
items={[
|
||||
{ label: "خانه", href: "/" },
|
||||
{ label: "سبد خرید", href: "/checkout/cart" },
|
||||
{ label: "تسویه حساب" },
|
||||
]}
|
||||
/>
|
||||
<h1 className="mb-6 text-2xl font-bold">تسویه حساب</h1>
|
||||
<CheckoutPage />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+9
-4
@@ -5,6 +5,8 @@ import "./globals.css";
|
||||
import { TopBar } from "@/components/home/TopBar";
|
||||
import { Header } from "@/components/home/Header";
|
||||
import { Footer } from "@/components/home/Footer";
|
||||
import { AppProviders } from "@/components/providers/AppProviders";
|
||||
import { Toast } from "@/components/ui/Toast";
|
||||
import { getBusinessInfo, getCategories, getCategoryTree } from "@/lib/meshkee";
|
||||
|
||||
// Body text — headings use the bold weight instead, see globals.css.
|
||||
@@ -45,10 +47,13 @@ export default async function RootLayout({ children }: LayoutProps<"/">) {
|
||||
className={`${iranyekan.variable} ${iranyekanBold.variable} ${syne.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">
|
||||
<TopBar />
|
||||
<Header categoryTree={categoryTree} categories={categories} />
|
||||
<main>{children}</main>
|
||||
<Footer businessInfo={businessInfo} categories={categories} />
|
||||
<AppProviders businessId={businessInfo?.id ?? ""}>
|
||||
<TopBar />
|
||||
<Header categoryTree={categoryTree} categories={categories} />
|
||||
<main>{children}</main>
|
||||
<Footer businessInfo={businessInfo} categories={categories} />
|
||||
<Toast />
|
||||
</AppProviders>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -58,6 +58,9 @@ export default async function ProductDetailPage({
|
||||
<h1 className="text-xl font-bold leading-relaxed md:text-2xl">{product.name}</h1>
|
||||
</>
|
||||
}
|
||||
slug={product.slug}
|
||||
name={product.name}
|
||||
image={images[0] ?? product.image}
|
||||
variations={variations}
|
||||
storeVariants={storeVariants}
|
||||
fallbackPrice={{
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { useCart } from "@/lib/cart";
|
||||
import { customerContinueCheckoutUrl } from "@/lib/customer-auth";
|
||||
|
||||
type CartPopupProps = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export function CartPopup({ open, onClose }: CartPopupProps) {
|
||||
const { isAuthenticated } = useAuth();
|
||||
const {
|
||||
items,
|
||||
itemCount,
|
||||
total,
|
||||
loading,
|
||||
removeItem,
|
||||
setQuantity,
|
||||
refresh,
|
||||
} = useCart();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) refresh();
|
||||
}, [open, refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
};
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
document.body.style.overflow = "hidden";
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
document.body.style.overflow = "";
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!mounted || !open) return null;
|
||||
|
||||
// Hand off current lines to customer dashboard via #guestCart=
|
||||
const continueHref = customerContinueCheckoutUrl(isAuthenticated, items);
|
||||
|
||||
return createPortal(
|
||||
<div>
|
||||
<div
|
||||
onClick={onClose}
|
||||
className="fixed inset-0 z-[120] bg-black/40 backdrop-blur-sm"
|
||||
/>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="سبد خرید"
|
||||
className="fixed top-0 left-0 z-[130] flex h-dvh w-full max-w-md animate-slide-in flex-col bg-surface shadow-2xl"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-border px-5 py-4">
|
||||
<div>
|
||||
<h2 className="text-base font-bold">سبد خرید</h2>
|
||||
{itemCount > 0 && (
|
||||
<p className="mt-0.5 text-xs text-muted">
|
||||
{new Intl.NumberFormat("fa-IR").format(itemCount)} کالا
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="بستن"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||
{items.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
|
||||
<p className="text-sm text-muted">سبد خرید شما خالی است</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-4">
|
||||
{items.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="flex gap-3 border-b border-border pb-4 last:border-0"
|
||||
>
|
||||
<Link
|
||||
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||
onClick={onClose}
|
||||
className="h-20 w-20 shrink-0 overflow-hidden rounded-lg border border-border bg-background"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={item.image || "/images/logo.png"}
|
||||
alt=""
|
||||
className="h-full w-full object-contain p-1"
|
||||
/>
|
||||
</Link>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link
|
||||
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||
onClick={onClose}
|
||||
className="line-clamp-2 text-sm font-medium leading-relaxed hover:text-red"
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
{item.optionLabel && (
|
||||
<p className="mt-1 text-xs text-muted">{item.optionLabel}</p>
|
||||
)}
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center rounded-lg border border-border">
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setQuantity(item.id, item.quantity + 1)}
|
||||
className="px-2 py-1 text-sm"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<span className="min-w-6 text-center text-xs">
|
||||
{new Intl.NumberFormat("fa-IR").format(item.quantity)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setQuantity(item.id, item.quantity - 1)}
|
||||
className="px-2 py-1 text-sm"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-bold text-red-dark">
|
||||
{formatPrice(item.price * item.quantity)}
|
||||
<span className="mr-0.5 text-[11px] font-normal text-muted">
|
||||
تومان
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => removeItem(item.id)}
|
||||
aria-label="حذف"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="none" className="h-4 w-4" aria-hidden>
|
||||
<path
|
||||
d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7M10 11v5M14 11v5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border px-5 py-4">
|
||||
{items.length > 0 && (
|
||||
<div className="mb-3 flex items-center justify-between text-sm">
|
||||
<span className="text-muted">جمع کل</span>
|
||||
<span className="font-bold text-red-dark">
|
||||
{formatPrice(total)}
|
||||
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{items.length > 0 ? (
|
||||
<Link
|
||||
href={continueHref}
|
||||
onClick={onClose}
|
||||
className="flex w-full items-center justify-center rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
ادامه
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex w-full items-center justify-center rounded-xl bg-red-light py-3 text-sm font-medium text-red-dark transition-colors hover:bg-red-muted/40"
|
||||
>
|
||||
ادامه خرید
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect } from "react";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { useCart } from "@/lib/cart";
|
||||
import { customerLoginUrl } from "@/lib/customer-auth";
|
||||
|
||||
export function CheckoutCartPage() {
|
||||
const { isAuthenticated, ready: authReady } = useAuth();
|
||||
const { items, itemCount, total, ready, loading, setQuantity, removeItem } = useCart();
|
||||
|
||||
useEffect(() => {
|
||||
if (!authReady) return;
|
||||
if (!isAuthenticated) {
|
||||
window.location.href = customerLoginUrl("/checkout/cart");
|
||||
}
|
||||
}, [authReady, isAuthenticated]);
|
||||
|
||||
if (!authReady || !ready || !isAuthenticated) {
|
||||
return <div className="py-16 text-center text-sm text-muted">در حال بارگذاری...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl">
|
||||
<h1 className="mb-6 text-2xl font-bold">سبد خرید</h1>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<div className="rounded-2xl border border-border bg-surface p-10 text-center">
|
||||
<p className="mb-4 text-muted">سبد خرید شما خالی است</p>
|
||||
<Link href="/products" className="text-sm font-medium text-red hover:text-red-dark">
|
||||
ادامه خرید
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ul className="space-y-4">
|
||||
{items.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="flex gap-4 rounded-2xl border border-border bg-surface p-4"
|
||||
>
|
||||
<div className="h-24 w-24 shrink-0 overflow-hidden rounded-lg border border-border bg-background">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={item.image || "/images/logo.png"}
|
||||
alt=""
|
||||
className="h-full w-full object-contain p-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link
|
||||
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||
className="line-clamp-2 font-medium hover:text-red"
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
{item.optionLabel && (
|
||||
<p className="mt-1 text-xs text-muted">{item.optionLabel}</p>
|
||||
)}
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center rounded-xl border border-border">
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setQuantity(item.id, item.quantity + 1)}
|
||||
className="px-3 py-1.5 text-lg"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<span className="min-w-8 text-center text-sm">
|
||||
{new Intl.NumberFormat("fa-IR").format(item.quantity)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setQuantity(item.id, item.quantity - 1)}
|
||||
className="px-3 py-1.5 text-lg"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-bold text-red-dark">
|
||||
{formatPrice(item.price * item.quantity)} تومان
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => removeItem(item.id)}
|
||||
aria-label="حذف"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="none" className="h-4 w-4" aria-hidden>
|
||||
<path
|
||||
d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7M10 11v5M14 11v5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<div className="mt-6 rounded-2xl border border-border bg-surface p-5">
|
||||
<div className="mb-4 flex items-center justify-between text-sm">
|
||||
<span className="text-muted">
|
||||
{new Intl.NumberFormat("fa-IR").format(itemCount)} کالا
|
||||
</span>
|
||||
<span className="text-lg font-bold text-red-dark">
|
||||
{formatPrice(total)} تومان
|
||||
</span>
|
||||
</div>
|
||||
<Link
|
||||
href="/checkout"
|
||||
className="flex w-full items-center justify-center rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
ادامه
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { useCart } from "@/lib/cart";
|
||||
import { customerLoginUrl } from "@/lib/customer-auth";
|
||||
|
||||
type Address = {
|
||||
id: string;
|
||||
label?: string;
|
||||
province: string;
|
||||
city: string;
|
||||
address: string;
|
||||
postalCode?: string;
|
||||
landline?: string;
|
||||
};
|
||||
|
||||
type PaymentMethods = {
|
||||
cash?: boolean;
|
||||
transfer?: boolean;
|
||||
pos?: boolean;
|
||||
ePayment?: {
|
||||
enabled?: boolean;
|
||||
defaultGateway?: string;
|
||||
gateways?: string[];
|
||||
};
|
||||
};
|
||||
|
||||
export function CheckoutPage() {
|
||||
const router = useRouter();
|
||||
const { isAuthenticated, ready: authReady, getAccessToken } = useAuth();
|
||||
const { items, total, ready: cartReady } = useCart();
|
||||
|
||||
const [addresses, setAddresses] = useState<Address[]>([]);
|
||||
const [methods, setMethods] = useState<PaymentMethods | null>(null);
|
||||
const [addressId, setAddressId] = useState("");
|
||||
const [paymentType, setPaymentType] = useState<"cash" | "transfer" | "e_payment_gate">("cash");
|
||||
const [gatewayType, setGatewayType] = useState("zarinpal");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [shipping, setShipping] = useState({
|
||||
province: "",
|
||||
city: "",
|
||||
address: "",
|
||||
postalCode: "",
|
||||
landline: "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!authReady) return;
|
||||
if (!isAuthenticated) {
|
||||
window.location.href = customerLoginUrl("/checkout");
|
||||
}
|
||||
}, [authReady, isAuthenticated]);
|
||||
|
||||
useEffect(() => {
|
||||
const token = getAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
Promise.all([
|
||||
fetch("/api/addresses", { headers: { Authorization: `Bearer ${token}` } }).then((r) =>
|
||||
r.ok ? r.json() : { items: [] },
|
||||
),
|
||||
fetch("/api/payments/methods", { headers: { Authorization: `Bearer ${token}` } }).then((r) =>
|
||||
r.ok ? r.json() : null,
|
||||
),
|
||||
]).then(([addressRes, methodsRes]) => {
|
||||
const nextAddresses = (addressRes.items ?? []) as Address[];
|
||||
setAddresses(nextAddresses);
|
||||
if (nextAddresses[0]) setAddressId(nextAddresses[0].id);
|
||||
|
||||
const nextMethods = (methodsRes ?? methodsRes?.methods ?? methodsRes) as PaymentMethods;
|
||||
setMethods(nextMethods);
|
||||
if (nextMethods?.ePayment?.enabled) {
|
||||
setPaymentType("e_payment_gate");
|
||||
setGatewayType(nextMethods.ePayment.defaultGateway ?? nextMethods.ePayment.gateways?.[0] ?? "zarinpal");
|
||||
} else if (nextMethods?.cash) {
|
||||
setPaymentType("cash");
|
||||
} else if (nextMethods?.transfer) {
|
||||
setPaymentType("transfer");
|
||||
}
|
||||
});
|
||||
}, [getAccessToken, isAuthenticated]);
|
||||
|
||||
const onSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
const token = getAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
payment: { type: paymentType },
|
||||
};
|
||||
|
||||
if (addressId) {
|
||||
payload.addressId = addressId;
|
||||
} else {
|
||||
payload.shippingAddress = shipping;
|
||||
}
|
||||
|
||||
if (paymentType === "e_payment_gate") {
|
||||
payload.payment = { type: paymentType, gatewayType };
|
||||
payload.returnUrl = `${window.location.origin}/checkout/complete`;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/cart/checkout", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error ?? "ثبت سفارش ناموفق بود");
|
||||
|
||||
const redirect = data.payment?.redirect;
|
||||
if (redirect?.url) {
|
||||
if (redirect.method === "POST" && redirect.fields) {
|
||||
const form = document.createElement("form");
|
||||
form.method = "POST";
|
||||
form.action = redirect.url;
|
||||
for (const [key, value] of Object.entries(redirect.fields as Record<string, string>)) {
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = key;
|
||||
input.value = value;
|
||||
form.appendChild(input);
|
||||
}
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
return;
|
||||
}
|
||||
window.location.href = redirect.url;
|
||||
return;
|
||||
}
|
||||
|
||||
router.push(`/checkout/complete?orderId=${data.order?.id ?? ""}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "خطا در ثبت سفارش");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!authReady || !cartReady || !isAuthenticated) {
|
||||
return <div className="py-16 text-center text-sm text-muted">در حال بارگذاری...</div>;
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-border bg-surface p-10 text-center">
|
||||
<p className="mb-4 text-muted">سبد خرید شما خالی است</p>
|
||||
<Link href="/products" className="text-sm font-medium text-red hover:text-red-dark">
|
||||
بازگشت به فروشگاه
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="grid gap-8 lg:grid-cols-3">
|
||||
<div className="space-y-6 lg:col-span-2">
|
||||
<section className="rounded-2xl border border-border bg-surface p-5">
|
||||
<h2 className="mb-4 text-lg font-bold">آدرس تحویل</h2>
|
||||
{addresses.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{addresses.map((address) => (
|
||||
<label
|
||||
key={address.id}
|
||||
className={`flex cursor-pointer gap-3 rounded-xl border p-3 ${
|
||||
addressId === address.id ? "border-red bg-red-light/30" : "border-border"
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="address"
|
||||
checked={addressId === address.id}
|
||||
onChange={() => setAddressId(address.id)}
|
||||
/>
|
||||
<span className="text-sm leading-relaxed">
|
||||
{address.label ? `${address.label} — ` : ""}
|
||||
{address.province}، {address.city}، {address.address}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<input
|
||||
required
|
||||
placeholder="استان"
|
||||
value={shipping.province}
|
||||
onChange={(e) => setShipping((s) => ({ ...s, province: e.target.value }))}
|
||||
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
required
|
||||
placeholder="شهر"
|
||||
value={shipping.city}
|
||||
onChange={(e) => setShipping((s) => ({ ...s, city: e.target.value }))}
|
||||
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
required
|
||||
placeholder="آدرس"
|
||||
value={shipping.address}
|
||||
onChange={(e) => setShipping((s) => ({ ...s, address: e.target.value }))}
|
||||
className="rounded-xl border border-border px-3 py-2 text-sm sm:col-span-2"
|
||||
/>
|
||||
<input
|
||||
placeholder="کد پستی"
|
||||
value={shipping.postalCode}
|
||||
onChange={(e) => setShipping((s) => ({ ...s, postalCode: e.target.value }))}
|
||||
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
placeholder="تلفن ثابت"
|
||||
value={shipping.landline}
|
||||
onChange={(e) => setShipping((s) => ({ ...s, landline: e.target.value }))}
|
||||
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-surface p-5">
|
||||
<h2 className="mb-4 text-lg font-bold">روش پرداخت</h2>
|
||||
<div className="space-y-2">
|
||||
{methods?.cash !== false && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="payment"
|
||||
checked={paymentType === "cash"}
|
||||
onChange={() => setPaymentType("cash")}
|
||||
/>
|
||||
پرداخت در محل / نقدی
|
||||
</label>
|
||||
)}
|
||||
{methods?.transfer && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="payment"
|
||||
checked={paymentType === "transfer"}
|
||||
onChange={() => setPaymentType("transfer")}
|
||||
/>
|
||||
کارت به کارت / انتقال
|
||||
</label>
|
||||
)}
|
||||
{methods?.ePayment?.enabled && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="payment"
|
||||
checked={paymentType === "e_payment_gate"}
|
||||
onChange={() => setPaymentType("e_payment_gate")}
|
||||
/>
|
||||
پرداخت آنلاین
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
{paymentType === "e_payment_gate" && methods?.ePayment?.gateways?.length ? (
|
||||
<select
|
||||
value={gatewayType}
|
||||
onChange={(e) => setGatewayType(e.target.value)}
|
||||
className="mt-3 w-full rounded-xl border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
{methods.ePayment.gateways.map((gateway) => (
|
||||
<option key={gateway} value={gateway}>
|
||||
{gateway}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : null}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<aside className="h-fit rounded-2xl border border-border bg-surface p-5">
|
||||
<h2 className="mb-4 text-lg font-bold">خلاصه سفارش</h2>
|
||||
<div className="mb-4 space-y-2 text-sm">
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className="flex justify-between gap-3">
|
||||
<span className="line-clamp-1 text-muted">{item.name}</span>
|
||||
<span>× {new Intl.NumberFormat("fa-IR").format(item.quantity)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mb-4 flex items-center justify-between border-t border-border pt-4">
|
||||
<span className="text-muted">جمع کل</span>
|
||||
<span className="text-lg font-bold text-red-dark">{formatPrice(total)} تومان</span>
|
||||
</div>
|
||||
{error && <p className="mb-3 text-sm text-red">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:bg-red/60"
|
||||
>
|
||||
{loading ? "در حال ثبت سفارش..." : "ثبت سفارش"}
|
||||
</button>
|
||||
</aside>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
+243
-22
@@ -1,9 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef, useState, type MouseEvent } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import type { Category, CategoryNode, CategoryTreeGroup } from "@/lib/meshkee";
|
||||
import { CartPopup } from "@/components/cart/CartPopup";
|
||||
import { EmptyState } from "@/components/ui/EmptyState";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import {
|
||||
businessDashboardUrl,
|
||||
customerDashboardUrl,
|
||||
customerLoginUrl,
|
||||
} from "@/lib/customer-auth";
|
||||
import { useCart } from "@/lib/cart";
|
||||
import { SearchBar } from "./SearchBar";
|
||||
|
||||
const navLinks = [
|
||||
@@ -13,8 +21,6 @@ const navLinks = [
|
||||
{ label: "تماس با ما", href: "#" },
|
||||
];
|
||||
|
||||
const LOGIN_URL = "https://customer.sanihome.ir";
|
||||
|
||||
function Logo({ large = false }: { large?: boolean }) {
|
||||
return (
|
||||
<a href="/" className="flex shrink-0 items-center">
|
||||
@@ -46,10 +52,186 @@ function ChevronDownIcon({ className = "" }: { className?: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function UserIcon({ className = "h-5 w-5" }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
|
||||
<circle cx="12" cy="8" r="3.25" stroke="currentColor" strokeWidth="1.75" />
|
||||
<path
|
||||
d="M5.5 19.25c1.4-3 3.8-4.5 6.5-4.5s5.1 1.5 6.5 4.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function CartIcon({ className = "h-5 w-5" }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
|
||||
<path
|
||||
d="M3.5 5.5h1.6l1.4 10.2a1.5 1.5 0 0 0 1.5 1.3h8.7a1.5 1.5 0 0 0 1.5-1.3L19.5 8H7"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<circle cx="9.5" cy="20" r="1.25" fill="currentColor" />
|
||||
<circle cx="16.5" cy="20" r="1.25" fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function flattenLevel2(categoryTree: CategoryTreeGroup[]): CategoryNode[] {
|
||||
return categoryTree.flatMap((group) => group.items);
|
||||
}
|
||||
|
||||
function AccountMenu({
|
||||
displayName,
|
||||
isWebsiteAdmin,
|
||||
onLogout,
|
||||
compact = false,
|
||||
}: {
|
||||
displayName: string;
|
||||
isWebsiteAdmin: boolean;
|
||||
onLogout: () => void;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [handoffBusy, setHandoffBusy] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const { getAccessToken } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
const onClickOutside = (event: Event) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setOpen(false);
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", onClickOutside);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", onClickOutside);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
async function openBusinessDashboard(event: MouseEvent<HTMLAnchorElement>) {
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (handoffBusy) return;
|
||||
|
||||
const baseUrl = businessDashboardUrl();
|
||||
const popup = window.open("about:blank", "_blank");
|
||||
setHandoffBusy(true);
|
||||
try {
|
||||
const token = getAccessToken();
|
||||
const res = await fetch("/api/auth/handoff", {
|
||||
method: "POST",
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||
});
|
||||
if (!res.ok) throw new Error("handoff failed");
|
||||
const data = (await res.json()) as { ticket?: string };
|
||||
const url = new URL(baseUrl);
|
||||
if (data.ticket) url.searchParams.set("handoff", data.ticket);
|
||||
if (popup) {
|
||||
popup.opener = null;
|
||||
popup.location.replace(url.toString());
|
||||
} else {
|
||||
window.open(url.toString(), "_blank", "noopener,noreferrer");
|
||||
}
|
||||
} catch {
|
||||
if (popup) popup.location.replace(baseUrl);
|
||||
else window.open(baseUrl, "_blank", "noopener,noreferrer");
|
||||
} finally {
|
||||
setHandoffBusy(false);
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
const itemClass =
|
||||
"block w-full px-3 py-2.5 text-right text-sm text-foreground transition-colors hover:bg-red-light/50 hover:text-red";
|
||||
|
||||
return (
|
||||
<div ref={menuRef} className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="menu"
|
||||
className={`group flex max-w-[12rem] items-center gap-1.5 text-muted transition-colors hover:text-red ${
|
||||
compact ? "w-full justify-between" : ""
|
||||
}`}
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<UserIcon className="h-5 w-5 shrink-0 transition-colors group-hover:text-red" />
|
||||
<span className="truncate font-medium text-foreground transition-colors group-hover:text-red">
|
||||
{displayName} عزیز
|
||||
</span>
|
||||
</span>
|
||||
<ChevronDownIcon
|
||||
className={`h-3.5 w-3.5 shrink-0 transition-transform group-hover:text-red ${open ? "rotate-180" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div
|
||||
role="menu"
|
||||
className={`absolute z-50 mt-2 min-w-[11rem] overflow-hidden rounded-xl border border-border bg-surface py-1 shadow-lg ${
|
||||
compact ? "start-0 end-0" : "start-0"
|
||||
}`}
|
||||
>
|
||||
<a
|
||||
role="menuitem"
|
||||
href={customerDashboardUrl("/profile")}
|
||||
className={itemClass}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
پروفایل من
|
||||
</a>
|
||||
<a
|
||||
role="menuitem"
|
||||
href={customerDashboardUrl("/orders")}
|
||||
className={itemClass}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
سفارشات من
|
||||
</a>
|
||||
{isWebsiteAdmin && (
|
||||
<a
|
||||
role="menuitem"
|
||||
href={businessDashboardUrl()}
|
||||
className={itemClass}
|
||||
onClick={openBusinessDashboard}
|
||||
>
|
||||
{handoffBusy ? "در حال انتقال…" : "مدیریت وبسایت"}
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={`${itemClass} text-red hover:text-red-dark`}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
onLogout();
|
||||
}}
|
||||
>
|
||||
خروج
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileDrawer({
|
||||
open,
|
||||
onClose,
|
||||
@@ -62,6 +244,8 @@ function MobileDrawer({
|
||||
const [categoriesOpen, setCategoriesOpen] = useState(false);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const level2 = flattenLevel2(categoryTree);
|
||||
const { isAuthenticated, user, logout, isWebsiteAdmin } = useAuth();
|
||||
const displayName = user?.firstName?.trim() || "حساب من";
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
@@ -180,13 +364,27 @@ function MobileDrawer({
|
||||
</a>
|
||||
))}
|
||||
|
||||
<a
|
||||
href={LOGIN_URL}
|
||||
className="flex items-center gap-2 px-5 py-4 text-right font-medium transition-colors hover:bg-red-light/40 hover:text-red"
|
||||
>
|
||||
<span aria-hidden>👤</span>
|
||||
ورود
|
||||
</a>
|
||||
{isAuthenticated ? (
|
||||
<div className="border-b border-border px-5 py-4">
|
||||
<AccountMenu
|
||||
displayName={displayName}
|
||||
isWebsiteAdmin={isWebsiteAdmin}
|
||||
compact
|
||||
onLogout={() => {
|
||||
logout();
|
||||
onClose();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<a
|
||||
href={customerLoginUrl("/")}
|
||||
className="flex items-center gap-2 px-5 py-4 text-right font-medium transition-colors hover:bg-red-light/40 hover:text-red"
|
||||
>
|
||||
<UserIcon className="h-5 w-5" />
|
||||
ورود
|
||||
</a>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</div>,
|
||||
@@ -203,11 +401,15 @@ export function Header({
|
||||
}) {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [cartOpen, setCartOpen] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const level2 = flattenLevel2(categoryTree);
|
||||
const { itemCount, ready } = useCart();
|
||||
const { isAuthenticated, user, logout, isWebsiteAdmin } = useAuth();
|
||||
const displayName = user?.firstName?.trim() || "حساب من";
|
||||
|
||||
useEffect(() => {
|
||||
const onClickOutside = (event: MouseEvent) => {
|
||||
const onClickOutside = (event: Event) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setMenuOpen(false);
|
||||
}
|
||||
@@ -244,22 +446,40 @@ export function Header({
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 text-sm">
|
||||
<a
|
||||
href={LOGIN_URL}
|
||||
className="hidden items-center gap-1.5 text-muted transition-colors hover:text-red sm:flex"
|
||||
>
|
||||
<span>👤</span>
|
||||
<span>ورود</span>
|
||||
</a>
|
||||
{isAuthenticated ? (
|
||||
<div className="hidden sm:block">
|
||||
<AccountMenu
|
||||
displayName={displayName}
|
||||
isWebsiteAdmin={isWebsiteAdmin}
|
||||
onLogout={logout}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<a
|
||||
href={customerLoginUrl("/")}
|
||||
className="hidden items-center gap-1.5 text-muted transition-colors hover:text-red sm:flex"
|
||||
>
|
||||
<UserIcon className="h-5 w-5" />
|
||||
<span>ورود</span>
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCartOpen(true)}
|
||||
aria-label={
|
||||
itemCount > 0
|
||||
? `سبد خرید، ${new Intl.NumberFormat("fa-IR").format(itemCount)} کالا`
|
||||
: "سبد خرید"
|
||||
}
|
||||
className="relative flex items-center gap-1.5 rounded-lg border border-border px-3 py-2 transition-colors hover:border-red hover:text-red"
|
||||
>
|
||||
<span>🛒</span>
|
||||
<CartIcon className="h-5 w-5" />
|
||||
<span className="hidden sm:inline">سبد خرید</span>
|
||||
<span className="absolute -top-1.5 -left-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-red text-[10px] font-bold text-white">
|
||||
۲
|
||||
</span>
|
||||
{ready && itemCount > 0 && (
|
||||
<span className="absolute -top-1.5 -left-1.5 flex h-5 min-w-5 items-center justify-center rounded-full bg-red px-1 text-[10px] font-bold text-white">
|
||||
{new Intl.NumberFormat("fa-IR").format(itemCount)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -368,6 +588,7 @@ export function Header({
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
categoryTree={categoryTree}
|
||||
/>
|
||||
<CartPopup open={cartOpen} onClose={() => setCartOpen(false)} />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { type ReactNode, useMemo, useState } from "react";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import { useCart } from "@/lib/cart";
|
||||
import type { ProductStoreVariant, ProductVariation } from "@/lib/meshkee";
|
||||
|
||||
function CheckIcon({ className }: { className?: string }) {
|
||||
@@ -20,6 +21,9 @@ function CheckIcon({ className }: { className?: string }) {
|
||||
|
||||
export function ProductPurchasePanel({
|
||||
header,
|
||||
slug,
|
||||
name,
|
||||
image,
|
||||
variations,
|
||||
storeVariants,
|
||||
fallbackPrice,
|
||||
@@ -28,6 +32,9 @@ export function ProductPurchasePanel({
|
||||
storeName,
|
||||
}: {
|
||||
header: ReactNode;
|
||||
slug: string;
|
||||
name: string;
|
||||
image?: string | null;
|
||||
variations: ProductVariation[];
|
||||
storeVariants: ProductStoreVariant[];
|
||||
fallbackPrice: {
|
||||
@@ -40,6 +47,7 @@ export function ProductPurchasePanel({
|
||||
contactPhone?: string;
|
||||
storeName?: string;
|
||||
}) {
|
||||
const { addItem, loading: cartLoading } = useCart();
|
||||
const [selected, setSelected] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
for (const variation of variations) {
|
||||
@@ -48,9 +56,10 @@ export function ProductPurchasePanel({
|
||||
return initial;
|
||||
});
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const matchedVariant = useMemo(() => {
|
||||
if (variations.length === 0) return null;
|
||||
if (variations.length === 0) return storeVariants[0] ?? null;
|
||||
return (
|
||||
storeVariants.find((variant) =>
|
||||
variations.every((variation) => {
|
||||
@@ -85,8 +94,40 @@ export function ProductPurchasePanel({
|
||||
: (fallbackPrice.discount ?? null);
|
||||
|
||||
const stockQuantity = hasVariations ? (matchedVariant?.stockQuantity ?? 0) : null;
|
||||
const available = hasVariations ? Boolean(matchedVariant) && stockQuantity! > 0 : inStock;
|
||||
const available = hasVariations
|
||||
? Boolean(matchedVariant) && stockQuantity! > 0
|
||||
: inStock && Boolean(matchedVariant);
|
||||
const maxQty = stockQuantity && stockQuantity > 0 ? stockQuantity : 99;
|
||||
const storeItemVariantId = matchedVariant?.id;
|
||||
|
||||
const optionLabel = hasVariations
|
||||
? variations
|
||||
.map((variation) => {
|
||||
const option = variation.options.find((o) => o.id === selected[variation.id]);
|
||||
return option?.label;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(" / ")
|
||||
: undefined;
|
||||
|
||||
const handleAddToCart = async () => {
|
||||
if (!available || price == null || priceRangeLabel || !storeItemVariantId) return;
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await addItem({
|
||||
storeItemVariantId,
|
||||
quantity,
|
||||
slug,
|
||||
name,
|
||||
image,
|
||||
price,
|
||||
optionLabel,
|
||||
});
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -197,10 +238,11 @@ export function ProductPurchasePanel({
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={!available}
|
||||
disabled={!available || Boolean(priceRangeLabel) || !storeItemVariantId || submitting || cartLoading}
|
||||
onClick={handleAddToCart}
|
||||
className="w-full rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:bg-red/60"
|
||||
>
|
||||
افزودن به سبد خرید
|
||||
{submitting || cartLoading ? "در حال افزودن..." : "افزودن به سبد خرید"}
|
||||
</button>
|
||||
</>
|
||||
) : contactPhone ? (
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { AuthProvider } from "@/lib/auth";
|
||||
import { CartProvider } from "@/lib/cart";
|
||||
|
||||
export function AppProviders({
|
||||
children,
|
||||
businessId,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
businessId: string;
|
||||
}) {
|
||||
return (
|
||||
<AuthProvider businessId={businessId}>
|
||||
<CartProvider>{children}</CartProvider>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useCart } from "@/lib/cart";
|
||||
|
||||
export function Toast() {
|
||||
const { toast, dismissToast } = useCart();
|
||||
|
||||
if (!toast) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={toast.id}
|
||||
role="status"
|
||||
className="fixed bottom-6 left-1/2 z-[200] flex -translate-x-1/2 items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 text-sm shadow-lg animate-fade-up"
|
||||
>
|
||||
<span className="flex h-7 w-7 items-center justify-center rounded-full bg-green-50 text-green-700">
|
||||
✓
|
||||
</span>
|
||||
<span className="font-medium text-foreground">{toast.message}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={dismissToast}
|
||||
aria-label="بستن"
|
||||
className="mr-1 text-muted transition-colors hover:text-foreground"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
clearSharedAuthCookies,
|
||||
hydrateLocalTokensFromSharedCookies,
|
||||
SHARED_ACCESS_TOKEN_KEY,
|
||||
SHARED_REFRESH_TOKEN_KEY,
|
||||
writeSharedAuthCookies,
|
||||
} from "@/lib/shared-auth-cookie";
|
||||
|
||||
const ACCESS_TOKEN_KEY = SHARED_ACCESS_TOKEN_KEY;
|
||||
const REFRESH_TOKEN_KEY = SHARED_REFRESH_TOKEN_KEY;
|
||||
const LEGACY_ACCESS_KEY = "sanihome-access-token";
|
||||
const LEGACY_REFRESH_KEY = "sanihome-refresh-token";
|
||||
|
||||
export type AuthBusinessMembership = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
isOwner: boolean;
|
||||
teamRole: string | null;
|
||||
};
|
||||
|
||||
export type AuthUser = {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
cellNumber?: string;
|
||||
email?: string;
|
||||
roles?: string[];
|
||||
isSuperAdmin?: boolean;
|
||||
businesses?: AuthBusinessMembership[];
|
||||
};
|
||||
|
||||
type AuthContextValue = {
|
||||
user: AuthUser | null;
|
||||
isAuthenticated: boolean;
|
||||
ready: boolean;
|
||||
businessId: string;
|
||||
/** Owner / team member of this storefront’s business (or super admin). */
|
||||
isWebsiteAdmin: boolean;
|
||||
login: (cellNumber: string, password: string) => Promise<void>;
|
||||
register: (input: {
|
||||
cellNumber: string;
|
||||
password: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email?: string;
|
||||
}) => Promise<void>;
|
||||
logout: () => void;
|
||||
getAccessToken: () => string | null;
|
||||
};
|
||||
|
||||
function normalizeUser(raw: Partial<AuthUser> & { id?: string | number }): AuthUser | null {
|
||||
if (raw.id == null) return null;
|
||||
return {
|
||||
id: String(raw.id),
|
||||
firstName: raw.firstName ?? undefined,
|
||||
lastName: raw.lastName ?? undefined,
|
||||
cellNumber: raw.cellNumber ?? undefined,
|
||||
email: raw.email ?? undefined,
|
||||
roles: Array.isArray(raw.roles) ? raw.roles : undefined,
|
||||
isSuperAdmin: Boolean(raw.isSuperAdmin),
|
||||
businesses: Array.isArray(raw.businesses)
|
||||
? raw.businesses.map((b) => ({
|
||||
id: String(b.id),
|
||||
name: b.name,
|
||||
slug: b.slug,
|
||||
isOwner: Boolean(b.isOwner),
|
||||
teamRole: b.teamRole ?? null,
|
||||
}))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function isWebsiteAdminForBusiness(
|
||||
user: AuthUser | null | undefined,
|
||||
businessId: string,
|
||||
): boolean {
|
||||
if (!user || !businessId) return false;
|
||||
if (user.isSuperAdmin || user.roles?.includes("super_admin")) return true;
|
||||
return Boolean(
|
||||
user.businesses?.some(
|
||||
(b) =>
|
||||
String(b.id) === String(businessId) && (b.isOwner || Boolean(b.teamRole)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
function readToken(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeToken(key: string, value: string | null) {
|
||||
try {
|
||||
if (value) localStorage.setItem(key, value);
|
||||
else localStorage.removeItem(key);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function migrateLegacyTokens() {
|
||||
const legacyAccess = readToken(LEGACY_ACCESS_KEY);
|
||||
if (!legacyAccess || readToken(ACCESS_TOKEN_KEY)) return;
|
||||
writeToken(ACCESS_TOKEN_KEY, legacyAccess);
|
||||
writeToken(LEGACY_ACCESS_KEY, null);
|
||||
const legacyRefresh = readToken(LEGACY_REFRESH_KEY);
|
||||
if (legacyRefresh) {
|
||||
writeToken(REFRESH_TOKEN_KEY, legacyRefresh);
|
||||
writeToken(LEGACY_REFRESH_KEY, null);
|
||||
}
|
||||
}
|
||||
|
||||
async function authRequest<T>(
|
||||
path: string,
|
||||
body: unknown,
|
||||
token?: string | null,
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(path, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const data = (await res.json().catch(() => null)) as T & { error?: string };
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
(data as { error?: string } | null)?.error ?? "درخواست با خطا مواجه شد",
|
||||
);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export function AuthProvider({
|
||||
children,
|
||||
businessId,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
businessId: string;
|
||||
}) {
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
const getAccessToken = useCallback(() => {
|
||||
migrateLegacyTokens();
|
||||
hydrateLocalTokensFromSharedCookies(ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY);
|
||||
return readToken(ACCESS_TOKEN_KEY);
|
||||
}, []);
|
||||
|
||||
const persistTokens = useCallback(
|
||||
(accessToken: string, refreshToken?: string) => {
|
||||
writeToken(ACCESS_TOKEN_KEY, accessToken);
|
||||
if (refreshToken) writeToken(REFRESH_TOKEN_KEY, refreshToken);
|
||||
writeToken(LEGACY_ACCESS_KEY, null);
|
||||
writeToken(LEGACY_REFRESH_KEY, null);
|
||||
writeSharedAuthCookies(accessToken, refreshToken);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const clearTokens = useCallback(() => {
|
||||
writeToken(ACCESS_TOKEN_KEY, null);
|
||||
writeToken(REFRESH_TOKEN_KEY, null);
|
||||
writeToken(LEGACY_ACCESS_KEY, null);
|
||||
writeToken(LEGACY_REFRESH_KEY, null);
|
||||
clearSharedAuthCookies();
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
const fetchMe = useCallback(async (token: string) => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (res.status === 401) return { user: null as AuthUser | null, unauthorized: true };
|
||||
if (!res.ok) return { user: null as AuthUser | null, unauthorized: false };
|
||||
const data = (await res.json()) as { user?: AuthUser } & AuthUser;
|
||||
// API may return { user } or the user object directly
|
||||
const normalized = normalizeUser(data.user ?? data);
|
||||
return { user: normalized, unauthorized: false };
|
||||
} catch {
|
||||
return { user: null as AuthUser | null, unauthorized: false };
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const token = getAccessToken();
|
||||
if (!token) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
// Ensure cookie mirror exists for customer dashboard
|
||||
const refresh = readToken(REFRESH_TOKEN_KEY);
|
||||
writeSharedAuthCookies(token, refresh ?? undefined);
|
||||
|
||||
fetchMe(token)
|
||||
.then(({ user: nextUser, unauthorized }) => {
|
||||
if (nextUser) setUser(nextUser);
|
||||
else if (unauthorized) clearTokens();
|
||||
})
|
||||
.finally(() => setReady(true));
|
||||
}, [clearTokens, fetchMe, getAccessToken]);
|
||||
|
||||
const login = useCallback(
|
||||
async (cellNumber: string, password: string) => {
|
||||
const data = await authRequest<{
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
user?: AuthUser;
|
||||
}>("/api/auth/login", { cellNumber, password });
|
||||
|
||||
persistTokens(data.accessToken, data.refreshToken);
|
||||
if (data.user) {
|
||||
setUser(normalizeUser(data.user));
|
||||
return;
|
||||
}
|
||||
const me = await fetchMe(data.accessToken);
|
||||
setUser(me.user);
|
||||
},
|
||||
[fetchMe, persistTokens],
|
||||
);
|
||||
|
||||
const register = useCallback(
|
||||
async (input: {
|
||||
cellNumber: string;
|
||||
password: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email?: string;
|
||||
}) => {
|
||||
const data = await authRequest<{
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
user?: AuthUser;
|
||||
}>("/api/auth/register", input);
|
||||
|
||||
persistTokens(data.accessToken, data.refreshToken);
|
||||
if (data.user) {
|
||||
setUser(normalizeUser(data.user));
|
||||
return;
|
||||
}
|
||||
const me = await fetchMe(data.accessToken);
|
||||
setUser(me.user);
|
||||
},
|
||||
[fetchMe, persistTokens],
|
||||
);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearTokens();
|
||||
}, [clearTokens]);
|
||||
|
||||
const isWebsiteAdmin = useMemo(
|
||||
() => isWebsiteAdminForBusiness(user, businessId),
|
||||
[user, businessId],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
user,
|
||||
isAuthenticated: Boolean(user),
|
||||
ready,
|
||||
businessId,
|
||||
isWebsiteAdmin,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
getAccessToken,
|
||||
}),
|
||||
[user, ready, businessId, isWebsiteAdmin, login, register, logout, getAccessToken],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
export type CartItem = {
|
||||
id: string;
|
||||
storeItemVariantId: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
image?: string | null;
|
||||
price: number;
|
||||
quantity: number;
|
||||
optionLabel?: string;
|
||||
};
|
||||
|
||||
export type CartSnapshot = {
|
||||
items: CartItem[];
|
||||
subtotal: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
function num(value: unknown): number | null {
|
||||
if (value == null) return null;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
function str(value: unknown): string {
|
||||
return value != null ? String(value) : "";
|
||||
}
|
||||
|
||||
export function normalizeCart(data: unknown): CartSnapshot {
|
||||
const root = data && typeof data === "object" ? (data as Record<string, unknown>) : {};
|
||||
const cart =
|
||||
root.cart && typeof root.cart === "object"
|
||||
? (root.cart as Record<string, unknown>)
|
||||
: root;
|
||||
const rawItems = Array.isArray(cart.items) ? cart.items : [];
|
||||
|
||||
const items: CartItem[] = rawItems.map((raw) => {
|
||||
const item = raw as Record<string, unknown>;
|
||||
const product =
|
||||
item.product && typeof item.product === "object"
|
||||
? (item.product as Record<string, unknown>)
|
||||
: {};
|
||||
const variant =
|
||||
item.variant && typeof item.variant === "object"
|
||||
? (item.variant as Record<string, unknown>)
|
||||
: {};
|
||||
const storeItem =
|
||||
item.storeItem && typeof item.storeItem === "object"
|
||||
? (item.storeItem as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
const quantity = num(item.quantity) ?? 1;
|
||||
const unitPrice =
|
||||
num(item.unitPrice) ??
|
||||
num(item.price) ??
|
||||
num(item.discountedPrice) ??
|
||||
num(variant.discountedPrice) ??
|
||||
num(variant.price) ??
|
||||
num(storeItem.discountedPrice) ??
|
||||
num(storeItem.price) ??
|
||||
0;
|
||||
|
||||
const name = str(
|
||||
item.productTitle ??
|
||||
item.productNameFa ??
|
||||
product.nameFa ??
|
||||
product.name ??
|
||||
product.title ??
|
||||
storeItem.productTitle ??
|
||||
storeItem.productNameFa,
|
||||
);
|
||||
|
||||
const slug = str(product.slug ?? item.productSlug ?? storeItem.productSlug);
|
||||
const image = str(
|
||||
item.productImage ??
|
||||
item.image ??
|
||||
product.image ??
|
||||
product.thumbnailUrl ??
|
||||
storeItem.productImage,
|
||||
);
|
||||
|
||||
const selections = Array.isArray(item.selections)
|
||||
? item.selections
|
||||
: Array.isArray(variant.selections)
|
||||
? variant.selections
|
||||
: [];
|
||||
const optionLabel = selections
|
||||
.map((s) => {
|
||||
const sel = s as Record<string, unknown>;
|
||||
return str(sel.label ?? sel.optionLabel ?? sel.value);
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(" / ");
|
||||
|
||||
return {
|
||||
id: str(item.id ?? item.itemId),
|
||||
storeItemVariantId: str(
|
||||
item.storeItemVariantId ?? variant.id ?? storeItem.id ?? item.variantId,
|
||||
),
|
||||
slug,
|
||||
name,
|
||||
image: image || null,
|
||||
price: unitPrice,
|
||||
quantity,
|
||||
optionLabel: optionLabel || undefined,
|
||||
};
|
||||
});
|
||||
|
||||
const subtotal =
|
||||
num(cart.subtotal) ??
|
||||
items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||
const total = num(cart.total) ?? subtotal;
|
||||
|
||||
return { items, subtotal, total };
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import type { CartItem, CartSnapshot } from "@/lib/cart-types";
|
||||
import { normalizeCart } from "@/lib/cart-types";
|
||||
import {
|
||||
clearGuestCart,
|
||||
readGuestCart,
|
||||
writeGuestCart,
|
||||
} from "@/lib/guest-cart";
|
||||
|
||||
type ToastState = {
|
||||
id: number;
|
||||
message: string;
|
||||
} | null;
|
||||
|
||||
export type AddCartItemInput = {
|
||||
storeItemVariantId: string;
|
||||
quantity?: number;
|
||||
slug?: string;
|
||||
name?: string;
|
||||
image?: string | null;
|
||||
price?: number;
|
||||
optionLabel?: string;
|
||||
};
|
||||
|
||||
type CartContextValue = {
|
||||
items: CartItem[];
|
||||
itemCount: number;
|
||||
subtotal: number;
|
||||
total: number;
|
||||
ready: boolean;
|
||||
loading: boolean;
|
||||
addItem: (input: AddCartItemInput) => Promise<boolean>;
|
||||
removeItem: (itemId: string) => Promise<void>;
|
||||
setQuantity: (itemId: string, quantity: number) => Promise<void>;
|
||||
refresh: () => Promise<void>;
|
||||
toast: ToastState;
|
||||
showToast: (message: string) => void;
|
||||
dismissToast: () => void;
|
||||
};
|
||||
|
||||
const CartContext = createContext<CartContextValue | null>(null);
|
||||
|
||||
function emptySnapshot(): CartSnapshot {
|
||||
return { items: [], subtotal: 0, total: 0 };
|
||||
}
|
||||
|
||||
function snapshotFromItems(items: CartItem[]): CartSnapshot {
|
||||
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||
return { items, subtotal, total: subtotal };
|
||||
}
|
||||
|
||||
async function cartRequest(
|
||||
path: string,
|
||||
token: string,
|
||||
init?: RequestInit,
|
||||
): Promise<CartSnapshot> {
|
||||
const res = await fetch(path, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
(data as { error?: string } | null)?.error ?? "خطا در ارتباط با سبد خرید",
|
||||
);
|
||||
}
|
||||
return normalizeCart(data);
|
||||
}
|
||||
|
||||
export function CartProvider({ children }: { children: ReactNode }) {
|
||||
const { isAuthenticated, ready: authReady, getAccessToken } = useAuth();
|
||||
const [snapshot, setSnapshot] = useState<CartSnapshot>(emptySnapshot());
|
||||
const [ready, setReady] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [toast, setToast] = useState<ToastState>(null);
|
||||
const syncedGuestRef = useRef(false);
|
||||
|
||||
const showToast = useCallback((message: string) => {
|
||||
setToast({ id: Date.now(), message });
|
||||
}, []);
|
||||
|
||||
const dismissToast = useCallback(() => setToast(null), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
const timer = window.setTimeout(() => setToast(null), 2800);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [toast]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const token = getAccessToken();
|
||||
if (!token) {
|
||||
setSnapshot(snapshotFromItems(readGuestCart()));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const next = await cartRequest("/api/cart", token);
|
||||
setSnapshot(next);
|
||||
} catch {
|
||||
setSnapshot(emptySnapshot());
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [getAccessToken]);
|
||||
|
||||
// Load guest cart first; after login, push guest lines into the API cart once.
|
||||
useEffect(() => {
|
||||
if (!authReady) return;
|
||||
|
||||
const bootstrap = async () => {
|
||||
const token = getAccessToken();
|
||||
if (!token) {
|
||||
syncedGuestRef.current = false;
|
||||
setSnapshot(snapshotFromItems(readGuestCart()));
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const guestItems = readGuestCart();
|
||||
if (guestItems.length > 0 && !syncedGuestRef.current) {
|
||||
syncedGuestRef.current = true;
|
||||
setLoading(true);
|
||||
try {
|
||||
for (const item of guestItems) {
|
||||
await cartRequest("/api/cart/items", token, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
storeItemVariantId: item.storeItemVariantId,
|
||||
quantity: item.quantity,
|
||||
}),
|
||||
});
|
||||
}
|
||||
clearGuestCart();
|
||||
} catch {
|
||||
// keep guest cart if sync fails
|
||||
syncedGuestRef.current = false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
await refresh();
|
||||
setReady(true);
|
||||
};
|
||||
|
||||
void bootstrap();
|
||||
}, [authReady, isAuthenticated, getAccessToken, refresh]);
|
||||
|
||||
const addItem = useCallback(
|
||||
async (input: AddCartItemInput) => {
|
||||
const quantity = Math.max(1, input.quantity ?? 1);
|
||||
const token = getAccessToken();
|
||||
|
||||
if (token) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const next = await cartRequest("/api/cart/items", token, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
storeItemVariantId: input.storeItemVariantId,
|
||||
quantity,
|
||||
}),
|
||||
});
|
||||
setSnapshot(next);
|
||||
showToast("به سبد خرید اضافه شد");
|
||||
return true;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const current = readGuestCart();
|
||||
const existing = current.find(
|
||||
(item) => item.storeItemVariantId === input.storeItemVariantId,
|
||||
);
|
||||
const nextItems = existing
|
||||
? current.map((item) =>
|
||||
item.storeItemVariantId === input.storeItemVariantId
|
||||
? {
|
||||
...item,
|
||||
quantity: item.quantity + quantity,
|
||||
price: input.price ?? item.price,
|
||||
name: input.name ?? item.name,
|
||||
image: input.image ?? item.image,
|
||||
optionLabel: input.optionLabel ?? item.optionLabel,
|
||||
}
|
||||
: item,
|
||||
)
|
||||
: [
|
||||
...current,
|
||||
{
|
||||
id: input.storeItemVariantId,
|
||||
storeItemVariantId: input.storeItemVariantId,
|
||||
slug: input.slug ?? "",
|
||||
name: input.name ?? "",
|
||||
image: input.image ?? null,
|
||||
price: input.price ?? 0,
|
||||
quantity,
|
||||
optionLabel: input.optionLabel,
|
||||
},
|
||||
];
|
||||
writeGuestCart(nextItems);
|
||||
setSnapshot(snapshotFromItems(nextItems));
|
||||
showToast("به سبد خرید اضافه شد");
|
||||
return true;
|
||||
},
|
||||
[getAccessToken, showToast],
|
||||
);
|
||||
|
||||
const removeItem = useCallback(
|
||||
async (itemId: string) => {
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const next = await cartRequest(`/api/cart/items/${itemId}`, token, {
|
||||
method: "DELETE",
|
||||
});
|
||||
setSnapshot(next);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextItems = readGuestCart().filter(
|
||||
(item) => item.id !== itemId && item.storeItemVariantId !== itemId,
|
||||
);
|
||||
writeGuestCart(nextItems);
|
||||
setSnapshot(snapshotFromItems(nextItems));
|
||||
},
|
||||
[getAccessToken],
|
||||
);
|
||||
|
||||
const setQuantity = useCallback(
|
||||
async (itemId: string, quantity: number) => {
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const next =
|
||||
quantity < 1
|
||||
? await cartRequest(`/api/cart/items/${itemId}`, token, {
|
||||
method: "DELETE",
|
||||
})
|
||||
: await cartRequest(`/api/cart/items/${itemId}`, token, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ quantity }),
|
||||
});
|
||||
setSnapshot(next);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (quantity < 1) {
|
||||
const nextItems = readGuestCart().filter(
|
||||
(item) => item.id !== itemId && item.storeItemVariantId !== itemId,
|
||||
);
|
||||
writeGuestCart(nextItems);
|
||||
setSnapshot(snapshotFromItems(nextItems));
|
||||
return;
|
||||
}
|
||||
|
||||
const nextItems = readGuestCart().map((item) =>
|
||||
item.id === itemId || item.storeItemVariantId === itemId
|
||||
? { ...item, quantity }
|
||||
: item,
|
||||
);
|
||||
writeGuestCart(nextItems);
|
||||
setSnapshot(snapshotFromItems(nextItems));
|
||||
},
|
||||
[getAccessToken],
|
||||
);
|
||||
|
||||
const itemCount = useMemo(
|
||||
() => snapshot.items.reduce((sum, item) => sum + item.quantity, 0),
|
||||
[snapshot.items],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
items: snapshot.items,
|
||||
itemCount,
|
||||
subtotal: snapshot.subtotal,
|
||||
total: snapshot.total,
|
||||
ready,
|
||||
loading,
|
||||
addItem,
|
||||
removeItem,
|
||||
setQuantity,
|
||||
refresh,
|
||||
toast,
|
||||
showToast,
|
||||
dismissToast,
|
||||
}),
|
||||
[
|
||||
snapshot,
|
||||
itemCount,
|
||||
ready,
|
||||
loading,
|
||||
addItem,
|
||||
removeItem,
|
||||
setQuantity,
|
||||
refresh,
|
||||
toast,
|
||||
showToast,
|
||||
dismissToast,
|
||||
],
|
||||
);
|
||||
|
||||
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
|
||||
}
|
||||
|
||||
export function useCart() {
|
||||
const ctx = useContext(CartContext);
|
||||
if (!ctx) throw new Error("useCart must be used within CartProvider");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { CartItem } from "@/lib/cart-types";
|
||||
import { encodeGuestCartForUrl, GUEST_CART_URL_PARAM } from "@/lib/guest-cart";
|
||||
import { DOMAIN } from "@/lib/meshkee";
|
||||
|
||||
/**
|
||||
* Shared checkout lives on the customer dashboard (all websites).
|
||||
* Local: http://customer.{domain}:5175
|
||||
* Prod: https://customer.{domain}
|
||||
*
|
||||
* Prefer NEXT_PUBLIC_CUSTOMER_ORIGIN. Otherwise derive from DOMAIN + build mode
|
||||
* so production deploys never bake in the local Vite URL.
|
||||
*/
|
||||
function resolveCustomerOrigin(): string {
|
||||
const configured = process.env.NEXT_PUBLIC_CUSTOMER_ORIGIN?.replace(/\/$/, "");
|
||||
if (configured) return configured;
|
||||
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
return `https://customer.${DOMAIN}`;
|
||||
}
|
||||
|
||||
return `http://customer.${DOMAIN}:5175`;
|
||||
}
|
||||
|
||||
export const CUSTOMER_ORIGIN = resolveCustomerOrigin();
|
||||
|
||||
/**
|
||||
* Business dashboard for website admins.
|
||||
* Local: http://business.{domain}:5173
|
||||
* Prod: https://business.{domain}
|
||||
*/
|
||||
export function businessDashboardUrl(): string {
|
||||
const configured = process.env.NEXT_PUBLIC_BUSINESS_ORIGIN?.replace(/\/$/, "");
|
||||
if (configured) return `${configured}/`;
|
||||
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
return `https://business.${DOMAIN}/`;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
const { protocol, port } = window.location;
|
||||
if (port === "3000" || port === "3001") {
|
||||
return `${protocol}//business.${DOMAIN}:5173/`;
|
||||
}
|
||||
}
|
||||
|
||||
return `https://business.${DOMAIN}/`;
|
||||
}
|
||||
|
||||
/** Absolute URL on the customer dashboard (e.g. /checkout/cart). */
|
||||
export function customerDashboardUrl(path = "/checkout/cart"): string {
|
||||
const normalized = path.startsWith("/") ? path : `/${path}`;
|
||||
return `${CUSTOMER_ORIGIN}${normalized}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guest Continue → customer login, then back to checkout cart.
|
||||
* Cart lines are passed in the redirect hash so the customer app can ingest them.
|
||||
*/
|
||||
export function customerLoginUrl(
|
||||
redirectPath = "/checkout/cart",
|
||||
cartItems?: CartItem[],
|
||||
): string {
|
||||
let redirect = redirectPath.startsWith("/") ? redirectPath : `/${redirectPath}`;
|
||||
if (cartItems && cartItems.length > 0) {
|
||||
const encoded = encodeGuestCartForUrl(cartItems);
|
||||
const join = redirect.includes("#") ? "&" : `#`;
|
||||
redirect = `${redirect}${join}${GUEST_CART_URL_PARAM}=${encoded}`;
|
||||
}
|
||||
const url = new URL("/login", CUSTOMER_ORIGIN);
|
||||
url.searchParams.set("redirect", redirect);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** Continue from cart popup: hand off cart lines via #guestCart=… */
|
||||
export function customerContinueCheckoutUrl(
|
||||
isAuthenticated: boolean,
|
||||
cartItems: CartItem[] = [],
|
||||
): string {
|
||||
if (isAuthenticated) {
|
||||
const url = new URL("/checkout/cart", CUSTOMER_ORIGIN);
|
||||
if (cartItems.length > 0) {
|
||||
url.hash = `${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
return customerLoginUrl("/checkout/cart", cartItems);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { CartItem } from "@/lib/cart-types";
|
||||
|
||||
/** Must match customer dashboard `GUEST_CART_STORAGE_KEY`. */
|
||||
export const MESHKEE_GUEST_CART_KEY = "meshkee-guest-cart";
|
||||
export const LEGACY_GUEST_CART_KEY = "sanihome-guest-cart";
|
||||
export const GUEST_CART_URL_PARAM = "guestCart";
|
||||
|
||||
export type MeshkeeGuestCartItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug?: string;
|
||||
price: number;
|
||||
originalPrice?: number;
|
||||
image: string | null;
|
||||
quantity: number;
|
||||
};
|
||||
|
||||
function cookieDomain(): string | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
const host = window.location.hostname.toLowerCase();
|
||||
if (host === "localhost" || host === "127.0.0.1") return undefined;
|
||||
const parts = host.split(".").filter(Boolean);
|
||||
if (parts.length < 2) return undefined;
|
||||
return `.${parts.slice(-2).join(".")}`;
|
||||
}
|
||||
|
||||
function parseItems(raw: string | null): CartItem[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as CartItem[];
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Map storefront cart lines to the shared guest-cart shape (id = variant id). */
|
||||
export function toMeshkeeGuestItems(items: CartItem[]): MeshkeeGuestCartItem[] {
|
||||
const result: MeshkeeGuestCartItem[] = [];
|
||||
for (const item of items) {
|
||||
const variantId = (item.storeItemVariantId || item.id || "").trim();
|
||||
if (!variantId) continue;
|
||||
result.push({
|
||||
id: variantId,
|
||||
name: item.name || "محصول",
|
||||
...(item.slug ? { slug: item.slug } : {}),
|
||||
price: item.price,
|
||||
image: item.image ?? null,
|
||||
quantity: Math.max(1, Math.floor(item.quantity) || 1),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function encodeGuestCartForUrl(items: CartItem[]): string {
|
||||
const payload = toMeshkeeGuestItems(items);
|
||||
const json = JSON.stringify(payload);
|
||||
return btoa(unescape(encodeURIComponent(json)))
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
}
|
||||
|
||||
function writeSharedCookie(items: MeshkeeGuestCartItem[]) {
|
||||
if (typeof document === "undefined") return;
|
||||
const domain = cookieDomain();
|
||||
const maxAge = 60 * 60 * 24 * 30;
|
||||
const encoded = encodeURIComponent(
|
||||
JSON.stringify(
|
||||
items.map(({ id, name, slug, price, originalPrice, quantity }) => ({
|
||||
id,
|
||||
name,
|
||||
slug,
|
||||
price,
|
||||
originalPrice,
|
||||
quantity,
|
||||
image: null as string | null,
|
||||
})),
|
||||
),
|
||||
);
|
||||
if (encoded.length > 3500) return;
|
||||
let cookie = `${MESHKEE_GUEST_CART_KEY}=${encoded}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
export function readGuestCart(): CartItem[] {
|
||||
if (typeof window === "undefined") return [];
|
||||
const primary = parseItems(localStorage.getItem(MESHKEE_GUEST_CART_KEY));
|
||||
if (primary.length > 0) return primary;
|
||||
const legacy = parseItems(localStorage.getItem(LEGACY_GUEST_CART_KEY));
|
||||
if (legacy.length > 0) {
|
||||
writeGuestCart(legacy);
|
||||
return legacy;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function writeGuestCart(items: CartItem[]) {
|
||||
if (typeof window === "undefined") return;
|
||||
const raw = JSON.stringify(items);
|
||||
localStorage.setItem(MESHKEE_GUEST_CART_KEY, raw);
|
||||
localStorage.removeItem(LEGACY_GUEST_CART_KEY);
|
||||
try {
|
||||
writeSharedCookie(toMeshkeeGuestItems(items));
|
||||
} catch {
|
||||
// ignore cookie failures
|
||||
}
|
||||
}
|
||||
|
||||
export function clearGuestCart() {
|
||||
if (typeof window === "undefined") return;
|
||||
localStorage.removeItem(MESHKEE_GUEST_CART_KEY);
|
||||
localStorage.removeItem(LEGACY_GUEST_CART_KEY);
|
||||
const domain = cookieDomain();
|
||||
let cookie = `${MESHKEE_GUEST_CART_KEY}=; path=/; max-age=0; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { DOMAIN } from "@/lib/meshkee";
|
||||
|
||||
export const MESHKEE_API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") ||
|
||||
"https://api.meshkee.com/api/v1";
|
||||
|
||||
export function getBearerToken(request: Request): string | null {
|
||||
const auth = request.headers.get("authorization");
|
||||
if (auth?.startsWith("Bearer ")) return auth.slice(7);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function meshkeeFetch(
|
||||
path: string,
|
||||
init?: RequestInit & { token?: string | null },
|
||||
): Promise<{ ok: boolean; status: number; data: unknown }> {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has("Content-Type") && init?.body) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
if (init?.token) {
|
||||
headers.set("Authorization", `Bearer ${init.token}`);
|
||||
}
|
||||
|
||||
const res = await fetch(`${MESHKEE_API_BASE}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
|
||||
return { ok: res.ok, status: res.status, data };
|
||||
}
|
||||
|
||||
export async function resolveBusinessId(): Promise<string | null> {
|
||||
const res = await meshkeeFetch(`/tenants/${DOMAIN}`);
|
||||
if (!res.ok || !res.data || typeof res.data !== "object") return null;
|
||||
const id = (res.data as { id?: string }).id;
|
||||
return id ?? null;
|
||||
}
|
||||
|
||||
export function jsonResponse(data: unknown, status = 200) {
|
||||
return Response.json(data, { status });
|
||||
}
|
||||
|
||||
export function unauthorizedResponse() {
|
||||
return jsonResponse({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
+16
-2
@@ -1,5 +1,19 @@
|
||||
const API_BASE = "https://api.meshkee.com/api/v1";
|
||||
const DOMAIN = "sanihome.ir";
|
||||
const API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") ||
|
||||
"https://api.meshkee.com/api/v1";
|
||||
export const DOMAIN = process.env.NEXT_PUBLIC_DOMAIN || "sanihome.ir";
|
||||
|
||||
export type Tenant = {
|
||||
id: string;
|
||||
name?: string;
|
||||
nameFa?: string;
|
||||
domain?: string;
|
||||
logoUrl?: string | null;
|
||||
};
|
||||
|
||||
export async function getTenant(): Promise<Tenant | null> {
|
||||
return apiGet<Tenant>(`/tenants/${DOMAIN}`);
|
||||
}
|
||||
|
||||
async function apiGet<T>(
|
||||
path: string,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Shared auth cookies so storefront + customer.{domain} share one login. */
|
||||
|
||||
export const SHARED_ACCESS_TOKEN_KEY = "meshkee_customer_access_token";
|
||||
export const SHARED_REFRESH_TOKEN_KEY = "meshkee_customer_refresh_token";
|
||||
|
||||
const CHUNK_SIZE = 2800;
|
||||
const MAX_CHUNKS = 24;
|
||||
|
||||
function cookieDomain(): string | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
const host = window.location.hostname.toLowerCase();
|
||||
if (host === "localhost" || host === "127.0.0.1") return undefined;
|
||||
const parts = host.split(".").filter(Boolean);
|
||||
if (parts.length < 2) return undefined;
|
||||
return `.${parts.slice(-2).join(".")}`;
|
||||
}
|
||||
|
||||
function readRawCookie(name: string): string | null {
|
||||
if (typeof document === "undefined") return null;
|
||||
const prefix = `${name}=`;
|
||||
const match = document.cookie.split("; ").find((row) => row.startsWith(prefix));
|
||||
if (!match) return null;
|
||||
return match.slice(prefix.length);
|
||||
}
|
||||
|
||||
function writeRawCookie(name: string, value: string | null) {
|
||||
if (typeof document === "undefined") return;
|
||||
const domain = cookieDomain();
|
||||
if (value == null) {
|
||||
let cookie = `${name}=; path=/; max-age=0; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
return;
|
||||
}
|
||||
const maxAge = 60 * 60 * 24 * 30;
|
||||
let cookie = `${name}=${value}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
function clearChunkedCookie(name: string) {
|
||||
writeRawCookie(name, null);
|
||||
const n = Number(readRawCookie(`${name}_n`) || "0");
|
||||
writeRawCookie(`${name}_n`, null);
|
||||
for (let i = 0; i < Math.max(n, MAX_CHUNKS); i++) {
|
||||
writeRawCookie(`${name}_${i}`, null);
|
||||
}
|
||||
}
|
||||
|
||||
function writeCookie(name: string, value: string | null) {
|
||||
clearChunkedCookie(name);
|
||||
if (value == null || value === "") return;
|
||||
|
||||
const encoded = encodeURIComponent(value);
|
||||
if (encoded.length <= 3500) {
|
||||
writeRawCookie(name, encoded);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: string[] = [];
|
||||
for (let i = 0; i < encoded.length; i += CHUNK_SIZE) {
|
||||
chunks.push(encoded.slice(i, i + CHUNK_SIZE));
|
||||
}
|
||||
writeRawCookie(`${name}_n`, String(chunks.length));
|
||||
chunks.forEach((chunk, i) => writeRawCookie(`${name}_${i}`, chunk));
|
||||
}
|
||||
|
||||
function readCookie(name: string): string | null {
|
||||
const n = Number(readRawCookie(`${name}_n`) || "0");
|
||||
if (n > 0) {
|
||||
let encoded = "";
|
||||
for (let i = 0; i < n; i++) {
|
||||
const part = readRawCookie(`${name}_${i}`);
|
||||
if (part == null) return null;
|
||||
encoded += part;
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(encoded);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const raw = readRawCookie(name);
|
||||
if (raw == null) return null;
|
||||
try {
|
||||
return decodeURIComponent(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSharedAuthCookies(accessToken: string, refreshToken?: string) {
|
||||
writeCookie(SHARED_ACCESS_TOKEN_KEY, accessToken);
|
||||
if (refreshToken) writeCookie(SHARED_REFRESH_TOKEN_KEY, refreshToken);
|
||||
}
|
||||
|
||||
export function clearSharedAuthCookies() {
|
||||
writeCookie(SHARED_ACCESS_TOKEN_KEY, null);
|
||||
writeCookie(SHARED_REFRESH_TOKEN_KEY, null);
|
||||
}
|
||||
|
||||
export function readSharedAccessToken(): string | null {
|
||||
return readCookie(SHARED_ACCESS_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function readSharedRefreshToken(): string | null {
|
||||
return readCookie(SHARED_REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function hydrateLocalTokensFromSharedCookies(
|
||||
accessKey = SHARED_ACCESS_TOKEN_KEY,
|
||||
refreshKey = SHARED_REFRESH_TOKEN_KEY,
|
||||
): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (localStorage.getItem(accessKey)) return false;
|
||||
const access = readSharedAccessToken();
|
||||
if (!access) return false;
|
||||
localStorage.setItem(accessKey, access);
|
||||
const refresh = readSharedRefreshToken();
|
||||
if (refresh) localStorage.setItem(refreshKey, refresh);
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user