Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18bf90bbb6 | ||
|
|
10c70359aa | ||
|
|
f0d8276c3e | ||
|
|
0d6e98bf89 | ||
|
|
c53fb99330 |
+1
-2
@@ -5,8 +5,7 @@
|
|||||||
"name": "sanihome-dev",
|
"name": "sanihome-dev",
|
||||||
"runtimeExecutable": "npm",
|
"runtimeExecutable": "npm",
|
||||||
"runtimeArgs": ["run", "dev"],
|
"runtimeArgs": ["run", "dev"],
|
||||||
"port": 3000,
|
"port": 3000
|
||||||
"autoPort": true
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,4 +39,3 @@ yarn-error.log*
|
|||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
banners.psd
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
Build the shopping cart for this Meshkee storefront using the Website API only (https://api.meshkee.com/api/v1).
|
||||||
|
|
||||||
|
Domain: sanihome.ir (replace if different)
|
||||||
|
|
||||||
|
Resolve tenant: GET /tenants/{domain} → save businessId.
|
||||||
|
Add to cart: authenticated POST /businesses/{businessId}/cart/items.
|
||||||
|
Cart popup/drawer: list items, update qty, remove item, show total; header badge with item count.
|
||||||
|
Click on popup cart list Continue button:
|
||||||
|
If logged in → go to /checkout (or /checkout/cart).
|
||||||
|
If not logged in → /login?redirect=/checkout/cart (same-origin path only).
|
||||||
|
After login/register: read redirect from URL and send user back to cart/checkout (not home).
|
||||||
|
Checkout: address + payment; for online pay use payment.type = "e_payment_gate", gatewayType, and absolute returnUrl.
|
||||||
|
Use bearer token for all cart/order calls. Register/login must include "domain": "{domain}".
|
||||||
|
Do not use CMS/dashboard APIs. Keep cart state in API (not only localStorage).
|
||||||
-230
@@ -1,230 +0,0 @@
|
|||||||
# 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,34 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const res = await meshkeeFetch("/auth/addresses", { token });
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Failed" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (!body?.province || !body?.city || !body?.address) {
|
||||||
|
return jsonResponse({ error: "آدرس کامل الزامی است" }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await meshkeeFetch("/auth/addresses", {
|
||||||
|
method: "POST",
|
||||||
|
token,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Failed" }, res.status);
|
||||||
|
return jsonResponse(res.data, res.status === 201 ? 201 : 200);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { getBearerToken, jsonResponse, meshkeeFetch, unauthorizedResponse } from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const res = await meshkeeFetch("/auth/handoff", {
|
||||||
|
method: "POST",
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return jsonResponse(
|
||||||
|
{ error: "امکان باز کردن پنل مدیریت نیست." },
|
||||||
|
res.status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { jsonResponse, meshkeeFetch } from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (!body?.cellNumber || !body?.password) {
|
||||||
|
return jsonResponse({ error: "شماره موبایل و رمز عبور الزامی است" }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await meshkeeFetch("/auth/login", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
cellNumber: body.cellNumber,
|
||||||
|
password: body.password,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return jsonResponse(
|
||||||
|
{ error: "ورود ناموفق بود. اطلاعات را بررسی کنید." },
|
||||||
|
res.status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const res = await meshkeeFetch("/auth/me", { token });
|
||||||
|
if (!res.ok) return jsonResponse({ error: "Unauthorized" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { DOMAIN } from "@/lib/meshkee";
|
||||||
|
import { jsonResponse, meshkeeFetch } from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (
|
||||||
|
!body?.cellNumber ||
|
||||||
|
!body?.password ||
|
||||||
|
!body?.firstName ||
|
||||||
|
!body?.lastName
|
||||||
|
) {
|
||||||
|
return jsonResponse({ error: "لطفاً همه فیلدهای الزامی را پر کنید" }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await meshkeeFetch("/auth/register", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
cellNumber: body.cellNumber,
|
||||||
|
password: body.password,
|
||||||
|
firstName: body.firstName,
|
||||||
|
lastName: body.lastName,
|
||||||
|
email: body.email,
|
||||||
|
domain: DOMAIN,
|
||||||
|
acknowledgeExistingAccount: body.acknowledgeExistingAccount ?? false,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return jsonResponse(
|
||||||
|
{ error: "ثبتنام ناموفق بود. اطلاعات را بررسی کنید." },
|
||||||
|
res.status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return jsonResponse(res.data, 201);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
resolveBusinessId,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (!body?.payment) {
|
||||||
|
return jsonResponse({ error: "payment is required" }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/cart/checkout`, {
|
||||||
|
method: "POST",
|
||||||
|
token,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Checkout failed" }, res.status);
|
||||||
|
return jsonResponse(res.data, res.status === 201 ? 201 : 200);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
resolveBusinessId,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
type RouteContext = { params: Promise<{ itemId: string }> };
|
||||||
|
|
||||||
|
export async function PATCH(request: Request, context: RouteContext) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const { itemId } = await context.params;
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (!body?.quantity) return jsonResponse({ error: "quantity is required" }, 400);
|
||||||
|
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/cart/items/${itemId}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
token,
|
||||||
|
body: JSON.stringify({ quantity: body.quantity }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Update failed" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_request: Request, context: RouteContext) {
|
||||||
|
const token = getBearerToken(_request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const { itemId } = await context.params;
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/cart/items/${itemId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Remove failed" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
resolveBusinessId,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (!body?.storeItemVariantId) {
|
||||||
|
return jsonResponse({ error: "storeItemVariantId is required" }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/cart/items`, {
|
||||||
|
method: "POST",
|
||||||
|
token,
|
||||||
|
body: JSON.stringify({
|
||||||
|
storeItemVariantId: body.storeItemVariantId,
|
||||||
|
quantity: body.quantity ?? 1,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Add to cart failed" }, res.status);
|
||||||
|
return jsonResponse(res.data, res.status === 201 ? 201 : 200);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
resolveBusinessId,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/cart`, { token });
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Cart error" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/cart`, {
|
||||||
|
method: "DELETE",
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Cart error" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import {
|
||||||
|
getBearerToken,
|
||||||
|
jsonResponse,
|
||||||
|
meshkeeFetch,
|
||||||
|
resolveBusinessId,
|
||||||
|
unauthorizedResponse,
|
||||||
|
} from "@/lib/meshkee-server";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const token = getBearerToken(request);
|
||||||
|
if (!token) return unauthorizedResponse();
|
||||||
|
|
||||||
|
const businessId = await resolveBusinessId();
|
||||||
|
if (!businessId) return jsonResponse({ error: "Tenant not found" }, 404);
|
||||||
|
|
||||||
|
const res = await meshkeeFetch(`/businesses/${businessId}/payments/methods`, { token });
|
||||||
|
if (!res.ok) return jsonResponse(res.data ?? { error: "Failed" }, res.status);
|
||||||
|
return jsonResponse(res.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||||
|
import { CheckoutCartPage } from "@/components/checkout/CheckoutCartPage";
|
||||||
|
|
||||||
|
export default function CheckoutCartRoute() {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||||
|
<Breadcrumb
|
||||||
|
items={[
|
||||||
|
{ label: "خانه", href: "/" },
|
||||||
|
{ label: "سبد خرید" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<CheckoutCartPage />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||||
|
|
||||||
|
export default async function CheckoutCompletePage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ status?: string; orderId?: string }>;
|
||||||
|
}) {
|
||||||
|
const { status, orderId } = await searchParams;
|
||||||
|
const failed = status === "failed";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||||
|
<Breadcrumb items={[{ label: "خانه", href: "/" }, { label: "نتیجه پرداخت" }]} />
|
||||||
|
<div className="mx-auto max-w-lg rounded-2xl border border-border bg-surface p-8 text-center">
|
||||||
|
<h1 className="mb-3 text-2xl font-bold">
|
||||||
|
{failed ? "پرداخت ناموفق بود" : "سفارش شما ثبت شد"}
|
||||||
|
</h1>
|
||||||
|
{orderId && (
|
||||||
|
<p className="mb-4 text-sm text-muted">
|
||||||
|
شماره سفارش: {new Intl.NumberFormat("fa-IR").format(Number(orderId) || 0) || orderId}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Link
|
||||||
|
href="/products"
|
||||||
|
className="inline-flex rounded-xl bg-red px-5 py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||||
|
>
|
||||||
|
بازگشت به فروشگاه
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+12
-186
@@ -1,192 +1,18 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
import { Breadcrumb } from "@/components/ui/Breadcrumb";
|
||||||
import { EmptyState } from "@/components/ui/EmptyState";
|
import { CheckoutPage } from "@/components/checkout/CheckoutPage";
|
||||||
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();
|
|
||||||
};
|
|
||||||
|
|
||||||
|
export default function CheckoutRoute() {
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto max-w-3xl px-4 py-10">
|
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||||
<Breadcrumb items={[{ label: "خانه", href: "/" }, { label: "تسویه حساب" }]} />
|
<Breadcrumb
|
||||||
<h1 className="mb-6 text-2xl font-bold text-red-dark">تسویه حساب</h1>
|
items={[
|
||||||
|
{ label: "خانه", href: "/" },
|
||||||
{!user ? (
|
{ label: "سبد خرید", href: "/checkout/cart" },
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-surface p-5">
|
{ label: "تسویه حساب" },
|
||||||
<span className="text-sm text-muted">برای تسویه حساب باید وارد حساب کاربری خود شوید.</span>
|
]}
|
||||||
<button
|
/>
|
||||||
type="button"
|
<h1 className="mb-6 text-2xl font-bold">تسویه حساب</h1>
|
||||||
onClick={openLoginModal}
|
<CheckoutPage />
|
||||||
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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+5
-3
@@ -5,7 +5,8 @@ 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 { AppProviders } from "@/components/providers/AppProviders";
|
||||||
|
import { Toast } from "@/components/ui/Toast";
|
||||||
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.
|
||||||
@@ -46,12 +47,13 @@ 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">
|
||||||
<Providers businessId={businessInfo?.id ?? "1"}>
|
<AppProviders businessId={businessInfo?.id ?? ""}>
|
||||||
<TopBar />
|
<TopBar />
|
||||||
<Header categoryTree={categoryTree} categories={categories} />
|
<Header categoryTree={categoryTree} categories={categories} />
|
||||||
<main>{children}</main>
|
<main>{children}</main>
|
||||||
<Footer businessInfo={businessInfo} categories={categories} />
|
<Footer businessInfo={businessInfo} categories={categories} />
|
||||||
</Providers>
|
<Toast />
|
||||||
|
</AppProviders>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,10 +3,8 @@ 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,
|
||||||
@@ -28,10 +26,7 @@ export default async function ProductDetailPage({
|
|||||||
|
|
||||||
if (!product) notFound();
|
if (!product) notFound();
|
||||||
|
|
||||||
const [storeVariants, comments] = await Promise.all([
|
const storeVariants = await getProductStoreVariants(product.id);
|
||||||
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] : [];
|
||||||
|
|
||||||
@@ -63,6 +58,9 @@ export default async function ProductDetailPage({
|
|||||||
<h1 className="text-xl font-bold leading-relaxed md:text-2xl">{product.name}</h1>
|
<h1 className="text-xl font-bold leading-relaxed md:text-2xl">{product.name}</h1>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
slug={product.slug}
|
||||||
|
name={product.name}
|
||||||
|
image={images[0] ?? product.image}
|
||||||
variations={variations}
|
variations={variations}
|
||||||
storeVariants={storeVariants}
|
storeVariants={storeVariants}
|
||||||
fallbackPrice={{
|
fallbackPrice={{
|
||||||
@@ -77,18 +75,7 @@ export default async function ProductDetailPage({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ProductTabs
|
<ProductTabs technicalInfo={technicalInfo} descriptionHtml={product.descriptionHtml} />
|
||||||
technicalInfo={technicalInfo}
|
|
||||||
descriptionHtml={product.descriptionHtml}
|
|
||||||
entityId={product.id}
|
|
||||||
initialComments={comments}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<SimilarProducts
|
|
||||||
categoryId={product.categoryId}
|
|
||||||
excludeProductId={product.id}
|
|
||||||
contactPhone={contactPhone}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,13 +78,10 @@ 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>
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { useAuth } from "@/context/AuthContext";
|
|
||||||
|
|
||||||
type Mode = "login" | "register";
|
|
||||||
type LoginMethod = "password" | "otp";
|
|
||||||
|
|
||||||
function CloseIcon() {
|
|
||||||
return (
|
|
||||||
<svg viewBox="0 0 24 24" fill="none" className="h-5 w-5" aria-hidden>
|
|
||||||
<path
|
|
||||||
d="M6 6l12 12M18 6 6 18"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
strokeLinecap="round"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const inputClass =
|
|
||||||
"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red";
|
|
||||||
|
|
||||||
export function LoginModal() {
|
|
||||||
const { loginModalOpen, closeLoginModal, login, loginOtp, sendOtp, register } = useAuth();
|
|
||||||
const [mode, setMode] = useState<Mode>("login");
|
|
||||||
const [method, setMethod] = useState<LoginMethod>("password");
|
|
||||||
const [cellNumber, setCellNumber] = useState("");
|
|
||||||
const [password, setPassword] = useState("");
|
|
||||||
const [code, setCode] = useState("");
|
|
||||||
const [otpSent, setOtpSent] = useState(false);
|
|
||||||
const [firstName, setFirstName] = useState("");
|
|
||||||
const [lastName, setLastName] = useState("");
|
|
||||||
const [email, setEmail] = useState("");
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [busy, setBusy] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!loginModalOpen) {
|
|
||||||
setError(null);
|
|
||||||
setBusy(false);
|
|
||||||
setOtpSent(false);
|
|
||||||
setCode("");
|
|
||||||
setPassword("");
|
|
||||||
}
|
|
||||||
}, [loginModalOpen]);
|
|
||||||
|
|
||||||
if (!loginModalOpen) return null;
|
|
||||||
|
|
||||||
const normalizedCell = cellNumber.trim();
|
|
||||||
|
|
||||||
const handleSendOtp = async () => {
|
|
||||||
setError(null);
|
|
||||||
setBusy(true);
|
|
||||||
const res = await sendOtp(normalizedCell);
|
|
||||||
setBusy(false);
|
|
||||||
if (!res.ok) return setError(res.message ?? "ارسال کد ناموفق بود.");
|
|
||||||
setOtpSent(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLoginSubmit = async (event: React.FormEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
setError(null);
|
|
||||||
setBusy(true);
|
|
||||||
const res =
|
|
||||||
method === "password" ? await login(normalizedCell, password) : await loginOtp(normalizedCell, code);
|
|
||||||
setBusy(false);
|
|
||||||
if (!res.ok) setError(res.message ?? "ورود ناموفق بود.");
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRegisterSubmit = async (event: React.FormEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
setError(null);
|
|
||||||
setBusy(true);
|
|
||||||
const res = await register({
|
|
||||||
cellNumber: normalizedCell,
|
|
||||||
password,
|
|
||||||
firstName,
|
|
||||||
lastName,
|
|
||||||
email: email || undefined,
|
|
||||||
});
|
|
||||||
setBusy(false);
|
|
||||||
if (!res.ok) setError(res.message ?? "ثبتنام ناموفق بود.");
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4"
|
|
||||||
onClick={closeLoginModal}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="w-full max-w-sm rounded-2xl bg-surface p-6 shadow-xl"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<div className="mb-5 flex items-center justify-between">
|
|
||||||
<h2 className="text-lg font-bold">{mode === "login" ? "ورود به حساب کاربری" : "ثبتنام"}</h2>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={closeLoginModal}
|
|
||||||
aria-label="بستن"
|
|
||||||
className="text-muted transition-colors hover:text-foreground"
|
|
||||||
>
|
|
||||||
<CloseIcon />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{mode === "login" ? (
|
|
||||||
<>
|
|
||||||
<div className="mb-4 flex gap-2 rounded-lg bg-background p-1 text-sm">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setMethod("password")}
|
|
||||||
className={`flex-1 rounded-md py-1.5 transition-colors ${
|
|
||||||
method === "password" ? "bg-surface font-medium text-red-dark shadow-sm" : "text-muted"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
رمز عبور
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setMethod("otp")}
|
|
||||||
className={`flex-1 rounded-md py-1.5 transition-colors ${
|
|
||||||
method === "otp" ? "bg-surface font-medium text-red-dark shadow-sm" : "text-muted"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
کد یکبار مصرف
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleLoginSubmit} className="space-y-3">
|
|
||||||
<input
|
|
||||||
type="tel"
|
|
||||||
inputMode="tel"
|
|
||||||
required
|
|
||||||
placeholder="شماره موبایل (مثلاً +989121234567)"
|
|
||||||
value={cellNumber}
|
|
||||||
onChange={(e) => setCellNumber(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{method === "password" ? (
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
required
|
|
||||||
placeholder="رمز عبور"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
) : otpSent ? (
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
inputMode="numeric"
|
|
||||||
required
|
|
||||||
maxLength={6}
|
|
||||||
placeholder="کد ۶ رقمی پیامکشده"
|
|
||||||
value={code}
|
|
||||||
onChange={(e) => setCode(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleSendOtp}
|
|
||||||
disabled={busy || !normalizedCell}
|
|
||||||
className="w-full rounded-lg border border-red text-red py-2 text-sm font-medium transition-colors hover:bg-red-light disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
>
|
|
||||||
ارسال کد
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{error && <p className="text-xs text-red-dark">{error}</p>}
|
|
||||||
|
|
||||||
{(method === "password" || otpSent) && (
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={busy}
|
|
||||||
className="w-full rounded-lg bg-red py-2.5 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
|
||||||
>
|
|
||||||
{busy ? "در حال ورود..." : "ورود"}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p className="mt-4 text-center text-xs text-muted">
|
|
||||||
حساب کاربری ندارید؟{" "}
|
|
||||||
<button type="button" onClick={() => setMode("register")} className="font-medium text-red">
|
|
||||||
ثبتنام کنید
|
|
||||||
</button>
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<form onSubmit={handleRegisterSubmit} className="space-y-3">
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
required
|
|
||||||
placeholder="نام"
|
|
||||||
value={firstName}
|
|
||||||
onChange={(e) => setFirstName(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
required
|
|
||||||
placeholder="نام خانوادگی"
|
|
||||||
value={lastName}
|
|
||||||
onChange={(e) => setLastName(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
type="tel"
|
|
||||||
inputMode="tel"
|
|
||||||
required
|
|
||||||
placeholder="شماره موبایل (مثلاً +989121234567)"
|
|
||||||
value={cellNumber}
|
|
||||||
onChange={(e) => setCellNumber(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="email"
|
|
||||||
placeholder="ایمیل (اختیاری)"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
required
|
|
||||||
minLength={8}
|
|
||||||
placeholder="رمز عبور (حداقل ۸ کاراکتر)"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
className={inputClass}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{error && <p className="text-xs text-red-dark">{error}</p>}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={busy}
|
|
||||||
className="w-full rounded-lg bg-red py-2.5 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
|
|
||||||
>
|
|
||||||
{busy ? "در حال ثبتنام..." : "ثبتنام"}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p className="mt-4 text-center text-xs text-muted">
|
|
||||||
قبلاً ثبتنام کردهاید؟{" "}
|
|
||||||
<button type="button" onClick={() => setMode("login")} className="font-medium text-red">
|
|
||||||
وارد شوید
|
|
||||||
</button>
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,105 +1,170 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { formatPrice } from "@/data/sample";
|
import { formatPrice } from "@/data/sample";
|
||||||
import { useCart } from "@/context/CartContext";
|
import { useAuth } from "@/lib/auth";
|
||||||
import { EmptyState } from "@/components/ui/EmptyState";
|
import { useCart } from "@/lib/cart";
|
||||||
|
import { customerContinueCheckoutUrl } from "@/lib/customer-auth";
|
||||||
|
|
||||||
export function CartPopup() {
|
type CartPopupProps = {
|
||||||
const { cart, popupOpen, closePopup, updateItem, removeItem } = useCart();
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CartPopup({ open, onClose }: CartPopupProps) {
|
||||||
|
const { isAuthenticated } = useAuth();
|
||||||
|
const {
|
||||||
|
items,
|
||||||
|
itemCount,
|
||||||
|
total,
|
||||||
|
loading,
|
||||||
|
removeItem,
|
||||||
|
setQuantity,
|
||||||
|
refresh,
|
||||||
|
} = useCart();
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
const [busyId, setBusyId] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => setMounted(true), []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.body.style.overflow = popupOpen ? "hidden" : "";
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) refresh();
|
||||||
|
}, [open, refresh]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") onClose();
|
||||||
|
};
|
||||||
|
document.addEventListener("keydown", onKeyDown);
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
return () => {
|
return () => {
|
||||||
|
document.removeEventListener("keydown", onKeyDown);
|
||||||
document.body.style.overflow = "";
|
document.body.style.overflow = "";
|
||||||
};
|
};
|
||||||
}, [popupOpen]);
|
}, [open, onClose]);
|
||||||
|
|
||||||
if (!mounted) return null;
|
if (!mounted || !open) return null;
|
||||||
|
|
||||||
const items = cart?.items ?? [];
|
// Hand off current lines to customer dashboard via #guestCart=
|
||||||
|
const continueHref = customerContinueCheckoutUrl(isAuthenticated, 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(
|
return createPortal(
|
||||||
<div aria-hidden={!popupOpen}>
|
<div>
|
||||||
<div
|
<div
|
||||||
onClick={closePopup}
|
onClick={onClose}
|
||||||
className={`fixed inset-0 z-[100] bg-black/50 backdrop-blur-sm transition-opacity duration-300 ${
|
className="fixed inset-0 z-[120] bg-black/40 backdrop-blur-sm"
|
||||||
popupOpen ? "opacity-100" : "pointer-events-none opacity-0"
|
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
<div
|
<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 ${
|
role="dialog"
|
||||||
popupOpen ? "translate-x-0" : "translate-x-full"
|
aria-modal="true"
|
||||||
}`}
|
aria-label="سبد خرید"
|
||||||
|
className="fixed top-0 left-0 z-[130] flex h-dvh w-full max-w-md animate-slide-in flex-col bg-surface shadow-2xl"
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between border-b border-border p-5">
|
<div className="flex items-center justify-between border-b border-border px-5 py-4">
|
||||||
<h2 className="text-lg font-bold">سبد خرید</h2>
|
<div>
|
||||||
|
<h2 className="text-base font-bold">سبد خرید</h2>
|
||||||
|
{itemCount > 0 && (
|
||||||
|
<p className="mt-0.5 text-xs text-muted">
|
||||||
|
{new Intl.NumberFormat("fa-IR").format(itemCount)} کالا
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={closePopup}
|
onClick={onClose}
|
||||||
aria-label="بستن"
|
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"
|
className="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||||
>
|
>
|
||||||
✕
|
✕
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex-1 overflow-y-auto p-5">
|
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||||
{items.length === 0 ? (
|
{items.length === 0 ? (
|
||||||
<EmptyState message="سبد خرید شما خالی است." />
|
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
|
||||||
|
<p className="text-sm text-muted">سبد خرید شما خالی است</p>
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<ul className="space-y-4">
|
<ul className="space-y-4">
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<li key={item.id} className="flex gap-3 border-b border-border pb-4">
|
<li
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
key={item.id}
|
||||||
<img
|
className="flex gap-3 border-b border-border pb-4 last:border-0"
|
||||||
src={item.productImage ?? "/images/placeholder.svg"}
|
>
|
||||||
alt={item.productNameFa ?? item.productTitle}
|
<Link
|
||||||
className="h-16 w-16 shrink-0 rounded-lg border border-border object-contain p-1"
|
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||||
/>
|
onClick={onClose}
|
||||||
|
className="h-20 w-20 shrink-0 overflow-hidden rounded-lg border border-border bg-background"
|
||||||
|
>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={item.image || "/images/logo.png"}
|
||||||
|
alt=""
|
||||||
|
className="h-full w-full object-contain p-1"
|
||||||
|
/>
|
||||||
|
</Link>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<p className="line-clamp-2 text-sm font-medium">
|
<Link
|
||||||
{item.productNameFa ?? item.productTitle}
|
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||||
</p>
|
onClick={onClose}
|
||||||
{item.label && <p className="mt-0.5 text-xs text-muted">{item.label}</p>}
|
className="line-clamp-2 text-sm font-medium leading-relaxed hover:text-red"
|
||||||
<div className="mt-2 flex items-center justify-between">
|
>
|
||||||
|
{item.name}
|
||||||
|
</Link>
|
||||||
|
{item.optionLabel && (
|
||||||
|
<p className="mt-1 text-xs text-muted">{item.optionLabel}</p>
|
||||||
|
)}
|
||||||
|
<div className="mt-2 flex items-center justify-between gap-2">
|
||||||
<div className="flex items-center rounded-lg border border-border">
|
<div className="flex items-center rounded-lg border border-border">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={busyId === item.id}
|
disabled={loading}
|
||||||
onClick={() => changeQty(item.id, item.quantity + 1)}
|
onClick={() => setQuantity(item.id, item.quantity + 1)}
|
||||||
className="px-2 py-1 text-sm disabled:opacity-40"
|
className="px-2 py-1 text-sm"
|
||||||
aria-label="افزایش تعداد"
|
|
||||||
>
|
>
|
||||||
+
|
+
|
||||||
</button>
|
</button>
|
||||||
<span className="min-w-6 text-center text-xs font-medium">{item.quantity}</span>
|
<span className="min-w-6 text-center text-xs">
|
||||||
|
{new Intl.NumberFormat("fa-IR").format(item.quantity)}
|
||||||
|
</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={busyId === item.id}
|
disabled={loading}
|
||||||
onClick={() => changeQty(item.id, item.quantity - 1)}
|
onClick={() => setQuantity(item.id, item.quantity - 1)}
|
||||||
className="px-2 py-1 text-sm disabled:opacity-40"
|
className="px-2 py-1 text-sm"
|
||||||
aria-label="کاهش تعداد"
|
|
||||||
>
|
>
|
||||||
−
|
−
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-sm font-bold text-red-dark">
|
<div className="flex items-center gap-3">
|
||||||
{formatPrice(item.lineTotal)}
|
<span className="text-sm font-bold text-red-dark">
|
||||||
<span className="mr-0.5 text-[11px] font-normal text-muted">تومان</span>
|
{formatPrice(item.price * item.quantity)}
|
||||||
</span>
|
<span className="mr-0.5 text-[11px] font-normal text-muted">
|
||||||
|
تومان
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => removeItem(item.id)}
|
||||||
|
aria-label="حذف"
|
||||||
|
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" className="h-4 w-4" aria-hidden>
|
||||||
|
<path
|
||||||
|
d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7M10 11v5M14 11v5"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.75"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
@@ -108,23 +173,34 @@ export function CartPopup() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{items.length > 0 && cart && (
|
<div className="border-t border-border px-5 py-4">
|
||||||
<div className="border-t border-border p-5">
|
{items.length > 0 && (
|
||||||
<div className="mb-4 flex items-center justify-between text-sm">
|
<div className="mb-3 flex items-center justify-between text-sm">
|
||||||
<span className="text-muted">جمع کل</span>
|
<span className="text-muted">جمع کل</span>
|
||||||
<span className="text-base font-bold text-red-dark">
|
<span className="font-bold text-red-dark">
|
||||||
{formatPrice(cart.subtotal)}
|
{formatPrice(total)}
|
||||||
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
|
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<a
|
)}
|
||||||
href="/checkout"
|
{items.length > 0 ? (
|
||||||
className="block w-full rounded-xl bg-red py-3 text-center text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
<Link
|
||||||
|
href={continueHref}
|
||||||
|
onClick={onClose}
|
||||||
|
className="flex w-full items-center justify-center rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||||
>
|
>
|
||||||
ادامه فرآیند خرید
|
ادامه
|
||||||
</a>
|
</Link>
|
||||||
</div>
|
) : (
|
||||||
)}
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="flex w-full items-center justify-center rounded-xl bg-red-light py-3 text-sm font-medium text-red-dark transition-colors hover:bg-red-muted/40"
|
||||||
|
>
|
||||||
|
ادامه خرید
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</div>,
|
||||||
document.body,
|
document.body,
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { formatPrice } from "@/data/sample";
|
||||||
|
import { useAuth } from "@/lib/auth";
|
||||||
|
import { useCart } from "@/lib/cart";
|
||||||
|
import { customerLoginUrl } from "@/lib/customer-auth";
|
||||||
|
|
||||||
|
export function CheckoutCartPage() {
|
||||||
|
const { isAuthenticated, ready: authReady } = useAuth();
|
||||||
|
const { items, itemCount, total, ready, loading, setQuantity, removeItem } = useCart();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authReady) return;
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
window.location.href = customerLoginUrl("/checkout/cart");
|
||||||
|
}
|
||||||
|
}, [authReady, isAuthenticated]);
|
||||||
|
|
||||||
|
if (!authReady || !ready || !isAuthenticated) {
|
||||||
|
return <div className="py-16 text-center text-sm text-muted">در حال بارگذاری...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-3xl">
|
||||||
|
<h1 className="mb-6 text-2xl font-bold">سبد خرید</h1>
|
||||||
|
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<div className="rounded-2xl border border-border bg-surface p-10 text-center">
|
||||||
|
<p className="mb-4 text-muted">سبد خرید شما خالی است</p>
|
||||||
|
<Link href="/products" className="text-sm font-medium text-red hover:text-red-dark">
|
||||||
|
ادامه خرید
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{items.map((item) => (
|
||||||
|
<li
|
||||||
|
key={item.id}
|
||||||
|
className="flex gap-4 rounded-2xl border border-border bg-surface p-4"
|
||||||
|
>
|
||||||
|
<div className="h-24 w-24 shrink-0 overflow-hidden rounded-lg border border-border bg-background">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={item.image || "/images/logo.png"}
|
||||||
|
alt=""
|
||||||
|
className="h-full w-full object-contain p-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<Link
|
||||||
|
href={item.slug ? `/products/${item.slug}` : "/products"}
|
||||||
|
className="line-clamp-2 font-medium hover:text-red"
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</Link>
|
||||||
|
{item.optionLabel && (
|
||||||
|
<p className="mt-1 text-xs text-muted">{item.optionLabel}</p>
|
||||||
|
)}
|
||||||
|
<div className="mt-3 flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div className="flex items-center rounded-xl border border-border">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => setQuantity(item.id, item.quantity + 1)}
|
||||||
|
className="px-3 py-1.5 text-lg"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
<span className="min-w-8 text-center text-sm">
|
||||||
|
{new Intl.NumberFormat("fa-IR").format(item.quantity)}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => setQuantity(item.id, item.quantity - 1)}
|
||||||
|
className="px-3 py-1.5 text-lg"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="font-bold text-red-dark">
|
||||||
|
{formatPrice(item.price * item.quantity)} تومان
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => removeItem(item.id)}
|
||||||
|
aria-label="حذف"
|
||||||
|
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" className="h-4 w-4" aria-hidden>
|
||||||
|
<path
|
||||||
|
d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7M10 11v5M14 11v5"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.75"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div className="mt-6 rounded-2xl border border-border bg-surface p-5">
|
||||||
|
<div className="mb-4 flex items-center justify-between text-sm">
|
||||||
|
<span className="text-muted">
|
||||||
|
{new Intl.NumberFormat("fa-IR").format(itemCount)} کالا
|
||||||
|
</span>
|
||||||
|
<span className="text-lg font-bold text-red-dark">
|
||||||
|
{formatPrice(total)} تومان
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
href="/checkout"
|
||||||
|
className="flex w-full items-center justify-center rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||||
|
>
|
||||||
|
ادامه
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { formatPrice } from "@/data/sample";
|
||||||
|
import { useAuth } from "@/lib/auth";
|
||||||
|
import { useCart } from "@/lib/cart";
|
||||||
|
import { customerLoginUrl } from "@/lib/customer-auth";
|
||||||
|
|
||||||
|
type Address = {
|
||||||
|
id: string;
|
||||||
|
label?: string;
|
||||||
|
province: string;
|
||||||
|
city: string;
|
||||||
|
address: string;
|
||||||
|
postalCode?: string;
|
||||||
|
landline?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PaymentMethods = {
|
||||||
|
cash?: boolean;
|
||||||
|
transfer?: boolean;
|
||||||
|
pos?: boolean;
|
||||||
|
ePayment?: {
|
||||||
|
enabled?: boolean;
|
||||||
|
defaultGateway?: string;
|
||||||
|
gateways?: string[];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CheckoutPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const { isAuthenticated, ready: authReady, getAccessToken } = useAuth();
|
||||||
|
const { items, total, ready: cartReady } = useCart();
|
||||||
|
|
||||||
|
const [addresses, setAddresses] = useState<Address[]>([]);
|
||||||
|
const [methods, setMethods] = useState<PaymentMethods | null>(null);
|
||||||
|
const [addressId, setAddressId] = useState("");
|
||||||
|
const [paymentType, setPaymentType] = useState<"cash" | "transfer" | "e_payment_gate">("cash");
|
||||||
|
const [gatewayType, setGatewayType] = useState("zarinpal");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [shipping, setShipping] = useState({
|
||||||
|
province: "",
|
||||||
|
city: "",
|
||||||
|
address: "",
|
||||||
|
postalCode: "",
|
||||||
|
landline: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authReady) return;
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
window.location.href = customerLoginUrl("/checkout");
|
||||||
|
}
|
||||||
|
}, [authReady, isAuthenticated]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (!token) return;
|
||||||
|
|
||||||
|
Promise.all([
|
||||||
|
fetch("/api/addresses", { headers: { Authorization: `Bearer ${token}` } }).then((r) =>
|
||||||
|
r.ok ? r.json() : { items: [] },
|
||||||
|
),
|
||||||
|
fetch("/api/payments/methods", { headers: { Authorization: `Bearer ${token}` } }).then((r) =>
|
||||||
|
r.ok ? r.json() : null,
|
||||||
|
),
|
||||||
|
]).then(([addressRes, methodsRes]) => {
|
||||||
|
const nextAddresses = (addressRes.items ?? []) as Address[];
|
||||||
|
setAddresses(nextAddresses);
|
||||||
|
if (nextAddresses[0]) setAddressId(nextAddresses[0].id);
|
||||||
|
|
||||||
|
const nextMethods = (methodsRes ?? methodsRes?.methods ?? methodsRes) as PaymentMethods;
|
||||||
|
setMethods(nextMethods);
|
||||||
|
if (nextMethods?.ePayment?.enabled) {
|
||||||
|
setPaymentType("e_payment_gate");
|
||||||
|
setGatewayType(nextMethods.ePayment.defaultGateway ?? nextMethods.ePayment.gateways?.[0] ?? "zarinpal");
|
||||||
|
} else if (nextMethods?.cash) {
|
||||||
|
setPaymentType("cash");
|
||||||
|
} else if (nextMethods?.transfer) {
|
||||||
|
setPaymentType("transfer");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, [getAccessToken, isAuthenticated]);
|
||||||
|
|
||||||
|
const onSubmit = async (event: React.FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (!token) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const payload: Record<string, unknown> = {
|
||||||
|
payment: { type: paymentType },
|
||||||
|
};
|
||||||
|
|
||||||
|
if (addressId) {
|
||||||
|
payload.addressId = addressId;
|
||||||
|
} else {
|
||||||
|
payload.shippingAddress = shipping;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (paymentType === "e_payment_gate") {
|
||||||
|
payload.payment = { type: paymentType, gatewayType };
|
||||||
|
payload.returnUrl = `${window.location.origin}/checkout/complete`;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/cart/checkout", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error ?? "ثبت سفارش ناموفق بود");
|
||||||
|
|
||||||
|
const redirect = data.payment?.redirect;
|
||||||
|
if (redirect?.url) {
|
||||||
|
if (redirect.method === "POST" && redirect.fields) {
|
||||||
|
const form = document.createElement("form");
|
||||||
|
form.method = "POST";
|
||||||
|
form.action = redirect.url;
|
||||||
|
for (const [key, value] of Object.entries(redirect.fields as Record<string, string>)) {
|
||||||
|
const input = document.createElement("input");
|
||||||
|
input.type = "hidden";
|
||||||
|
input.name = key;
|
||||||
|
input.value = value;
|
||||||
|
form.appendChild(input);
|
||||||
|
}
|
||||||
|
document.body.appendChild(form);
|
||||||
|
form.submit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.location.href = redirect.url;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
router.push(`/checkout/complete?orderId=${data.order?.id ?? ""}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "خطا در ثبت سفارش");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!authReady || !cartReady || !isAuthenticated) {
|
||||||
|
return <div className="py-16 text-center text-sm text-muted">در حال بارگذاری...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (items.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-2xl border border-border bg-surface p-10 text-center">
|
||||||
|
<p className="mb-4 text-muted">سبد خرید شما خالی است</p>
|
||||||
|
<Link href="/products" className="text-sm font-medium text-red hover:text-red-dark">
|
||||||
|
بازگشت به فروشگاه
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={onSubmit} className="grid gap-8 lg:grid-cols-3">
|
||||||
|
<div className="space-y-6 lg:col-span-2">
|
||||||
|
<section className="rounded-2xl border border-border bg-surface p-5">
|
||||||
|
<h2 className="mb-4 text-lg font-bold">آدرس تحویل</h2>
|
||||||
|
{addresses.length > 0 ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{addresses.map((address) => (
|
||||||
|
<label
|
||||||
|
key={address.id}
|
||||||
|
className={`flex cursor-pointer gap-3 rounded-xl border p-3 ${
|
||||||
|
addressId === address.id ? "border-red bg-red-light/30" : "border-border"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="address"
|
||||||
|
checked={addressId === address.id}
|
||||||
|
onChange={() => setAddressId(address.id)}
|
||||||
|
/>
|
||||||
|
<span className="text-sm leading-relaxed">
|
||||||
|
{address.label ? `${address.label} — ` : ""}
|
||||||
|
{address.province}، {address.city}، {address.address}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
placeholder="استان"
|
||||||
|
value={shipping.province}
|
||||||
|
onChange={(e) => setShipping((s) => ({ ...s, province: e.target.value }))}
|
||||||
|
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
placeholder="شهر"
|
||||||
|
value={shipping.city}
|
||||||
|
onChange={(e) => setShipping((s) => ({ ...s, city: e.target.value }))}
|
||||||
|
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
placeholder="آدرس"
|
||||||
|
value={shipping.address}
|
||||||
|
onChange={(e) => setShipping((s) => ({ ...s, address: e.target.value }))}
|
||||||
|
className="rounded-xl border border-border px-3 py-2 text-sm sm:col-span-2"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="کد پستی"
|
||||||
|
value={shipping.postalCode}
|
||||||
|
onChange={(e) => setShipping((s) => ({ ...s, postalCode: e.target.value }))}
|
||||||
|
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="تلفن ثابت"
|
||||||
|
value={shipping.landline}
|
||||||
|
onChange={(e) => setShipping((s) => ({ ...s, landline: e.target.value }))}
|
||||||
|
className="rounded-xl border border-border px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-2xl border border-border bg-surface p-5">
|
||||||
|
<h2 className="mb-4 text-lg font-bold">روش پرداخت</h2>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{methods?.cash !== false && (
|
||||||
|
<label className="flex items-center gap-2 text-sm">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="payment"
|
||||||
|
checked={paymentType === "cash"}
|
||||||
|
onChange={() => setPaymentType("cash")}
|
||||||
|
/>
|
||||||
|
پرداخت در محل / نقدی
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{methods?.transfer && (
|
||||||
|
<label className="flex items-center gap-2 text-sm">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="payment"
|
||||||
|
checked={paymentType === "transfer"}
|
||||||
|
onChange={() => setPaymentType("transfer")}
|
||||||
|
/>
|
||||||
|
کارت به کارت / انتقال
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{methods?.ePayment?.enabled && (
|
||||||
|
<label className="flex items-center gap-2 text-sm">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="payment"
|
||||||
|
checked={paymentType === "e_payment_gate"}
|
||||||
|
onChange={() => setPaymentType("e_payment_gate")}
|
||||||
|
/>
|
||||||
|
پرداخت آنلاین
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{paymentType === "e_payment_gate" && methods?.ePayment?.gateways?.length ? (
|
||||||
|
<select
|
||||||
|
value={gatewayType}
|
||||||
|
onChange={(e) => setGatewayType(e.target.value)}
|
||||||
|
className="mt-3 w-full rounded-xl border border-border px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
{methods.ePayment.gateways.map((gateway) => (
|
||||||
|
<option key={gateway} value={gateway}>
|
||||||
|
{gateway}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside className="h-fit rounded-2xl border border-border bg-surface p-5">
|
||||||
|
<h2 className="mb-4 text-lg font-bold">خلاصه سفارش</h2>
|
||||||
|
<div className="mb-4 space-y-2 text-sm">
|
||||||
|
{items.map((item) => (
|
||||||
|
<div key={item.id} className="flex justify-between gap-3">
|
||||||
|
<span className="line-clamp-1 text-muted">{item.name}</span>
|
||||||
|
<span>× {new Intl.NumberFormat("fa-IR").format(item.quantity)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mb-4 flex items-center justify-between border-t border-border pt-4">
|
||||||
|
<span className="text-muted">جمع کل</span>
|
||||||
|
<span className="text-lg font-bold text-red-dark">{formatPrice(total)} تومان</span>
|
||||||
|
</div>
|
||||||
|
{error && <p className="mb-3 text-sm text-red">{error}</p>}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:bg-red/60"
|
||||||
|
>
|
||||||
|
{loading ? "در حال ثبت سفارش..." : "ثبت سفارش"}
|
||||||
|
</button>
|
||||||
|
</aside>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -35,13 +35,10 @@ 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>
|
||||||
|
|||||||
+249
-21
@@ -1,22 +1,26 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState, type MouseEvent } 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 { CartPopup } from "@/components/cart/CartPopup";
|
||||||
import { EmptyState } from "@/components/ui/EmptyState";
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
import { CartButton } from "@/components/cart/CartButton";
|
import { useAuth } from "@/lib/auth";
|
||||||
|
import {
|
||||||
|
businessDashboardUrl,
|
||||||
|
customerDashboardUrl,
|
||||||
|
customerLoginUrl,
|
||||||
|
} from "@/lib/customer-auth";
|
||||||
|
import { useCart } from "@/lib/cart";
|
||||||
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: "/contact" },
|
{ label: "تماس با ما", href: "#" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const LOGIN_URL = "https://customer.sanihome.ir";
|
|
||||||
|
|
||||||
function Logo({ large = false }: { large?: boolean }) {
|
function Logo({ large = false }: { large?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<a href="/" className="flex shrink-0 items-center">
|
<a href="/" className="flex shrink-0 items-center">
|
||||||
@@ -48,10 +52,186 @@ function ChevronDownIcon({ className = "" }: { className?: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function UserIcon({ className = "h-5 w-5" }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
|
||||||
|
<circle cx="12" cy="8" r="3.25" stroke="currentColor" strokeWidth="1.75" />
|
||||||
|
<path
|
||||||
|
d="M5.5 19.25c1.4-3 3.8-4.5 6.5-4.5s5.1 1.5 6.5 4.5"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.75"
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CartIcon({ className = "h-5 w-5" }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
|
||||||
|
<path
|
||||||
|
d="M3.5 5.5h1.6l1.4 10.2a1.5 1.5 0 0 0 1.5 1.3h8.7a1.5 1.5 0 0 0 1.5-1.3L19.5 8H7"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.75"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
<circle cx="9.5" cy="20" r="1.25" fill="currentColor" />
|
||||||
|
<circle cx="16.5" cy="20" r="1.25" fill="currentColor" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function flattenLevel2(categoryTree: CategoryTreeGroup[]): CategoryNode[] {
|
function flattenLevel2(categoryTree: CategoryTreeGroup[]): CategoryNode[] {
|
||||||
return categoryTree.flatMap((group) => group.items);
|
return categoryTree.flatMap((group) => group.items);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AccountMenu({
|
||||||
|
displayName,
|
||||||
|
isWebsiteAdmin,
|
||||||
|
onLogout,
|
||||||
|
compact = false,
|
||||||
|
}: {
|
||||||
|
displayName: string;
|
||||||
|
isWebsiteAdmin: boolean;
|
||||||
|
onLogout: () => void;
|
||||||
|
compact?: boolean;
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [handoffBusy, setHandoffBusy] = useState(false);
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null);
|
||||||
|
const { getAccessToken } = useAuth();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
|
||||||
|
const onClickOutside = (event: Event) => {
|
||||||
|
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") setOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("mousedown", onClickOutside);
|
||||||
|
document.addEventListener("keydown", onKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousedown", onClickOutside);
|
||||||
|
document.removeEventListener("keydown", onKeyDown);
|
||||||
|
};
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
async function openBusinessDashboard(event: MouseEvent<HTMLAnchorElement>) {
|
||||||
|
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
if (handoffBusy) return;
|
||||||
|
|
||||||
|
const baseUrl = businessDashboardUrl();
|
||||||
|
const popup = window.open("about:blank", "_blank");
|
||||||
|
setHandoffBusy(true);
|
||||||
|
try {
|
||||||
|
const token = getAccessToken();
|
||||||
|
const res = await fetch("/api/auth/handoff", {
|
||||||
|
method: "POST",
|
||||||
|
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error("handoff failed");
|
||||||
|
const data = (await res.json()) as { ticket?: string };
|
||||||
|
const url = new URL(baseUrl);
|
||||||
|
if (data.ticket) url.searchParams.set("handoff", data.ticket);
|
||||||
|
if (popup) {
|
||||||
|
popup.opener = null;
|
||||||
|
popup.location.replace(url.toString());
|
||||||
|
} else {
|
||||||
|
window.open(url.toString(), "_blank", "noopener,noreferrer");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (popup) popup.location.replace(baseUrl);
|
||||||
|
else window.open(baseUrl, "_blank", "noopener,noreferrer");
|
||||||
|
} finally {
|
||||||
|
setHandoffBusy(false);
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemClass =
|
||||||
|
"block w-full px-3 py-2.5 text-right text-sm text-foreground transition-colors hover:bg-red-light/50 hover:text-red";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={menuRef} className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen((v) => !v)}
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
className={`group flex max-w-[12rem] items-center gap-1.5 text-muted transition-colors hover:text-red ${
|
||||||
|
compact ? "w-full justify-between" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="flex min-w-0 items-center gap-1.5">
|
||||||
|
<UserIcon className="h-5 w-5 shrink-0 transition-colors group-hover:text-red" />
|
||||||
|
<span className="truncate font-medium text-foreground transition-colors group-hover:text-red">
|
||||||
|
{displayName} عزیز
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<ChevronDownIcon
|
||||||
|
className={`h-3.5 w-3.5 shrink-0 transition-transform group-hover:text-red ${open ? "rotate-180" : ""}`}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div
|
||||||
|
role="menu"
|
||||||
|
className={`absolute z-50 mt-2 min-w-[11rem] overflow-hidden rounded-xl border border-border bg-surface py-1 shadow-lg ${
|
||||||
|
compact ? "start-0 end-0" : "start-0"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<a
|
||||||
|
role="menuitem"
|
||||||
|
href={customerDashboardUrl("/profile")}
|
||||||
|
className={itemClass}
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
پروفایل من
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
role="menuitem"
|
||||||
|
href={customerDashboardUrl("/orders")}
|
||||||
|
className={itemClass}
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
سفارشات من
|
||||||
|
</a>
|
||||||
|
{isWebsiteAdmin && (
|
||||||
|
<a
|
||||||
|
role="menuitem"
|
||||||
|
href={businessDashboardUrl()}
|
||||||
|
className={itemClass}
|
||||||
|
onClick={openBusinessDashboard}
|
||||||
|
>
|
||||||
|
{handoffBusy ? "در حال انتقال…" : "مدیریت وبسایت"}
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className={`${itemClass} text-red hover:text-red-dark`}
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
onLogout();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
خروج
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function MobileDrawer({
|
function MobileDrawer({
|
||||||
open,
|
open,
|
||||||
onClose,
|
onClose,
|
||||||
@@ -64,6 +244,8 @@ function MobileDrawer({
|
|||||||
const [categoriesOpen, setCategoriesOpen] = useState(false);
|
const [categoriesOpen, setCategoriesOpen] = useState(false);
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
const level2 = flattenLevel2(categoryTree);
|
const level2 = flattenLevel2(categoryTree);
|
||||||
|
const { isAuthenticated, user, logout, isWebsiteAdmin } = useAuth();
|
||||||
|
const displayName = user?.firstName?.trim() || "حساب من";
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
@@ -182,13 +364,27 @@ function MobileDrawer({
|
|||||||
</a>
|
</a>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<a
|
{isAuthenticated ? (
|
||||||
href={LOGIN_URL}
|
<div className="border-b border-border px-5 py-4">
|
||||||
className="flex items-center gap-2 px-5 py-4 text-right font-medium transition-colors hover:bg-red-light/40 hover:text-red"
|
<AccountMenu
|
||||||
>
|
displayName={displayName}
|
||||||
<span aria-hidden>👤</span>
|
isWebsiteAdmin={isWebsiteAdmin}
|
||||||
ورود
|
compact
|
||||||
</a>
|
onLogout={() => {
|
||||||
|
logout();
|
||||||
|
onClose();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<a
|
||||||
|
href={customerLoginUrl("/")}
|
||||||
|
className="flex items-center gap-2 px-5 py-4 text-right font-medium transition-colors hover:bg-red-light/40 hover:text-red"
|
||||||
|
>
|
||||||
|
<UserIcon className="h-5 w-5" />
|
||||||
|
ورود
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</div>,
|
||||||
@@ -205,11 +401,15 @@ export function Header({
|
|||||||
}) {
|
}) {
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
const [cartOpen, setCartOpen] = useState(false);
|
||||||
const menuRef = useRef<HTMLDivElement>(null);
|
const menuRef = useRef<HTMLDivElement>(null);
|
||||||
const level2 = flattenLevel2(categoryTree);
|
const level2 = flattenLevel2(categoryTree);
|
||||||
|
const { itemCount, ready } = useCart();
|
||||||
|
const { isAuthenticated, user, logout, isWebsiteAdmin } = useAuth();
|
||||||
|
const displayName = user?.firstName?.trim() || "حساب من";
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onClickOutside = (event: MouseEvent) => {
|
const onClickOutside = (event: Event) => {
|
||||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||||
setMenuOpen(false);
|
setMenuOpen(false);
|
||||||
}
|
}
|
||||||
@@ -246,14 +446,41 @@ export function Header({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-end gap-3 text-sm">
|
<div className="flex items-center justify-end gap-3 text-sm">
|
||||||
<a
|
{isAuthenticated ? (
|
||||||
href={LOGIN_URL}
|
<div className="hidden sm:block">
|
||||||
className="hidden items-center gap-1.5 text-muted transition-colors hover:text-red sm:flex"
|
<AccountMenu
|
||||||
|
displayName={displayName}
|
||||||
|
isWebsiteAdmin={isWebsiteAdmin}
|
||||||
|
onLogout={logout}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<a
|
||||||
|
href={customerLoginUrl("/")}
|
||||||
|
className="hidden items-center gap-1.5 text-muted transition-colors hover:text-red sm:flex"
|
||||||
|
>
|
||||||
|
<UserIcon className="h-5 w-5" />
|
||||||
|
<span>ورود</span>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCartOpen(true)}
|
||||||
|
aria-label={
|
||||||
|
itemCount > 0
|
||||||
|
? `سبد خرید، ${new Intl.NumberFormat("fa-IR").format(itemCount)} کالا`
|
||||||
|
: "سبد خرید"
|
||||||
|
}
|
||||||
|
className="relative flex items-center gap-1.5 rounded-lg border border-border px-3 py-2 transition-colors hover:border-red hover:text-red"
|
||||||
>
|
>
|
||||||
<span>👤</span>
|
<CartIcon className="h-5 w-5" />
|
||||||
<span>ورود</span>
|
<span className="hidden sm:inline">سبد خرید</span>
|
||||||
</a>
|
{ready && itemCount > 0 && (
|
||||||
<CartButton />
|
<span className="absolute -top-1.5 -left-1.5 flex h-5 min-w-5 items-center justify-center rounded-full bg-red px-1 text-[10px] font-bold text-white">
|
||||||
|
{new Intl.NumberFormat("fa-IR").format(itemCount)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -361,6 +588,7 @@ export function Header({
|
|||||||
onClose={() => setDrawerOpen(false)}
|
onClose={() => setDrawerOpen(false)}
|
||||||
categoryTree={categoryTree}
|
categoryTree={categoryTree}
|
||||||
/>
|
/>
|
||||||
|
<CartPopup open={cartOpen} onClose={() => setCartOpen(false)} />
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,6 @@ export function SpecialSaleCarousel({
|
|||||||
variant="sale"
|
variant="sale"
|
||||||
href={productHref(product)}
|
href={productHref(product)}
|
||||||
contactPhone={contactPhone}
|
contactPhone={contactPhone}
|
||||||
variantId={product.variantId}
|
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Carousel>
|
</Carousel>
|
||||||
|
|||||||
@@ -29,12 +29,9 @@ 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,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { 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";
|
||||||
@@ -12,115 +11,10 @@ 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;
|
||||||
@@ -147,12 +41,11 @@ 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-in" : "zoom-in",
|
cursor: zoomed ? "zoom-out" : "zoom-in",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -196,16 +89,6 @@ 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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,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 { useCart } from "@/lib/cart";
|
||||||
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 (
|
||||||
@@ -22,15 +21,20 @@ function CheckIcon({ className }: { className?: string }) {
|
|||||||
|
|
||||||
export function ProductPurchasePanel({
|
export function ProductPurchasePanel({
|
||||||
header,
|
header,
|
||||||
|
slug,
|
||||||
|
name,
|
||||||
|
image,
|
||||||
variations,
|
variations,
|
||||||
storeVariants,
|
storeVariants,
|
||||||
fallbackPrice,
|
fallbackPrice,
|
||||||
inStock,
|
inStock,
|
||||||
contactPhone,
|
contactPhone,
|
||||||
storeName,
|
storeName,
|
||||||
initialSelections,
|
|
||||||
}: {
|
}: {
|
||||||
header: ReactNode;
|
header: ReactNode;
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
image?: string | null;
|
||||||
variations: ProductVariation[];
|
variations: ProductVariation[];
|
||||||
storeVariants: ProductStoreVariant[];
|
storeVariants: ProductStoreVariant[];
|
||||||
fallbackPrice: {
|
fallbackPrice: {
|
||||||
@@ -42,15 +46,9 @@ 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, loading: cartLoading } = useCart();
|
||||||
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;
|
||||||
@@ -58,11 +56,9 @@ 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 [submitting, setSubmitting] = useState(false);
|
||||||
const [cartError, setCartError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const matchedVariant = useMemo(() => {
|
const matchedVariant = useMemo(() => {
|
||||||
if (storeVariants.length === 0) return null;
|
|
||||||
if (variations.length === 0) return storeVariants[0] ?? null;
|
if (variations.length === 0) return storeVariants[0] ?? null;
|
||||||
return (
|
return (
|
||||||
storeVariants.find((variant) =>
|
storeVariants.find((variant) =>
|
||||||
@@ -97,25 +93,39 @@ 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 = matchedVariant ? matchedVariant.stockQuantity : null;
|
const stockQuantity = hasVariations ? (matchedVariant?.stockQuantity ?? 0) : null;
|
||||||
const available = matchedVariant ? stockQuantity! > 0 : inStock;
|
const available = hasVariations
|
||||||
|
? Boolean(matchedVariant) && stockQuantity! > 0
|
||||||
|
: inStock && Boolean(matchedVariant);
|
||||||
const maxQty = stockQuantity && stockQuantity > 0 ? stockQuantity : 99;
|
const maxQty = stockQuantity && stockQuantity > 0 ? stockQuantity : 99;
|
||||||
|
const storeItemVariantId = matchedVariant?.id;
|
||||||
|
|
||||||
|
const optionLabel = hasVariations
|
||||||
|
? variations
|
||||||
|
.map((variation) => {
|
||||||
|
const option = variation.options.find((o) => o.id === selected[variation.id]);
|
||||||
|
return option?.label;
|
||||||
|
})
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" / ")
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const handleAddToCart = async () => {
|
const handleAddToCart = async () => {
|
||||||
if (!matchedVariant) return;
|
if (!available || price == null || priceRangeLabel || !storeItemVariantId) return;
|
||||||
if (!user) {
|
|
||||||
openLoginModal();
|
setSubmitting(true);
|
||||||
return;
|
try {
|
||||||
}
|
await addItem({
|
||||||
setCartError(null);
|
storeItemVariantId,
|
||||||
setCartStatus("busy");
|
quantity,
|
||||||
const res = await addItem(matchedVariant.id, quantity);
|
slug,
|
||||||
if (res.ok) {
|
name,
|
||||||
setCartStatus("done");
|
image,
|
||||||
setTimeout(() => setCartStatus("idle"), 1500);
|
price,
|
||||||
} else {
|
optionLabel,
|
||||||
setCartStatus("idle");
|
});
|
||||||
setCartError(res.message ?? "افزودن به سبد ناموفق بود.");
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -226,15 +236,13 @@ 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 || Boolean(priceRangeLabel) || !storeItemVariantId || submitting || cartLoading}
|
||||||
onClick={handleAddToCart}
|
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" ? "به سبد اضافه شد ✓" : "افزودن به سبد خرید"}
|
{submitting || cartLoading ? "در حال افزودن..." : "افزودن به سبد خرید"}
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
) : contactPhone ? (
|
) : contactPhone ? (
|
||||||
|
|||||||
@@ -2,8 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { EmptyState } from "@/components/ui/EmptyState";
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
import { useAuth } from "@/context/AuthContext";
|
import type { TechnicalInfoField } from "@/lib/meshkee";
|
||||||
import { postComment, type EntityComment, type TechnicalInfoField } from "@/lib/meshkee";
|
|
||||||
|
|
||||||
type Tab = "specs" | "review" | "comments";
|
type Tab = "specs" | "review" | "comments";
|
||||||
|
|
||||||
@@ -13,105 +12,12 @@ 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 ?? "";
|
||||||
@@ -166,7 +72,9 @@ export function ProductTabs({
|
|||||||
<EmptyState message="هنوز نقد و بررسیای برای این محصول ثبت نشده است." />
|
<EmptyState message="هنوز نقد و بررسیای برای این محصول ثبت نشده است." />
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{active === "comments" && <CommentsPanel entityId={entityId} initialComments={initialComments} />}
|
{active === "comments" && (
|
||||||
|
<EmptyState message="هنوز نظری برای این محصول ثبت نشده است." />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { AuthProvider } from "@/lib/auth";
|
||||||
|
import { CartProvider } from "@/lib/cart";
|
||||||
|
|
||||||
|
export function AppProviders({
|
||||||
|
children,
|
||||||
|
businessId,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
businessId: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<AuthProvider businessId={businessId}>
|
||||||
|
<CartProvider>{children}</CartProvider>
|
||||||
|
</AuthProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +1,5 @@
|
|||||||
"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;
|
||||||
@@ -17,10 +12,6 @@ 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({
|
||||||
@@ -34,24 +25,7 @@ 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]">
|
||||||
@@ -113,22 +87,13 @@ 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 && variantId ? (
|
{price != null ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleAddToCart}
|
className="w-full rounded-lg bg-red py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
|
||||||
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"
|
|
||||||
>
|
>
|
||||||
افزودن به سبد
|
افزودن به سبد
|
||||||
</a>
|
</button>
|
||||||
) : contactPhone ? (
|
) : contactPhone ? (
|
||||||
<a
|
<a
|
||||||
href={`tel:${contactPhone}`}
|
href={`tel:${contactPhone}`}
|
||||||
|
|||||||
@@ -1,13 +1,30 @@
|
|||||||
export function Toast({ message, show }: { message: string; show: boolean }) {
|
"use client";
|
||||||
|
|
||||||
|
import { useCart } from "@/lib/cart";
|
||||||
|
|
||||||
|
export function Toast() {
|
||||||
|
const { toast, dismissToast } = useCart();
|
||||||
|
|
||||||
|
if (!toast) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
key={toast.id}
|
||||||
role="status"
|
role="status"
|
||||||
aria-live="polite"
|
className="fixed bottom-6 left-1/2 z-[200] flex -translate-x-1/2 items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 text-sm shadow-lg animate-fade-up"
|
||||||
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}
|
<span className="flex h-7 w-7 items-center justify-center rounded-full bg-green-50 text-green-700">
|
||||||
|
✓
|
||||||
|
</span>
|
||||||
|
<span className="font-medium text-foreground">{toast.message}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={dismissToast}
|
||||||
|
aria-label="بستن"
|
||||||
|
className="mr-1 text-muted transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,147 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
|
||||||
import {
|
|
||||||
type AuthUser,
|
|
||||||
clearTokens,
|
|
||||||
fetchMe,
|
|
||||||
getStoredTokens,
|
|
||||||
loginWithOtp,
|
|
||||||
loginWithPassword,
|
|
||||||
refreshAccessToken,
|
|
||||||
register as registerRequest,
|
|
||||||
sendOtp as sendOtpRequest,
|
|
||||||
storeTokens,
|
|
||||||
} from "@/lib/auth";
|
|
||||||
|
|
||||||
type AuthContextValue = {
|
|
||||||
user: AuthUser | null;
|
|
||||||
accessToken: string | null;
|
|
||||||
loading: boolean;
|
|
||||||
loginModalOpen: boolean;
|
|
||||||
openLoginModal: () => void;
|
|
||||||
closeLoginModal: () => void;
|
|
||||||
login: (cellNumber: string, password: string) => Promise<{ ok: boolean; message?: string }>;
|
|
||||||
loginOtp: (cellNumber: string, code: string) => Promise<{ ok: boolean; message?: string }>;
|
|
||||||
sendOtp: (cellNumber: string) => Promise<{ ok: boolean; message?: string }>;
|
|
||||||
register: (input: {
|
|
||||||
cellNumber: string;
|
|
||||||
password: string;
|
|
||||||
firstName: string;
|
|
||||||
lastName: string;
|
|
||||||
email?: string;
|
|
||||||
}) => Promise<{ ok: boolean; message?: string }>;
|
|
||||||
logout: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
|
||||||
|
|
||||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
||||||
const [user, setUser] = useState<AuthUser | null>(null);
|
|
||||||
const [accessToken, setAccessToken] = useState<string | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [loginModalOpen, setLoginModalOpen] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const stored = getStoredTokens();
|
|
||||||
if (!stored) {
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fetchMe(stored.accessToken).then(async (res) => {
|
|
||||||
if (res.ok) {
|
|
||||||
setUser(res.data);
|
|
||||||
setAccessToken(stored.accessToken);
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Access token likely expired (~15 min lifetime) — try a silent
|
|
||||||
// refresh before giving up on the session.
|
|
||||||
const fresh = await refreshAccessToken();
|
|
||||||
if (fresh) {
|
|
||||||
const retry = await fetchMe(fresh);
|
|
||||||
if (retry.ok) {
|
|
||||||
setUser(retry.data);
|
|
||||||
setAccessToken(fresh);
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
clearTokens();
|
|
||||||
setLoading(false);
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const applySession = useCallback((session: { accessToken: string; refreshToken: string | null; user: AuthUser }) => {
|
|
||||||
storeTokens(session.accessToken, session.refreshToken);
|
|
||||||
setAccessToken(session.accessToken);
|
|
||||||
setUser(session.user);
|
|
||||||
setLoginModalOpen(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const login = useCallback(
|
|
||||||
async (cellNumber: string, password: string) => {
|
|
||||||
const res = await loginWithPassword(cellNumber, password);
|
|
||||||
if (!res.ok) return { ok: false, message: res.message };
|
|
||||||
applySession(res.data);
|
|
||||||
return { ok: true };
|
|
||||||
},
|
|
||||||
[applySession],
|
|
||||||
);
|
|
||||||
|
|
||||||
const loginOtp = useCallback(
|
|
||||||
async (cellNumber: string, code: string) => {
|
|
||||||
const res = await loginWithOtp(cellNumber, code);
|
|
||||||
if (!res.ok) return { ok: false, message: res.message };
|
|
||||||
applySession(res.data);
|
|
||||||
return { ok: true };
|
|
||||||
},
|
|
||||||
[applySession],
|
|
||||||
);
|
|
||||||
|
|
||||||
const sendOtp = useCallback(async (cellNumber: string) => {
|
|
||||||
const res = await sendOtpRequest(cellNumber);
|
|
||||||
return res.ok ? { ok: true } : { ok: false, message: res.message };
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const register = useCallback(
|
|
||||||
async (input: { cellNumber: string; password: string; firstName: string; lastName: string; email?: string }) => {
|
|
||||||
const res = await registerRequest(input);
|
|
||||||
if (!res.ok) return { ok: false, message: res.message };
|
|
||||||
applySession(res.data);
|
|
||||||
return { ok: true };
|
|
||||||
},
|
|
||||||
[applySession],
|
|
||||||
);
|
|
||||||
|
|
||||||
const logout = useCallback(() => {
|
|
||||||
clearTokens();
|
|
||||||
setUser(null);
|
|
||||||
setAccessToken(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const value = useMemo<AuthContextValue>(
|
|
||||||
() => ({
|
|
||||||
user,
|
|
||||||
accessToken,
|
|
||||||
loading,
|
|
||||||
loginModalOpen,
|
|
||||||
openLoginModal: () => setLoginModalOpen(true),
|
|
||||||
closeLoginModal: () => setLoginModalOpen(false),
|
|
||||||
login,
|
|
||||||
loginOtp,
|
|
||||||
sendOtp,
|
|
||||||
register,
|
|
||||||
logout,
|
|
||||||
}),
|
|
||||||
[user, accessToken, loading, loginModalOpen, login, loginOtp, sendOtp, register, logout],
|
|
||||||
);
|
|
||||||
|
|
||||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useAuth() {
|
|
||||||
const ctx = useContext(AuthContext);
|
|
||||||
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
"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;
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
"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
@@ -1,211 +0,0 @@
|
|||||||
// Client-side session storage for Meshkee customer auth. Tokens live in
|
|
||||||
// localStorage (per-browser, never sent anywhere but api.meshkee.com).
|
|
||||||
const ACCESS_KEY = "sanihome_access_token";
|
|
||||||
const REFRESH_KEY = "sanihome_refresh_token";
|
|
||||||
|
|
||||||
export type AuthUser = {
|
|
||||||
id: string;
|
|
||||||
firstName?: string;
|
|
||||||
lastName?: string;
|
|
||||||
cellNumber?: string;
|
|
||||||
email?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function getStoredTokens(): { accessToken: string; refreshToken: string | null } | null {
|
|
||||||
if (typeof window === "undefined") return null;
|
|
||||||
try {
|
|
||||||
const accessToken = window.localStorage.getItem(ACCESS_KEY);
|
|
||||||
if (!accessToken) return null;
|
|
||||||
return { accessToken, refreshToken: window.localStorage.getItem(REFRESH_KEY) };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function storeTokens(accessToken: string, refreshToken?: string | null): void {
|
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
try {
|
|
||||||
window.localStorage.setItem(ACCESS_KEY, accessToken);
|
|
||||||
if (refreshToken) window.localStorage.setItem(REFRESH_KEY, refreshToken);
|
|
||||||
} catch {
|
|
||||||
// Private browsing / storage disabled — session just won't persist.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Access tokens are short-lived (~15 min). Call this whenever a request
|
|
||||||
// comes back 401 so the shopper doesn't get silently logged out mid-session.
|
|
||||||
// Returns the fresh access token, or null if the refresh token is also gone/invalid
|
|
||||||
// (caller should then clear the session and prompt login again).
|
|
||||||
//
|
|
||||||
// AuthContext and CartContext each independently notice an expired token and
|
|
||||||
// call this — without coordination they'd fire two concurrent /auth/refresh
|
|
||||||
// requests. If the backend rotates the refresh token on use, the second
|
|
||||||
// request then fails (observed as a 500/400). This in-flight guard makes
|
|
||||||
// every concurrent caller share the same single request instead of racing.
|
|
||||||
let inFlightRefresh: Promise<string | null> | null = null;
|
|
||||||
|
|
||||||
export async function refreshAccessToken(): Promise<string | null> {
|
|
||||||
if (inFlightRefresh) return inFlightRefresh;
|
|
||||||
|
|
||||||
inFlightRefresh = (async () => {
|
|
||||||
const stored = getStoredTokens();
|
|
||||||
if (!stored?.refreshToken) return null;
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${AUTH_API_BASE}/auth/refresh`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ refreshToken: stored.refreshToken }),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
clearTokens();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const data = (await res.json()) as RawAuthResponse;
|
|
||||||
const accessToken = data.accessToken ?? data.token ?? data.access_token;
|
|
||||||
if (!accessToken) return null;
|
|
||||||
storeTokens(accessToken, data.refreshToken ?? data.refresh_token ?? stored.refreshToken);
|
|
||||||
return accessToken;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await inFlightRefresh;
|
|
||||||
} finally {
|
|
||||||
inFlightRefresh = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function clearTokens(): void {
|
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
try {
|
|
||||||
window.localStorage.removeItem(ACCESS_KEY);
|
|
||||||
window.localStorage.removeItem(REFRESH_KEY);
|
|
||||||
} catch {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const AUTH_API_BASE = "https://api.meshkee.com/api/v1";
|
|
||||||
export const WEBSITE_DOMAIN = "sanihome.ir";
|
|
||||||
|
|
||||||
async function authFetch<T>(
|
|
||||||
path: string,
|
|
||||||
options: { method?: string; body?: unknown; token?: string } = {},
|
|
||||||
): Promise<{ ok: true; data: T } | { ok: false; status: number; message: string }> {
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${AUTH_API_BASE}${path}`, {
|
|
||||||
method: options.method ?? "GET",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),
|
|
||||||
},
|
|
||||||
body: options.body != null ? JSON.stringify(options.body) : undefined,
|
|
||||||
});
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
status: res.status,
|
|
||||||
message: (data as { message?: string })?.message ?? "خطایی رخ داد. دوباره تلاش کنید.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return { ok: true, data: data as T };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, status: 0, message: "ارتباط با سرور برقرار نشد." };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The API doesn't document the exact success-response field names for
|
|
||||||
// login/register/login-otp — accessToken/refreshToken/user is the standard
|
|
||||||
// shape (confirmed accessToken+refreshToken naming via /auth/refresh's own
|
|
||||||
// request body, and a `user` wrapper via /auth/me's documented description).
|
|
||||||
// Read defensively in case a field is nested or named slightly differently.
|
|
||||||
type RawAuthResponse = {
|
|
||||||
accessToken?: string;
|
|
||||||
token?: string;
|
|
||||||
access_token?: string;
|
|
||||||
refreshToken?: string;
|
|
||||||
refresh_token?: string;
|
|
||||||
user?: Record<string, unknown>;
|
|
||||||
customer?: Record<string, unknown>;
|
|
||||||
};
|
|
||||||
|
|
||||||
function extractSession(raw: RawAuthResponse): { accessToken: string; refreshToken: string | null; user: AuthUser } | null {
|
|
||||||
const accessToken = raw.accessToken ?? raw.token ?? raw.access_token;
|
|
||||||
if (!accessToken) return null;
|
|
||||||
const refreshToken = raw.refreshToken ?? raw.refresh_token ?? null;
|
|
||||||
const rawUser = raw.user ?? raw.customer ?? {};
|
|
||||||
return {
|
|
||||||
accessToken,
|
|
||||||
refreshToken,
|
|
||||||
user: {
|
|
||||||
id: String(rawUser.id ?? ""),
|
|
||||||
firstName: rawUser.firstName as string | undefined,
|
|
||||||
lastName: rawUser.lastName as string | undefined,
|
|
||||||
cellNumber: rawUser.cellNumber as string | undefined,
|
|
||||||
email: rawUser.email as string | undefined,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loginWithPassword(cellNumber: string, password: string) {
|
|
||||||
const res = await authFetch<RawAuthResponse>("/auth/login", {
|
|
||||||
method: "POST",
|
|
||||||
body: { cellNumber, password },
|
|
||||||
});
|
|
||||||
if (!res.ok) return res;
|
|
||||||
const session = extractSession(res.data);
|
|
||||||
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
|
|
||||||
return { ok: true as const, data: session };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loginWithOtp(cellNumber: string, code: string) {
|
|
||||||
const res = await authFetch<RawAuthResponse>("/auth/login-otp", {
|
|
||||||
method: "POST",
|
|
||||||
body: { cellNumber, code },
|
|
||||||
});
|
|
||||||
if (!res.ok) return res;
|
|
||||||
const session = extractSession(res.data);
|
|
||||||
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
|
|
||||||
return { ok: true as const, data: session };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function sendOtp(cellNumber: string) {
|
|
||||||
return authFetch<{ message?: string }>("/auth/send-otp", {
|
|
||||||
method: "POST",
|
|
||||||
body: { cellNumber, domain: WEBSITE_DOMAIN },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function register(input: {
|
|
||||||
cellNumber: string;
|
|
||||||
password: string;
|
|
||||||
firstName: string;
|
|
||||||
lastName: string;
|
|
||||||
email?: string;
|
|
||||||
}) {
|
|
||||||
const res = await authFetch<RawAuthResponse>("/auth/register", {
|
|
||||||
method: "POST",
|
|
||||||
body: { ...input, domain: WEBSITE_DOMAIN },
|
|
||||||
});
|
|
||||||
if (!res.ok) return res;
|
|
||||||
const session = extractSession(res.data);
|
|
||||||
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
|
|
||||||
return { ok: true as const, data: session };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchMe(accessToken: string) {
|
|
||||||
const res = await authFetch<{ user?: Record<string, unknown> }>("/auth/me", { token: accessToken });
|
|
||||||
if (!res.ok) return res;
|
|
||||||
const rawUser = res.data.user ?? {};
|
|
||||||
const user: AuthUser = {
|
|
||||||
id: String(rawUser.id ?? ""),
|
|
||||||
firstName: rawUser.firstName as string | undefined,
|
|
||||||
lastName: rawUser.lastName as string | undefined,
|
|
||||||
cellNumber: rawUser.cellNumber as string | undefined,
|
|
||||||
email: rawUser.email as string | undefined,
|
|
||||||
};
|
|
||||||
return { ok: true as const, data: user };
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
|
import {
|
||||||
|
clearSharedAuthCookies,
|
||||||
|
hydrateLocalTokensFromSharedCookies,
|
||||||
|
SHARED_ACCESS_TOKEN_KEY,
|
||||||
|
SHARED_REFRESH_TOKEN_KEY,
|
||||||
|
writeSharedAuthCookies,
|
||||||
|
} from "@/lib/shared-auth-cookie";
|
||||||
|
|
||||||
|
const ACCESS_TOKEN_KEY = SHARED_ACCESS_TOKEN_KEY;
|
||||||
|
const REFRESH_TOKEN_KEY = SHARED_REFRESH_TOKEN_KEY;
|
||||||
|
const LEGACY_ACCESS_KEY = "sanihome-access-token";
|
||||||
|
const LEGACY_REFRESH_KEY = "sanihome-refresh-token";
|
||||||
|
|
||||||
|
export type AuthBusinessMembership = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
isOwner: boolean;
|
||||||
|
teamRole: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuthUser = {
|
||||||
|
id: string;
|
||||||
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
cellNumber?: string;
|
||||||
|
email?: string;
|
||||||
|
roles?: string[];
|
||||||
|
isSuperAdmin?: boolean;
|
||||||
|
businesses?: AuthBusinessMembership[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type AuthContextValue = {
|
||||||
|
user: AuthUser | null;
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
ready: boolean;
|
||||||
|
businessId: string;
|
||||||
|
/** Owner / team member of this storefront’s business (or super admin). */
|
||||||
|
isWebsiteAdmin: boolean;
|
||||||
|
login: (cellNumber: string, password: string) => Promise<void>;
|
||||||
|
register: (input: {
|
||||||
|
cellNumber: string;
|
||||||
|
password: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email?: string;
|
||||||
|
}) => Promise<void>;
|
||||||
|
logout: () => void;
|
||||||
|
getAccessToken: () => string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeUser(raw: Partial<AuthUser> & { id?: string | number }): AuthUser | null {
|
||||||
|
if (raw.id == null) return null;
|
||||||
|
return {
|
||||||
|
id: String(raw.id),
|
||||||
|
firstName: raw.firstName ?? undefined,
|
||||||
|
lastName: raw.lastName ?? undefined,
|
||||||
|
cellNumber: raw.cellNumber ?? undefined,
|
||||||
|
email: raw.email ?? undefined,
|
||||||
|
roles: Array.isArray(raw.roles) ? raw.roles : undefined,
|
||||||
|
isSuperAdmin: Boolean(raw.isSuperAdmin),
|
||||||
|
businesses: Array.isArray(raw.businesses)
|
||||||
|
? raw.businesses.map((b) => ({
|
||||||
|
id: String(b.id),
|
||||||
|
name: b.name,
|
||||||
|
slug: b.slug,
|
||||||
|
isOwner: Boolean(b.isOwner),
|
||||||
|
teamRole: b.teamRole ?? null,
|
||||||
|
}))
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isWebsiteAdminForBusiness(
|
||||||
|
user: AuthUser | null | undefined,
|
||||||
|
businessId: string,
|
||||||
|
): boolean {
|
||||||
|
if (!user || !businessId) return false;
|
||||||
|
if (user.isSuperAdmin || user.roles?.includes("super_admin")) return true;
|
||||||
|
return Boolean(
|
||||||
|
user.businesses?.some(
|
||||||
|
(b) =>
|
||||||
|
String(b.id) === String(businessId) && (b.isOwner || Boolean(b.teamRole)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||||
|
|
||||||
|
function readToken(key: string): string | null {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(key);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeToken(key: string, value: string | null) {
|
||||||
|
try {
|
||||||
|
if (value) localStorage.setItem(key, value);
|
||||||
|
else localStorage.removeItem(key);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function migrateLegacyTokens() {
|
||||||
|
const legacyAccess = readToken(LEGACY_ACCESS_KEY);
|
||||||
|
if (!legacyAccess || readToken(ACCESS_TOKEN_KEY)) return;
|
||||||
|
writeToken(ACCESS_TOKEN_KEY, legacyAccess);
|
||||||
|
writeToken(LEGACY_ACCESS_KEY, null);
|
||||||
|
const legacyRefresh = readToken(LEGACY_REFRESH_KEY);
|
||||||
|
if (legacyRefresh) {
|
||||||
|
writeToken(REFRESH_TOKEN_KEY, legacyRefresh);
|
||||||
|
writeToken(LEGACY_REFRESH_KEY, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authRequest<T>(
|
||||||
|
path: string,
|
||||||
|
body: unknown,
|
||||||
|
token?: string | null,
|
||||||
|
): Promise<T> {
|
||||||
|
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||||
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
|
|
||||||
|
const res = await fetch(path, {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = (await res.json().catch(() => null)) as T & { error?: string };
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(
|
||||||
|
(data as { error?: string } | null)?.error ?? "درخواست با خطا مواجه شد",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuthProvider({
|
||||||
|
children,
|
||||||
|
businessId,
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
businessId: string;
|
||||||
|
}) {
|
||||||
|
const [user, setUser] = useState<AuthUser | null>(null);
|
||||||
|
const [ready, setReady] = useState(false);
|
||||||
|
|
||||||
|
const getAccessToken = useCallback(() => {
|
||||||
|
migrateLegacyTokens();
|
||||||
|
hydrateLocalTokensFromSharedCookies(ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY);
|
||||||
|
return readToken(ACCESS_TOKEN_KEY);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const persistTokens = useCallback(
|
||||||
|
(accessToken: string, refreshToken?: string) => {
|
||||||
|
writeToken(ACCESS_TOKEN_KEY, accessToken);
|
||||||
|
if (refreshToken) writeToken(REFRESH_TOKEN_KEY, refreshToken);
|
||||||
|
writeToken(LEGACY_ACCESS_KEY, null);
|
||||||
|
writeToken(LEGACY_REFRESH_KEY, null);
|
||||||
|
writeSharedAuthCookies(accessToken, refreshToken);
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const clearTokens = useCallback(() => {
|
||||||
|
writeToken(ACCESS_TOKEN_KEY, null);
|
||||||
|
writeToken(REFRESH_TOKEN_KEY, null);
|
||||||
|
writeToken(LEGACY_ACCESS_KEY, null);
|
||||||
|
writeToken(LEGACY_REFRESH_KEY, null);
|
||||||
|
clearSharedAuthCookies();
|
||||||
|
setUser(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchMe = useCallback(async (token: string) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/auth/me", {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
if (res.status === 401) return { user: null as AuthUser | null, unauthorized: true };
|
||||||
|
if (!res.ok) return { user: null as AuthUser | null, unauthorized: false };
|
||||||
|
const data = (await res.json()) as { user?: AuthUser } & AuthUser;
|
||||||
|
// API may return { user } or the user object directly
|
||||||
|
const normalized = normalizeUser(data.user ?? data);
|
||||||
|
return { user: normalized, unauthorized: false };
|
||||||
|
} catch {
|
||||||
|
return { user: null as AuthUser | null, unauthorized: false };
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (!token) {
|
||||||
|
setReady(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Ensure cookie mirror exists for customer dashboard
|
||||||
|
const refresh = readToken(REFRESH_TOKEN_KEY);
|
||||||
|
writeSharedAuthCookies(token, refresh ?? undefined);
|
||||||
|
|
||||||
|
fetchMe(token)
|
||||||
|
.then(({ user: nextUser, unauthorized }) => {
|
||||||
|
if (nextUser) setUser(nextUser);
|
||||||
|
else if (unauthorized) clearTokens();
|
||||||
|
})
|
||||||
|
.finally(() => setReady(true));
|
||||||
|
}, [clearTokens, fetchMe, getAccessToken]);
|
||||||
|
|
||||||
|
const login = useCallback(
|
||||||
|
async (cellNumber: string, password: string) => {
|
||||||
|
const data = await authRequest<{
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken?: string;
|
||||||
|
user?: AuthUser;
|
||||||
|
}>("/api/auth/login", { cellNumber, password });
|
||||||
|
|
||||||
|
persistTokens(data.accessToken, data.refreshToken);
|
||||||
|
if (data.user) {
|
||||||
|
setUser(normalizeUser(data.user));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const me = await fetchMe(data.accessToken);
|
||||||
|
setUser(me.user);
|
||||||
|
},
|
||||||
|
[fetchMe, persistTokens],
|
||||||
|
);
|
||||||
|
|
||||||
|
const register = useCallback(
|
||||||
|
async (input: {
|
||||||
|
cellNumber: string;
|
||||||
|
password: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email?: string;
|
||||||
|
}) => {
|
||||||
|
const data = await authRequest<{
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken?: string;
|
||||||
|
user?: AuthUser;
|
||||||
|
}>("/api/auth/register", input);
|
||||||
|
|
||||||
|
persistTokens(data.accessToken, data.refreshToken);
|
||||||
|
if (data.user) {
|
||||||
|
setUser(normalizeUser(data.user));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const me = await fetchMe(data.accessToken);
|
||||||
|
setUser(me.user);
|
||||||
|
},
|
||||||
|
[fetchMe, persistTokens],
|
||||||
|
);
|
||||||
|
|
||||||
|
const logout = useCallback(() => {
|
||||||
|
clearTokens();
|
||||||
|
}, [clearTokens]);
|
||||||
|
|
||||||
|
const isWebsiteAdmin = useMemo(
|
||||||
|
() => isWebsiteAdminForBusiness(user, businessId),
|
||||||
|
[user, businessId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({
|
||||||
|
user,
|
||||||
|
isAuthenticated: Boolean(user),
|
||||||
|
ready,
|
||||||
|
businessId,
|
||||||
|
isWebsiteAdmin,
|
||||||
|
login,
|
||||||
|
register,
|
||||||
|
logout,
|
||||||
|
getAccessToken,
|
||||||
|
}),
|
||||||
|
[user, ready, businessId, isWebsiteAdmin, login, register, logout, getAccessToken],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
const ctx = useContext(AuthContext);
|
||||||
|
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
export type CartItem = {
|
||||||
|
id: string;
|
||||||
|
storeItemVariantId: string;
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
image?: string | null;
|
||||||
|
price: number;
|
||||||
|
quantity: number;
|
||||||
|
optionLabel?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CartSnapshot = {
|
||||||
|
items: CartItem[];
|
||||||
|
subtotal: number;
|
||||||
|
total: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function num(value: unknown): number | null {
|
||||||
|
if (value == null) return null;
|
||||||
|
const n = Number(value);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function str(value: unknown): string {
|
||||||
|
return value != null ? String(value) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeCart(data: unknown): CartSnapshot {
|
||||||
|
const root = data && typeof data === "object" ? (data as Record<string, unknown>) : {};
|
||||||
|
const cart =
|
||||||
|
root.cart && typeof root.cart === "object"
|
||||||
|
? (root.cart as Record<string, unknown>)
|
||||||
|
: root;
|
||||||
|
const rawItems = Array.isArray(cart.items) ? cart.items : [];
|
||||||
|
|
||||||
|
const items: CartItem[] = rawItems.map((raw) => {
|
||||||
|
const item = raw as Record<string, unknown>;
|
||||||
|
const product =
|
||||||
|
item.product && typeof item.product === "object"
|
||||||
|
? (item.product as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
const variant =
|
||||||
|
item.variant && typeof item.variant === "object"
|
||||||
|
? (item.variant as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
const storeItem =
|
||||||
|
item.storeItem && typeof item.storeItem === "object"
|
||||||
|
? (item.storeItem as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
|
||||||
|
const quantity = num(item.quantity) ?? 1;
|
||||||
|
const unitPrice =
|
||||||
|
num(item.unitPrice) ??
|
||||||
|
num(item.price) ??
|
||||||
|
num(item.discountedPrice) ??
|
||||||
|
num(variant.discountedPrice) ??
|
||||||
|
num(variant.price) ??
|
||||||
|
num(storeItem.discountedPrice) ??
|
||||||
|
num(storeItem.price) ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
const name = str(
|
||||||
|
item.productTitle ??
|
||||||
|
item.productNameFa ??
|
||||||
|
product.nameFa ??
|
||||||
|
product.name ??
|
||||||
|
product.title ??
|
||||||
|
storeItem.productTitle ??
|
||||||
|
storeItem.productNameFa,
|
||||||
|
);
|
||||||
|
|
||||||
|
const slug = str(product.slug ?? item.productSlug ?? storeItem.productSlug);
|
||||||
|
const image = str(
|
||||||
|
item.productImage ??
|
||||||
|
item.image ??
|
||||||
|
product.image ??
|
||||||
|
product.thumbnailUrl ??
|
||||||
|
storeItem.productImage,
|
||||||
|
);
|
||||||
|
|
||||||
|
const selections = Array.isArray(item.selections)
|
||||||
|
? item.selections
|
||||||
|
: Array.isArray(variant.selections)
|
||||||
|
? variant.selections
|
||||||
|
: [];
|
||||||
|
const optionLabel = selections
|
||||||
|
.map((s) => {
|
||||||
|
const sel = s as Record<string, unknown>;
|
||||||
|
return str(sel.label ?? sel.optionLabel ?? sel.value);
|
||||||
|
})
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" / ");
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: str(item.id ?? item.itemId),
|
||||||
|
storeItemVariantId: str(
|
||||||
|
item.storeItemVariantId ?? variant.id ?? storeItem.id ?? item.variantId,
|
||||||
|
),
|
||||||
|
slug,
|
||||||
|
name,
|
||||||
|
image: image || null,
|
||||||
|
price: unitPrice,
|
||||||
|
quantity,
|
||||||
|
optionLabel: optionLabel || undefined,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const subtotal =
|
||||||
|
num(cart.subtotal) ??
|
||||||
|
items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||||
|
const total = num(cart.total) ?? subtotal;
|
||||||
|
|
||||||
|
return { items, subtotal, total };
|
||||||
|
}
|
||||||
-171
@@ -1,171 +0,0 @@
|
|||||||
// Cart/checkout — requires a logged-in customer (Bearer token) and the
|
|
||||||
// business id, per Meshkee's /businesses/{businessId}/cart... routes.
|
|
||||||
import { getStoredTokens, refreshAccessToken } from "@/lib/auth";
|
|
||||||
|
|
||||||
const API_BASE = "https://api.meshkee.com/api/v1";
|
|
||||||
|
|
||||||
export type CartItem = {
|
|
||||||
id: string;
|
|
||||||
storeItemVariantId: string;
|
|
||||||
productId: string;
|
|
||||||
productTitle: string;
|
|
||||||
productNameFa?: string;
|
|
||||||
productImage: string | null;
|
|
||||||
label: string;
|
|
||||||
selections: { variationId: string; variationName: string; optionId: string; value: string }[];
|
|
||||||
quantity: number;
|
|
||||||
unitPrice: number;
|
|
||||||
compareAtPrice: number | null;
|
|
||||||
lineTotal: number;
|
|
||||||
stockQuantity: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Cart = {
|
|
||||||
id: string;
|
|
||||||
items: CartItem[];
|
|
||||||
itemCount: number;
|
|
||||||
subtotal: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
function normalizeCart(raw: Record<string, unknown>): Cart {
|
|
||||||
const items = (raw.items as Record<string, unknown>[] | undefined) ?? [];
|
|
||||||
return {
|
|
||||||
id: String(raw.id ?? ""),
|
|
||||||
itemCount: Number(raw.itemCount ?? items.length),
|
|
||||||
subtotal: Number(raw.subtotal ?? 0),
|
|
||||||
items: items.map((item) => ({
|
|
||||||
id: String(item.id ?? ""),
|
|
||||||
storeItemVariantId: String(item.storeItemVariantId ?? ""),
|
|
||||||
productId: String(item.productId ?? ""),
|
|
||||||
productTitle: String(item.productTitle ?? ""),
|
|
||||||
productNameFa: item.productNameFa as string | undefined,
|
|
||||||
productImage: (item.productImage as string | undefined) ?? null,
|
|
||||||
label: String(item.label ?? ""),
|
|
||||||
selections: ((item.selections as Record<string, unknown>[] | undefined) ?? []).map((s) => ({
|
|
||||||
variationId: String(s.variationId ?? ""),
|
|
||||||
variationName: String(s.variationName ?? ""),
|
|
||||||
optionId: String(s.optionId ?? ""),
|
|
||||||
value: String(s.value ?? ""),
|
|
||||||
})),
|
|
||||||
quantity: Number(item.quantity ?? 0),
|
|
||||||
unitPrice: Number(item.unitPrice ?? 0),
|
|
||||||
compareAtPrice: item.compareAtPrice != null ? Number(item.compareAtPrice) : null,
|
|
||||||
lineTotal: Number(item.lineTotal ?? 0),
|
|
||||||
stockQuantity: Number(item.stockQuantity ?? 0),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
type Result<T> = { ok: true; data: T } | { ok: false; message: string; unauthorized?: boolean };
|
|
||||||
|
|
||||||
// Always reads the current token from storage (not a stale value captured
|
|
||||||
// earlier by the caller) and, on a 401, transparently refreshes it once and
|
|
||||||
// retries — access tokens only last ~15 minutes, so this is the difference
|
|
||||||
// between "cart just works" and shoppers getting logged out mid-browse.
|
|
||||||
async function cartFetch<T>(
|
|
||||||
path: string,
|
|
||||||
options: { method?: string; body?: unknown } = {},
|
|
||||||
isRetry = false,
|
|
||||||
): Promise<Result<T>> {
|
|
||||||
const token = getStoredTokens()?.accessToken;
|
|
||||||
if (!token) return { ok: false, message: "برای این کار باید وارد شوید.", unauthorized: true };
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_BASE}${path}`, {
|
|
||||||
method: options.method ?? "GET",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
body: options.body != null ? JSON.stringify(options.body) : undefined,
|
|
||||||
});
|
|
||||||
if (res.status === 401 && !isRetry) {
|
|
||||||
const refreshed = await refreshAccessToken();
|
|
||||||
if (refreshed) return cartFetch<T>(path, options, true);
|
|
||||||
return { ok: false, message: "نشست شما منقضی شده. دوباره وارد شوید.", unauthorized: true };
|
|
||||||
}
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
return { ok: false, message: (data as { message?: string })?.message ?? "خطایی رخ داد." };
|
|
||||||
}
|
|
||||||
return { ok: true, data: data as T };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, message: "ارتباط با سرور برقرار نشد." };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getCart(businessId: string): Promise<Result<Cart>> {
|
|
||||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart`);
|
|
||||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function addCartItem(
|
|
||||||
businessId: string,
|
|
||||||
storeItemVariantId: string,
|
|
||||||
quantity: number,
|
|
||||||
): Promise<Result<Cart>> {
|
|
||||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart/items`, {
|
|
||||||
method: "POST",
|
|
||||||
body: { storeItemVariantId, quantity },
|
|
||||||
});
|
|
||||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateCartItem(
|
|
||||||
businessId: string,
|
|
||||||
itemId: string,
|
|
||||||
quantity: number,
|
|
||||||
): Promise<Result<Cart>> {
|
|
||||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart/items/${itemId}`, {
|
|
||||||
method: "PATCH",
|
|
||||||
body: { quantity },
|
|
||||||
});
|
|
||||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function removeCartItem(businessId: string, itemId: string): Promise<Result<Cart>> {
|
|
||||||
const res = await cartFetch<{ cart: Record<string, unknown> }>(`/businesses/${businessId}/cart/items/${itemId}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
});
|
|
||||||
return res.ok ? { ok: true, data: normalizeCart(res.data.cart) } : res;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type CheckoutPayload = {
|
|
||||||
addressId?: string;
|
|
||||||
shippingAddress?: {
|
|
||||||
province: string;
|
|
||||||
city: string;
|
|
||||||
address: string;
|
|
||||||
postalCode?: string;
|
|
||||||
landline?: string;
|
|
||||||
};
|
|
||||||
customerNotes?: string;
|
|
||||||
payment: { type: "cash" | "transfer"; transferAccount?: string; transferRefNumber?: string; notes?: string };
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Order = {
|
|
||||||
id: string;
|
|
||||||
orderNumber: string;
|
|
||||||
status: string;
|
|
||||||
processStepLabelFa?: string;
|
|
||||||
total: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function checkout(businessId: string, payload: CheckoutPayload): Promise<Result<Order>> {
|
|
||||||
const res = await cartFetch<{ order: Record<string, unknown> }>(`/businesses/${businessId}/cart/checkout`, {
|
|
||||||
method: "POST",
|
|
||||||
body: payload,
|
|
||||||
});
|
|
||||||
if (!res.ok) return res;
|
|
||||||
const order = res.data.order;
|
|
||||||
return {
|
|
||||||
ok: true,
|
|
||||||
data: {
|
|
||||||
id: String(order.id ?? ""),
|
|
||||||
orderNumber: String(order.orderNumber ?? ""),
|
|
||||||
status: String(order.status ?? ""),
|
|
||||||
processStepLabelFa: order.processStepLabelFa as string | undefined,
|
|
||||||
total: Number(order.total ?? 0),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
|
import { useAuth } from "@/lib/auth";
|
||||||
|
import type { CartItem, CartSnapshot } from "@/lib/cart-types";
|
||||||
|
import { normalizeCart } from "@/lib/cart-types";
|
||||||
|
import {
|
||||||
|
clearGuestCart,
|
||||||
|
readGuestCart,
|
||||||
|
writeGuestCart,
|
||||||
|
} from "@/lib/guest-cart";
|
||||||
|
|
||||||
|
type ToastState = {
|
||||||
|
id: number;
|
||||||
|
message: string;
|
||||||
|
} | null;
|
||||||
|
|
||||||
|
export type AddCartItemInput = {
|
||||||
|
storeItemVariantId: string;
|
||||||
|
quantity?: number;
|
||||||
|
slug?: string;
|
||||||
|
name?: string;
|
||||||
|
image?: string | null;
|
||||||
|
price?: number;
|
||||||
|
optionLabel?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type CartContextValue = {
|
||||||
|
items: CartItem[];
|
||||||
|
itemCount: number;
|
||||||
|
subtotal: number;
|
||||||
|
total: number;
|
||||||
|
ready: boolean;
|
||||||
|
loading: boolean;
|
||||||
|
addItem: (input: AddCartItemInput) => Promise<boolean>;
|
||||||
|
removeItem: (itemId: string) => Promise<void>;
|
||||||
|
setQuantity: (itemId: string, quantity: number) => Promise<void>;
|
||||||
|
refresh: () => Promise<void>;
|
||||||
|
toast: ToastState;
|
||||||
|
showToast: (message: string) => void;
|
||||||
|
dismissToast: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CartContext = createContext<CartContextValue | null>(null);
|
||||||
|
|
||||||
|
function emptySnapshot(): CartSnapshot {
|
||||||
|
return { items: [], subtotal: 0, total: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshotFromItems(items: CartItem[]): CartSnapshot {
|
||||||
|
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||||
|
return { items, subtotal, total: subtotal };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cartRequest(
|
||||||
|
path: string,
|
||||||
|
token: string,
|
||||||
|
init?: RequestInit,
|
||||||
|
): Promise<CartSnapshot> {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
...init,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
...(init?.headers as Record<string, string> | undefined),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json().catch(() => null);
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(
|
||||||
|
(data as { error?: string } | null)?.error ?? "خطا در ارتباط با سبد خرید",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return normalizeCart(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CartProvider({ children }: { children: ReactNode }) {
|
||||||
|
const { isAuthenticated, ready: authReady, getAccessToken } = useAuth();
|
||||||
|
const [snapshot, setSnapshot] = useState<CartSnapshot>(emptySnapshot());
|
||||||
|
const [ready, setReady] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [toast, setToast] = useState<ToastState>(null);
|
||||||
|
const syncedGuestRef = useRef(false);
|
||||||
|
|
||||||
|
const showToast = useCallback((message: string) => {
|
||||||
|
setToast({ id: Date.now(), message });
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const dismissToast = useCallback(() => setToast(null), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!toast) return;
|
||||||
|
const timer = window.setTimeout(() => setToast(null), 2800);
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
}, [toast]);
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (!token) {
|
||||||
|
setSnapshot(snapshotFromItems(readGuestCart()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const next = await cartRequest("/api/cart", token);
|
||||||
|
setSnapshot(next);
|
||||||
|
} catch {
|
||||||
|
setSnapshot(emptySnapshot());
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [getAccessToken]);
|
||||||
|
|
||||||
|
// Load guest cart first; after login, push guest lines into the API cart once.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authReady) return;
|
||||||
|
|
||||||
|
const bootstrap = async () => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (!token) {
|
||||||
|
syncedGuestRef.current = false;
|
||||||
|
setSnapshot(snapshotFromItems(readGuestCart()));
|
||||||
|
setReady(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const guestItems = readGuestCart();
|
||||||
|
if (guestItems.length > 0 && !syncedGuestRef.current) {
|
||||||
|
syncedGuestRef.current = true;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
for (const item of guestItems) {
|
||||||
|
await cartRequest("/api/cart/items", token, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
storeItemVariantId: item.storeItemVariantId,
|
||||||
|
quantity: item.quantity,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
clearGuestCart();
|
||||||
|
} catch {
|
||||||
|
// keep guest cart if sync fails
|
||||||
|
syncedGuestRef.current = false;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await refresh();
|
||||||
|
setReady(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
void bootstrap();
|
||||||
|
}, [authReady, isAuthenticated, getAccessToken, refresh]);
|
||||||
|
|
||||||
|
const addItem = useCallback(
|
||||||
|
async (input: AddCartItemInput) => {
|
||||||
|
const quantity = Math.max(1, input.quantity ?? 1);
|
||||||
|
const token = getAccessToken();
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const next = await cartRequest("/api/cart/items", token, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
storeItemVariantId: input.storeItemVariantId,
|
||||||
|
quantity,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
setSnapshot(next);
|
||||||
|
showToast("به سبد خرید اضافه شد");
|
||||||
|
return true;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = readGuestCart();
|
||||||
|
const existing = current.find(
|
||||||
|
(item) => item.storeItemVariantId === input.storeItemVariantId,
|
||||||
|
);
|
||||||
|
const nextItems = existing
|
||||||
|
? current.map((item) =>
|
||||||
|
item.storeItemVariantId === input.storeItemVariantId
|
||||||
|
? {
|
||||||
|
...item,
|
||||||
|
quantity: item.quantity + quantity,
|
||||||
|
price: input.price ?? item.price,
|
||||||
|
name: input.name ?? item.name,
|
||||||
|
image: input.image ?? item.image,
|
||||||
|
optionLabel: input.optionLabel ?? item.optionLabel,
|
||||||
|
}
|
||||||
|
: item,
|
||||||
|
)
|
||||||
|
: [
|
||||||
|
...current,
|
||||||
|
{
|
||||||
|
id: input.storeItemVariantId,
|
||||||
|
storeItemVariantId: input.storeItemVariantId,
|
||||||
|
slug: input.slug ?? "",
|
||||||
|
name: input.name ?? "",
|
||||||
|
image: input.image ?? null,
|
||||||
|
price: input.price ?? 0,
|
||||||
|
quantity,
|
||||||
|
optionLabel: input.optionLabel,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
writeGuestCart(nextItems);
|
||||||
|
setSnapshot(snapshotFromItems(nextItems));
|
||||||
|
showToast("به سبد خرید اضافه شد");
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
[getAccessToken, showToast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const removeItem = useCallback(
|
||||||
|
async (itemId: string) => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (token) {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const next = await cartRequest(`/api/cart/items/${itemId}`, token, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
setSnapshot(next);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextItems = readGuestCart().filter(
|
||||||
|
(item) => item.id !== itemId && item.storeItemVariantId !== itemId,
|
||||||
|
);
|
||||||
|
writeGuestCart(nextItems);
|
||||||
|
setSnapshot(snapshotFromItems(nextItems));
|
||||||
|
},
|
||||||
|
[getAccessToken],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setQuantity = useCallback(
|
||||||
|
async (itemId: string, quantity: number) => {
|
||||||
|
const token = getAccessToken();
|
||||||
|
if (token) {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const next =
|
||||||
|
quantity < 1
|
||||||
|
? await cartRequest(`/api/cart/items/${itemId}`, token, {
|
||||||
|
method: "DELETE",
|
||||||
|
})
|
||||||
|
: await cartRequest(`/api/cart/items/${itemId}`, token, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({ quantity }),
|
||||||
|
});
|
||||||
|
setSnapshot(next);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quantity < 1) {
|
||||||
|
const nextItems = readGuestCart().filter(
|
||||||
|
(item) => item.id !== itemId && item.storeItemVariantId !== itemId,
|
||||||
|
);
|
||||||
|
writeGuestCart(nextItems);
|
||||||
|
setSnapshot(snapshotFromItems(nextItems));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextItems = readGuestCart().map((item) =>
|
||||||
|
item.id === itemId || item.storeItemVariantId === itemId
|
||||||
|
? { ...item, quantity }
|
||||||
|
: item,
|
||||||
|
);
|
||||||
|
writeGuestCart(nextItems);
|
||||||
|
setSnapshot(snapshotFromItems(nextItems));
|
||||||
|
},
|
||||||
|
[getAccessToken],
|
||||||
|
);
|
||||||
|
|
||||||
|
const itemCount = useMemo(
|
||||||
|
() => snapshot.items.reduce((sum, item) => sum + item.quantity, 0),
|
||||||
|
[snapshot.items],
|
||||||
|
);
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({
|
||||||
|
items: snapshot.items,
|
||||||
|
itemCount,
|
||||||
|
subtotal: snapshot.subtotal,
|
||||||
|
total: snapshot.total,
|
||||||
|
ready,
|
||||||
|
loading,
|
||||||
|
addItem,
|
||||||
|
removeItem,
|
||||||
|
setQuantity,
|
||||||
|
refresh,
|
||||||
|
toast,
|
||||||
|
showToast,
|
||||||
|
dismissToast,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
snapshot,
|
||||||
|
itemCount,
|
||||||
|
ready,
|
||||||
|
loading,
|
||||||
|
addItem,
|
||||||
|
removeItem,
|
||||||
|
setQuantity,
|
||||||
|
refresh,
|
||||||
|
toast,
|
||||||
|
showToast,
|
||||||
|
dismissToast,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCart() {
|
||||||
|
const ctx = useContext(CartContext);
|
||||||
|
if (!ctx) throw new Error("useCart must be used within CartProvider");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import type { CartItem } from "@/lib/cart-types";
|
||||||
|
import { encodeGuestCartForUrl, GUEST_CART_URL_PARAM } from "@/lib/guest-cart";
|
||||||
|
import { DOMAIN } from "@/lib/meshkee";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared checkout lives on the customer dashboard (all websites).
|
||||||
|
* Local: http://customer.{domain}:5175
|
||||||
|
* Prod: https://customer.{domain}
|
||||||
|
*
|
||||||
|
* Prefer NEXT_PUBLIC_CUSTOMER_ORIGIN. Otherwise derive from DOMAIN + build mode
|
||||||
|
* so production deploys never bake in the local Vite URL.
|
||||||
|
*/
|
||||||
|
function resolveCustomerOrigin(): string {
|
||||||
|
const configured = process.env.NEXT_PUBLIC_CUSTOMER_ORIGIN?.replace(/\/$/, "");
|
||||||
|
if (configured) return configured;
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === "production") {
|
||||||
|
return `https://customer.${DOMAIN}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `http://customer.${DOMAIN}:5175`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CUSTOMER_ORIGIN = resolveCustomerOrigin();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Business dashboard for website admins.
|
||||||
|
* Local: http://business.{domain}:5173
|
||||||
|
* Prod: https://business.{domain}
|
||||||
|
*/
|
||||||
|
export function businessDashboardUrl(): string {
|
||||||
|
const configured = process.env.NEXT_PUBLIC_BUSINESS_ORIGIN?.replace(/\/$/, "");
|
||||||
|
if (configured) return `${configured}/`;
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === "production") {
|
||||||
|
return `https://business.${DOMAIN}/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
const { protocol, port } = window.location;
|
||||||
|
if (port === "3000" || port === "3001") {
|
||||||
|
return `${protocol}//business.${DOMAIN}:5173/`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `https://business.${DOMAIN}/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Absolute URL on the customer dashboard (e.g. /checkout/cart). */
|
||||||
|
export function customerDashboardUrl(path = "/checkout/cart"): string {
|
||||||
|
const normalized = path.startsWith("/") ? path : `/${path}`;
|
||||||
|
return `${CUSTOMER_ORIGIN}${normalized}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guest Continue → customer login, then back to checkout cart.
|
||||||
|
* Cart lines are passed in the redirect hash so the customer app can ingest them.
|
||||||
|
*/
|
||||||
|
export function customerLoginUrl(
|
||||||
|
redirectPath = "/checkout/cart",
|
||||||
|
cartItems?: CartItem[],
|
||||||
|
): string {
|
||||||
|
let redirect = redirectPath.startsWith("/") ? redirectPath : `/${redirectPath}`;
|
||||||
|
if (cartItems && cartItems.length > 0) {
|
||||||
|
const encoded = encodeGuestCartForUrl(cartItems);
|
||||||
|
const join = redirect.includes("#") ? "&" : `#`;
|
||||||
|
redirect = `${redirect}${join}${GUEST_CART_URL_PARAM}=${encoded}`;
|
||||||
|
}
|
||||||
|
const url = new URL("/login", CUSTOMER_ORIGIN);
|
||||||
|
url.searchParams.set("redirect", redirect);
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Continue from cart popup: hand off cart lines via #guestCart=… */
|
||||||
|
export function customerContinueCheckoutUrl(
|
||||||
|
isAuthenticated: boolean,
|
||||||
|
cartItems: CartItem[] = [],
|
||||||
|
): string {
|
||||||
|
if (isAuthenticated) {
|
||||||
|
const url = new URL("/checkout/cart", CUSTOMER_ORIGIN);
|
||||||
|
if (cartItems.length > 0) {
|
||||||
|
url.hash = `${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
||||||
|
}
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
return customerLoginUrl("/checkout/cart", cartItems);
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import type { CartItem } from "@/lib/cart-types";
|
||||||
|
|
||||||
|
/** Must match customer dashboard `GUEST_CART_STORAGE_KEY`. */
|
||||||
|
export const MESHKEE_GUEST_CART_KEY = "meshkee-guest-cart";
|
||||||
|
export const LEGACY_GUEST_CART_KEY = "sanihome-guest-cart";
|
||||||
|
export const GUEST_CART_URL_PARAM = "guestCart";
|
||||||
|
|
||||||
|
export type MeshkeeGuestCartItem = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
slug?: string;
|
||||||
|
price: number;
|
||||||
|
originalPrice?: number;
|
||||||
|
image: string | null;
|
||||||
|
quantity: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function cookieDomain(): string | undefined {
|
||||||
|
if (typeof window === "undefined") return undefined;
|
||||||
|
const host = window.location.hostname.toLowerCase();
|
||||||
|
if (host === "localhost" || host === "127.0.0.1") return undefined;
|
||||||
|
const parts = host.split(".").filter(Boolean);
|
||||||
|
if (parts.length < 2) return undefined;
|
||||||
|
return `.${parts.slice(-2).join(".")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseItems(raw: string | null): CartItem[] {
|
||||||
|
if (!raw) return [];
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as CartItem[];
|
||||||
|
return Array.isArray(parsed) ? parsed : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Map storefront cart lines to the shared guest-cart shape (id = variant id). */
|
||||||
|
export function toMeshkeeGuestItems(items: CartItem[]): MeshkeeGuestCartItem[] {
|
||||||
|
const result: MeshkeeGuestCartItem[] = [];
|
||||||
|
for (const item of items) {
|
||||||
|
const variantId = (item.storeItemVariantId || item.id || "").trim();
|
||||||
|
if (!variantId) continue;
|
||||||
|
result.push({
|
||||||
|
id: variantId,
|
||||||
|
name: item.name || "محصول",
|
||||||
|
...(item.slug ? { slug: item.slug } : {}),
|
||||||
|
price: item.price,
|
||||||
|
image: item.image ?? null,
|
||||||
|
quantity: Math.max(1, Math.floor(item.quantity) || 1),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeGuestCartForUrl(items: CartItem[]): string {
|
||||||
|
const payload = toMeshkeeGuestItems(items);
|
||||||
|
const json = JSON.stringify(payload);
|
||||||
|
return btoa(unescape(encodeURIComponent(json)))
|
||||||
|
.replace(/\+/g, "-")
|
||||||
|
.replace(/\//g, "_")
|
||||||
|
.replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeSharedCookie(items: MeshkeeGuestCartItem[]) {
|
||||||
|
if (typeof document === "undefined") return;
|
||||||
|
const domain = cookieDomain();
|
||||||
|
const maxAge = 60 * 60 * 24 * 30;
|
||||||
|
const encoded = encodeURIComponent(
|
||||||
|
JSON.stringify(
|
||||||
|
items.map(({ id, name, slug, price, originalPrice, quantity }) => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
slug,
|
||||||
|
price,
|
||||||
|
originalPrice,
|
||||||
|
quantity,
|
||||||
|
image: null as string | null,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (encoded.length > 3500) return;
|
||||||
|
let cookie = `${MESHKEE_GUEST_CART_KEY}=${encoded}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||||
|
if (domain) cookie += `; domain=${domain}`;
|
||||||
|
document.cookie = cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readGuestCart(): CartItem[] {
|
||||||
|
if (typeof window === "undefined") return [];
|
||||||
|
const primary = parseItems(localStorage.getItem(MESHKEE_GUEST_CART_KEY));
|
||||||
|
if (primary.length > 0) return primary;
|
||||||
|
const legacy = parseItems(localStorage.getItem(LEGACY_GUEST_CART_KEY));
|
||||||
|
if (legacy.length > 0) {
|
||||||
|
writeGuestCart(legacy);
|
||||||
|
return legacy;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeGuestCart(items: CartItem[]) {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
const raw = JSON.stringify(items);
|
||||||
|
localStorage.setItem(MESHKEE_GUEST_CART_KEY, raw);
|
||||||
|
localStorage.removeItem(LEGACY_GUEST_CART_KEY);
|
||||||
|
try {
|
||||||
|
writeSharedCookie(toMeshkeeGuestItems(items));
|
||||||
|
} catch {
|
||||||
|
// ignore cookie failures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearGuestCart() {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
localStorage.removeItem(MESHKEE_GUEST_CART_KEY);
|
||||||
|
localStorage.removeItem(LEGACY_GUEST_CART_KEY);
|
||||||
|
const domain = cookieDomain();
|
||||||
|
let cookie = `${MESHKEE_GUEST_CART_KEY}=; path=/; max-age=0; SameSite=Lax`;
|
||||||
|
if (domain) cookie += `; domain=${domain}`;
|
||||||
|
document.cookie = cookie;
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { DOMAIN } from "@/lib/meshkee";
|
||||||
|
|
||||||
|
export const MESHKEE_API_BASE =
|
||||||
|
process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") ||
|
||||||
|
"https://api.meshkee.com/api/v1";
|
||||||
|
|
||||||
|
export function getBearerToken(request: Request): string | null {
|
||||||
|
const auth = request.headers.get("authorization");
|
||||||
|
if (auth?.startsWith("Bearer ")) return auth.slice(7);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function meshkeeFetch(
|
||||||
|
path: string,
|
||||||
|
init?: RequestInit & { token?: string | null },
|
||||||
|
): Promise<{ ok: boolean; status: number; data: unknown }> {
|
||||||
|
const headers = new Headers(init?.headers);
|
||||||
|
if (!headers.has("Content-Type") && init?.body) {
|
||||||
|
headers.set("Content-Type", "application/json");
|
||||||
|
}
|
||||||
|
if (init?.token) {
|
||||||
|
headers.set("Authorization", `Bearer ${init.token}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${MESHKEE_API_BASE}${path}`, {
|
||||||
|
...init,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
let data: unknown = null;
|
||||||
|
try {
|
||||||
|
data = await res.json();
|
||||||
|
} catch {
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: res.ok, status: res.status, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveBusinessId(): Promise<string | null> {
|
||||||
|
const res = await meshkeeFetch(`/tenants/${DOMAIN}`);
|
||||||
|
if (!res.ok || !res.data || typeof res.data !== "object") return null;
|
||||||
|
const id = (res.data as { id?: string }).id;
|
||||||
|
return id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function jsonResponse(data: unknown, status = 200) {
|
||||||
|
return Response.json(data, { status });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unauthorizedResponse() {
|
||||||
|
return jsonResponse({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
+21
-124
@@ -1,5 +1,19 @@
|
|||||||
const API_BASE = "https://api.meshkee.com/api/v1";
|
const API_BASE =
|
||||||
const DOMAIN = "sanihome.ir";
|
process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") ||
|
||||||
|
"https://api.meshkee.com/api/v1";
|
||||||
|
export const DOMAIN = process.env.NEXT_PUBLIC_DOMAIN || "sanihome.ir";
|
||||||
|
|
||||||
|
export type Tenant = {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
nameFa?: string;
|
||||||
|
domain?: string;
|
||||||
|
logoUrl?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getTenant(): Promise<Tenant | null> {
|
||||||
|
return apiGet<Tenant>(`/tenants/${DOMAIN}`);
|
||||||
|
}
|
||||||
|
|
||||||
async function apiGet<T>(
|
async function apiGet<T>(
|
||||||
path: string,
|
path: string,
|
||||||
@@ -21,30 +35,6 @@ 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;
|
||||||
@@ -140,11 +130,6 @@ 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 {
|
||||||
@@ -192,9 +177,6 @@ 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,
|
||||||
@@ -354,41 +336,29 @@ export async function getProductTechnicalInfo(slug: string): Promise<TechnicalIn
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type StoreItem = {
|
export type StoreItem = {
|
||||||
id: string; // the store-item VARIANT id — what the cart API calls storeItemVariantId
|
id: string;
|
||||||
productId: string;
|
productId: string;
|
||||||
name: string;
|
name: string;
|
||||||
label: string;
|
|
||||||
image: string | null;
|
image: string | null;
|
||||||
price: number | null;
|
price: number | null;
|
||||||
oldPrice: number | null;
|
discountedPrice: 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 ?? ""),
|
||||||
// Prefer the Persian name — sanihome.ir is a Persian storefront.
|
name: String(raw.productTitle ?? raw.productNameFa ?? raw.label ?? ""),
|
||||||
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: hasDiscount ? rawDiscounted : rawPrice,
|
price: raw.price != null ? Number(raw.price) : null,
|
||||||
oldPrice: hasDiscount ? rawPrice : null,
|
discountedPrice: raw.discountedPrice != null ? Number(raw.discountedPrice) : 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;
|
||||||
@@ -408,30 +378,6 @@ 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;
|
||||||
@@ -643,52 +589,3 @@ 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 };
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/** Shared auth cookies so storefront + customer.{domain} share one login. */
|
||||||
|
|
||||||
|
export const SHARED_ACCESS_TOKEN_KEY = "meshkee_customer_access_token";
|
||||||
|
export const SHARED_REFRESH_TOKEN_KEY = "meshkee_customer_refresh_token";
|
||||||
|
|
||||||
|
const CHUNK_SIZE = 2800;
|
||||||
|
const MAX_CHUNKS = 24;
|
||||||
|
|
||||||
|
function cookieDomain(): string | undefined {
|
||||||
|
if (typeof window === "undefined") return undefined;
|
||||||
|
const host = window.location.hostname.toLowerCase();
|
||||||
|
if (host === "localhost" || host === "127.0.0.1") return undefined;
|
||||||
|
const parts = host.split(".").filter(Boolean);
|
||||||
|
if (parts.length < 2) return undefined;
|
||||||
|
return `.${parts.slice(-2).join(".")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRawCookie(name: string): string | null {
|
||||||
|
if (typeof document === "undefined") return null;
|
||||||
|
const prefix = `${name}=`;
|
||||||
|
const match = document.cookie.split("; ").find((row) => row.startsWith(prefix));
|
||||||
|
if (!match) return null;
|
||||||
|
return match.slice(prefix.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeRawCookie(name: string, value: string | null) {
|
||||||
|
if (typeof document === "undefined") return;
|
||||||
|
const domain = cookieDomain();
|
||||||
|
if (value == null) {
|
||||||
|
let cookie = `${name}=; path=/; max-age=0; SameSite=Lax`;
|
||||||
|
if (domain) cookie += `; domain=${domain}`;
|
||||||
|
document.cookie = cookie;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const maxAge = 60 * 60 * 24 * 30;
|
||||||
|
let cookie = `${name}=${value}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||||
|
if (domain) cookie += `; domain=${domain}`;
|
||||||
|
document.cookie = cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearChunkedCookie(name: string) {
|
||||||
|
writeRawCookie(name, null);
|
||||||
|
const n = Number(readRawCookie(`${name}_n`) || "0");
|
||||||
|
writeRawCookie(`${name}_n`, null);
|
||||||
|
for (let i = 0; i < Math.max(n, MAX_CHUNKS); i++) {
|
||||||
|
writeRawCookie(`${name}_${i}`, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeCookie(name: string, value: string | null) {
|
||||||
|
clearChunkedCookie(name);
|
||||||
|
if (value == null || value === "") return;
|
||||||
|
|
||||||
|
const encoded = encodeURIComponent(value);
|
||||||
|
if (encoded.length <= 3500) {
|
||||||
|
writeRawCookie(name, encoded);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunks: string[] = [];
|
||||||
|
for (let i = 0; i < encoded.length; i += CHUNK_SIZE) {
|
||||||
|
chunks.push(encoded.slice(i, i + CHUNK_SIZE));
|
||||||
|
}
|
||||||
|
writeRawCookie(`${name}_n`, String(chunks.length));
|
||||||
|
chunks.forEach((chunk, i) => writeRawCookie(`${name}_${i}`, chunk));
|
||||||
|
}
|
||||||
|
|
||||||
|
function readCookie(name: string): string | null {
|
||||||
|
const n = Number(readRawCookie(`${name}_n`) || "0");
|
||||||
|
if (n > 0) {
|
||||||
|
let encoded = "";
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const part = readRawCookie(`${name}_${i}`);
|
||||||
|
if (part == null) return null;
|
||||||
|
encoded += part;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(encoded);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = readRawCookie(name);
|
||||||
|
if (raw == null) return null;
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(raw);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeSharedAuthCookies(accessToken: string, refreshToken?: string) {
|
||||||
|
writeCookie(SHARED_ACCESS_TOKEN_KEY, accessToken);
|
||||||
|
if (refreshToken) writeCookie(SHARED_REFRESH_TOKEN_KEY, refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearSharedAuthCookies() {
|
||||||
|
writeCookie(SHARED_ACCESS_TOKEN_KEY, null);
|
||||||
|
writeCookie(SHARED_REFRESH_TOKEN_KEY, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readSharedAccessToken(): string | null {
|
||||||
|
return readCookie(SHARED_ACCESS_TOKEN_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readSharedRefreshToken(): string | null {
|
||||||
|
return readCookie(SHARED_REFRESH_TOKEN_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hydrateLocalTokensFromSharedCookies(
|
||||||
|
accessKey = SHARED_ACCESS_TOKEN_KEY,
|
||||||
|
refreshKey = SHARED_REFRESH_TOKEN_KEY,
|
||||||
|
): boolean {
|
||||||
|
if (typeof window === "undefined") return false;
|
||||||
|
if (localStorage.getItem(accessKey)) return false;
|
||||||
|
const access = readSharedAccessToken();
|
||||||
|
if (!access) return false;
|
||||||
|
localStorage.setItem(accessKey, access);
|
||||||
|
const refresh = readSharedRefreshToken();
|
||||||
|
if (refresh) localStorage.setItem(refreshKey, refresh);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user