Add guest cart drawer, Continue handoff, and shared customer login.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
ad05241a77
commit
16340c3b48
@@ -0,0 +1,36 @@
|
|||||||
|
Build storefront cart UI + Continue handoff + shared customer login for this Meshkee website.
|
||||||
|
## Remote only
|
||||||
|
- Production Meshkee API and live site only — no localhost / local ports.
|
||||||
|
- Customer app: https://customer.<WEBSITE_DOMAIN>
|
||||||
|
- Business app: https://business.<WEBSITE_DOMAIN>
|
||||||
|
Production env:
|
||||||
|
NEXT_PUBLIC_API_BASE_URL=https://api.meshkee.com/api/v1
|
||||||
|
NEXT_PUBLIC_DOMAIN=<WEBSITE_DOMAIN>
|
||||||
|
NEXT_PUBLIC_CUSTOMER_ORIGIN=https://customer.<WEBSITE_DOMAIN>
|
||||||
|
NEXT_PUBLIC_BUSINESS_ORIGIN=https://business.<WEBSITE_DOMAIN>
|
||||||
|
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
Website only. Do not rebuild customer checkout, payment, addresses, or account pages — those are global on customer.<WEBSITE_DOMAIN>.
|
||||||
|
|
||||||
|
|
||||||
|
## Cart UI
|
||||||
|
- Header cart icon + count badge
|
||||||
|
- Popup/drawer: lines, quantity, remove, total, Continue
|
||||||
|
- Cart lines use store item variant id (not product id)
|
||||||
|
- Guest cart: localStorage key meshkee-guest-cart + cookie on .<WEBSITE_DOMAIN>
|
||||||
|
- Guest line: { id, name, slug?, price, quantity, image? } (id = variant id)
|
||||||
|
|
||||||
|
|
||||||
|
## Continue
|
||||||
|
- Logged in → customer.<WEBSITE_DOMAIN>/checkout/cart#guestCart=<base64url JSON>
|
||||||
|
- Guest → customer.<WEBSITE_DOMAIN>/login?redirect=/checkout/cart#guestCart=<base64url JSON>
|
||||||
|
- If no guest lines left, open /checkout/cart without the hash
|
||||||
|
|
||||||
|
|
||||||
|
## Shared session
|
||||||
|
- Cookies: meshkee_customer_access_token / meshkee_customer_refresh_token on .<WEBSITE_DOMAIN> (SameSite=Lax; chunk large tokens)
|
||||||
|
- Hydrate site session from those cookies
|
||||||
|
- ورود → customer login with redirect=/
|
||||||
|
- Logged in: "{firstName} عزیز" menu → profile, orders, logout; “مدیریت وبسایت” only for site admins → business app (handoff when available)
|
||||||
|
Match existing site design. Keep the change limited to cart popup, Continue handoff, and header auth.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
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,10 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
+7
-1
@@ -1,8 +1,10 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Carter_One, Oswald, Vazirmatn } from "next/font/google";
|
import { Carter_One, Oswald, Vazirmatn } from "next/font/google";
|
||||||
|
import { AppProviders } from "@/components/AppProviders";
|
||||||
import { Footer } from "@/components/Footer";
|
import { Footer } from "@/components/Footer";
|
||||||
import { Header } from "@/components/Header";
|
import { Header } from "@/components/Header";
|
||||||
import { TopHeader } from "@/components/TopHeader";
|
import { TopHeader } from "@/components/TopHeader";
|
||||||
|
import { getTenant } from "@/lib/api";
|
||||||
import { SITE } from "@/lib/site";
|
import { SITE } from "@/lib/site";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
@@ -30,14 +32,18 @@ export const metadata: Metadata = {
|
|||||||
description: SITE.aboutShort,
|
description: SITE.aboutShort,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({ children }: LayoutProps<"/">) {
|
export default async function RootLayout({ children }: LayoutProps<"/">) {
|
||||||
|
const tenant = await getTenant();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="fa" dir="rtl" className={`${vazir.variable} ${oswald.variable} ${carter.variable} h-full antialiased`}>
|
<html lang="fa" dir="rtl" className={`${vazir.variable} ${oswald.variable} ${carter.variable} h-full antialiased`}>
|
||||||
<body className="min-h-full flex flex-col bg-white text-ink">
|
<body className="min-h-full flex flex-col bg-white text-ink">
|
||||||
|
<AppProviders businessId={tenant ? String(tenant.id) : ""}>
|
||||||
<TopHeader />
|
<TopHeader />
|
||||||
<Header />
|
<Header />
|
||||||
<main className="flex-1">{children}</main>
|
<main className="flex-1">{children}</main>
|
||||||
<Footer />
|
<Footer />
|
||||||
|
</AppProviders>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState, type MouseEvent } from "react";
|
||||||
|
import { businessDashboardUrl, customerDashboardUrl } from "@/lib/customer";
|
||||||
|
import { useSession } from "@/lib/session";
|
||||||
|
import { IconChevron, IconUser } from "./Icons";
|
||||||
|
|
||||||
|
const itemClass =
|
||||||
|
"block w-full px-3 py-2.5 text-right text-sm text-ink transition-colors hover:bg-brand-soft hover:text-brand";
|
||||||
|
|
||||||
|
export 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 } = useSession();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const onClickOutside = (event: Event) => {
|
||||||
|
if (menuRef.current && event.target instanceof Node && !menuRef.current.contains(event.target)) {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={menuRef} className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen((value) => !value)}
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
className={`flex max-w-[12rem] items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-zinc-100 ${
|
||||||
|
compact ? "w-full justify-between px-0 hover:bg-transparent" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="flex min-w-0 items-center gap-2">
|
||||||
|
<IconUser />
|
||||||
|
<span className="truncate font-medium">
|
||||||
|
{displayName} عزیز
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<IconChevron className={`w-3.5 h-3.5 shrink-0 transition-transform ${open ? "rotate-90" : "-rotate-90"}`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div
|
||||||
|
role="menu"
|
||||||
|
className={`absolute z-50 mt-2 min-w-[11rem] overflow-hidden rounded-2xl border border-black/5 bg-white py-1 shadow-xl ${
|
||||||
|
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-brand hover:text-[#e51f1f]`}
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
onLogout();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
خروج
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { CartProvider } from "@/lib/cart";
|
||||||
|
import { SessionProvider } from "@/lib/session";
|
||||||
|
|
||||||
|
export function AppProviders({
|
||||||
|
children,
|
||||||
|
businessId,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
businessId: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SessionProvider businessId={businessId}>
|
||||||
|
<CartProvider>{children}</CartProvider>
|
||||||
|
</SessionProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { customerContinueCheckoutUrl } from "@/lib/customer";
|
||||||
|
import { useCart } from "@/lib/cart";
|
||||||
|
import { formatPrice } from "@/lib/format";
|
||||||
|
import { PLACEHOLDER } from "@/lib/data";
|
||||||
|
import { useSession } from "@/lib/session";
|
||||||
|
import { IconClose } from "./Icons";
|
||||||
|
import { Media } from "./Media";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CartPopup({ open, onClose }: Props) {
|
||||||
|
const { isAuthenticated } = useSession();
|
||||||
|
const { items, itemCount, total, removeItem, setQuantity } = useCart();
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
const continueHref = customerContinueCheckoutUrl(isAuthenticated, items);
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div>
|
||||||
|
<button type="button" className="fixed inset-0 z-[120] bg-black/40" aria-label="بستن" onClick={onClose} />
|
||||||
|
<div
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label="سبد خرید"
|
||||||
|
className="fixed inset-y-0 left-0 z-[130] flex h-dvh w-full max-w-md flex-col bg-white shadow-2xl"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between border-b border-black/5 px-5 py-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-base font-extrabold">سبد خرید</h2>
|
||||||
|
{itemCount > 0 && (
|
||||||
|
<p className="mt-0.5 text-xs text-zinc-400">
|
||||||
|
{itemCount.toLocaleString("fa-IR")} کالا
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="بستن"
|
||||||
|
className="grid size-9 place-items-center rounded-full hover:bg-zinc-100"
|
||||||
|
>
|
||||||
|
<IconClose className="w-4 h-4" />
|
||||||
|
</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 text-center">
|
||||||
|
<p className="text-sm text-zinc-500">سبد خرید شما خالی است</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{items.map((item) => (
|
||||||
|
<li key={item.id} className="flex gap-3 border-b border-black/5 pb-4 last:border-0">
|
||||||
|
<Link
|
||||||
|
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||||
|
onClick={onClose}
|
||||||
|
className="size-20 shrink-0 overflow-hidden rounded-xl border border-black/5"
|
||||||
|
>
|
||||||
|
<Media src={item.image || PLACEHOLDER.product} alt="" className="size-full" sizes="80px" />
|
||||||
|
</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-6 hover:text-brand"
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</Link>
|
||||||
|
<div className="mt-2 flex items-center justify-between gap-2">
|
||||||
|
<div className="flex items-center overflow-hidden rounded-lg border border-black/10">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="افزایش"
|
||||||
|
onClick={() => setQuantity(item.id, item.quantity + 1)}
|
||||||
|
className="grid size-8 place-items-center text-sm hover:bg-zinc-50"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
<span className="min-w-7 text-center text-xs font-bold">
|
||||||
|
{item.quantity.toLocaleString("fa-IR")}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="کاهش"
|
||||||
|
onClick={() => setQuantity(item.id, item.quantity - 1)}
|
||||||
|
className="grid size-8 place-items-center text-sm hover:bg-zinc-50"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-bold">
|
||||||
|
{formatPrice(item.price * item.quantity)}
|
||||||
|
<span className="mr-0.5 text-[11px] font-normal text-zinc-400">تومان</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeItem(item.id)}
|
||||||
|
aria-label="حذف"
|
||||||
|
className="grid size-8 place-items-center rounded-lg text-zinc-400 hover:bg-brand-soft hover:text-brand"
|
||||||
|
>
|
||||||
|
<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-black/5 px-5 py-4">
|
||||||
|
{items.length > 0 && (
|
||||||
|
<div className="mb-3 flex items-center justify-between text-sm">
|
||||||
|
<span className="text-zinc-500">جمع کل</span>
|
||||||
|
<span className="font-extrabold">
|
||||||
|
{formatPrice(total)}
|
||||||
|
<span className="mr-0.5 text-xs font-normal text-zinc-400">تومان</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{items.length > 0 ? (
|
||||||
|
<a
|
||||||
|
href={continueHref}
|
||||||
|
onClick={onClose}
|
||||||
|
className="flex w-full items-center justify-center rounded-xl bg-brand py-3 text-sm text-white hover:bg-[#e51f1f]"
|
||||||
|
>
|
||||||
|
ادامه
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="flex w-full items-center justify-center rounded-xl bg-brand-soft py-3 text-sm font-medium text-brand"
|
||||||
|
>
|
||||||
|
ادامه خرید
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
+44
-23
@@ -2,10 +2,14 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { useState } from "react";
|
||||||
import { cartCount } from "@/lib/cart";
|
import { customerLoginUrl } from "@/lib/customer";
|
||||||
import { parentCategories } from "@/lib/data";
|
import { parentCategories } from "@/lib/data";
|
||||||
import { SITE } from "@/lib/site";
|
import { SITE } from "@/lib/site";
|
||||||
|
import { useCart } from "@/lib/cart";
|
||||||
|
import { useSession } from "@/lib/session";
|
||||||
|
import { AccountMenu } from "./AccountMenu";
|
||||||
|
import { CartPopup } from "./CartPopup";
|
||||||
import { IconCart, IconChevron, IconClose, IconMenu, IconUser } from "./Icons";
|
import { IconCart, IconChevron, IconClose, IconMenu, IconUser } from "./Icons";
|
||||||
import { SearchBox } from "./SearchBox";
|
import { SearchBox } from "./SearchBox";
|
||||||
|
|
||||||
@@ -19,18 +23,11 @@ const nav = [
|
|||||||
export function Header() {
|
export function Header() {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [mega, setMega] = useState(false);
|
const [mega, setMega] = useState(false);
|
||||||
const [count, setCount] = useState(0);
|
const [cartOpen, setCartOpen] = useState(false);
|
||||||
|
const { itemCount } = useCart();
|
||||||
useEffect(() => {
|
const { isAuthenticated, user, logout, isWebsiteAdmin } = useSession();
|
||||||
const sync = () => setCount(cartCount());
|
const displayName = user?.firstName?.trim() || "حساب من";
|
||||||
sync();
|
const loginHref = customerLoginUrl("/");
|
||||||
window.addEventListener("cart-updated", sync);
|
|
||||||
window.addEventListener("storage", sync);
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener("cart-updated", sync);
|
|
||||||
window.removeEventListener("storage", sync);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-50 bg-white border-b border-black/5">
|
<header className="sticky top-0 z-50 bg-white border-b border-black/5">
|
||||||
@@ -95,19 +92,29 @@ export function Header() {
|
|||||||
<SearchBox className="hidden md:block ms-4 max-w-sm flex-1 rounded-full bg-zinc-100 px-3" />
|
<SearchBox className="hidden md:block ms-4 max-w-sm flex-1 rounded-full bg-zinc-100 px-3" />
|
||||||
|
|
||||||
<div className="flex items-center gap-2 ms-auto">
|
<div className="flex items-center gap-2 ms-auto">
|
||||||
<a
|
{isAuthenticated ? (
|
||||||
href={SITE.customerUrl}
|
<div className="hidden sm:block">
|
||||||
className="flex items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-zinc-100"
|
<AccountMenu displayName={displayName} isWebsiteAdmin={isWebsiteAdmin} onLogout={logout} />
|
||||||
>
|
</div>
|
||||||
|
) : (
|
||||||
|
<a href={loginHref} className="flex items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-zinc-100">
|
||||||
<IconUser />
|
<IconUser />
|
||||||
<span className="hidden sm:inline">ورود / ثبت نام</span>
|
<span className="hidden sm:inline">ورود / ثبت نام</span>
|
||||||
</a>
|
</a>
|
||||||
<Link href="/cart" className="relative grid place-items-center w-10 h-10 rounded-full hover:bg-zinc-100">
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCartOpen(true)}
|
||||||
|
aria-label={itemCount > 0 ? `سبد خرید، ${itemCount.toLocaleString("fa-IR")} کالا` : "سبد خرید"}
|
||||||
|
className="relative grid place-items-center w-10 h-10 rounded-full hover:bg-zinc-100"
|
||||||
|
>
|
||||||
<IconCart className="w-6 h-6 text-brand" />
|
<IconCart className="w-6 h-6 text-brand" />
|
||||||
<span className="absolute top-1 left-1 grid place-items-center w-4 h-4 rounded-full bg-brand text-[10px] text-white">
|
{itemCount > 0 && (
|
||||||
{count.toLocaleString("fa-IR")}
|
<span className="absolute top-1 left-1 grid place-items-center min-w-4 h-4 rounded-full bg-brand px-0.5 text-[10px] text-white">
|
||||||
|
{itemCount.toLocaleString("fa-IR")}
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
)}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -147,13 +154,27 @@ export function Header() {
|
|||||||
{item.name}
|
{item.name}
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
<a href={SITE.customerUrl} className="py-2">
|
{isAuthenticated ? (
|
||||||
|
<AccountMenu
|
||||||
|
displayName={displayName}
|
||||||
|
isWebsiteAdmin={isWebsiteAdmin}
|
||||||
|
compact
|
||||||
|
onLogout={() => {
|
||||||
|
logout();
|
||||||
|
setOpen(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<a href={loginHref} className="py-2">
|
||||||
ورود / ثبت نام
|
ورود / ثبت نام
|
||||||
</a>
|
</a>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<CartPopup open={cartOpen} onClose={() => setCartOpen(false)} />
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, type FormEvent } from "react";
|
import { useState, type FormEvent } from "react";
|
||||||
import type { ApiComment } from "@/lib/api";
|
import type { ApiComment } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/format";
|
import { formatDate } from "@/lib/format";
|
||||||
import { SITE } from "@/lib/site";
|
import { customerLoginUrl } from "@/lib/customer";
|
||||||
|
import { useSession } from "@/lib/session";
|
||||||
import { RichContent } from "./RichContent";
|
import { RichContent } from "./RichContent";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
@@ -23,26 +24,13 @@ const tabs: Tab[] = [
|
|||||||
{ id: "comments", fa: "نظرات", en: "Comments" },
|
{ id: "comments", fa: "نظرات", en: "Comments" },
|
||||||
];
|
];
|
||||||
|
|
||||||
function readToken() {
|
|
||||||
if (typeof window === "undefined") return "";
|
|
||||||
return (
|
|
||||||
window.localStorage.getItem("accessToken") ||
|
|
||||||
window.localStorage.getItem("meshkee_access_token") ||
|
|
||||||
""
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ProductTabs({ productId, descriptionHtml, comments: initialComments }: Props) {
|
export function ProductTabs({ productId, descriptionHtml, comments: initialComments }: Props) {
|
||||||
const [tab, setTab] = useState<"description" | "comments">("description");
|
const [tab, setTab] = useState<"description" | "comments">("description");
|
||||||
const [comments, setComments] = useState(initialComments);
|
const [comments, setComments] = useState(initialComments);
|
||||||
const [sent, setSent] = useState(false);
|
const [sent, setSent] = useState(false);
|
||||||
const [sending, setSending] = useState(false);
|
const [sending, setSending] = useState(false);
|
||||||
const [loggedIn, setLoggedIn] = useState(false);
|
const { isAuthenticated: loggedIn, user } = useSession();
|
||||||
const authorName = "کاربر";
|
const authorName = user?.firstName?.trim() || "کاربر";
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setLoggedIn(Boolean(readToken()));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
async function onSubmit(event: FormEvent<HTMLFormElement>) {
|
async function onSubmit(event: FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -157,7 +145,7 @@ export function ProductTabs({ productId, descriptionHtml, comments: initialComme
|
|||||||
<div className="rounded-xl bg-zinc-50 px-4 py-5 text-center">
|
<div className="rounded-xl bg-zinc-50 px-4 py-5 text-center">
|
||||||
<p className="text-sm text-zinc-600">برای ثبت نظر ابتدا وارد حساب کاربری شوید.</p>
|
<p className="text-sm text-zinc-600">برای ثبت نظر ابتدا وارد حساب کاربری شوید.</p>
|
||||||
<a
|
<a
|
||||||
href={SITE.customerUrl}
|
href={customerLoginUrl("/")}
|
||||||
className="mt-3 inline-block text-sm text-brand"
|
className="mt-3 inline-block text-sm text-brand"
|
||||||
>
|
>
|
||||||
ورود / ثبت نام
|
ورود / ثبت نام
|
||||||
|
|||||||
@@ -131,19 +131,20 @@ export function ProductView({ product, variants }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
disabled={!variant?.id}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
if (!variant?.id) return;
|
||||||
addToCart({
|
addToCart({
|
||||||
productId: product.id,
|
id: variant.id,
|
||||||
variantId: variant?.id,
|
|
||||||
slug: product.slug,
|
slug: product.slug,
|
||||||
name: product.nameFa || product.title,
|
name: product.nameFa || product.title,
|
||||||
image: images[0] || PLACEHOLDER.product,
|
image: images[0] || PLACEHOLDER.product,
|
||||||
price,
|
price,
|
||||||
qty,
|
quantity: qty,
|
||||||
});
|
});
|
||||||
setAdded(true);
|
setAdded(true);
|
||||||
}}
|
}}
|
||||||
className="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-brand px-5 py-2.5 text-sm text-white hover:bg-[#e51f1f]"
|
className="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-brand px-5 py-2.5 text-sm text-white hover:bg-[#e51f1f] disabled:opacity-60"
|
||||||
>
|
>
|
||||||
<IconCart className="w-5 h-5 text-white" />
|
<IconCart className="w-5 h-5 text-white" />
|
||||||
{added ? "به سبد اضافه شد" : "افزودن به سبد خرید"}
|
{added ? "به سبد اضافه شد" : "افزودن به سبد خرید"}
|
||||||
|
|||||||
+16
@@ -195,6 +195,22 @@ export async function getCategoryBySlug(slug: string) {
|
|||||||
return categories.find((category) => category.slug === slug) ?? null;
|
return categories.find((category) => category.slug === slug) ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ApiTenant = {
|
||||||
|
id: string | number;
|
||||||
|
name: string;
|
||||||
|
nameFa?: string | null;
|
||||||
|
slug?: string;
|
||||||
|
domain?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getTenant() {
|
||||||
|
try {
|
||||||
|
return await apiGet<ApiTenant>(`/tenants/${API.domain}`);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function getComments(entityType: "product" | "blog", entityId: string) {
|
export async function getComments(entityType: "product" | "blog", entityId: string) {
|
||||||
try {
|
try {
|
||||||
const data = await apiGet<{ items: ApiComment[] }>(`${tenant()}/comments`, { entityType, entityId });
|
const data = await apiGet<{ items: ApiComment[] }>(`${tenant()}/comments`, { entityType, entityId });
|
||||||
|
|||||||
-39
@@ -1,39 +0,0 @@
|
|||||||
export type CartItem = {
|
|
||||||
productId: string;
|
|
||||||
variantId?: string;
|
|
||||||
slug: string;
|
|
||||||
name: string;
|
|
||||||
image: string;
|
|
||||||
price: number;
|
|
||||||
qty: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const KEY = "salar-cart";
|
|
||||||
|
|
||||||
export function getCart(): CartItem[] {
|
|
||||||
if (typeof window === "undefined") return [];
|
|
||||||
try {
|
|
||||||
const raw = window.localStorage.getItem(KEY);
|
|
||||||
return raw ? (JSON.parse(raw) as CartItem[]) : [];
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function cartCount() {
|
|
||||||
return getCart().reduce((sum, item) => sum + item.qty, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function addToCart(item: CartItem) {
|
|
||||||
const cart = getCart();
|
|
||||||
const index = cart.findIndex(
|
|
||||||
(entry) => entry.productId === item.productId && entry.variantId === item.variantId,
|
|
||||||
);
|
|
||||||
if (index >= 0) {
|
|
||||||
cart[index] = { ...cart[index], qty: cart[index].qty + item.qty };
|
|
||||||
} else {
|
|
||||||
cart.push(item);
|
|
||||||
}
|
|
||||||
window.localStorage.setItem(KEY, JSON.stringify(cart));
|
|
||||||
window.dispatchEvent(new Event("cart-updated"));
|
|
||||||
}
|
|
||||||
+187
@@ -0,0 +1,187 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
|
import type { GuestCartLine } from "./customer";
|
||||||
|
|
||||||
|
export type CartItem = GuestCartLine;
|
||||||
|
|
||||||
|
const KEY = "meshkee-guest-cart";
|
||||||
|
const LEGACY_KEY = "salar-cart";
|
||||||
|
const CART_EVENT = "cart-updated";
|
||||||
|
|
||||||
|
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 unknown;
|
||||||
|
if (!Array.isArray(parsed)) return [];
|
||||||
|
return parsed
|
||||||
|
.map((entry) => normalizeLine(entry))
|
||||||
|
.filter((item): item is CartItem => Boolean(item));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLine(entry: unknown): CartItem | null {
|
||||||
|
if (!entry || typeof entry !== "object") return null;
|
||||||
|
const item = entry as Record<string, unknown>;
|
||||||
|
const id = String(item.id ?? item.variantId ?? item.storeItemVariantId ?? "").trim();
|
||||||
|
if (!id) return null;
|
||||||
|
const quantity = Math.max(1, Math.floor(Number(item.quantity ?? item.qty) || 1));
|
||||||
|
const price = Number(item.price) || 0;
|
||||||
|
const name = String(item.name ?? "محصول");
|
||||||
|
const slug = item.slug ? String(item.slug) : undefined;
|
||||||
|
const image = item.image != null && item.image !== "" ? String(item.image) : undefined;
|
||||||
|
return { id, name, ...(slug ? { slug } : {}), price, quantity, ...(image ? { image } : {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeSharedCookie(items: CartItem[]) {
|
||||||
|
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, quantity }) => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
slug,
|
||||||
|
price,
|
||||||
|
quantity,
|
||||||
|
image: null as string | null,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (encoded.length > 3500) return;
|
||||||
|
let cookie = `${KEY}=${encoded}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||||
|
if (domain) cookie += `; domain=${domain}`;
|
||||||
|
document.cookie = cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
function notify() {
|
||||||
|
window.dispatchEvent(new Event(CART_EVENT));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCart(): CartItem[] {
|
||||||
|
if (typeof window === "undefined") return [];
|
||||||
|
const primary = parseItems(window.localStorage.getItem(KEY));
|
||||||
|
if (primary.length > 0) return primary;
|
||||||
|
const legacy = parseItems(window.localStorage.getItem(LEGACY_KEY));
|
||||||
|
if (legacy.length > 0) {
|
||||||
|
writeCart(legacy);
|
||||||
|
window.localStorage.removeItem(LEGACY_KEY);
|
||||||
|
return legacy;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeCart(items: CartItem[]) {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
window.localStorage.setItem(KEY, JSON.stringify(items));
|
||||||
|
window.localStorage.removeItem(LEGACY_KEY);
|
||||||
|
try {
|
||||||
|
writeSharedCookie(items);
|
||||||
|
} catch {
|
||||||
|
// ignore cookie failures
|
||||||
|
}
|
||||||
|
notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cartCount() {
|
||||||
|
return getCart().reduce((sum, item) => sum + item.quantity, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cartTotal() {
|
||||||
|
return getCart().reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addToCart(item: CartItem) {
|
||||||
|
const cart = getCart();
|
||||||
|
const quantity = Math.max(1, Math.floor(item.quantity) || 1);
|
||||||
|
const index = cart.findIndex((entry) => entry.id === item.id);
|
||||||
|
if (index >= 0) {
|
||||||
|
cart[index] = {
|
||||||
|
...cart[index],
|
||||||
|
...item,
|
||||||
|
quantity: cart[index].quantity + quantity,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
cart.push({ ...item, quantity });
|
||||||
|
}
|
||||||
|
writeCart(cart);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCartQuantity(id: string, quantity: number) {
|
||||||
|
if (quantity < 1) {
|
||||||
|
writeCart(getCart().filter((item) => item.id !== id));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
writeCart(getCart().map((item) => (item.id === id ? { ...item, quantity } : item)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeFromCart(id: string) {
|
||||||
|
writeCart(getCart().filter((item) => item.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
type CartContextValue = {
|
||||||
|
items: CartItem[];
|
||||||
|
itemCount: number;
|
||||||
|
total: number;
|
||||||
|
addItem: (item: CartItem) => void;
|
||||||
|
removeItem: (id: string) => void;
|
||||||
|
setQuantity: (id: string, quantity: number) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CartContext = createContext<CartContextValue | null>(null);
|
||||||
|
|
||||||
|
export function CartProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [items, setItems] = useState<CartItem[]>([]);
|
||||||
|
|
||||||
|
const sync = useCallback(() => setItems(getCart()), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
sync();
|
||||||
|
window.addEventListener(CART_EVENT, sync);
|
||||||
|
window.addEventListener("storage", sync);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(CART_EVENT, sync);
|
||||||
|
window.removeEventListener("storage", sync);
|
||||||
|
};
|
||||||
|
}, [sync]);
|
||||||
|
|
||||||
|
const addItem = useCallback((item: CartItem) => addToCart(item), []);
|
||||||
|
const removeItem = useCallback((id: string) => removeFromCart(id), []);
|
||||||
|
const setQuantity = useCallback((id: string, quantity: number) => setCartQuantity(id, quantity), []);
|
||||||
|
|
||||||
|
const itemCount = useMemo(() => items.reduce((sum, item) => sum + item.quantity, 0), [items]);
|
||||||
|
const total = useMemo(() => items.reduce((sum, item) => sum + item.price * item.quantity, 0), [items]);
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({ items, itemCount, total, addItem, removeItem, setQuantity }),
|
||||||
|
[items, itemCount, total, addItem, removeItem, setQuantity],
|
||||||
|
);
|
||||||
|
|
||||||
|
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,59 @@
|
|||||||
|
import { BUSINESS_ORIGIN, CUSTOMER_ORIGIN } from "./site";
|
||||||
|
|
||||||
|
export const GUEST_CART_URL_PARAM = "guestCart";
|
||||||
|
|
||||||
|
export type GuestCartLine = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
slug?: string;
|
||||||
|
price: number;
|
||||||
|
quantity: number;
|
||||||
|
image?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function encodeGuestCartForUrl(items: GuestCartLine[]): string {
|
||||||
|
const payload = items.map(({ id, name, slug, price, quantity, image }) => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
...(slug ? { slug } : {}),
|
||||||
|
price,
|
||||||
|
quantity,
|
||||||
|
image: image ?? null,
|
||||||
|
}));
|
||||||
|
const json = JSON.stringify(payload);
|
||||||
|
return btoa(unescape(encodeURIComponent(json)))
|
||||||
|
.replace(/\+/g, "-")
|
||||||
|
.replace(/\//g, "_")
|
||||||
|
.replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function customerDashboardUrl(path = "/"): string {
|
||||||
|
const normalized = path.startsWith("/") ? path : `/${path}`;
|
||||||
|
return `${CUSTOMER_ORIGIN}${normalized}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function businessDashboardUrl(): string {
|
||||||
|
return `${BUSINESS_ORIGIN}/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function customerLoginUrl(redirectPath = "/", cartItems?: GuestCartLine[]): string {
|
||||||
|
let redirect = redirectPath.startsWith("/") ? redirectPath : `/${redirectPath}`;
|
||||||
|
if (cartItems && cartItems.length > 0) {
|
||||||
|
const join = redirect.includes("#") ? "&" : "#";
|
||||||
|
redirect = `${redirect}${join}${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
||||||
|
}
|
||||||
|
const url = new URL("/login", CUSTOMER_ORIGIN);
|
||||||
|
url.searchParams.set("redirect", redirect);
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function customerContinueCheckoutUrl(isAuthenticated: boolean, cartItems: GuestCartLine[] = []): 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,42 @@
|
|||||||
|
import { API } from "./site";
|
||||||
|
|
||||||
|
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(`${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 function jsonResponse(data: unknown, status = 200) {
|
||||||
|
return Response.json(data, { status });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unauthorizedResponse() {
|
||||||
|
return jsonResponse({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
+175
@@ -0,0 +1,175 @@
|
|||||||
|
"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 "./shared-auth-cookie";
|
||||||
|
|
||||||
|
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 SessionContextValue = {
|
||||||
|
user: AuthUser | null;
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
ready: boolean;
|
||||||
|
businessId: string;
|
||||||
|
isWebsiteAdmin: boolean;
|
||||||
|
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((business) => ({
|
||||||
|
id: String(business.id),
|
||||||
|
name: business.name,
|
||||||
|
slug: business.slug,
|
||||||
|
isOwner: Boolean(business.isOwner),
|
||||||
|
teamRole: business.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(
|
||||||
|
(business) => String(business.id) === String(businessId) && (business.isOwner || Boolean(business.teamRole)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const SessionContext = createContext<SessionContextValue | 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SessionProvider({
|
||||||
|
children,
|
||||||
|
businessId,
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
businessId: string;
|
||||||
|
}) {
|
||||||
|
const [user, setUser] = useState<AuthUser | null>(null);
|
||||||
|
const [ready, setReady] = useState(false);
|
||||||
|
|
||||||
|
const getAccessToken = useCallback(() => {
|
||||||
|
hydrateLocalTokensFromSharedCookies(SHARED_ACCESS_TOKEN_KEY, SHARED_REFRESH_TOKEN_KEY);
|
||||||
|
return readToken(SHARED_ACCESS_TOKEN_KEY);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const clearTokens = useCallback(() => {
|
||||||
|
writeToken(SHARED_ACCESS_TOKEN_KEY, null);
|
||||||
|
writeToken(SHARED_REFRESH_TOKEN_KEY, null);
|
||||||
|
writeToken("accessToken", null);
|
||||||
|
writeToken("meshkee_access_token", null);
|
||||||
|
clearSharedAuthCookies();
|
||||||
|
setUser(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (!token) {
|
||||||
|
setReady(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const refresh = readToken(SHARED_REFRESH_TOKEN_KEY);
|
||||||
|
writeSharedAuthCookies(token, refresh ?? undefined);
|
||||||
|
|
||||||
|
fetch("/api/auth/me", { headers: { Authorization: `Bearer ${token}` } })
|
||||||
|
.then(async (res) => {
|
||||||
|
if (res.status === 401) {
|
||||||
|
clearTokens();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!res.ok) return;
|
||||||
|
const data = (await res.json()) as { user?: AuthUser } & AuthUser;
|
||||||
|
const next = normalizeUser(data.user ?? data);
|
||||||
|
if (next) setUser(next);
|
||||||
|
})
|
||||||
|
.catch(() => undefined)
|
||||||
|
.finally(() => setReady(true));
|
||||||
|
}, [clearTokens, getAccessToken]);
|
||||||
|
|
||||||
|
const logout = useCallback(() => {
|
||||||
|
clearTokens();
|
||||||
|
}, [clearTokens]);
|
||||||
|
|
||||||
|
const isWebsiteAdmin = useMemo(() => isWebsiteAdminForBusiness(user, businessId), [user, businessId]);
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({
|
||||||
|
user,
|
||||||
|
isAuthenticated: Boolean(user),
|
||||||
|
ready,
|
||||||
|
businessId,
|
||||||
|
isWebsiteAdmin,
|
||||||
|
logout,
|
||||||
|
getAccessToken,
|
||||||
|
}),
|
||||||
|
[user, ready, businessId, isWebsiteAdmin, logout, getAccessToken],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSession() {
|
||||||
|
const ctx = useContext(SessionContext);
|
||||||
|
if (!ctx) throw new Error("useSession must be used within SessionProvider");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
+9
-3
@@ -1,16 +1,22 @@
|
|||||||
export const DOMAIN = "salarstore.com";
|
export const DOMAIN = process.env.NEXT_PUBLIC_DOMAIN || "salarstore.com";
|
||||||
|
|
||||||
export const API = {
|
export const API = {
|
||||||
base: "https://api.meshkee.com/api/v1",
|
base: process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") || "https://api.meshkee.com/api/v1",
|
||||||
domain: DOMAIN,
|
domain: DOMAIN,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const CUSTOMER_ORIGIN =
|
||||||
|
process.env.NEXT_PUBLIC_CUSTOMER_ORIGIN?.replace(/\/$/, "") || `https://customer.${DOMAIN}`;
|
||||||
|
|
||||||
|
export const BUSINESS_ORIGIN =
|
||||||
|
process.env.NEXT_PUBLIC_BUSINESS_ORIGIN?.replace(/\/$/, "") || `https://business.${DOMAIN}`;
|
||||||
|
|
||||||
export const SITE = {
|
export const SITE = {
|
||||||
nameFa: "سالار استور",
|
nameFa: "سالار استور",
|
||||||
nameEn: "SALAR STORE",
|
nameEn: "SALAR STORE",
|
||||||
tagline: "فروشگاه لوازم ورزشی و کوهنوردی",
|
tagline: "فروشگاه لوازم ورزشی و کوهنوردی",
|
||||||
domain: DOMAIN,
|
domain: DOMAIN,
|
||||||
customerUrl: `https://customer.${DOMAIN}`,
|
customerUrl: CUSTOMER_ORIGIN,
|
||||||
phone: "09127491700",
|
phone: "09127491700",
|
||||||
phoneDisplay: "0912 749 1700",
|
phoneDisplay: "0912 749 1700",
|
||||||
address: "قم، بسیج (هنرستان)، نبش کوچه ۹",
|
address: "قم، بسیج (هنرستان)، نبش کوچه ۹",
|
||||||
|
|||||||
Reference in New Issue
Block a user