Revert to guest-cart architecture, drop in-site auth/checkout
Per api.meshkee.com/docs/website/AI_PROMPT.md's hard rules (which an
earlier pass on this branch missed): login, register, OTP, the real
cart, addresses, and payment are the customer dashboard's job
(customer.sanihome.ir), not this storefront's. This site should only
ever run a local guest mini-cart and hand off to the dashboard.
- Remove: AuthContext, LoginModal, lib/auth.ts, lib/cart.ts (the real
/businesses/{id}/cart integration), and the /checkout page entirely.
- Add lib/guestCart.ts: localStorage + shared cookie
(meshkee-guest-cart, Domain=.sanihome.ir) cart, storeItemVariantId
keyed, matching the spec's line shape and ~3500-char cookie-size
cutoff.
- CartContext is now a thin React wrapper over the guest cart (no
server round-trip, so add/update/remove are synchronous); CartPopup's
"Continue" builds the exact customer.sanihome.ir/checkout/cart
(or /login?redirect=...) URL from the spec, base64url-encoding the
cart and detecting an existing dashboard session via the shared
meshkee_customer_access_token cookie.
- ProductCard and ProductPurchasePanel add to the guest cart directly;
no login gate on add-to-cart anymore.
- Comments panel is a plain guest name/email/text form again (the
comments API never required auth — gating it on the now-removed
login system was wrong regardless).
- CONTEXT.md rewritten to document the guest-cart contract explicitly
and flag this exact mistake so it doesn't get reintroduced.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
053a9ba361
commit
5152b16d61
+70
-80
@@ -51,81 +51,72 @@ before touching App Router APIs you're not 100% sure of.
|
||||
because different endpoints shape the "same" concept differently (see
|
||||
Data quirks below). Prefer extending an existing `normalize*`/type over
|
||||
adding a parallel one.
|
||||
- **`auth.ts`** — client-only (uses `localStorage`) Meshkee customer auth:
|
||||
register/login/OTP/refresh. Access tokens last **~15 minutes** — this is
|
||||
short enough that you *will* hit expiry during normal use, so every
|
||||
authenticated call must self-heal (see Auth below), not just fail.
|
||||
- **`cart.ts`** — cart/checkout, needs a Bearer token + `businessId`
|
||||
(`GET /tenants/{domain}` and `.../website/business-info` both return the
|
||||
same numeric id as their `id` field — `getBusinessInfo().id` is enough,
|
||||
no separate tenant-resolve call needed).
|
||||
- **`guestCart.ts`** — the storefront's entire cart story (see next
|
||||
section). No token, no backend call, no `businessId` — just
|
||||
`localStorage` + a shared cookie.
|
||||
|
||||
## Auth
|
||||
## Auth, cart & checkout: this site does none of it
|
||||
|
||||
Real in-site login (not a redirect to `customer.sanihome.ir` — that link
|
||||
still exists in the header/footer as a legacy "ورود" pointer but is
|
||||
independent of this system). `AuthProvider` (`src/context/AuthContext.tsx`)
|
||||
+ `LoginModal` (`src/components/auth/LoginModal.tsx`), mounted once in
|
||||
`src/context/Providers.tsx` inside the root layout.
|
||||
**This was built wrong once already** — an earlier pass added real in-site
|
||||
login (password/OTP), a real backend cart (`/businesses/{businessId}/cart`),
|
||||
and a `/checkout` page. That's explicitly **not** how Meshkee storefronts
|
||||
work, per `https://api.meshkee.com/docs/website/AI_PROMPT.md`'s hard rules:
|
||||
login, register, OTP, the real cart, addresses, and payment all belong to
|
||||
**`https://customer.<domain>`** (the customer dashboard) — a *separate app*,
|
||||
not a page on this site. If you're about to add a `/login`, `/register`,
|
||||
`/checkout`, `/cart`, or `/account` route, or call `/auth/*` or
|
||||
`/businesses/{id}/cart*` from this codebase: **stop, re-read the AI_PROMPT.md
|
||||
"Shopping cart on the storefront" and "Shared login" sections first.**
|
||||
|
||||
- Login methods: password (`POST /auth/login`) and SMS OTP
|
||||
(`POST /auth/send-otp` → `POST /auth/login-otp`). Register:
|
||||
`POST /auth/register` (requires `domain: "sanihome.ir"`).
|
||||
- **Confirmed live response shape** (undocumented in OpenAPI, verified by
|
||||
actually registering a test account): `{ accessToken, refreshToken, user }`
|
||||
from register/login/login-otp/refresh alike. `GET /auth/me` returns `{ user }`.
|
||||
- **Password login requires a verified phone number**
|
||||
(`cellNumber is not verified` 401) — a freshly-registered account can still
|
||||
use the tokens *from that register response* immediately, but if the
|
||||
session is lost before verifying, password login is blocked until OTP
|
||||
verification. There's no verify-OTP UI built yet (see Known gaps).
|
||||
- **Token refresh race**: `AuthContext` and `CartContext` each independently
|
||||
notice a 401 and try to refresh. Without coordination this fires two
|
||||
concurrent `/auth/refresh` calls and the second one fails (likely
|
||||
refresh-token rotation server-side) — observed as 500/400 errors. Fixed
|
||||
with an in-flight-promise singleton in `auth.ts`'s `refreshAccessToken()`
|
||||
— **do not** add another independent refresh call anywhere; always go
|
||||
through that function.
|
||||
- `cart.ts` functions take no token parameter — they read the freshest token
|
||||
from storage internally and self-refresh-and-retry once on 401. Gate UI on
|
||||
`useAuth().user` (session identity), not on a captured `accessToken` value.
|
||||
|
||||
## Cart & checkout
|
||||
|
||||
`CartProvider` (`src/context/CartContext.tsx`) fetches the real backend cart
|
||||
whenever `user` changes and exposes `addItem/updateItem/removeItem/refresh`.
|
||||
`CartButton` + `CartPopup` (`src/components/cart/`) live in the header via
|
||||
`Providers`. `/checkout` (`src/app/checkout/page.tsx`) posts to
|
||||
`POST /businesses/{businessId}/cart/checkout` with `payment.type` of `cash`
|
||||
or `transfer` only — no online payment gateway (Zarinpal/Mellat/etc.) is
|
||||
wired up, by explicit scope decision (see Known gaps).
|
||||
|
||||
**Important:** a successful checkout clears the cart server-side. Any flow
|
||||
that calls `checkout()` must also call `useCart().refresh()` afterward, or
|
||||
the header badge and cart state go stale until next reload.
|
||||
|
||||
**Which store-item variant does "add to cart" target?**
|
||||
- On the product/store-item **detail** pages, `ProductPurchasePanel` always
|
||||
resolves a `matchedVariant` from `storeVariants` (even for a single-SKU
|
||||
product with no selectable variations — it just uses the one variant) and
|
||||
adds `matchedVariant.id`.
|
||||
- On **cards** (`ProductCard`), only sources that already carry a specific
|
||||
variant id can quick-add: `Product.variantId`, populated in
|
||||
`normalizeProduct` from `raw.variants[0].id` (store-specials, brand-groups).
|
||||
Cards from the plain `/products` list endpoint have no variant info, so the
|
||||
button renders as a link to the detail page instead of a cart action —
|
||||
never fabricate a variant id to force a quick-add.
|
||||
- **Detecting a logged-in shopper**: read the `meshkee_customer_access_token`
|
||||
cookie (written by the customer dashboard with `Domain=.sanihome.ir`, so
|
||||
it's readable here too) — see `isCustomerLoggedIn()` in `guestCart.ts`.
|
||||
Never build a login UI or call `/auth/login` from this site.
|
||||
- **Guest cart** (`guestCart.ts`): lines are
|
||||
`{ id, name, slug, price, originalPrice?, image, quantity }` where `id` is
|
||||
always a `storeItemVariantId` — never a product id or store-item id.
|
||||
Persisted to `localStorage` (key `meshkee-guest-cart`) **and** a cookie of
|
||||
the same name (`Domain=.sanihome.ir`, skipped if the encoded JSON is
|
||||
>~3500 chars — rely on the URL param instead). `CartProvider`
|
||||
(`src/context/CartContext.tsx`) just wraps this in React state; there is
|
||||
no server round-trip, so `addItem`/`updateItem`/`removeItem` are
|
||||
synchronous.
|
||||
- **"Continue" in the mini-cart** (`CartPopup`) builds a URL with
|
||||
`continueToCheckoutUrl()`: the guest cart, base64url-encoded (exact
|
||||
algorithm from the spec) into a `guestCart` query param, pointed at
|
||||
`https://customer.sanihome.ir/checkout/cart?guestCart=...` if the shopper
|
||||
looks logged in, or `.../login?redirect=...` (wrapping that same cart URL)
|
||||
if not. The dashboard is responsible for decoding it and syncing it into
|
||||
the real server cart after login — this site's job ends at building that
|
||||
URL correctly.
|
||||
- **Which variant does "add to cart" target?**
|
||||
- On the product/store-item **detail** pages, `ProductPurchasePanel`
|
||||
resolves a `matchedVariant` from `storeVariants` (even for a single-SKU
|
||||
product with no selectable variations — it just uses the one variant)
|
||||
and adds `matchedVariant.id`.
|
||||
- On **cards** (`ProductCard`), only sources that already carry a specific
|
||||
variant id can quick-add: `Product.variantId`, populated in
|
||||
`normalizeProduct` from `raw.variants[0].id` (store-specials,
|
||||
brand-groups). Cards from the plain `/products` list endpoint have no
|
||||
variant info, so the button links to the detail page instead — never
|
||||
fabricate a variant id to force a quick-add.
|
||||
- The spec's fuller flow (`GET /store-items/by-product/{productId}`,
|
||||
then: hide the button if no in-stock variant exists, force a picker
|
||||
when more than one is in stock) isn't separately re-implemented per
|
||||
card — the existing variation-picker UI on the detail page already
|
||||
satisfies "shopper must choose before adding."
|
||||
|
||||
## Comments
|
||||
|
||||
`GET/POST /tenants/{domain}/comments` needs no auth on Meshkee's side
|
||||
(`authorName`/`authorEmail` are plain body fields) — the login requirement is
|
||||
a **product decision by this site**, not an API constraint. Gate the comment
|
||||
form in `ProductTabs`' comments panel on `useAuth().user`; when posting, use
|
||||
the logged-in user's name/email. `GET /comments` only returns **approved**
|
||||
comments, so a freshly-posted comment won't reappear on refetch until an
|
||||
admin approves it — the UI appends it optimistically to local state instead
|
||||
of re-fetching, which is correct, not a bug.
|
||||
`GET/POST /tenants/{domain}/comments` needs no auth on Meshkee's side —
|
||||
`authorName`/`authorEmail` are plain body fields, same as the contact form.
|
||||
`ProductTabs`' comments panel is a guest name+email(optional)+text form, no
|
||||
login involved (this also isn't gated on the dashboard cookie — keep it
|
||||
that way; there's no reason to require a customer-dashboard session just to
|
||||
leave a comment). `GET /comments` only returns **approved** comments, so a
|
||||
freshly-posted comment won't reappear on refetch until an admin approves it
|
||||
— the UI appends it optimistically to local state instead of re-fetching,
|
||||
which is correct, not a bug.
|
||||
|
||||
## Data quirks (verified against the live catalog)
|
||||
|
||||
@@ -213,18 +204,17 @@ else the pre-existing UI unchanged).
|
||||
| `/products/id/[id]` | Redirect-only resolver, see "Group-source id vs productId" above |
|
||||
| `/store-items`, `/store-items/[id]` | Variant-level browsing/detail, see above |
|
||||
| `/blog`, `/blog/[slug]` | Blog listing/detail |
|
||||
| `/checkout` | Cart → order, cash/transfer only |
|
||||
| `/contact` | Contact form → `POST /contact-submissions`, toast + reset on success |
|
||||
|
||||
No `/login`, `/register`, `/checkout`, `/cart`, or `/account` route exists
|
||||
here on purpose — see "Auth, cart & checkout" above.
|
||||
|
||||
## Known gaps / explicit scope decisions
|
||||
|
||||
- No OTP-verification UI for a registered-but-unverified phone number — if a
|
||||
returning shopper's session is lost pre-verification, password login fails
|
||||
with a clear error but there's no in-app way to complete verification yet
|
||||
(OTP *login* still works as a workaround).
|
||||
- No online payment gateway integration (Zarinpal/Mellat/etc.) — checkout
|
||||
only supports cash-on-delivery and bank transfer, by explicit user choice
|
||||
over building the bank-redirect + return-URL callback flow.
|
||||
- A throwaway test customer account exists in the live business database
|
||||
from building/verifying this integration: `+989120000001` / "Test Dev".
|
||||
Safe to delete from the Meshkee admin panel.
|
||||
- Login, registration, OTP, the real cart, addresses, and payment are all
|
||||
out of scope for this codebase by design — they live on
|
||||
`customer.sanihome.ir`. Don't reintroduce them here.
|
||||
- A throwaway test customer account was created against the live business
|
||||
database while an earlier (since-reverted) pass tested a real backend
|
||||
cart: `+989120000001` / "Test Dev". Safe to delete from the Meshkee admin
|
||||
panel — it's not used by anything in this codebase anymore.
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||
import { EmptyState } from "@/components/ui/EmptyState";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useCart } from "@/context/CartContext";
|
||||
import { checkout, type Order } from "@/lib/cart";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
|
||||
type PaymentType = "cash" | "transfer";
|
||||
|
||||
const inputClass =
|
||||
"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red";
|
||||
|
||||
export default function CheckoutPage() {
|
||||
const { user, openLoginModal } = useAuth();
|
||||
const { cart, businessId, refresh } = useCart();
|
||||
const [province, setProvince] = useState("");
|
||||
const [city, setCity] = useState("");
|
||||
const [address, setAddress] = useState("");
|
||||
const [postalCode, setPostalCode] = useState("");
|
||||
const [paymentType, setPaymentType] = useState<PaymentType>("cash");
|
||||
const [transferRefNumber, setTransferRefNumber] = useState("");
|
||||
const [customerNotes, setCustomerNotes] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [order, setOrder] = useState<Order | null>(null);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await checkout(businessId, {
|
||||
shippingAddress: { province, city, address, postalCode: postalCode || undefined },
|
||||
customerNotes: customerNotes || undefined,
|
||||
payment:
|
||||
paymentType === "transfer"
|
||||
? { type: "transfer", transferRefNumber: transferRefNumber || undefined }
|
||||
: { type: "cash" },
|
||||
});
|
||||
setBusy(false);
|
||||
if (!res.ok) {
|
||||
setError(res.message);
|
||||
return;
|
||||
}
|
||||
setOrder(res.data);
|
||||
refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-4 py-10">
|
||||
<Breadcrumb items={[{ label: "خانه", href: "/" }, { label: "تسویه حساب" }]} />
|
||||
<h1 className="mb-6 text-2xl font-bold text-red-dark">تسویه حساب</h1>
|
||||
|
||||
{!user ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-surface p-5">
|
||||
<span className="text-sm text-muted">برای تسویه حساب باید وارد حساب کاربری خود شوید.</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={openLoginModal}
|
||||
className="rounded-lg bg-red px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
ورود
|
||||
</button>
|
||||
</div>
|
||||
) : order ? (
|
||||
<div className="rounded-xl border border-green-200 bg-green-50 p-6 text-center">
|
||||
<p className="mb-2 text-lg font-bold text-green-800">سفارش شما با موفقیت ثبت شد ✓</p>
|
||||
<p className="mb-1 text-sm text-green-700">شماره سفارش: {order.orderNumber}</p>
|
||||
<p className="text-sm text-green-700">
|
||||
مبلغ کل: {formatPrice(order.total)} تومان
|
||||
</p>
|
||||
<a href="/" className="mt-4 inline-block text-sm font-medium text-red hover:text-red-dark">
|
||||
بازگشت به فروشگاه ←
|
||||
</a>
|
||||
</div>
|
||||
) : !cart || cart.items.length === 0 ? (
|
||||
<EmptyState message="سبد خرید شما خالی است." />
|
||||
) : (
|
||||
<div className="grid gap-8 md:grid-cols-3">
|
||||
<form onSubmit={handleSubmit} className="space-y-4 md:col-span-2">
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-bold">آدرس ارسال</h2>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<input
|
||||
required
|
||||
placeholder="استان"
|
||||
value={province}
|
||||
onChange={(e) => setProvince(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
<input
|
||||
required
|
||||
placeholder="شهر"
|
||||
value={city}
|
||||
onChange={(e) => setCity(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
required
|
||||
rows={2}
|
||||
placeholder="آدرس کامل"
|
||||
value={address}
|
||||
onChange={(e) => setAddress(e.target.value)}
|
||||
className={`${inputClass} mt-3`}
|
||||
/>
|
||||
<input
|
||||
placeholder="کد پستی (اختیاری)"
|
||||
value={postalCode}
|
||||
onChange={(e) => setPostalCode(e.target.value)}
|
||||
className={`${inputClass} mt-3`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-bold">روش پرداخت</h2>
|
||||
<div className="space-y-2">
|
||||
<label className="flex items-center gap-2 rounded-lg border border-border p-3 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="payment"
|
||||
checked={paymentType === "cash"}
|
||||
onChange={() => setPaymentType("cash")}
|
||||
/>
|
||||
پرداخت در محل (نقدی)
|
||||
</label>
|
||||
<label className="flex items-center gap-2 rounded-lg border border-border p-3 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="payment"
|
||||
checked={paymentType === "transfer"}
|
||||
onChange={() => setPaymentType("transfer")}
|
||||
/>
|
||||
کارت به کارت / واریز بانکی
|
||||
</label>
|
||||
{paymentType === "transfer" && (
|
||||
<input
|
||||
placeholder="شماره پیگیری واریز (اختیاری)"
|
||||
value={transferRefNumber}
|
||||
onChange={(e) => setTransferRefNumber(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
rows={2}
|
||||
placeholder="توضیحات سفارش (اختیاری)"
|
||||
value={customerNotes}
|
||||
onChange={(e) => setCustomerNotes(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
|
||||
{error && <p className="text-sm text-red-dark">{error}</p>}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
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:opacity-60"
|
||||
>
|
||||
{busy ? "در حال ثبت سفارش..." : "ثبت نهایی سفارش"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="rounded-xl border border-border bg-surface p-5">
|
||||
<h2 className="mb-4 text-sm font-bold">خلاصه سفارش</h2>
|
||||
<ul className="mb-4 space-y-2 text-sm">
|
||||
{cart.items.map((item) => (
|
||||
<li key={item.id} className="flex items-center justify-between gap-2">
|
||||
<span className="line-clamp-1 text-muted">
|
||||
{item.productNameFa ?? item.productTitle} × {item.quantity}
|
||||
</span>
|
||||
<span className="shrink-0 font-medium">{formatPrice(item.lineTotal)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex items-center justify-between border-t border-border pt-3 text-sm font-bold">
|
||||
<span>جمع کل</span>
|
||||
<span className="text-red-dark">
|
||||
{formatPrice(cart.subtotal)}
|
||||
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -46,7 +46,7 @@ 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">
|
||||
<Providers businessId={businessInfo?.id ?? "1"}>
|
||||
<Providers>
|
||||
<TopBar />
|
||||
<Header categoryTree={categoryTree} categories={categories} />
|
||||
<main>{children}</main>
|
||||
|
||||
@@ -74,6 +74,9 @@ export default async function ProductDetailPage({
|
||||
inStock={product.inStock}
|
||||
contactPhone={contactPhone}
|
||||
storeName={businessInfo?.nameFa}
|
||||
productName={product.name}
|
||||
productSlug={product.slug}
|
||||
productImage={product.image ?? images[0] ?? ""}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ export default async function ProductsPage({
|
||||
fluid
|
||||
contactPhone={contactPhone}
|
||||
variantId={product.variantId}
|
||||
slug={product.slug}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -83,6 +83,9 @@ export default async function StoreItemDetailPage({
|
||||
contactPhone={contactPhone}
|
||||
storeName={businessInfo?.nameFa}
|
||||
initialSelections={initialSelections}
|
||||
productName={product.name}
|
||||
productSlug={product.slug}
|
||||
productImage={product.image ?? images[0] ?? ""}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
type Mode = "login" | "register";
|
||||
type LoginMethod = "password" | "otp";
|
||||
|
||||
function CloseIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="none" className="h-5 w-5" aria-hidden>
|
||||
<path
|
||||
d="M6 6l12 12M18 6 6 18"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const inputClass =
|
||||
"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red";
|
||||
|
||||
export function LoginModal() {
|
||||
const { loginModalOpen, closeLoginModal, login, loginOtp, sendOtp, register } = useAuth();
|
||||
const [mode, setMode] = useState<Mode>("login");
|
||||
const [method, setMethod] = useState<LoginMethod>("password");
|
||||
const [cellNumber, setCellNumber] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
const [otpSent, setOtpSent] = useState(false);
|
||||
const [firstName, setFirstName] = useState("");
|
||||
const [lastName, setLastName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loginModalOpen) {
|
||||
setError(null);
|
||||
setBusy(false);
|
||||
setOtpSent(false);
|
||||
setCode("");
|
||||
setPassword("");
|
||||
}
|
||||
}, [loginModalOpen]);
|
||||
|
||||
if (!loginModalOpen) return null;
|
||||
|
||||
const normalizedCell = cellNumber.trim();
|
||||
|
||||
const handleSendOtp = async () => {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
const res = await sendOtp(normalizedCell);
|
||||
setBusy(false);
|
||||
if (!res.ok) return setError(res.message ?? "ارسال کد ناموفق بود.");
|
||||
setOtpSent(true);
|
||||
};
|
||||
|
||||
const handleLoginSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
const res =
|
||||
method === "password" ? await login(normalizedCell, password) : await loginOtp(normalizedCell, code);
|
||||
setBusy(false);
|
||||
if (!res.ok) setError(res.message ?? "ورود ناموفق بود.");
|
||||
};
|
||||
|
||||
const handleRegisterSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
const res = await register({
|
||||
cellNumber: normalizedCell,
|
||||
password,
|
||||
firstName,
|
||||
lastName,
|
||||
email: email || undefined,
|
||||
});
|
||||
setBusy(false);
|
||||
if (!res.ok) setError(res.message ?? "ثبتنام ناموفق بود.");
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={closeLoginModal}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-sm rounded-2xl bg-surface p-6 shadow-xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="mb-5 flex items-center justify-between">
|
||||
<h2 className="text-lg font-bold">{mode === "login" ? "ورود به حساب کاربری" : "ثبتنام"}</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeLoginModal}
|
||||
aria-label="بستن"
|
||||
className="text-muted transition-colors hover:text-foreground"
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{mode === "login" ? (
|
||||
<>
|
||||
<div className="mb-4 flex gap-2 rounded-lg bg-background p-1 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMethod("password")}
|
||||
className={`flex-1 rounded-md py-1.5 transition-colors ${
|
||||
method === "password" ? "bg-surface font-medium text-red-dark shadow-sm" : "text-muted"
|
||||
}`}
|
||||
>
|
||||
رمز عبور
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMethod("otp")}
|
||||
className={`flex-1 rounded-md py-1.5 transition-colors ${
|
||||
method === "otp" ? "bg-surface font-medium text-red-dark shadow-sm" : "text-muted"
|
||||
}`}
|
||||
>
|
||||
کد یکبار مصرف
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleLoginSubmit} className="space-y-3">
|
||||
<input
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
required
|
||||
placeholder="شماره موبایل (مثلاً +989121234567)"
|
||||
value={cellNumber}
|
||||
onChange={(e) => setCellNumber(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
|
||||
{method === "password" ? (
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
placeholder="رمز عبور"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
) : otpSent ? (
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
required
|
||||
maxLength={6}
|
||||
placeholder="کد ۶ رقمی پیامکشده"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSendOtp}
|
||||
disabled={busy || !normalizedCell}
|
||||
className="w-full rounded-lg border border-red text-red py-2 text-sm font-medium transition-colors hover:bg-red-light disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
ارسال کد
|
||||
</button>
|
||||
)}
|
||||
|
||||
{error && <p className="text-xs text-red-dark">{error}</p>}
|
||||
|
||||
{(method === "password" || otpSent) && (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
className="w-full rounded-lg bg-red py-2.5 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{busy ? "در حال ورود..." : "ورود"}
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
|
||||
<p className="mt-4 text-center text-xs text-muted">
|
||||
حساب کاربری ندارید؟{" "}
|
||||
<button type="button" onClick={() => setMode("register")} className="font-medium text-red">
|
||||
ثبتنام کنید
|
||||
</button>
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<form onSubmit={handleRegisterSubmit} className="space-y-3">
|
||||
<div className="flex gap-3">
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="نام"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="نام خانوادگی"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
required
|
||||
placeholder="شماره موبایل (مثلاً +989121234567)"
|
||||
value={cellNumber}
|
||||
onChange={(e) => setCellNumber(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="ایمیل (اختیاری)"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
placeholder="رمز عبور (حداقل ۸ کاراکتر)"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
|
||||
{error && <p className="text-xs text-red-dark">{error}</p>}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
className="w-full rounded-lg bg-red py-2.5 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{busy ? "در حال ثبتنام..." : "ثبتنام"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="mt-4 text-center text-xs text-muted">
|
||||
قبلاً ثبتنام کردهاید؟{" "}
|
||||
<button type="button" onClick={() => setMode("login")} className="font-medium text-red">
|
||||
وارد شوید
|
||||
</button>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useCart } from "@/context/CartContext";
|
||||
|
||||
export function CartButton() {
|
||||
const { user } = useAuth();
|
||||
const { itemCount, openPopup } = useCart();
|
||||
const { openLoginModal } = useAuth();
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={user ? openPopup : openLoginModal}
|
||||
onClick={openPopup}
|
||||
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 aria-hidden>🛒</span>
|
||||
|
||||
@@ -4,12 +4,12 @@ import { useEffect, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import { useCart } from "@/context/CartContext";
|
||||
import { continueToCheckoutUrl } from "@/lib/guestCart";
|
||||
import { EmptyState } from "@/components/ui/EmptyState";
|
||||
|
||||
export function CartPopup() {
|
||||
const { cart, popupOpen, closePopup, updateItem, removeItem } = useCart();
|
||||
const { items, subtotal, popupOpen, closePopup, updateItem, removeItem } = useCart();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
@@ -22,15 +22,6 @@ export function CartPopup() {
|
||||
|
||||
if (!mounted) return null;
|
||||
|
||||
const items = cart?.items ?? [];
|
||||
|
||||
const changeQty = async (itemId: string, quantity: number) => {
|
||||
setBusyId(itemId);
|
||||
if (quantity <= 0) await removeItem(itemId);
|
||||
else await updateItem(itemId, quantity);
|
||||
setBusyId(null);
|
||||
};
|
||||
|
||||
return createPortal(
|
||||
<div aria-hidden={!popupOpen}>
|
||||
<div
|
||||
@@ -65,22 +56,18 @@ export function CartPopup() {
|
||||
<li key={item.id} className="flex gap-3 border-b border-border pb-4">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={item.productImage ?? "/images/placeholder.svg"}
|
||||
alt={item.productNameFa ?? item.productTitle}
|
||||
src={item.image || "/images/placeholder.svg"}
|
||||
alt={item.name}
|
||||
className="h-16 w-16 shrink-0 rounded-lg border border-border object-contain p-1"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="line-clamp-2 text-sm font-medium">
|
||||
{item.productNameFa ?? item.productTitle}
|
||||
</p>
|
||||
{item.label && <p className="mt-0.5 text-xs text-muted">{item.label}</p>}
|
||||
<p className="line-clamp-2 text-sm font-medium">{item.name}</p>
|
||||
<div className="mt-2 flex items-center justify-between">
|
||||
<div className="flex items-center rounded-lg border border-border">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyId === item.id}
|
||||
onClick={() => changeQty(item.id, item.quantity + 1)}
|
||||
className="px-2 py-1 text-sm disabled:opacity-40"
|
||||
onClick={() => updateItem(item.id, item.quantity + 1)}
|
||||
className="px-2 py-1 text-sm"
|
||||
aria-label="افزایش تعداد"
|
||||
>
|
||||
+
|
||||
@@ -88,37 +75,44 @@ export function CartPopup() {
|
||||
<span className="min-w-6 text-center text-xs font-medium">{item.quantity}</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyId === item.id}
|
||||
onClick={() => changeQty(item.id, item.quantity - 1)}
|
||||
className="px-2 py-1 text-sm disabled:opacity-40"
|
||||
onClick={() => updateItem(item.id, item.quantity - 1)}
|
||||
className="px-2 py-1 text-sm"
|
||||
aria-label="کاهش تعداد"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
</div>
|
||||
<span className="text-sm font-bold text-red-dark">
|
||||
{formatPrice(item.lineTotal)}
|
||||
{formatPrice(item.price * item.quantity)}
|
||||
<span className="mr-0.5 text-[11px] font-normal text-muted">تومان</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeItem(item.id)}
|
||||
aria-label="حذف از سبد"
|
||||
className="shrink-0 self-start text-muted transition-colors hover:text-red-dark"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items.length > 0 && cart && (
|
||||
{items.length > 0 && (
|
||||
<div className="border-t border-border p-5">
|
||||
<div className="mb-4 flex items-center justify-between text-sm">
|
||||
<span className="text-muted">جمع کل</span>
|
||||
<span className="text-base font-bold text-red-dark">
|
||||
{formatPrice(cart.subtotal)}
|
||||
{formatPrice(subtotal)}
|
||||
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
|
||||
</span>
|
||||
</div>
|
||||
<a
|
||||
href="/checkout"
|
||||
href={continueToCheckoutUrl(items)}
|
||||
className="block w-full rounded-xl bg-red py-3 text-center text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
ادامه فرآیند خرید
|
||||
|
||||
@@ -42,6 +42,7 @@ export function BrandGroupCarousels({
|
||||
href={productHref(product)}
|
||||
contactPhone={contactPhone}
|
||||
variantId={product.variantId}
|
||||
slug={product.slug}
|
||||
/>
|
||||
))}
|
||||
</Carousel>
|
||||
|
||||
@@ -54,6 +54,7 @@ export function SpecialSaleCarousel({
|
||||
href={productHref(product)}
|
||||
contactPhone={contactPhone}
|
||||
variantId={product.variantId}
|
||||
slug={product.slug}
|
||||
/>
|
||||
))}
|
||||
</Carousel>
|
||||
|
||||
@@ -35,6 +35,7 @@ export function TopSellingCarousel({
|
||||
href={productHref(product)}
|
||||
contactPhone={contactPhone}
|
||||
variantId={product.variantId}
|
||||
slug={product.slug}
|
||||
/>
|
||||
))}
|
||||
</Carousel>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { type ReactNode, useMemo, useState } from "react";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import type { ProductStoreVariant, ProductVariation } from "@/lib/meshkee";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useCart } from "@/context/CartContext";
|
||||
|
||||
function CheckIcon({ className }: { className?: string }) {
|
||||
@@ -29,6 +28,9 @@ export function ProductPurchasePanel({
|
||||
contactPhone,
|
||||
storeName,
|
||||
initialSelections,
|
||||
productName,
|
||||
productSlug,
|
||||
productImage,
|
||||
}: {
|
||||
header: ReactNode;
|
||||
variations: ProductVariation[];
|
||||
@@ -46,8 +48,11 @@ export function ProductPurchasePanel({
|
||||
// detail page for one specific variant), instead of defaulting to the
|
||||
// first option of every variation.
|
||||
initialSelections?: Record<string, string>;
|
||||
// For the guest-cart line (id alone isn't enough to render a mini-cart row).
|
||||
productName: string;
|
||||
productSlug: string;
|
||||
productImage: string;
|
||||
}) {
|
||||
const { user, openLoginModal } = useAuth();
|
||||
const { addItem } = useCart();
|
||||
const [selected, setSelected] = useState<Record<string, string>>(() => {
|
||||
if (initialSelections && Object.keys(initialSelections).length > 0) return initialSelections;
|
||||
@@ -58,8 +63,7 @@ export function ProductPurchasePanel({
|
||||
return initial;
|
||||
});
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [cartStatus, setCartStatus] = useState<"idle" | "busy" | "done">("idle");
|
||||
const [cartError, setCartError] = useState<string | null>(null);
|
||||
const [cartStatus, setCartStatus] = useState<"idle" | "done">("idle");
|
||||
|
||||
const matchedVariant = useMemo(() => {
|
||||
if (storeVariants.length === 0) return null;
|
||||
@@ -101,22 +105,19 @@ export function ProductPurchasePanel({
|
||||
const available = matchedVariant ? stockQuantity! > 0 : inStock;
|
||||
const maxQty = stockQuantity && stockQuantity > 0 ? stockQuantity : 99;
|
||||
|
||||
const handleAddToCart = async () => {
|
||||
if (!matchedVariant) return;
|
||||
if (!user) {
|
||||
openLoginModal();
|
||||
return;
|
||||
}
|
||||
setCartError(null);
|
||||
setCartStatus("busy");
|
||||
const res = await addItem(matchedVariant.id, quantity);
|
||||
if (res.ok) {
|
||||
setCartStatus("done");
|
||||
setTimeout(() => setCartStatus("idle"), 1500);
|
||||
} else {
|
||||
setCartStatus("idle");
|
||||
setCartError(res.message ?? "افزودن به سبد ناموفق بود.");
|
||||
}
|
||||
const handleAddToCart = () => {
|
||||
if (!matchedVariant || price == null) return;
|
||||
addItem({
|
||||
id: matchedVariant.id,
|
||||
name: productName,
|
||||
slug: productSlug,
|
||||
price,
|
||||
originalPrice: oldPrice ?? undefined,
|
||||
image: productImage,
|
||||
quantity,
|
||||
});
|
||||
setCartStatus("done");
|
||||
setTimeout(() => setCartStatus("idle"), 1500);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -226,12 +227,10 @@ export function ProductPurchasePanel({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cartError && <p className="mb-3 text-xs text-red-dark">{cartError}</p>}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddToCart}
|
||||
disabled={!available || cartStatus === "busy"}
|
||||
disabled={!available}
|
||||
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"
|
||||
>
|
||||
{cartStatus === "done" ? "به سبد اضافه شد ✓" : "افزودن به سبد خرید"}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { EmptyState } from "@/components/ui/EmptyState";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { postComment, type EntityComment, type TechnicalInfoField } from "@/lib/meshkee";
|
||||
|
||||
type Tab = "specs" | "review" | "comments";
|
||||
@@ -19,23 +18,23 @@ function formatDate(iso?: string) {
|
||||
}
|
||||
|
||||
function CommentsPanel({ entityId, initialComments }: { entityId: string; initialComments: EntityComment[] }) {
|
||||
const { user, openLoginModal } = useAuth();
|
||||
const [comments, setComments] = useState(initialComments);
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [text, setText] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!user || !text.trim()) return;
|
||||
if (!name.trim() || !text.trim()) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const authorName = [user.firstName, user.lastName].filter(Boolean).join(" ") || "کاربر";
|
||||
const res = await postComment({
|
||||
entityType: "product",
|
||||
entityId,
|
||||
authorName,
|
||||
authorEmail: user.email,
|
||||
authorName: name.trim(),
|
||||
authorEmail: email.trim() || undefined,
|
||||
text: text.trim(),
|
||||
});
|
||||
setBusy(false);
|
||||
@@ -43,43 +42,46 @@ function CommentsPanel({ entityId, initialComments }: { entityId: string; initia
|
||||
setError(res.message ?? "ثبت نظر ناموفق بود.");
|
||||
return;
|
||||
}
|
||||
setComments((prev) => [{ id: `local-${Date.now()}`, authorName, text: text.trim() }, ...prev]);
|
||||
setComments((prev) => [{ id: `local-${Date.now()}`, authorName: name.trim(), text: text.trim() }, ...prev]);
|
||||
setText("");
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{user ? (
|
||||
<form onSubmit={handleSubmit} className="mb-6 space-y-3">
|
||||
<textarea
|
||||
<form onSubmit={handleSubmit} className="mb-6 space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<input
|
||||
required
|
||||
rows={3}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="نظر خود را درباره این محصول بنویسید..."
|
||||
className="w-full rounded-xl border border-border bg-background p-3 text-sm outline-none transition-colors focus:border-red"
|
||||
placeholder="نام شما"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red"
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="ایمیل (اختیاری)"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red"
|
||||
/>
|
||||
{error && <p className="text-xs text-red-dark">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy || !text.trim()}
|
||||
className="rounded-lg bg-red px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{busy ? "در حال ثبت..." : "ثبت نظر"}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-background p-4 text-sm">
|
||||
<span className="text-muted">برای ثبت نظر ابتدا وارد حساب کاربری خود شوید.</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={openLoginModal}
|
||||
className="rounded-lg bg-red px-4 py-1.5 text-xs font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
ورود
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
required
|
||||
rows={3}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="نظر خود را درباره این محصول بنویسید..."
|
||||
className="w-full rounded-xl border border-border bg-background p-3 text-sm outline-none transition-colors focus:border-red"
|
||||
/>
|
||||
{error && <p className="text-xs text-red-dark">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy || !name.trim() || !text.trim()}
|
||||
className="rounded-lg bg-red px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{busy ? "در حال ثبت..." : "ثبت نظر"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{comments.length === 0 ? (
|
||||
<EmptyState message="هنوز نظری برای این محصول ثبت نشده است." />
|
||||
|
||||
@@ -37,6 +37,7 @@ export async function SimilarProducts({
|
||||
href={productHref(product)}
|
||||
contactPhone={contactPhone}
|
||||
variantId={product.variantId}
|
||||
slug={product.slug}
|
||||
/>
|
||||
))}
|
||||
</Carousel>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useState } from "react";
|
||||
import { Placeholder } from "./Placeholder";
|
||||
import { formatPrice } from "@/data/sample";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useCart } from "@/context/CartContext";
|
||||
|
||||
type ProductCardProps = {
|
||||
@@ -18,9 +17,11 @@ type ProductCardProps = {
|
||||
fluid?: boolean;
|
||||
contactPhone?: string;
|
||||
// When known (store-specials/brand-groups/store-items cards already point
|
||||
// at one purchasable variant), the button adds straight to cart. Otherwise
|
||||
// it just links to the detail page, where a variant can be picked first.
|
||||
// at one purchasable variant), the button adds straight to the guest cart.
|
||||
// Otherwise it just links to the detail page, where a variant can be
|
||||
// picked first — never fabricate a variant id to force a quick-add.
|
||||
variantId?: string;
|
||||
slug?: string;
|
||||
};
|
||||
|
||||
export function ProductCard({
|
||||
@@ -35,21 +36,23 @@ export function ProductCard({
|
||||
fluid = false,
|
||||
contactPhone,
|
||||
variantId,
|
||||
slug,
|
||||
}: ProductCardProps) {
|
||||
const { user, openLoginModal } = useAuth();
|
||||
const { addItem } = useCart();
|
||||
const [status, setStatus] = useState<"idle" | "busy" | "done">("idle");
|
||||
const [status, setStatus] = useState<"idle" | "done">("idle");
|
||||
|
||||
const handleAddToCart = async () => {
|
||||
if (!variantId) return;
|
||||
if (!user) {
|
||||
openLoginModal();
|
||||
return;
|
||||
}
|
||||
setStatus("busy");
|
||||
const res = await addItem(variantId, 1);
|
||||
setStatus(res.ok ? "done" : "idle");
|
||||
if (res.ok) setTimeout(() => setStatus("idle"), 1500);
|
||||
const handleAddToCart = () => {
|
||||
if (!variantId || price == null) return;
|
||||
addItem({
|
||||
id: variantId,
|
||||
name,
|
||||
slug: slug ?? "",
|
||||
price,
|
||||
originalPrice: oldPrice ?? undefined,
|
||||
image,
|
||||
});
|
||||
setStatus("done");
|
||||
setTimeout(() => setStatus("idle"), 1500);
|
||||
};
|
||||
|
||||
const info = (
|
||||
@@ -117,8 +120,7 @@ export function ProductCard({
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddToCart}
|
||||
disabled={status === "busy"}
|
||||
className="w-full rounded-lg bg-red py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-70"
|
||||
className="w-full rounded-lg bg-red py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||
>
|
||||
{status === "done" ? "افزوده شد ✓" : "افزودن به سبد"}
|
||||
</button>
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
type AuthUser,
|
||||
clearTokens,
|
||||
fetchMe,
|
||||
getStoredTokens,
|
||||
loginWithOtp,
|
||||
loginWithPassword,
|
||||
refreshAccessToken,
|
||||
register as registerRequest,
|
||||
sendOtp as sendOtpRequest,
|
||||
storeTokens,
|
||||
} from "@/lib/auth";
|
||||
|
||||
type AuthContextValue = {
|
||||
user: AuthUser | null;
|
||||
accessToken: string | null;
|
||||
loading: boolean;
|
||||
loginModalOpen: boolean;
|
||||
openLoginModal: () => void;
|
||||
closeLoginModal: () => void;
|
||||
login: (cellNumber: string, password: string) => Promise<{ ok: boolean; message?: string }>;
|
||||
loginOtp: (cellNumber: string, code: string) => Promise<{ ok: boolean; message?: string }>;
|
||||
sendOtp: (cellNumber: string) => Promise<{ ok: boolean; message?: string }>;
|
||||
register: (input: {
|
||||
cellNumber: string;
|
||||
password: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email?: string;
|
||||
}) => Promise<{ ok: boolean; message?: string }>;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [accessToken, setAccessToken] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loginModalOpen, setLoginModalOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = getStoredTokens();
|
||||
if (!stored) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
fetchMe(stored.accessToken).then(async (res) => {
|
||||
if (res.ok) {
|
||||
setUser(res.data);
|
||||
setAccessToken(stored.accessToken);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
// Access token likely expired (~15 min lifetime) — try a silent
|
||||
// refresh before giving up on the session.
|
||||
const fresh = await refreshAccessToken();
|
||||
if (fresh) {
|
||||
const retry = await fetchMe(fresh);
|
||||
if (retry.ok) {
|
||||
setUser(retry.data);
|
||||
setAccessToken(fresh);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
clearTokens();
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const applySession = useCallback((session: { accessToken: string; refreshToken: string | null; user: AuthUser }) => {
|
||||
storeTokens(session.accessToken, session.refreshToken);
|
||||
setAccessToken(session.accessToken);
|
||||
setUser(session.user);
|
||||
setLoginModalOpen(false);
|
||||
}, []);
|
||||
|
||||
const login = useCallback(
|
||||
async (cellNumber: string, password: string) => {
|
||||
const res = await loginWithPassword(cellNumber, password);
|
||||
if (!res.ok) return { ok: false, message: res.message };
|
||||
applySession(res.data);
|
||||
return { ok: true };
|
||||
},
|
||||
[applySession],
|
||||
);
|
||||
|
||||
const loginOtp = useCallback(
|
||||
async (cellNumber: string, code: string) => {
|
||||
const res = await loginWithOtp(cellNumber, code);
|
||||
if (!res.ok) return { ok: false, message: res.message };
|
||||
applySession(res.data);
|
||||
return { ok: true };
|
||||
},
|
||||
[applySession],
|
||||
);
|
||||
|
||||
const sendOtp = useCallback(async (cellNumber: string) => {
|
||||
const res = await sendOtpRequest(cellNumber);
|
||||
return res.ok ? { ok: true } : { ok: false, message: res.message };
|
||||
}, []);
|
||||
|
||||
const register = useCallback(
|
||||
async (input: { cellNumber: string; password: string; firstName: string; lastName: string; email?: string }) => {
|
||||
const res = await registerRequest(input);
|
||||
if (!res.ok) return { ok: false, message: res.message };
|
||||
applySession(res.data);
|
||||
return { ok: true };
|
||||
},
|
||||
[applySession],
|
||||
);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearTokens();
|
||||
setUser(null);
|
||||
setAccessToken(null);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
user,
|
||||
accessToken,
|
||||
loading,
|
||||
loginModalOpen,
|
||||
openLoginModal: () => setLoginModalOpen(true),
|
||||
closeLoginModal: () => setLoginModalOpen(false),
|
||||
login,
|
||||
loginOtp,
|
||||
sendOtp,
|
||||
register,
|
||||
logout,
|
||||
}),
|
||||
[user, accessToken, loading, loginModalOpen, login, loginOtp, sendOtp, register, logout],
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
+35
-82
@@ -1,114 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { addCartItem, type Cart, getCart, removeCartItem, updateCartItem } from "@/lib/cart";
|
||||
|
||||
type ActionResult = { ok: boolean; message?: string };
|
||||
import {
|
||||
addToGuestCart,
|
||||
type GuestCartLine,
|
||||
getGuestCart,
|
||||
removeFromGuestCart,
|
||||
setGuestCartQuantity,
|
||||
} from "@/lib/guestCart";
|
||||
|
||||
type CartContextValue = {
|
||||
cart: Cart | null;
|
||||
items: GuestCartLine[];
|
||||
itemCount: number;
|
||||
loading: boolean;
|
||||
subtotal: number;
|
||||
popupOpen: boolean;
|
||||
openPopup: () => void;
|
||||
closePopup: () => void;
|
||||
businessId: string;
|
||||
addItem: (storeItemVariantId: string, quantity: number) => Promise<ActionResult>;
|
||||
updateItem: (itemId: string, quantity: number) => Promise<ActionResult>;
|
||||
removeItem: (itemId: string) => Promise<ActionResult>;
|
||||
refresh: () => Promise<void>;
|
||||
addItem: (line: Omit<GuestCartLine, "quantity"> & { quantity?: number }) => void;
|
||||
updateItem: (id: string, quantity: number) => void;
|
||||
removeItem: (id: string) => void;
|
||||
};
|
||||
|
||||
const CartContext = createContext<CartContextValue | null>(null);
|
||||
|
||||
export function CartProvider({ businessId, children }: { businessId: string; children: React.ReactNode }) {
|
||||
const { user, logout } = useAuth();
|
||||
const [cart, setCart] = useState<Cart | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
export function CartProvider({ children }: { children: React.ReactNode }) {
|
||||
const [items, setItems] = useState<GuestCartLine[]>([]);
|
||||
const [popupOpen, setPopupOpen] = useState(false);
|
||||
|
||||
// cart.ts always reads the freshest token from storage (and self-refreshes
|
||||
// on expiry) — gate here only on "is someone logged in at all".
|
||||
const handleUnauthorized = useCallback(() => {
|
||||
setCart(null);
|
||||
logout();
|
||||
}, [logout]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!user) {
|
||||
setCart(null);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
const res = await getCart(businessId);
|
||||
if (res.ok) setCart(res.data);
|
||||
else if (res.unauthorized) handleUnauthorized();
|
||||
setLoading(false);
|
||||
}, [user, businessId, handleUnauthorized]);
|
||||
|
||||
// Guest cart lives in localStorage/cookies only — nothing to fetch from a
|
||||
// server, just read what's already there once mounted in the browser.
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
setItems(getGuestCart());
|
||||
}, []);
|
||||
|
||||
const addItem = useCallback(
|
||||
async (storeItemVariantId: string, quantity: number): Promise<ActionResult> => {
|
||||
if (!user) return { ok: false, message: "برای افزودن به سبد باید وارد شوید." };
|
||||
const res = await addCartItem(businessId, storeItemVariantId, quantity);
|
||||
if (res.ok) {
|
||||
setCart(res.data);
|
||||
setPopupOpen(true);
|
||||
return { ok: true };
|
||||
}
|
||||
if (res.unauthorized) handleUnauthorized();
|
||||
return { ok: false, message: res.message };
|
||||
},
|
||||
[user, businessId, handleUnauthorized],
|
||||
);
|
||||
const addItem = useCallback((line: Omit<GuestCartLine, "quantity"> & { quantity?: number }) => {
|
||||
setItems(addToGuestCart(line));
|
||||
setPopupOpen(true);
|
||||
}, []);
|
||||
|
||||
const updateItem = useCallback(
|
||||
async (itemId: string, quantity: number): Promise<ActionResult> => {
|
||||
if (!user) return { ok: false, message: "برای این کار باید وارد شوید." };
|
||||
const res = await updateCartItem(businessId, itemId, quantity);
|
||||
if (res.ok) {
|
||||
setCart(res.data);
|
||||
return { ok: true };
|
||||
}
|
||||
if (res.unauthorized) handleUnauthorized();
|
||||
return { ok: false, message: res.message };
|
||||
},
|
||||
[user, businessId, handleUnauthorized],
|
||||
);
|
||||
const updateItem = useCallback((id: string, quantity: number) => {
|
||||
setItems(setGuestCartQuantity(id, quantity));
|
||||
}, []);
|
||||
|
||||
const removeItem = useCallback(
|
||||
async (itemId: string): Promise<ActionResult> => {
|
||||
if (!user) return { ok: false, message: "برای این کار باید وارد شوید." };
|
||||
const res = await removeCartItem(businessId, itemId);
|
||||
if (res.ok) {
|
||||
setCart(res.data);
|
||||
return { ok: true };
|
||||
}
|
||||
if (res.unauthorized) handleUnauthorized();
|
||||
return { ok: false, message: res.message };
|
||||
},
|
||||
[user, businessId, handleUnauthorized],
|
||||
);
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(removeFromGuestCart(id));
|
||||
}, []);
|
||||
|
||||
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
|
||||
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||
|
||||
const value = useMemo<CartContextValue>(
|
||||
() => ({
|
||||
cart,
|
||||
itemCount: cart?.itemCount ?? 0,
|
||||
loading,
|
||||
items,
|
||||
itemCount,
|
||||
subtotal,
|
||||
popupOpen,
|
||||
openPopup: () => setPopupOpen(true),
|
||||
closePopup: () => setPopupOpen(false),
|
||||
businessId,
|
||||
addItem,
|
||||
updateItem,
|
||||
removeItem,
|
||||
refresh,
|
||||
}),
|
||||
[cart, loading, popupOpen, businessId, addItem, updateItem, removeItem, refresh],
|
||||
[items, itemCount, subtotal, popupOpen, addItem, updateItem, removeItem],
|
||||
);
|
||||
|
||||
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { AuthProvider } from "@/context/AuthContext";
|
||||
import { CartProvider } from "@/context/CartContext";
|
||||
import { LoginModal } from "@/components/auth/LoginModal";
|
||||
import { CartPopup } from "@/components/cart/CartPopup";
|
||||
|
||||
export function Providers({ businessId, children }: { businessId: string; children: React.ReactNode }) {
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<CartProvider businessId={businessId}>
|
||||
{children}
|
||||
<LoginModal />
|
||||
<CartPopup />
|
||||
</CartProvider>
|
||||
</AuthProvider>
|
||||
<CartProvider>
|
||||
{children}
|
||||
<CartPopup />
|
||||
</CartProvider>
|
||||
);
|
||||
}
|
||||
|
||||
-211
@@ -1,211 +0,0 @@
|
||||
// Client-side session storage for Meshkee customer auth. Tokens live in
|
||||
// localStorage (per-browser, never sent anywhere but api.meshkee.com).
|
||||
const ACCESS_KEY = "sanihome_access_token";
|
||||
const REFRESH_KEY = "sanihome_refresh_token";
|
||||
|
||||
export type AuthUser = {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
cellNumber?: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
export function getStoredTokens(): { accessToken: string; refreshToken: string | null } | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const accessToken = window.localStorage.getItem(ACCESS_KEY);
|
||||
if (!accessToken) return null;
|
||||
return { accessToken, refreshToken: window.localStorage.getItem(REFRESH_KEY) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function storeTokens(accessToken: string, refreshToken?: string | null): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(ACCESS_KEY, accessToken);
|
||||
if (refreshToken) window.localStorage.setItem(REFRESH_KEY, refreshToken);
|
||||
} catch {
|
||||
// Private browsing / storage disabled — session just won't persist.
|
||||
}
|
||||
}
|
||||
|
||||
// Access tokens are short-lived (~15 min). Call this whenever a request
|
||||
// comes back 401 so the shopper doesn't get silently logged out mid-session.
|
||||
// Returns the fresh access token, or null if the refresh token is also gone/invalid
|
||||
// (caller should then clear the session and prompt login again).
|
||||
//
|
||||
// AuthContext and CartContext each independently notice an expired token and
|
||||
// call this — without coordination they'd fire two concurrent /auth/refresh
|
||||
// requests. If the backend rotates the refresh token on use, the second
|
||||
// request then fails (observed as a 500/400). This in-flight guard makes
|
||||
// every concurrent caller share the same single request instead of racing.
|
||||
let inFlightRefresh: Promise<string | null> | null = null;
|
||||
|
||||
export async function refreshAccessToken(): Promise<string | null> {
|
||||
if (inFlightRefresh) return inFlightRefresh;
|
||||
|
||||
inFlightRefresh = (async () => {
|
||||
const stored = getStoredTokens();
|
||||
if (!stored?.refreshToken) return null;
|
||||
try {
|
||||
const res = await fetch(`${AUTH_API_BASE}/auth/refresh`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refreshToken: stored.refreshToken }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
clearTokens();
|
||||
return null;
|
||||
}
|
||||
const data = (await res.json()) as RawAuthResponse;
|
||||
const accessToken = data.accessToken ?? data.token ?? data.access_token;
|
||||
if (!accessToken) return null;
|
||||
storeTokens(accessToken, data.refreshToken ?? data.refresh_token ?? stored.refreshToken);
|
||||
return accessToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
return await inFlightRefresh;
|
||||
} finally {
|
||||
inFlightRefresh = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearTokens(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.removeItem(ACCESS_KEY);
|
||||
window.localStorage.removeItem(REFRESH_KEY);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const AUTH_API_BASE = "https://api.meshkee.com/api/v1";
|
||||
export const WEBSITE_DOMAIN = "sanihome.ir";
|
||||
|
||||
async function authFetch<T>(
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown; token?: string } = {},
|
||||
): Promise<{ ok: true; data: T } | { ok: false; status: number; message: string }> {
|
||||
try {
|
||||
const res = await fetch(`${AUTH_API_BASE}${path}`, {
|
||||
method: options.method ?? "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),
|
||||
},
|
||||
body: options.body != null ? JSON.stringify(options.body) : undefined,
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
status: res.status,
|
||||
message: (data as { message?: string })?.message ?? "خطایی رخ داد. دوباره تلاش کنید.",
|
||||
};
|
||||
}
|
||||
return { ok: true, data: data as T };
|
||||
} catch {
|
||||
return { ok: false, status: 0, message: "ارتباط با سرور برقرار نشد." };
|
||||
}
|
||||
}
|
||||
|
||||
// The API doesn't document the exact success-response field names for
|
||||
// login/register/login-otp — accessToken/refreshToken/user is the standard
|
||||
// shape (confirmed accessToken+refreshToken naming via /auth/refresh's own
|
||||
// request body, and a `user` wrapper via /auth/me's documented description).
|
||||
// Read defensively in case a field is nested or named slightly differently.
|
||||
type RawAuthResponse = {
|
||||
accessToken?: string;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refreshToken?: string;
|
||||
refresh_token?: string;
|
||||
user?: Record<string, unknown>;
|
||||
customer?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function extractSession(raw: RawAuthResponse): { accessToken: string; refreshToken: string | null; user: AuthUser } | null {
|
||||
const accessToken = raw.accessToken ?? raw.token ?? raw.access_token;
|
||||
if (!accessToken) return null;
|
||||
const refreshToken = raw.refreshToken ?? raw.refresh_token ?? null;
|
||||
const rawUser = raw.user ?? raw.customer ?? {};
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
user: {
|
||||
id: String(rawUser.id ?? ""),
|
||||
firstName: rawUser.firstName as string | undefined,
|
||||
lastName: rawUser.lastName as string | undefined,
|
||||
cellNumber: rawUser.cellNumber as string | undefined,
|
||||
email: rawUser.email as string | undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function loginWithPassword(cellNumber: string, password: string) {
|
||||
const res = await authFetch<RawAuthResponse>("/auth/login", {
|
||||
method: "POST",
|
||||
body: { cellNumber, password },
|
||||
});
|
||||
if (!res.ok) return res;
|
||||
const session = extractSession(res.data);
|
||||
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
|
||||
return { ok: true as const, data: session };
|
||||
}
|
||||
|
||||
export async function loginWithOtp(cellNumber: string, code: string) {
|
||||
const res = await authFetch<RawAuthResponse>("/auth/login-otp", {
|
||||
method: "POST",
|
||||
body: { cellNumber, code },
|
||||
});
|
||||
if (!res.ok) return res;
|
||||
const session = extractSession(res.data);
|
||||
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
|
||||
return { ok: true as const, data: session };
|
||||
}
|
||||
|
||||
export async function sendOtp(cellNumber: string) {
|
||||
return authFetch<{ message?: string }>("/auth/send-otp", {
|
||||
method: "POST",
|
||||
body: { cellNumber, domain: WEBSITE_DOMAIN },
|
||||
});
|
||||
}
|
||||
|
||||
export async function register(input: {
|
||||
cellNumber: string;
|
||||
password: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email?: string;
|
||||
}) {
|
||||
const res = await authFetch<RawAuthResponse>("/auth/register", {
|
||||
method: "POST",
|
||||
body: { ...input, domain: WEBSITE_DOMAIN },
|
||||
});
|
||||
if (!res.ok) return res;
|
||||
const session = extractSession(res.data);
|
||||
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
|
||||
return { ok: true as const, data: session };
|
||||
}
|
||||
|
||||
export async function fetchMe(accessToken: string) {
|
||||
const res = await authFetch<{ user?: Record<string, unknown> }>("/auth/me", { token: accessToken });
|
||||
if (!res.ok) return res;
|
||||
const rawUser = res.data.user ?? {};
|
||||
const user: AuthUser = {
|
||||
id: String(rawUser.id ?? ""),
|
||||
firstName: rawUser.firstName as string | undefined,
|
||||
lastName: rawUser.lastName as string | undefined,
|
||||
cellNumber: rawUser.cellNumber as string | undefined,
|
||||
email: rawUser.email as string | undefined,
|
||||
};
|
||||
return { ok: true as const, data: user };
|
||||
}
|
||||
-171
@@ -1,171 +0,0 @@
|
||||
// Cart/checkout — requires a logged-in customer (Bearer token) and the
|
||||
// business id, per Meshkee's /businesses/{businessId}/cart... routes.
|
||||
import { getStoredTokens, refreshAccessToken } from "@/lib/auth";
|
||||
|
||||
const API_BASE = "https://api.meshkee.com/api/v1";
|
||||
|
||||
export type CartItem = {
|
||||
id: string;
|
||||
storeItemVariantId: string;
|
||||
productId: string;
|
||||
productTitle: string;
|
||||
productNameFa?: string;
|
||||
productImage: string | null;
|
||||
label: string;
|
||||
selections: { variationId: string; variationName: string; optionId: string; value: string }[];
|
||||
quantity: number;
|
||||
unitPrice: number;
|
||||
compareAtPrice: number | null;
|
||||
lineTotal: number;
|
||||
stockQuantity: number;
|
||||
};
|
||||
|
||||
export type Cart = {
|
||||
id: string;
|
||||
items: CartItem[];
|
||||
itemCount: number;
|
||||
subtotal: number;
|
||||
};
|
||||
|
||||
function normalizeCart(raw: Record<string, unknown>): Cart {
|
||||
const items = (raw.items as Record<string, unknown>[] | undefined) ?? [];
|
||||
return {
|
||||
id: String(raw.id ?? ""),
|
||||
itemCount: Number(raw.itemCount ?? items.length),
|
||||
subtotal: Number(raw.subtotal ?? 0),
|
||||
items: items.map((item) => ({
|
||||
id: String(item.id ?? ""),
|
||||
storeItemVariantId: String(item.storeItemVariantId ?? ""),
|
||||
productId: String(item.productId ?? ""),
|
||||
productTitle: String(item.productTitle ?? ""),
|
||||
productNameFa: item.productNameFa as string | undefined,
|
||||
productImage: (item.productImage as string | undefined) ?? null,
|
||||
label: String(item.label ?? ""),
|
||||
selections: ((item.selections as Record<string, unknown>[] | undefined) ?? []).map((s) => ({
|
||||
variationId: String(s.variationId ?? ""),
|
||||
variationName: String(s.variationName ?? ""),
|
||||
optionId: String(s.optionId ?? ""),
|
||||
value: String(s.value ?? ""),
|
||||
})),
|
||||
quantity: Number(item.quantity ?? 0),
|
||||
unitPrice: Number(item.unitPrice ?? 0),
|
||||
compareAtPrice: item.compareAtPrice != null ? Number(item.compareAtPrice) : null,
|
||||
lineTotal: Number(item.lineTotal ?? 0),
|
||||
stockQuantity: Number(item.stockQuantity ?? 0),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
type Result<T> = { ok: true; data: T } | { ok: false; message: string; unauthorized?: boolean };
|
||||
|
||||
// Always reads the current token from storage (not a stale value captured
|
||||
// earlier by the caller) and, on a 401, transparently refreshes it once and
|
||||
// retries — access tokens only last ~15 minutes, so this is the difference
|
||||
// between "cart just works" and shoppers getting logged out mid-browse.
|
||||
async function cartFetch<T>(
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown } = {},
|
||||
isRetry = false,
|
||||
): Promise<Result<T>> {
|
||||
const token = getStoredTokens()?.accessToken;
|
||||
if (!token) return { ok: false, message: "برای این کار باید وارد شوید.", unauthorized: true };
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
method: options.method ?? "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: options.body != null ? JSON.stringify(options.body) : undefined,
|
||||
});
|
||||
if (res.status === 401 && !isRetry) {
|
||||
const refreshed = await refreshAccessToken();
|
||||
if (refreshed) return cartFetch<T>(path, options, true);
|
||||
return { ok: false, message: "نشست شما منقضی شده. دوباره وارد شوید.", unauthorized: true };
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, message: (data as { message?: string })?.message ?? "خطایی رخ داد." };
|
||||
}
|
||||
return { ok: true, data: data as T };
|
||||
} catch {
|
||||
return { ok: false, message: "ارتباط با سرور برقرار نشد." };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCart(businessId: string): Promise<Result<Cart>> {
|
||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart`);
|
||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
||||
}
|
||||
|
||||
export async function addCartItem(
|
||||
businessId: string,
|
||||
storeItemVariantId: string,
|
||||
quantity: number,
|
||||
): Promise<Result<Cart>> {
|
||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart/items`, {
|
||||
method: "POST",
|
||||
body: { storeItemVariantId, quantity },
|
||||
});
|
||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
||||
}
|
||||
|
||||
export async function updateCartItem(
|
||||
businessId: string,
|
||||
itemId: string,
|
||||
quantity: number,
|
||||
): Promise<Result<Cart>> {
|
||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart/items/${itemId}`, {
|
||||
method: "PATCH",
|
||||
body: { quantity },
|
||||
});
|
||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
||||
}
|
||||
|
||||
export async function removeCartItem(businessId: string, itemId: string): Promise<Result<Cart>> {
|
||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart/items/${itemId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
||||
}
|
||||
|
||||
export type CheckoutPayload = {
|
||||
addressId?: string;
|
||||
shippingAddress?: {
|
||||
province: string;
|
||||
city: string;
|
||||
address: string;
|
||||
postalCode?: string;
|
||||
landline?: string;
|
||||
};
|
||||
customerNotes?: string;
|
||||
payment: { type: "cash" | "transfer"; transferAccount?: string; transferRefNumber?: string; notes?: string };
|
||||
};
|
||||
|
||||
export type Order = {
|
||||
id: string;
|
||||
orderNumber: string;
|
||||
status: string;
|
||||
processStepLabelFa?: string;
|
||||
total: number;
|
||||
};
|
||||
|
||||
export async function checkout(businessId: string, payload: CheckoutPayload): Promise<Result<Order>> {
|
||||
const res = await cartFetch<{ order: Record<string, unknown> }>(`/businesses/${businessId}/cart/checkout`, {
|
||||
method: "POST",
|
||||
body: payload,
|
||||
});
|
||||
if (!res.ok) return res;
|
||||
const order = res.data.order;
|
||||
return {
|
||||
ok: true,
|
||||
data: {
|
||||
id: String(order.id ?? ""),
|
||||
orderNumber: String(order.orderNumber ?? ""),
|
||||
status: String(order.status ?? ""),
|
||||
processStepLabelFa: order.processStepLabelFa as string | undefined,
|
||||
total: Number(order.total ?? 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// Storefront mini-cart per Meshkee's contract (api.meshkee.com/docs/website/AI_PROMPT.md
|
||||
// — "Shopping cart on the storefront"). This site never calls the real cart/checkout
|
||||
// API (/businesses/{id}/cart...) — that's the customer dashboard's job. This is a
|
||||
// local, guest-only cart that gets handed off to customer.<domain> on "Continue".
|
||||
const STORAGE_KEY = "meshkee-guest-cart";
|
||||
const DOMAIN = "sanihome.ir";
|
||||
const MAX_COOKIE_LEN = 3500;
|
||||
const THIRTY_DAYS = 30 * 24 * 60 * 60;
|
||||
|
||||
export type GuestCartLine = {
|
||||
id: string; // storeItemVariantId — never a product id or store-item id
|
||||
name: string;
|
||||
slug: string;
|
||||
price: number;
|
||||
originalPrice?: number;
|
||||
image: string;
|
||||
quantity: number;
|
||||
};
|
||||
|
||||
function readCart(): GuestCartLine[] {
|
||||
if (typeof window === "undefined") return [];
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
return raw ? (JSON.parse(raw) as GuestCartLine[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeCart(items: GuestCartLine[]): void {
|
||||
if (typeof window === "undefined") return;
|
||||
const json = JSON.stringify(items);
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, json);
|
||||
} catch {
|
||||
// ignore — private browsing / storage disabled
|
||||
}
|
||||
try {
|
||||
const encoded = encodeURIComponent(json);
|
||||
// Skip the cookie (rely on localStorage + the URL param on Continue)
|
||||
// when it would blow past a sane cookie size.
|
||||
if (encoded.length <= MAX_COOKIE_LEN) {
|
||||
const secure = window.location.protocol === "https:" ? "; Secure" : "";
|
||||
document.cookie = `${STORAGE_KEY}=${encoded}; Domain=.${DOMAIN}; Path=/; SameSite=Lax; Max-Age=${THIRTY_DAYS}${secure}`;
|
||||
}
|
||||
} catch {
|
||||
// Domain=.sanihome.ir is rejected on hosts that don't match (e.g. local
|
||||
// dev on localhost) — localStorage still works, cross-domain handoff
|
||||
// just isn't testable outside the real domain.
|
||||
}
|
||||
}
|
||||
|
||||
export function getGuestCart(): GuestCartLine[] {
|
||||
return readCart();
|
||||
}
|
||||
|
||||
export function addToGuestCart(line: Omit<GuestCartLine, "quantity"> & { quantity?: number }): GuestCartLine[] {
|
||||
const items = readCart();
|
||||
const quantity = line.quantity ?? 1;
|
||||
const existing = items.findIndex((i) => i.id === line.id);
|
||||
if (existing >= 0) {
|
||||
items[existing] = { ...items[existing], quantity: items[existing].quantity + quantity };
|
||||
} else {
|
||||
items.push({
|
||||
id: line.id,
|
||||
name: line.name,
|
||||
slug: line.slug,
|
||||
price: line.price,
|
||||
originalPrice: line.originalPrice,
|
||||
image: line.image,
|
||||
quantity,
|
||||
});
|
||||
}
|
||||
writeCart(items);
|
||||
return items;
|
||||
}
|
||||
|
||||
export function setGuestCartQuantity(id: string, quantity: number): GuestCartLine[] {
|
||||
let items = readCart();
|
||||
items = quantity <= 0 ? items.filter((i) => i.id !== id) : items.map((i) => (i.id === id ? { ...i, quantity } : i));
|
||||
writeCart(items);
|
||||
return items;
|
||||
}
|
||||
|
||||
export function removeFromGuestCart(id: string): GuestCartLine[] {
|
||||
return setGuestCartQuantity(id, 0);
|
||||
}
|
||||
|
||||
// Base64url-encode the cart for the `guestCart` query param — exact algorithm
|
||||
// from the AI_PROMPT.md spec so the customer dashboard can decode it.
|
||||
export function encodeGuestCart(items: GuestCartLine[]): string {
|
||||
const json = JSON.stringify(items);
|
||||
return btoa(unescape(encodeURIComponent(json)))
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
}
|
||||
|
||||
function readCookie(name: string): string | undefined {
|
||||
if (typeof document === "undefined") return undefined;
|
||||
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
// The customer dashboard writes this on login (Domain=.sanihome.ir), so it's
|
||||
// readable here too — chunked as `_0`, `_1`, ... when long.
|
||||
export function isCustomerLoggedIn(): boolean {
|
||||
return (
|
||||
readCookie("meshkee_customer_access_token") != null ||
|
||||
readCookie("meshkee_customer_access_token_0") != null
|
||||
);
|
||||
}
|
||||
|
||||
export function customerDashboardOrigin(): string {
|
||||
return `https://customer.${DOMAIN}`;
|
||||
}
|
||||
|
||||
// Where the mini-cart's "Continue" button sends the shopper: the dashboard's
|
||||
// cart page carrying the guest cart, or its login page (redirecting back to
|
||||
// that same cart page) when no session cookie is present yet.
|
||||
export function continueToCheckoutUrl(items: GuestCartLine[]): string {
|
||||
const encoded = encodeGuestCart(items);
|
||||
const cartPath = `/checkout/cart?guestCart=${encoded}`;
|
||||
if (isCustomerLoggedIn()) return `${customerDashboardOrigin()}${cartPath}`;
|
||||
return `${customerDashboardOrigin()}/login?redirect=${encodeURIComponent(cartPath)}`;
|
||||
}
|
||||
+3
-4
@@ -21,10 +21,9 @@ async function apiGet<T>(
|
||||
}
|
||||
}
|
||||
|
||||
// POST helper for the handful of public, unauthenticated write endpoints
|
||||
// (contact form, comments) — distinct from the cart/auth flows in
|
||||
// lib/cart.ts and lib/auth.ts, which need a Bearer token and browser-only
|
||||
// APIs (localStorage) this module (used from Server Components too) avoids.
|
||||
// POST helper for the public, unauthenticated write endpoints this storefront
|
||||
// is allowed to call directly (contact form, comments). Cart/checkout/auth
|
||||
// are the customer dashboard's job, not this site's — see lib/guestCart.ts.
|
||||
async function apiPost<T>(
|
||||
path: string,
|
||||
body: Record<string, unknown>,
|
||||
|
||||
Reference in New Issue
Block a user