Add customer auth, real cart/checkout, store-items pages, comments, contact form
- Real in-site login/register (password + SMS OTP) against Meshkee's /auth API, with self-healing access-token refresh (15 min lifetime) and an in-flight-refresh guard so AuthContext and CartContext don't race each other into a failed concurrent refresh. - Real cart: header cart button/badge, a cart popup, and a working "add to cart" on both product cards (where a specific variant id is known) and the product/store-item detail buy-box (always resolves a purchasable variant, even for single-SKU products with no selectable variation). - /checkout: address + cash/bank-transfer payment, posts to the real checkout API and creates an order; refreshes the cart afterward so the header badge doesn't go stale. - New /store-items and /store-items/[id] pages (variant-level browsing, separate from the product-level /products catalog), cross-referencing the parent product for images/description/technical-info. - Product gallery: click-to-open fullscreen lightbox alongside the existing hover-zoom. - Comments tab wired to the real comments API, gated to logged-in users (a product decision — the API itself doesn't require auth) with a login prompt otherwise. - Similar-products row on product/store-item detail pages. - Contact page wired to the real contact-submissions API, with a toast and inline confirmation on success, and the form resetting. - CONTEXT.md: a maintained architecture/conventions doc for this repo, now auto-loaded via CLAUDE.md, covering the Meshkee integration quirks and UI conventions established across this project. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
c2552af079
commit
66f92b634e
+2
-1
@@ -5,7 +5,8 @@
|
|||||||
"name": "sanihome-dev",
|
"name": "sanihome-dev",
|
||||||
"runtimeExecutable": "npm",
|
"runtimeExecutable": "npm",
|
||||||
"runtimeArgs": ["run", "dev"],
|
"runtimeArgs": ["run", "dev"],
|
||||||
"port": 3000
|
"port": 3000,
|
||||||
|
"autoPort": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,3 +39,4 @@ yarn-error.log*
|
|||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
banners.psd
|
||||||
+230
@@ -0,0 +1,230 @@
|
|||||||
|
# sanihome.ir — project context
|
||||||
|
|
||||||
|
> **Keep this file current.** Whenever a change touches architecture, conventions,
|
||||||
|
> API integration, or adds/removes a major feature, update the relevant section
|
||||||
|
> here in the same session. This file exists so any AI assistant or developer
|
||||||
|
> picking up the repo cold — without the conversation history that produced it —
|
||||||
|
> can get oriented in minutes instead of re-deriving everything from the code
|
||||||
|
> and from trial-and-error against the live API.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
A Next.js 16 (App Router, Turbopack) storefront for **سانیهوم (Sanihome)**, a
|
||||||
|
Persian-language (RTL) home-appliance retailer, backed entirely by the
|
||||||
|
**Meshkee** commerce platform's public API. There is no local database —
|
||||||
|
every page reads live from `https://api.meshkee.com/api/v1`, tenant domain
|
||||||
|
`sanihome.ir`. See [`AGENTS.md`](AGENTS.md) — Next.js 16 has breaking changes
|
||||||
|
from what most training data assumes; read `node_modules/next/dist/docs/`
|
||||||
|
before touching App Router APIs you're not 100% sure of.
|
||||||
|
|
||||||
|
**Meshkee API docs** (always check before assuming a field/endpoint shape):
|
||||||
|
- Hub: https://api.meshkee.com/docs/website
|
||||||
|
- OpenAPI: https://api.meshkee.com/docs/website/openapi.json
|
||||||
|
- AI brief: https://api.meshkee.com/docs/website/AI_PROMPT.md
|
||||||
|
- The OpenAPI spec's `responses` are often undocumented (just a one-line
|
||||||
|
description like `{ cart }`) — when a shape isn't documented, `curl` the
|
||||||
|
live endpoint rather than guessing. Real examples discovered this way are
|
||||||
|
noted below.
|
||||||
|
|
||||||
|
## Stack
|
||||||
|
|
||||||
|
- Next.js 16, Turbopack, TypeScript, Tailwind v4 (`@tailwindcss/typography` for
|
||||||
|
rich HTML content).
|
||||||
|
- Swiper for carousels (`src/components/ui/Carousel.tsx` for
|
||||||
|
auto-width/free-mode rows; `FeaturedCategories.tsx` for a fixed
|
||||||
|
slides-per-view row).
|
||||||
|
- Two local font files supplied by the client — `public/fonts/*.woff`
|
||||||
|
(IRANYekan Light + Bold), loaded via `next/font/local` in
|
||||||
|
`src/app/layout.tsx`. Body text uses the light weight; **every heading tag
|
||||||
|
(`h1`–`h6`) uses the bold weight** via a plain CSS rule in `globals.css` —
|
||||||
|
don't reintroduce a Google-fonted Vazirmatn/etc., this was deliberately
|
||||||
|
replaced.
|
||||||
|
- No local dev-server port is guaranteed — `.claude/launch.json` has
|
||||||
|
`"autoPort": true` because other projects on this machine also default to
|
||||||
|
port 3000.
|
||||||
|
|
||||||
|
## Data layer (`src/lib/`)
|
||||||
|
|
||||||
|
- **`meshkee.ts`** — all public, unauthenticated reads (and the two
|
||||||
|
unauthenticated writes: comments, contact form) live here. Every
|
||||||
|
`normalize*` function reads defensively from multiple possible field names
|
||||||
|
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).
|
||||||
|
|
||||||
|
## Auth
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
## Data quirks (verified against the live catalog)
|
||||||
|
|
||||||
|
- **Persian name always wins**: every `name`-ish field prefers `nameFa` /
|
||||||
|
`productNameFa` over the English `title`/`name` — this is a Persian
|
||||||
|
storefront front-to-back.
|
||||||
|
- **Price/discount fields differ by source.** Some endpoints (plain
|
||||||
|
`/products` list) only ever give `store.minPrice/maxPrice` with no
|
||||||
|
original/discounted distinction. Others (store-specials, brand-groups,
|
||||||
|
store-items) nest `price`/`discountedPrice` one level down, in
|
||||||
|
`variants[0]` or on the item directly. `normalizeProduct` computes a
|
||||||
|
`discount` **percent** from real price/oldPrice numbers when the API
|
||||||
|
doesn't send one explicitly — never invent a percent without two real
|
||||||
|
prices behind it.
|
||||||
|
- **Most of the catalog has no price at all** (`store.minPrice: null`) and
|
||||||
|
**`technical-info` is empty for almost every product** — this is real data
|
||||||
|
state on the client's side, not a bug. The honest-empty-state path (a
|
||||||
|
disabled/"تماس با فروشگاه" control, or an `EmptyState` message) is the one
|
||||||
|
actually exercised for most products; don't "fix" it by fabricating values.
|
||||||
|
- **Group-source `id` vs `productId`**: store-specials/brand-groups/store-items
|
||||||
|
wrap a store-item row whose own `id` is *not* the product id — the real
|
||||||
|
product id is `raw.productId`. `normalizeProduct` prefers `productId`, and
|
||||||
|
cards/links that only have this id (no slug) route through
|
||||||
|
`/products/id/[id]` (`src/app/products/id/[id]/page.tsx`), which resolves
|
||||||
|
`GET /products/by-id/{id}` and redirects to the canonical slug URL.
|
||||||
|
- **Store-items vs Products**: a "store item" is one purchasable
|
||||||
|
variant/SKU (id = `storeItemVariantId` for the cart API). `/store-items`
|
||||||
|
and `/store-items/[id]` (variant-level browsing/detail) are a separate
|
||||||
|
surface from `/products` and `/products/[slug]` (product-level, with
|
||||||
|
descriptions/technical-info/full variation picker) — the store-item detail
|
||||||
|
page cross-references its parent product (`getProductById`) for
|
||||||
|
images/description/specs, since the variant endpoint alone only has
|
||||||
|
price/stock/selections.
|
||||||
|
|
||||||
|
## UI conventions (apply these by default; also noted in this session's
|
||||||
|
persistent memory as "for all the user's sites", not just this one)
|
||||||
|
|
||||||
|
- **Breadcrumb on every page except the homepage** — above the `<h1>`, via
|
||||||
|
`src/components/ui/Breadcrumb.tsx`.
|
||||||
|
- **Product detail layout**: 3-column grid (desktop) — gallery
|
||||||
|
(`ProductGallery`, ~1/3, includes hover-zoom + click-to-open lightbox) →
|
||||||
|
title + variation pickers (~5/12) → sticky buy-box (~1/4). One
|
||||||
|
`ProductPurchasePanel` client component owns the shared
|
||||||
|
selection/quantity/cart state and renders as a `Fragment` with two
|
||||||
|
grid-column-span children so it can span two non-adjacent grid cells while
|
||||||
|
the server renders the static header content into it via a prop.
|
||||||
|
- **Discount price display** (cards and buy-box both): old price
|
||||||
|
strikethrough + green percent badge **on the same line, badge to the
|
||||||
|
old price's left** — current price alone, bold, on the next line. Never a
|
||||||
|
min–max range once a real variant-driven price exists.
|
||||||
|
- **Equal-height cards in a `slidesPerView: "auto"` + freeMode Swiper row**:
|
||||||
|
Swiper's own `.swiper-slide { height: 100% }` doesn't stretch to the
|
||||||
|
tallest sibling in this mode (no definite ancestor height for the
|
||||||
|
percentage to resolve against). Fix applied in `Carousel.tsx`: override
|
||||||
|
the `<SwiperSlide>` to `height: "auto"` via inline style (wins over the
|
||||||
|
stylesheet regardless of import order) so normal flex-stretch equalizes
|
||||||
|
the row; pair with `flex h-full flex-col` on the card root and put the
|
||||||
|
button last so it pins to the bottom.
|
||||||
|
- **Tabbed product-detail section** (`ProductTabs`): مشخصات فنی / نقد و
|
||||||
|
بررسی / نظرات کاربران, in that RTL order (rightmost/default-active first
|
||||||
|
in the array — first DOM child renders rightmost under `dir="rtl"`).
|
||||||
|
- Category tile images: 110px, no border, no border-radius
|
||||||
|
(`FeaturedCategories.tsx`).
|
||||||
|
|
||||||
|
## Static-image slots
|
||||||
|
|
||||||
|
Admin-managed marketing images (banners, category tiles) — not tied to real
|
||||||
|
catalog data. `STATIC_IMAGE_SLOT_CATALOG` in `meshkee.ts` is the source of
|
||||||
|
truth for which slots exist; publishing it via
|
||||||
|
`src/app/meshkee/static-image-slots/route.ts` (`/meshkee/static-image-slots`)
|
||||||
|
is how the admin dashboard's "refresh" imports new keys. Current keys:
|
||||||
|
`home-hero`, `two-banner`, `three-banner-row`, `featured-categories`. Adding
|
||||||
|
a slot here does **not** make images appear — someone still has to upload
|
||||||
|
them in the dashboard; the code path just needs to fall back to whatever the
|
||||||
|
"current" behavior was before the slot existed when it's empty (see
|
||||||
|
`FeaturedCategories.tsx` for the pattern: real slot images when present,
|
||||||
|
else the pre-existing UI unchanged).
|
||||||
|
|
||||||
|
## Route map
|
||||||
|
|
||||||
|
| Route | Notes |
|
||||||
|
|---|---|
|
||||||
|
| `/` | Homepage — all the carousels/banners |
|
||||||
|
| `/products`, `/products/[slug]` | Catalog browsing, category filter via `?categoryId=` |
|
||||||
|
| `/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 |
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||||
|
import { Toast } from "@/components/ui/Toast";
|
||||||
|
import { submitContactForm } from "@/lib/meshkee";
|
||||||
|
|
||||||
|
const inputClass =
|
||||||
|
"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red";
|
||||||
|
|
||||||
|
const initialForm = { title: "", name: "", email: "", cellNumber: "", text: "" };
|
||||||
|
|
||||||
|
export default function ContactPage() {
|
||||||
|
const [form, setForm] = useState(initialForm);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [success, setSuccess] = useState(false);
|
||||||
|
const [toast, setToast] = useState(false);
|
||||||
|
|
||||||
|
const update = (field: keyof typeof form) => (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
|
||||||
|
setForm((prev) => ({ ...prev, [field]: event.target.value }));
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setSuccess(false);
|
||||||
|
const res = await submitContactForm({
|
||||||
|
title: form.title,
|
||||||
|
name: form.name,
|
||||||
|
email: form.email || undefined,
|
||||||
|
cellNumber: form.cellNumber || undefined,
|
||||||
|
text: form.text,
|
||||||
|
});
|
||||||
|
setBusy(false);
|
||||||
|
if (!res.ok) {
|
||||||
|
setError(res.message ?? "ارسال پیام ناموفق بود.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSuccess(true);
|
||||||
|
setForm(initialForm);
|
||||||
|
setToast(true);
|
||||||
|
setTimeout(() => setToast(false), 3000);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-2xl px-4 py-10">
|
||||||
|
<Breadcrumb items={[{ label: "خانه", href: "/" }, { label: "تماس با ما" }]} />
|
||||||
|
<h1 className="mb-2 text-2xl font-bold text-red-dark">تماس با ما</h1>
|
||||||
|
<p className="mb-6 text-sm text-muted">
|
||||||
|
سوال یا پیشنهادی دارید؟ فرم زیر را پر کنید تا در اسرع وقت پاسخ دهیم.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
placeholder="نام و نام خانوادگی"
|
||||||
|
value={form.name}
|
||||||
|
onChange={update("name")}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
placeholder="موضوع پیام"
|
||||||
|
value={form.title}
|
||||||
|
onChange={update("title")}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
placeholder="ایمیل (اختیاری)"
|
||||||
|
value={form.email}
|
||||||
|
onChange={update("email")}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
placeholder="شماره تماس (اختیاری)"
|
||||||
|
value={form.cellNumber}
|
||||||
|
onChange={update("cellNumber")}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
rows={5}
|
||||||
|
placeholder="متن پیام"
|
||||||
|
value={form.text}
|
||||||
|
onChange={update("text")}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error && <p className="text-sm text-red-dark">{error}</p>}
|
||||||
|
{success && <p className="text-sm text-green-700">پیام شما با موفقیت ارسال شد. متشکریم!</p>}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={busy}
|
||||||
|
className="rounded-xl bg-red px-8 py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{busy ? "در حال ارسال..." : "ارسال پیام"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<Toast message="پیام شما با موفقیت ارسال شد ✓" show={toast} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+7
-4
@@ -5,6 +5,7 @@ import "./globals.css";
|
|||||||
import { TopBar } from "@/components/home/TopBar";
|
import { TopBar } from "@/components/home/TopBar";
|
||||||
import { Header } from "@/components/home/Header";
|
import { Header } from "@/components/home/Header";
|
||||||
import { Footer } from "@/components/home/Footer";
|
import { Footer } from "@/components/home/Footer";
|
||||||
|
import { Providers } from "@/context/Providers";
|
||||||
import { getBusinessInfo, getCategories, getCategoryTree } from "@/lib/meshkee";
|
import { getBusinessInfo, getCategories, getCategoryTree } from "@/lib/meshkee";
|
||||||
|
|
||||||
// Body text — headings use the bold weight instead, see globals.css.
|
// Body text — headings use the bold weight instead, see globals.css.
|
||||||
@@ -45,10 +46,12 @@ export default async function RootLayout({ children }: LayoutProps<"/">) {
|
|||||||
className={`${iranyekan.variable} ${iranyekanBold.variable} ${syne.variable} h-full antialiased`}
|
className={`${iranyekan.variable} ${iranyekanBold.variable} ${syne.variable} h-full antialiased`}
|
||||||
>
|
>
|
||||||
<body className="min-h-full flex flex-col">
|
<body className="min-h-full flex flex-col">
|
||||||
<TopBar />
|
<Providers businessId={businessInfo?.id ?? "1"}>
|
||||||
<Header categoryTree={categoryTree} categories={categories} />
|
<TopBar />
|
||||||
<main>{children}</main>
|
<Header categoryTree={categoryTree} categories={categories} />
|
||||||
<Footer businessInfo={businessInfo} categories={categories} />
|
<main>{children}</main>
|
||||||
|
<Footer businessInfo={businessInfo} categories={categories} />
|
||||||
|
</Providers>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
|||||||
import { ProductGallery } from "@/components/product/ProductGallery";
|
import { ProductGallery } from "@/components/product/ProductGallery";
|
||||||
import { ProductPurchasePanel } from "@/components/product/ProductPurchasePanel";
|
import { ProductPurchasePanel } from "@/components/product/ProductPurchasePanel";
|
||||||
import { ProductTabs } from "@/components/product/ProductTabs";
|
import { ProductTabs } from "@/components/product/ProductTabs";
|
||||||
|
import { SimilarProducts } from "@/components/product/SimilarProducts";
|
||||||
import {
|
import {
|
||||||
getBusinessInfo,
|
getBusinessInfo,
|
||||||
|
getComments,
|
||||||
getProduct,
|
getProduct,
|
||||||
getProductStoreVariants,
|
getProductStoreVariants,
|
||||||
getProductTechnicalInfo,
|
getProductTechnicalInfo,
|
||||||
@@ -26,7 +28,10 @@ export default async function ProductDetailPage({
|
|||||||
|
|
||||||
if (!product) notFound();
|
if (!product) notFound();
|
||||||
|
|
||||||
const storeVariants = await getProductStoreVariants(product.id);
|
const [storeVariants, comments] = await Promise.all([
|
||||||
|
getProductStoreVariants(product.id),
|
||||||
|
getComments("product", product.id),
|
||||||
|
]);
|
||||||
const contactPhone = businessInfo?.phoneNumbers[0];
|
const contactPhone = businessInfo?.phoneNumbers[0];
|
||||||
const images = product.images.length > 0 ? product.images : product.image ? [product.image] : [];
|
const images = product.images.length > 0 ? product.images : product.image ? [product.image] : [];
|
||||||
|
|
||||||
@@ -72,7 +77,18 @@ export default async function ProductDetailPage({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ProductTabs technicalInfo={technicalInfo} descriptionHtml={product.descriptionHtml} />
|
<ProductTabs
|
||||||
|
technicalInfo={technicalInfo}
|
||||||
|
descriptionHtml={product.descriptionHtml}
|
||||||
|
entityId={product.id}
|
||||||
|
initialComments={comments}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SimilarProducts
|
||||||
|
categoryId={product.categoryId}
|
||||||
|
excludeProductId={product.id}
|
||||||
|
contactPhone={contactPhone}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,10 +78,13 @@ export default async function ProductsPage({
|
|||||||
name={product.name}
|
name={product.name}
|
||||||
brand={product.brand ?? ""}
|
brand={product.brand ?? ""}
|
||||||
price={product.price}
|
price={product.price}
|
||||||
|
oldPrice={product.oldPrice}
|
||||||
|
discount={product.discount}
|
||||||
image={product.image ?? "/images/placeholder.svg"}
|
image={product.image ?? "/images/placeholder.svg"}
|
||||||
href={productHref(product)}
|
href={productHref(product)}
|
||||||
fluid
|
fluid
|
||||||
contactPhone={contactPhone}
|
contactPhone={contactPhone}
|
||||||
|
variantId={product.variantId}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||||
|
import { ProductGallery } from "@/components/product/ProductGallery";
|
||||||
|
import { ProductPurchasePanel } from "@/components/product/ProductPurchasePanel";
|
||||||
|
import { ProductTabs } from "@/components/product/ProductTabs";
|
||||||
|
import { SimilarProducts } from "@/components/product/SimilarProducts";
|
||||||
|
import {
|
||||||
|
getBusinessInfo,
|
||||||
|
getComments,
|
||||||
|
getProductById,
|
||||||
|
getProductStoreVariants,
|
||||||
|
getProductTechnicalInfo,
|
||||||
|
getProductVariations,
|
||||||
|
getStoreItemVariant,
|
||||||
|
} from "@/lib/meshkee";
|
||||||
|
|
||||||
|
export default async function StoreItemDetailPage({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
}) {
|
||||||
|
const { id } = await params;
|
||||||
|
const variant = await getStoreItemVariant(id);
|
||||||
|
if (!variant) notFound();
|
||||||
|
|
||||||
|
const product = await getProductById(variant.productId);
|
||||||
|
if (!product) notFound();
|
||||||
|
|
||||||
|
const [technicalInfo, variations, businessInfo, comments] = await Promise.all([
|
||||||
|
getProductTechnicalInfo(product.slug),
|
||||||
|
getProductVariations(product.slug),
|
||||||
|
getBusinessInfo(),
|
||||||
|
getComments("product", product.id),
|
||||||
|
]);
|
||||||
|
const storeVariants = await getProductStoreVariants(product.id);
|
||||||
|
const contactPhone = businessInfo?.phoneNumbers[0];
|
||||||
|
const images = product.images.length > 0 ? product.images : product.image ? [product.image] : [];
|
||||||
|
|
||||||
|
// Land on the exact variant the shopper opened, not the first option of
|
||||||
|
// every variation.
|
||||||
|
const initialSelections = Object.fromEntries(
|
||||||
|
variant.selections.map((s) => [s.variationId, s.optionId]),
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||||
|
<Breadcrumb
|
||||||
|
items={[
|
||||||
|
{ label: "خانه", href: "/" },
|
||||||
|
{ label: "فروشگاه", href: "/store-items" },
|
||||||
|
...(product.categoryName
|
||||||
|
? [{ label: product.categoryName, href: `/products?categoryId=${product.categoryId}` }]
|
||||||
|
: []),
|
||||||
|
{ label: product.name },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="grid gap-8 md:grid-cols-12">
|
||||||
|
<div className="md:col-span-4">
|
||||||
|
<ProductGallery images={images} alt={product.name} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ProductPurchasePanel
|
||||||
|
header={
|
||||||
|
<>
|
||||||
|
{product.brand && (
|
||||||
|
<p className="font-display mb-2 text-xs tracking-wide text-muted uppercase">
|
||||||
|
{product.brand}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<h1 className="text-xl font-bold leading-relaxed md:text-2xl">{product.name}</h1>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
variations={variations}
|
||||||
|
storeVariants={storeVariants}
|
||||||
|
fallbackPrice={{
|
||||||
|
minPrice: product.minPrice,
|
||||||
|
maxPrice: product.maxPrice,
|
||||||
|
oldPrice: product.oldPrice,
|
||||||
|
discount: product.discount,
|
||||||
|
}}
|
||||||
|
inStock={product.inStock}
|
||||||
|
contactPhone={contactPhone}
|
||||||
|
storeName={businessInfo?.nameFa}
|
||||||
|
initialSelections={initialSelections}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ProductTabs
|
||||||
|
technicalInfo={technicalInfo}
|
||||||
|
descriptionHtml={product.descriptionHtml}
|
||||||
|
entityId={product.id}
|
||||||
|
initialComments={comments}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SimilarProducts
|
||||||
|
categoryId={product.categoryId}
|
||||||
|
excludeProductId={product.id}
|
||||||
|
contactPhone={contactPhone}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||||
|
import { ProductCard } from "@/components/ui/ProductCard";
|
||||||
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
|
import { getBusinessInfo, getStoreItems, storeItemHref } from "@/lib/meshkee";
|
||||||
|
|
||||||
|
const PAGE_SIZE = 24;
|
||||||
|
|
||||||
|
export default async function StoreItemsPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ categoryId?: string; q?: string; page?: string }>;
|
||||||
|
}) {
|
||||||
|
const params = await searchParams;
|
||||||
|
const page = Math.max(1, Number(params.page ?? 1) || 1);
|
||||||
|
const [{ items, total }, businessInfo] = await Promise.all([
|
||||||
|
getStoreItems({
|
||||||
|
categoryId: params.categoryId,
|
||||||
|
name: params.q,
|
||||||
|
page,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
}),
|
||||||
|
getBusinessInfo(),
|
||||||
|
]);
|
||||||
|
const contactPhone = businessInfo?.phoneNumbers[0];
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||||
|
|
||||||
|
const pageHref = (p: number) => {
|
||||||
|
const sp = new URLSearchParams();
|
||||||
|
if (params.categoryId) sp.set("categoryId", params.categoryId);
|
||||||
|
if (params.q) sp.set("q", params.q);
|
||||||
|
sp.set("page", String(p));
|
||||||
|
return `/store-items?${sp.toString()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||||
|
<Breadcrumb
|
||||||
|
items={[
|
||||||
|
{ label: "خانه", href: "/" },
|
||||||
|
{ label: "فروشگاه" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<h1 className="mb-6 text-2xl font-bold text-red-dark">
|
||||||
|
{params.q ? `نتایج جستجو برای «${params.q}»` : "فروشگاه"}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<EmptyState message="کالایی یافت نشد." />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
|
{items.map((item) => (
|
||||||
|
<ProductCard
|
||||||
|
key={item.id}
|
||||||
|
name={item.name}
|
||||||
|
brand={item.label}
|
||||||
|
price={item.price}
|
||||||
|
oldPrice={item.oldPrice}
|
||||||
|
discount={item.discount}
|
||||||
|
image={item.image ?? "/images/placeholder.svg"}
|
||||||
|
href={storeItemHref(item)}
|
||||||
|
fluid
|
||||||
|
contactPhone={contactPhone}
|
||||||
|
variantId={item.id}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="mt-8 flex items-center justify-center gap-3">
|
||||||
|
{page > 1 ? (
|
||||||
|
<a
|
||||||
|
href={pageHref(page - 1)}
|
||||||
|
className="rounded-lg border border-border px-4 py-2 text-sm text-muted transition-colors hover:border-red hover:text-red"
|
||||||
|
>
|
||||||
|
قبلی
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="rounded-lg border border-border px-4 py-2 text-sm text-muted/40">
|
||||||
|
قبلی
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="text-sm text-muted">
|
||||||
|
صفحه {page} از {totalPages}
|
||||||
|
</span>
|
||||||
|
{page < totalPages ? (
|
||||||
|
<a
|
||||||
|
href={pageHref(page + 1)}
|
||||||
|
className="rounded-lg border border-border px-4 py-2 text-sm text-muted transition-colors hover:border-red hover:text-red"
|
||||||
|
>
|
||||||
|
بعدی
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="rounded-lg border border-border px-4 py-2 text-sm text-muted/40">
|
||||||
|
بعدی
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"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}
|
||||||
|
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>
|
||||||
|
<span className="hidden sm:inline">سبد خرید</span>
|
||||||
|
{itemCount > 0 && (
|
||||||
|
<span className="absolute -top-1.5 -left-1.5 flex h-5 min-w-5 items-center justify-center rounded-full bg-red px-1 text-[10px] font-bold text-white">
|
||||||
|
{itemCount}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { formatPrice } from "@/data/sample";
|
||||||
|
import { useCart } from "@/context/CartContext";
|
||||||
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
|
|
||||||
|
export function CartPopup() {
|
||||||
|
const { cart, popupOpen, closePopup, updateItem, removeItem } = useCart();
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
const [busyId, setBusyId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => setMounted(true), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.body.style.overflow = popupOpen ? "hidden" : "";
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = "";
|
||||||
|
};
|
||||||
|
}, [popupOpen]);
|
||||||
|
|
||||||
|
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
|
||||||
|
onClick={closePopup}
|
||||||
|
className={`fixed inset-0 z-[100] bg-black/50 backdrop-blur-sm transition-opacity duration-300 ${
|
||||||
|
popupOpen ? "opacity-100" : "pointer-events-none opacity-0"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={`fixed top-0 right-0 z-[110] flex h-dvh w-[90%] max-w-md flex-col bg-surface shadow-2xl transition-transform duration-300 ease-out ${
|
||||||
|
popupOpen ? "translate-x-0" : "translate-x-full"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between border-b border-border p-5">
|
||||||
|
<h2 className="text-lg font-bold">سبد خرید</h2>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={closePopup}
|
||||||
|
aria-label="بستن"
|
||||||
|
className="flex h-9 w-9 items-center justify-center rounded-lg text-xl text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto p-5">
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<EmptyState message="سبد خرید شما خالی است." />
|
||||||
|
) : (
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{items.map((item) => (
|
||||||
|
<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}
|
||||||
|
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>}
|
||||||
|
<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"
|
||||||
|
aria-label="افزایش تعداد"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
<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"
|
||||||
|
aria-label="کاهش تعداد"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm font-bold text-red-dark">
|
||||||
|
{formatPrice(item.lineTotal)}
|
||||||
|
<span className="mr-0.5 text-[11px] font-normal text-muted">تومان</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{items.length > 0 && cart && (
|
||||||
|
<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)}
|
||||||
|
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href="/checkout"
|
||||||
|
className="block w-full rounded-xl bg-red py-3 text-center text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||||
|
>
|
||||||
|
ادامه فرآیند خرید
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -35,10 +35,13 @@ export function BrandGroupCarousels({
|
|||||||
name={product.name}
|
name={product.name}
|
||||||
brand={product.brand ?? ""}
|
brand={product.brand ?? ""}
|
||||||
price={product.price}
|
price={product.price}
|
||||||
|
oldPrice={product.oldPrice}
|
||||||
|
discount={product.discount}
|
||||||
image={product.image ?? "/images/placeholder.svg"}
|
image={product.image ?? "/images/placeholder.svg"}
|
||||||
variant="brand"
|
variant="brand"
|
||||||
href={productHref(product)}
|
href={productHref(product)}
|
||||||
contactPhone={contactPhone}
|
contactPhone={contactPhone}
|
||||||
|
variantId={product.variantId}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Carousel>
|
</Carousel>
|
||||||
|
|||||||
@@ -4,13 +4,15 @@ import { useEffect, useRef, useState } from "react";
|
|||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import type { Category, CategoryNode, CategoryTreeGroup } from "@/lib/meshkee";
|
import type { Category, CategoryNode, CategoryTreeGroup } from "@/lib/meshkee";
|
||||||
import { EmptyState } from "@/components/ui/EmptyState";
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
|
import { CartButton } from "@/components/cart/CartButton";
|
||||||
import { SearchBar } from "./SearchBar";
|
import { SearchBar } from "./SearchBar";
|
||||||
|
|
||||||
const navLinks = [
|
const navLinks = [
|
||||||
|
{ label: "فروشگاه", href: "/store-items" },
|
||||||
{ label: "فروش ویژه", href: "#" },
|
{ label: "فروش ویژه", href: "#" },
|
||||||
{ label: "درباره ما", href: "#" },
|
{ label: "درباره ما", href: "#" },
|
||||||
{ label: "سوالات متداول", href: "#" },
|
{ label: "سوالات متداول", href: "#" },
|
||||||
{ label: "تماس با ما", href: "#" },
|
{ label: "تماس با ما", href: "/contact" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const LOGIN_URL = "https://customer.sanihome.ir";
|
const LOGIN_URL = "https://customer.sanihome.ir";
|
||||||
@@ -251,16 +253,7 @@ export function Header({
|
|||||||
<span>👤</span>
|
<span>👤</span>
|
||||||
<span>ورود</span>
|
<span>ورود</span>
|
||||||
</a>
|
</a>
|
||||||
<button
|
<CartButton />
|
||||||
type="button"
|
|
||||||
className="relative flex items-center gap-1.5 rounded-lg border border-border px-3 py-2 transition-colors hover:border-red hover:text-red"
|
|
||||||
>
|
|
||||||
<span>🛒</span>
|
|
||||||
<span className="hidden sm:inline">سبد خرید</span>
|
|
||||||
<span className="absolute -top-1.5 -left-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-red text-[10px] font-bold text-white">
|
|
||||||
۲
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ export function SpecialSaleCarousel({
|
|||||||
variant="sale"
|
variant="sale"
|
||||||
href={productHref(product)}
|
href={productHref(product)}
|
||||||
contactPhone={contactPhone}
|
contactPhone={contactPhone}
|
||||||
|
variantId={product.variantId}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Carousel>
|
</Carousel>
|
||||||
|
|||||||
@@ -29,9 +29,12 @@ export function TopSellingCarousel({
|
|||||||
name={product.name}
|
name={product.name}
|
||||||
brand={product.brand ?? ""}
|
brand={product.brand ?? ""}
|
||||||
price={product.price}
|
price={product.price}
|
||||||
|
oldPrice={product.oldPrice}
|
||||||
|
discount={product.discount}
|
||||||
image={product.image ?? "/images/placeholder.svg"}
|
image={product.image ?? "/images/placeholder.svg"}
|
||||||
href={productHref(product)}
|
href={productHref(product)}
|
||||||
contactPhone={contactPhone}
|
contactPhone={contactPhone}
|
||||||
|
variantId={product.variantId}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Carousel>
|
</Carousel>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
|
||||||
function ChevronIcon({ direction, className }: { direction: "prev" | "next"; className?: string }) {
|
function ChevronIcon({ direction, className }: { direction: "prev" | "next"; className?: string }) {
|
||||||
const d = direction === "prev" ? "M14.5 6.5 9 12l5.5 5.5" : "M9.5 6.5 15 12l-5.5 5.5";
|
const d = direction === "prev" ? "M14.5 6.5 9 12l5.5 5.5" : "M9.5 6.5 15 12l-5.5 5.5";
|
||||||
@@ -11,10 +12,115 @@ function ChevronIcon({ direction, className }: { direction: "prev" | "next"; cla
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function CloseIcon({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
|
||||||
|
<path d="M6 6l12 12M18 6 6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Lightbox({
|
||||||
|
images,
|
||||||
|
alt,
|
||||||
|
index,
|
||||||
|
onIndexChange,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
images: string[];
|
||||||
|
alt: string;
|
||||||
|
index: number;
|
||||||
|
onIndexChange: (i: number) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
const hasMultiple = images.length > 1;
|
||||||
|
|
||||||
|
useEffect(() => setMounted(true), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") onClose();
|
||||||
|
if (event.key === "ArrowLeft") onIndexChange((index + 1) % images.length);
|
||||||
|
if (event.key === "ArrowRight") onIndexChange((index - 1 + images.length) % images.length);
|
||||||
|
};
|
||||||
|
document.addEventListener("keydown", onKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = "";
|
||||||
|
document.removeEventListener("keydown", onKeyDown);
|
||||||
|
};
|
||||||
|
}, [index, images.length, onClose, onIndexChange]);
|
||||||
|
|
||||||
|
if (!mounted) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="fixed inset-0 z-[120] flex flex-col bg-black/95" onClick={onClose}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="بستن"
|
||||||
|
className="absolute top-4 left-4 z-10 flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/20"
|
||||||
|
>
|
||||||
|
<CloseIcon className="h-6 w-6" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="relative flex flex-1 items-center justify-center p-6" onClick={(e) => e.stopPropagation()}>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={images[index]} alt={alt} className="max-h-full max-w-full object-contain" />
|
||||||
|
|
||||||
|
{hasMultiple && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onIndexChange((index - 1 + images.length) % images.length)}
|
||||||
|
aria-label="تصویر بعدی"
|
||||||
|
className="absolute top-1/2 right-4 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/20"
|
||||||
|
>
|
||||||
|
<ChevronIcon direction="prev" className="h-6 w-6" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onIndexChange((index + 1) % images.length)}
|
||||||
|
aria-label="تصویر قبلی"
|
||||||
|
className="absolute top-1/2 left-4 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/20"
|
||||||
|
>
|
||||||
|
<ChevronIcon direction="next" className="h-6 w-6" />
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hasMultiple && (
|
||||||
|
<div
|
||||||
|
className="flex justify-center gap-2 overflow-x-auto p-4"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{images.map((img, i) => (
|
||||||
|
<button
|
||||||
|
key={img + i}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onIndexChange(i)}
|
||||||
|
className={`h-14 w-14 shrink-0 overflow-hidden rounded-lg border-2 transition-colors ${
|
||||||
|
i === index ? "border-red" : "border-white/20"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={img} alt="" className="h-full w-full object-cover" />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ProductGallery({ images, alt }: { images: string[]; alt: string }) {
|
export function ProductGallery({ images, alt }: { images: string[]; alt: string }) {
|
||||||
const [index, setIndex] = useState(0);
|
const [index, setIndex] = useState(0);
|
||||||
const [zoomed, setZoomed] = useState(false);
|
const [zoomed, setZoomed] = useState(false);
|
||||||
const [origin, setOrigin] = useState({ x: 50, y: 50 });
|
const [origin, setOrigin] = useState({ x: 50, y: 50 });
|
||||||
|
const [lightboxOpen, setLightboxOpen] = useState(false);
|
||||||
|
|
||||||
const list = images.length > 0 ? images : ["/images/placeholder.svg"];
|
const list = images.length > 0 ? images : ["/images/placeholder.svg"];
|
||||||
const hasMultiple = list.length > 1;
|
const hasMultiple = list.length > 1;
|
||||||
@@ -41,11 +147,12 @@ export function ProductGallery({ images, alt }: { images: string[]; alt: string
|
|||||||
<img
|
<img
|
||||||
src={list[index]}
|
src={list[index]}
|
||||||
alt={alt}
|
alt={alt}
|
||||||
|
onClick={() => setLightboxOpen(true)}
|
||||||
className="h-full w-full object-contain transition-transform duration-200 ease-out"
|
className="h-full w-full object-contain transition-transform duration-200 ease-out"
|
||||||
style={{
|
style={{
|
||||||
transform: zoomed ? "scale(2)" : "scale(1)",
|
transform: zoomed ? "scale(2)" : "scale(1)",
|
||||||
transformOrigin: `${origin.x}% ${origin.y}%`,
|
transformOrigin: `${origin.x}% ${origin.y}%`,
|
||||||
cursor: zoomed ? "zoom-out" : "zoom-in",
|
cursor: zoomed ? "zoom-in" : "zoom-in",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -89,6 +196,16 @@ export function ProductGallery({ images, alt }: { images: string[]; alt: string
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{lightboxOpen && (
|
||||||
|
<Lightbox
|
||||||
|
images={list}
|
||||||
|
alt={alt}
|
||||||
|
index={index}
|
||||||
|
onIndexChange={setIndex}
|
||||||
|
onClose={() => setLightboxOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
import { type ReactNode, useMemo, useState } from "react";
|
import { type ReactNode, useMemo, useState } from "react";
|
||||||
import { formatPrice } from "@/data/sample";
|
import { formatPrice } from "@/data/sample";
|
||||||
import type { ProductStoreVariant, ProductVariation } from "@/lib/meshkee";
|
import type { ProductStoreVariant, ProductVariation } from "@/lib/meshkee";
|
||||||
|
import { useAuth } from "@/context/AuthContext";
|
||||||
|
import { useCart } from "@/context/CartContext";
|
||||||
|
|
||||||
function CheckIcon({ className }: { className?: string }) {
|
function CheckIcon({ className }: { className?: string }) {
|
||||||
return (
|
return (
|
||||||
@@ -26,6 +28,7 @@ export function ProductPurchasePanel({
|
|||||||
inStock,
|
inStock,
|
||||||
contactPhone,
|
contactPhone,
|
||||||
storeName,
|
storeName,
|
||||||
|
initialSelections,
|
||||||
}: {
|
}: {
|
||||||
header: ReactNode;
|
header: ReactNode;
|
||||||
variations: ProductVariation[];
|
variations: ProductVariation[];
|
||||||
@@ -39,8 +42,15 @@ export function ProductPurchasePanel({
|
|||||||
inStock: boolean;
|
inStock: boolean;
|
||||||
contactPhone?: string;
|
contactPhone?: string;
|
||||||
storeName?: string;
|
storeName?: string;
|
||||||
|
// Pre-select the variant a shopper landed on directly (e.g. a store-item
|
||||||
|
// detail page for one specific variant), instead of defaulting to the
|
||||||
|
// first option of every variation.
|
||||||
|
initialSelections?: Record<string, string>;
|
||||||
}) {
|
}) {
|
||||||
|
const { user, openLoginModal } = useAuth();
|
||||||
|
const { addItem } = useCart();
|
||||||
const [selected, setSelected] = useState<Record<string, string>>(() => {
|
const [selected, setSelected] = useState<Record<string, string>>(() => {
|
||||||
|
if (initialSelections && Object.keys(initialSelections).length > 0) return initialSelections;
|
||||||
const initial: Record<string, string> = {};
|
const initial: Record<string, string> = {};
|
||||||
for (const variation of variations) {
|
for (const variation of variations) {
|
||||||
if (variation.options[0]) initial[variation.id] = variation.options[0].id;
|
if (variation.options[0]) initial[variation.id] = variation.options[0].id;
|
||||||
@@ -48,9 +58,12 @@ export function ProductPurchasePanel({
|
|||||||
return initial;
|
return initial;
|
||||||
});
|
});
|
||||||
const [quantity, setQuantity] = useState(1);
|
const [quantity, setQuantity] = useState(1);
|
||||||
|
const [cartStatus, setCartStatus] = useState<"idle" | "busy" | "done">("idle");
|
||||||
|
const [cartError, setCartError] = useState<string | null>(null);
|
||||||
|
|
||||||
const matchedVariant = useMemo(() => {
|
const matchedVariant = useMemo(() => {
|
||||||
if (variations.length === 0) return null;
|
if (storeVariants.length === 0) return null;
|
||||||
|
if (variations.length === 0) return storeVariants[0] ?? null;
|
||||||
return (
|
return (
|
||||||
storeVariants.find((variant) =>
|
storeVariants.find((variant) =>
|
||||||
variations.every((variation) => {
|
variations.every((variation) => {
|
||||||
@@ -84,10 +97,28 @@ export function ProductPurchasePanel({
|
|||||||
? (oldPrice != null && price != null ? Math.round((1 - price / oldPrice) * 100) : null)
|
? (oldPrice != null && price != null ? Math.round((1 - price / oldPrice) * 100) : null)
|
||||||
: (fallbackPrice.discount ?? null);
|
: (fallbackPrice.discount ?? null);
|
||||||
|
|
||||||
const stockQuantity = hasVariations ? (matchedVariant?.stockQuantity ?? 0) : null;
|
const stockQuantity = matchedVariant ? matchedVariant.stockQuantity : null;
|
||||||
const available = hasVariations ? Boolean(matchedVariant) && stockQuantity! > 0 : inStock;
|
const available = matchedVariant ? stockQuantity! > 0 : inStock;
|
||||||
const maxQty = stockQuantity && stockQuantity > 0 ? stockQuantity : 99;
|
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 ?? "افزودن به سبد ناموفق بود.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="md:col-span-5">
|
<div className="md:col-span-5">
|
||||||
@@ -195,12 +226,15 @@ export function ProductPurchasePanel({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{cartError && <p className="mb-3 text-xs text-red-dark">{cartError}</p>}
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={!available}
|
onClick={handleAddToCart}
|
||||||
|
disabled={!available || cartStatus === "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:bg-red/60"
|
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" ? "به سبد اضافه شد ✓" : "افزودن به سبد خرید"}
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
) : contactPhone ? (
|
) : contactPhone ? (
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { EmptyState } from "@/components/ui/EmptyState";
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
import type { TechnicalInfoField } from "@/lib/meshkee";
|
import { useAuth } from "@/context/AuthContext";
|
||||||
|
import { postComment, type EntityComment, type TechnicalInfoField } from "@/lib/meshkee";
|
||||||
|
|
||||||
type Tab = "specs" | "review" | "comments";
|
type Tab = "specs" | "review" | "comments";
|
||||||
|
|
||||||
@@ -12,12 +13,105 @@ const TABS: { id: Tab; label: string }[] = [
|
|||||||
{ id: "comments", label: "نظرات کاربران" },
|
{ id: "comments", label: "نظرات کاربران" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
function formatDate(iso?: string) {
|
||||||
|
if (!iso) return "";
|
||||||
|
return new Intl.DateTimeFormat("fa-IR", { dateStyle: "medium" }).format(new Date(iso));
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommentsPanel({ entityId, initialComments }: { entityId: string; initialComments: EntityComment[] }) {
|
||||||
|
const { user, openLoginModal } = useAuth();
|
||||||
|
const [comments, setComments] = useState(initialComments);
|
||||||
|
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;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
const authorName = [user.firstName, user.lastName].filter(Boolean).join(" ") || "کاربر";
|
||||||
|
const res = await postComment({
|
||||||
|
entityType: "product",
|
||||||
|
entityId,
|
||||||
|
authorName,
|
||||||
|
authorEmail: user.email,
|
||||||
|
text: text.trim(),
|
||||||
|
});
|
||||||
|
setBusy(false);
|
||||||
|
if (!res.ok) {
|
||||||
|
setError(res.message ?? "ثبت نظر ناموفق بود.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setComments((prev) => [{ id: `local-${Date.now()}`, authorName, text: text.trim() }, ...prev]);
|
||||||
|
setText("");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{user ? (
|
||||||
|
<form onSubmit={handleSubmit} className="mb-6 space-y-3">
|
||||||
|
<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 || !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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{comments.length === 0 ? (
|
||||||
|
<EmptyState message="هنوز نظری برای این محصول ثبت نشده است." />
|
||||||
|
) : (
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{comments.map((comment) => (
|
||||||
|
<li key={comment.id} className="rounded-xl bg-background p-4">
|
||||||
|
<div className="mb-1 flex items-center justify-between">
|
||||||
|
<span className="text-sm font-bold">{comment.authorName}</span>
|
||||||
|
{comment.createdAt && (
|
||||||
|
<span className="text-xs text-muted">{formatDate(comment.createdAt)}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted">{comment.text}</p>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ProductTabs({
|
export function ProductTabs({
|
||||||
technicalInfo,
|
technicalInfo,
|
||||||
descriptionHtml,
|
descriptionHtml,
|
||||||
|
entityId,
|
||||||
|
initialComments = [],
|
||||||
}: {
|
}: {
|
||||||
technicalInfo: TechnicalInfoField[];
|
technicalInfo: TechnicalInfoField[];
|
||||||
descriptionHtml?: string;
|
descriptionHtml?: string;
|
||||||
|
entityId: string;
|
||||||
|
initialComments?: EntityComment[];
|
||||||
}) {
|
}) {
|
||||||
const [active, setActive] = useState<Tab>("specs");
|
const [active, setActive] = useState<Tab>("specs");
|
||||||
const activeLabel = TABS.find((t) => t.id === active)?.label ?? "";
|
const activeLabel = TABS.find((t) => t.id === active)?.label ?? "";
|
||||||
@@ -72,9 +166,7 @@ export function ProductTabs({
|
|||||||
<EmptyState message="هنوز نقد و بررسیای برای این محصول ثبت نشده است." />
|
<EmptyState message="هنوز نقد و بررسیای برای این محصول ثبت نشده است." />
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{active === "comments" && (
|
{active === "comments" && <CommentsPanel entityId={entityId} initialComments={initialComments} />}
|
||||||
<EmptyState message="هنوز نظری برای این محصول ثبت نشده است." />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { Carousel } from "@/components/ui/Carousel";
|
||||||
|
import { ProductCard } from "@/components/ui/ProductCard";
|
||||||
|
import { getProducts, productHref, type Product } from "@/lib/meshkee";
|
||||||
|
|
||||||
|
export async function SimilarProducts({
|
||||||
|
categoryId,
|
||||||
|
excludeProductId,
|
||||||
|
contactPhone,
|
||||||
|
}: {
|
||||||
|
categoryId?: string;
|
||||||
|
excludeProductId: string;
|
||||||
|
contactPhone?: string;
|
||||||
|
}) {
|
||||||
|
if (!categoryId) return null;
|
||||||
|
|
||||||
|
const { items } = await getProducts({ categoryId, pageSize: 9 });
|
||||||
|
const products: Product[] = items.filter((p) => p.id !== excludeProductId).slice(0, 8);
|
||||||
|
|
||||||
|
if (products.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-12 border-t border-border pt-10">
|
||||||
|
<h2 className="mb-5 flex items-center gap-2 text-lg font-bold">
|
||||||
|
<span className="h-2 w-2 shrink-0 rounded-full bg-red" aria-hidden />
|
||||||
|
محصولات مشابه
|
||||||
|
</h2>
|
||||||
|
<Carousel ariaLabel="محصولات مشابه">
|
||||||
|
{products.map((product) => (
|
||||||
|
<ProductCard
|
||||||
|
key={product.id}
|
||||||
|
name={product.name}
|
||||||
|
brand={product.brand ?? ""}
|
||||||
|
price={product.price}
|
||||||
|
oldPrice={product.oldPrice}
|
||||||
|
discount={product.discount}
|
||||||
|
image={product.image ?? "/images/placeholder.svg"}
|
||||||
|
href={productHref(product)}
|
||||||
|
contactPhone={contactPhone}
|
||||||
|
variantId={product.variantId}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Carousel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
import { Placeholder } from "./Placeholder";
|
import { Placeholder } from "./Placeholder";
|
||||||
import { formatPrice } from "@/data/sample";
|
import { formatPrice } from "@/data/sample";
|
||||||
|
import { useAuth } from "@/context/AuthContext";
|
||||||
|
import { useCart } from "@/context/CartContext";
|
||||||
|
|
||||||
type ProductCardProps = {
|
type ProductCardProps = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -12,6 +17,10 @@ type ProductCardProps = {
|
|||||||
href?: string;
|
href?: string;
|
||||||
fluid?: boolean;
|
fluid?: boolean;
|
||||||
contactPhone?: string;
|
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.
|
||||||
|
variantId?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function ProductCard({
|
export function ProductCard({
|
||||||
@@ -25,7 +34,24 @@ export function ProductCard({
|
|||||||
href,
|
href,
|
||||||
fluid = false,
|
fluid = false,
|
||||||
contactPhone,
|
contactPhone,
|
||||||
|
variantId,
|
||||||
}: ProductCardProps) {
|
}: ProductCardProps) {
|
||||||
|
const { user, openLoginModal } = useAuth();
|
||||||
|
const { addItem } = useCart();
|
||||||
|
const [status, setStatus] = useState<"idle" | "busy" | "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 info = (
|
const info = (
|
||||||
<>
|
<>
|
||||||
<div className="relative p-[10px]">
|
<div className="relative p-[10px]">
|
||||||
@@ -87,13 +113,22 @@ export function ProductCard({
|
|||||||
<div className="flex-1">{info}</div>
|
<div className="flex-1">{info}</div>
|
||||||
)}
|
)}
|
||||||
<div className="p-4">
|
<div className="p-4">
|
||||||
{price != null ? (
|
{price != null && variantId ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="w-full rounded-lg bg-red py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
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"
|
||||||
|
>
|
||||||
|
{status === "done" ? "افزوده شد ✓" : "افزودن به سبد"}
|
||||||
|
</button>
|
||||||
|
) : price != null && href ? (
|
||||||
|
<a
|
||||||
|
href={href}
|
||||||
|
className="block w-full rounded-lg bg-red py-2 text-center text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||||
>
|
>
|
||||||
افزودن به سبد
|
افزودن به سبد
|
||||||
</button>
|
</a>
|
||||||
) : contactPhone ? (
|
) : contactPhone ? (
|
||||||
<a
|
<a
|
||||||
href={`tel:${contactPhone}`}
|
href={`tel:${contactPhone}`}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export function Toast({ message, show }: { message: string; show: boolean }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
className={`fixed bottom-6 left-1/2 z-[130] -translate-x-1/2 rounded-xl bg-foreground px-5 py-3 text-sm text-white shadow-lg transition-all duration-300 ${
|
||||||
|
show ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-4 opacity-0"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"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 };
|
||||||
|
|
||||||
|
type CartContextValue = {
|
||||||
|
cart: Cart | null;
|
||||||
|
itemCount: number;
|
||||||
|
loading: boolean;
|
||||||
|
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>;
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
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]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
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 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 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 value = useMemo<CartContextValue>(
|
||||||
|
() => ({
|
||||||
|
cart,
|
||||||
|
itemCount: cart?.itemCount ?? 0,
|
||||||
|
loading,
|
||||||
|
popupOpen,
|
||||||
|
openPopup: () => setPopupOpen(true),
|
||||||
|
closePopup: () => setPopupOpen(false),
|
||||||
|
businessId,
|
||||||
|
addItem,
|
||||||
|
updateItem,
|
||||||
|
removeItem,
|
||||||
|
refresh,
|
||||||
|
}),
|
||||||
|
[cart, loading, popupOpen, businessId, addItem, updateItem, removeItem, refresh],
|
||||||
|
);
|
||||||
|
|
||||||
|
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,18 @@
|
|||||||
|
"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 }) {
|
||||||
|
return (
|
||||||
|
<AuthProvider>
|
||||||
|
<CartProvider businessId={businessId}>
|
||||||
|
{children}
|
||||||
|
<LoginModal />
|
||||||
|
<CartPopup />
|
||||||
|
</CartProvider>
|
||||||
|
</AuthProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
+211
@@ -0,0 +1,211 @@
|
|||||||
|
// 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
@@ -0,0 +1,171 @@
|
|||||||
|
// 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),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+122
-5
@@ -21,6 +21,30 @@ 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.
|
||||||
|
async function apiPost<T>(
|
||||||
|
path: string,
|
||||||
|
body: Record<string, unknown>,
|
||||||
|
): Promise<{ ok: true; data: T } | { ok: false; message: string }> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}${path}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
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 type BusinessInfo = {
|
export type BusinessInfo = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -116,6 +140,11 @@ export type Product = {
|
|||||||
oldPrice?: number | null;
|
oldPrice?: number | null;
|
||||||
discount?: number;
|
discount?: number;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
|
// The specific purchasable store-item variant this card came from (only
|
||||||
|
// known for sources that already resolved one, e.g. store-specials,
|
||||||
|
// brand-groups, store-items — lets "add to cart" skip a variant picker).
|
||||||
|
variantId?: string;
|
||||||
|
stockQuantity?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
function normalizeProduct(raw: Record<string, unknown>): Product {
|
function normalizeProduct(raw: Record<string, unknown>): Product {
|
||||||
@@ -163,6 +192,9 @@ function normalizeProduct(raw: Record<string, unknown>): Product {
|
|||||||
? brand
|
? brand
|
||||||
: ((brand as Record<string, unknown> | undefined)?.name as string | undefined) ??
|
: ((brand as Record<string, unknown> | undefined)?.name as string | undefined) ??
|
||||||
(raw.brandName as string | undefined),
|
(raw.brandName as string | undefined),
|
||||||
|
variantId: firstVariant?.id != null ? String(firstVariant.id) : undefined,
|
||||||
|
stockQuantity:
|
||||||
|
firstVariant?.stockQuantity != null ? Number(firstVariant.stockQuantity) : undefined,
|
||||||
price: numericPrice,
|
price: numericPrice,
|
||||||
oldPrice: numericOldPrice,
|
oldPrice: numericOldPrice,
|
||||||
discount,
|
discount,
|
||||||
@@ -322,29 +354,41 @@ export async function getProductTechnicalInfo(slug: string): Promise<TechnicalIn
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type StoreItem = {
|
export type StoreItem = {
|
||||||
id: string;
|
id: string; // the store-item VARIANT id — what the cart API calls storeItemVariantId
|
||||||
productId: string;
|
productId: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
label: string;
|
||||||
image: string | null;
|
image: string | null;
|
||||||
price: number | null;
|
price: number | null;
|
||||||
discountedPrice: number | null;
|
oldPrice: number | null;
|
||||||
|
discount?: number;
|
||||||
stockQuantity: number;
|
stockQuantity: number;
|
||||||
isFestival: boolean;
|
isFestival: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function normalizeStoreItem(raw: Record<string, unknown>): StoreItem {
|
function normalizeStoreItem(raw: Record<string, unknown>): StoreItem {
|
||||||
|
const rawPrice = raw.price != null ? Number(raw.price) : null;
|
||||||
|
const rawDiscounted = raw.discountedPrice != null ? Number(raw.discountedPrice) : null;
|
||||||
|
const hasDiscount = rawDiscounted != null && rawPrice != null && rawDiscounted !== rawPrice;
|
||||||
return {
|
return {
|
||||||
id: String(raw.id ?? ""),
|
id: String(raw.id ?? ""),
|
||||||
productId: String(raw.productId ?? ""),
|
productId: String(raw.productId ?? ""),
|
||||||
name: String(raw.productTitle ?? raw.productNameFa ?? raw.label ?? ""),
|
// Prefer the Persian name — sanihome.ir is a Persian storefront.
|
||||||
|
name: String(raw.productNameFa ?? raw.productTitle ?? raw.label ?? ""),
|
||||||
|
label: String(raw.label ?? ""),
|
||||||
image: (raw.productImage as string | undefined) ?? null,
|
image: (raw.productImage as string | undefined) ?? null,
|
||||||
price: raw.price != null ? Number(raw.price) : null,
|
price: hasDiscount ? rawDiscounted : rawPrice,
|
||||||
discountedPrice: raw.discountedPrice != null ? Number(raw.discountedPrice) : null,
|
oldPrice: hasDiscount ? rawPrice : null,
|
||||||
|
discount: hasDiscount ? Math.round((1 - rawDiscounted! / rawPrice!) * 100) : undefined,
|
||||||
stockQuantity: Number(raw.stockQuantity ?? 0),
|
stockQuantity: Number(raw.stockQuantity ?? 0),
|
||||||
isFestival: Boolean(raw.isFestival),
|
isFestival: Boolean(raw.isFestival),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function storeItemHref(item: { id: string }): string {
|
||||||
|
return `/store-items/${item.id}`;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getStoreItems(params?: {
|
export async function getStoreItems(params?: {
|
||||||
page?: number;
|
page?: number;
|
||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
@@ -364,6 +408,30 @@ export async function getStoreItems(params?: {
|
|||||||
return { items: (res?.items ?? []).map(normalizeStoreItem), total: res?.total ?? 0 };
|
return { items: (res?.items ?? []).map(normalizeStoreItem), total: res?.total ?? 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One specific variant's full detail — cross-referenced with its parent
|
||||||
|
// product (getProductById) for images/description/technical-info, since the
|
||||||
|
// variant endpoint itself only carries price/stock/selections.
|
||||||
|
export type StoreItemVariantDetail = StoreItem & {
|
||||||
|
selections: { variationId: string; variationName: string; optionId: string; value: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getStoreItemVariant(variantId: string): Promise<StoreItemVariantDetail | null> {
|
||||||
|
const res = await apiGet<{ variant: Record<string, unknown> }>(
|
||||||
|
`/tenants/${DOMAIN}/store-items/${variantId}`,
|
||||||
|
);
|
||||||
|
if (!res?.variant) return null;
|
||||||
|
const raw = res.variant;
|
||||||
|
return {
|
||||||
|
...normalizeStoreItem(raw),
|
||||||
|
selections: ((raw.selections as Record<string, unknown>[] | undefined) ?? []).map((s) => ({
|
||||||
|
variationId: String(s.variationId ?? ""),
|
||||||
|
variationName: String(s.variationName ?? ""),
|
||||||
|
optionId: String(s.optionId ?? ""),
|
||||||
|
value: String(s.value ?? ""),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export type BlogSummary = {
|
export type BlogSummary = {
|
||||||
id: string;
|
id: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -575,3 +643,52 @@ export function firstImageForSlot(
|
|||||||
): StaticImageWithUrl | undefined {
|
): StaticImageWithUrl | undefined {
|
||||||
return imagesForSlot(slots, key)[0];
|
return imagesForSlot(slots, key)[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Comments — public read, public write (POST /comments needs no auth on
|
||||||
|
// Meshkee's side), but the user wants the storefront itself to only let
|
||||||
|
// logged-in customers post; see ProductTabs' comments panel.
|
||||||
|
export type EntityComment = {
|
||||||
|
id: string;
|
||||||
|
authorName: string;
|
||||||
|
text: string;
|
||||||
|
createdAt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getComments(
|
||||||
|
entityType: "product" | "blog" | "portfolio" | "video",
|
||||||
|
entityId: string,
|
||||||
|
): Promise<EntityComment[]> {
|
||||||
|
const res = await apiGet<{ items: Record<string, unknown>[] }>(`/tenants/${DOMAIN}/comments`, {
|
||||||
|
entityType,
|
||||||
|
entityId,
|
||||||
|
});
|
||||||
|
return (res?.items ?? []).map((c) => ({
|
||||||
|
id: String(c.id ?? ""),
|
||||||
|
authorName: String(c.authorName ?? ""),
|
||||||
|
text: String(c.text ?? ""),
|
||||||
|
createdAt: c.createdAt as string | undefined,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function postComment(input: {
|
||||||
|
entityType: "product" | "blog" | "portfolio" | "video";
|
||||||
|
entityId: string;
|
||||||
|
authorName: string;
|
||||||
|
authorEmail?: string;
|
||||||
|
text: string;
|
||||||
|
}): Promise<{ ok: boolean; message?: string }> {
|
||||||
|
const res = await apiPost(`/tenants/${DOMAIN}/comments`, input);
|
||||||
|
return res.ok ? { ok: true } : { ok: false, message: res.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contact form
|
||||||
|
export async function submitContactForm(input: {
|
||||||
|
title: string;
|
||||||
|
name: string;
|
||||||
|
email?: string;
|
||||||
|
cellNumber?: string;
|
||||||
|
text: string;
|
||||||
|
}): Promise<{ ok: boolean; message?: string }> {
|
||||||
|
const res = await apiPost(`/tenants/${DOMAIN}/contact-submissions`, input);
|
||||||
|
return res.ok ? { ok: true } : { ok: false, message: res.message };
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user