Compare commits

...
15 Commits
Author SHA1 Message Date
Alireza HassaniandCursor 7ea3fe76c9 Inject CMS meta tags as full HTML from business-info.
metaTags is now { html }; parse into head <meta> elements instead of name/content metadata.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 18:39:21 +03:30
Alireza HassaniandCursor f60c98184b Render CMS meta tags and trust badges from business-info.
Injects dashboard-managed meta tags in the head and eNamad/Samandehi HTML in the footer, and enables Next standalone output for deploy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 18:11:28 +03:30
amirhosein.ashourloo 804eb8702f feat: unify catalog and improve detail pages 2026-09-28 09:35:40 +03:30
amirhosein.ashourloo 3af4e04bdd feat: refine storefront product and sale sections 2026-09-23 13:43:18 +03:30
amirhosein.ashourlooandClaude Sonnet 5 69c54d3b17 Set footer top border color to #dddddd
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 19:41:15 +03:30
amirhosein.ashourlooandClaude Sonnet 5 c4411ebc28 Set mobile/non-desktop header logo height to 65px
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 19:40:17 +03:30
amirhosein.ashourlooandClaude Sonnet 5 69d17a6f8f Change footer background to #f1f1f1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 19:39:04 +03:30
amirhosein.ashourlooandClaude Sonnet 5 d292bfc74c Resize header login/cart icon buttons to 40px, cart bg to #f1f1f1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 19:35:15 +03:30
amirhosein.ashourlooandClaude Sonnet 5 d090f57540 Redesign header icons/account-cart chip, light footer, fix sticky-footer gap
- New shared SVG icon set (src/components/ui/icons.tsx): Menu, User,
  Cart, Close, ChevronLeft — replaces emoji (☰ 👤 🛒 ✕) across the
  header, and the literal "←" text arrow on every "view more"-style
  link (SectionTitle's action, the mega-menu link, BlogCarousel's
  "ادامه مطلب").
- Header desktop account/cart area redesigned as a borderless chip:
  cart icon button (right) + divider + account icon-badge/two-line
  "حساب کاربری / ورود/ثبت‌نام" (left), matching a supplied reference.
  Got the RTL DOM order backwards on the first pass (cart needs to be
  first in DOM to render rightmost) and corrected it.
- Header logo: -10px (was already doubled from an earlier request).
- Footer: background is now bg-[#9a21291a] (exact hex given, not a
  token substitute) with black text throughout instead of solid
  dark-red/white; footer logo doubled; the meshkee-credit logo gets
  brightness-0 so the white source asset stays visible on the new
  light background.
- Fixed a real layout bug: <main> had no flex-1, so on any page
  shorter than the viewport the footer stuck to the content instead of
  the bottom of the screen, leaving a gap of bare background beneath
  it. Standard sticky-footer flex fix.
- CONTEXT.md: documented the icon set, the account/cart chip's RTL DOM
  ordering (to stop this regressing again), and the footer's new
  color scheme + the flex-1 fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 19:31:00 +03:30
amirhosein.ashourlooandClaude Sonnet 5 7a78adc7f3 Footer Meshkee credit widget, fix carousel title row alignment/action button
- Footer bottom-right credit link now matches the badge used on other
  Meshkee storefronts (reference: safeteb.com) — logo + two-line label
  inside an animated corner-drawing border on hover, linking to
  https://meshkee.com. Added the shared credit-widget logo asset
  (public/images/meshkee-logo-white.png).
- SectionTitle: title/action row uses items-center instead of items-end
  (was visibly offset once a carousel title could wrap or carry a
  caption); the action button ("مشاهده همه" etc.) is now styled like
  the site's other primary buttons (filled red, white text, rounded)
  instead of a plain text link.
- Carousel English captions (SPECIAL SALE, TOP SELLING, FAVORITE SELL)
  moved back from a below-title "enSubtitle" line to the existing
  inline enTitle treatment, matching every other section heading's
  convention on the site.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 19:14:10 +03:30
amirhosein.ashourlooandClaude Sonnet 5 ab1b07ff28 Footer credit line links to meshkee.com
Replace the static "Designed for Sanihome" text with a real link
("Powered by meshkee.com" -> https://meshkee.com).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 18:58:56 +03:30
amirhosein.ashourlooandClaude Sonnet 5 0de5abb879 Double desktop header logo, add English caption under each carousel title
- Header logo (desktop variant) doubled: 40/48px -> 80/96px.
- Each dynamic store-specials carousel now shows an English caption
  under its title at 50% opacity, derived from the group's real `key`
  (e.g. "top-selling" -> "TOP SELLING") rather than inventing a
  translation of the Persian title, which the API doesn't provide.
  New SectionTitle `enSubtitle` prop (separate from the existing
  inline `enTitle`) carries this.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 18:06:42 +03:30
amirhosein.ashourlooandClaude Sonnet 5 7c04316f3a Interleave banners between carousels, real "view all" links, bigger desktop logo
- StoreSpecialCarousels now inserts one of the two banner sections
  (TwoBanners/ThreeBanners, cycling) between every pair of carousels
  instead of stacking all carousels together with the banners fixed
  elsewhere on the page — works for any number of dynamic carousels.
- SectionTitle's action button is a real link now (actionHref), not an
  inert <button>. Each carousel's "مشاهده همه" goes to
  /products?specialId={group.id}, which renders that exact
  admin-curated group in the full product grid — store-specials groups
  have no pagination, so this is genuinely the complete set, not a
  truncated preview. Also fixed BlogCarousel's dead "وبلاگ" button the
  same way, now linking to /blog.
- Reduced FeaturedCategories' vertical padding (py-10/14 -> py-4/6).
- Desktop header logo was smaller than the mobile one (36px vs 46px) —
  bumped to 40/48px so it reads properly at desktop width.
- CONTEXT.md: document the banner-interleaving and specialId patterns.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 17:57:01 +03:30
amirhosein.ashourlooandClaude Sonnet 5 bc6cafaffa Make homepage carousels fully dynamic, drop brand carousels, dynamic logo/favicon
- Replace the two hardcoded homepage carousels (SpecialSaleCarousel
  pinned to store-specials group 0 only, TopSellingCarousel reading
  from an unrelated plain product query) with StoreSpecialCarousels:
  loops over every group GET /store-specials returns, using each
  group's own title. A new carousel created in the admin panel (e.g.
  the "بهترین‌ها از نگاه شما" one just added) shows up automatically,
  no code change needed.
- Remove the brand-groups integration and its "سامسونگ" carousel
  entirely (getBrandGroups, BrandGroupCarousels) — brand-name
  carousels aren't wanted on this site per explicit instruction.
- SectionTitle's enTitle is now optional, since dynamic store-specials
  groups only have one title string, not a Persian/English pair.
- Move featured categories above the hero-adjacent special carousels
  per the requested homepage order; drop the "دسته‌بندی‌های پرطرفدار"
  heading and its "همه دسته‌ها" button, per request.
- Wire the header/footer logo and the favicon to the real business
  data (logoUrl/logoDarkUrl/faviconUrl from GET business-info) instead
  of static files; removed src/app/favicon.ico, which was silently
  winning over the new dynamic <link rel="icon">.
- CONTEXT.md: document the dynamic-carousel contract and the
  logo/favicon wiring so neither regresses to hardcoded.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 17:41:46 +03:30
amirhosein.ashourlooandClaude Sonnet 5 5152b16d61 Revert to guest-cart architecture, drop in-site auth/checkout
Per api.meshkee.com/docs/website/AI_PROMPT.md's hard rules (which an
earlier pass on this branch missed): login, register, OTP, the real
cart, addresses, and payment are the customer dashboard's job
(customer.sanihome.ir), not this storefront's. This site should only
ever run a local guest mini-cart and hand off to the dashboard.

- Remove: AuthContext, LoginModal, lib/auth.ts, lib/cart.ts (the real
  /businesses/{id}/cart integration), and the /checkout page entirely.
- Add lib/guestCart.ts: localStorage + shared cookie
  (meshkee-guest-cart, Domain=.sanihome.ir) cart, storeItemVariantId
  keyed, matching the spec's line shape and ~3500-char cookie-size
  cutoff.
- CartContext is now a thin React wrapper over the guest cart (no
  server round-trip, so add/update/remove are synchronous); CartPopup's
  "Continue" builds the exact customer.sanihome.ir/checkout/cart
  (or /login?redirect=...) URL from the spec, base64url-encoding the
  cart and detecting an existing dashboard session via the shared
  meshkee_customer_access_token cookie.
- ProductCard and ProductPurchasePanel add to the guest cart directly;
  no login gate on add-to-cart anymore.
- Comments panel is a plain guest name/email/text form again (the
  comments API never required auth — gating it on the now-removed
  login system was wrong regardless).
- CONTEXT.md rewritten to document the guest-cart contract explicitly
  and flag this exact mistake so it doesn't get reintroduced.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 15:01:22 +03:30
48 changed files with 2022 additions and 1951 deletions
+269 -81
View File
@@ -51,81 +51,72 @@ before touching App Router APIs you're not 100% sure of.
because different endpoints shape the "same" concept differently (see
Data quirks below). Prefer extending an existing `normalize*`/type over
adding a parallel one.
- **`auth.ts`** — client-only (uses `localStorage`) Meshkee customer auth:
register/login/OTP/refresh. Access tokens last **~15 minutes** — this is
short enough that you *will* hit expiry during normal use, so every
authenticated call must self-heal (see Auth below), not just fail.
- **`cart.ts`** — cart/checkout, needs a Bearer token + `businessId`
(`GET /tenants/{domain}` and `.../website/business-info` both return the
same numeric id as their `id` field — `getBusinessInfo().id` is enough,
no separate tenant-resolve call needed).
- **`guestCart.ts`** — the storefront's entire cart story (see next
section). No token, no backend call, no `businessId` — just
`localStorage` + a shared cookie.
## Auth
## Auth, cart & checkout: this site does none of it
Real in-site login (not a redirect to `customer.sanihome.ir` — that link
still exists in the header/footer as a legacy "ورود" pointer but is
independent of this system). `AuthProvider` (`src/context/AuthContext.tsx`)
+ `LoginModal` (`src/components/auth/LoginModal.tsx`), mounted once in
`src/context/Providers.tsx` inside the root layout.
**This was built wrong once already** — an earlier pass added real in-site
login (password/OTP), a real backend cart (`/businesses/{businessId}/cart`),
and a `/checkout` page. That's explicitly **not** how Meshkee storefronts
work, per `https://api.meshkee.com/docs/website/AI_PROMPT.md`'s hard rules:
login, register, OTP, the real cart, addresses, and payment all belong to
**`https://customer.<domain>`** (the customer dashboard) — a *separate app*,
not a page on this site. If you're about to add a `/login`, `/register`,
`/checkout`, `/cart`, or `/account` route, or call `/auth/*` or
`/businesses/{id}/cart*` from this codebase: **stop, re-read the AI_PROMPT.md
"Shopping cart on the storefront" and "Shared login" sections first.**
- Login methods: password (`POST /auth/login`) and SMS OTP
(`POST /auth/send-otp` → `POST /auth/login-otp`). Register:
`POST /auth/register` (requires `domain: "sanihome.ir"`).
- **Confirmed live response shape** (undocumented in OpenAPI, verified by
actually registering a test account): `{ accessToken, refreshToken, user }`
from register/login/login-otp/refresh alike. `GET /auth/me` returns `{ user }`.
- **Password login requires a verified phone number**
(`cellNumber is not verified` 401) — a freshly-registered account can still
use the tokens *from that register response* immediately, but if the
session is lost before verifying, password login is blocked until OTP
verification. There's no verify-OTP UI built yet (see Known gaps).
- **Token refresh race**: `AuthContext` and `CartContext` each independently
notice a 401 and try to refresh. Without coordination this fires two
concurrent `/auth/refresh` calls and the second one fails (likely
refresh-token rotation server-side) — observed as 500/400 errors. Fixed
with an in-flight-promise singleton in `auth.ts`'s `refreshAccessToken()`
— **do not** add another independent refresh call anywhere; always go
through that function.
- `cart.ts` functions take no token parameter — they read the freshest token
from storage internally and self-refresh-and-retry once on 401. Gate UI on
`useAuth().user` (session identity), not on a captured `accessToken` value.
## Cart & checkout
`CartProvider` (`src/context/CartContext.tsx`) fetches the real backend cart
whenever `user` changes and exposes `addItem/updateItem/removeItem/refresh`.
`CartButton` + `CartPopup` (`src/components/cart/`) live in the header via
`Providers`. `/checkout` (`src/app/checkout/page.tsx`) posts to
`POST /businesses/{businessId}/cart/checkout` with `payment.type` of `cash`
or `transfer` only — no online payment gateway (Zarinpal/Mellat/etc.) is
wired up, by explicit scope decision (see Known gaps).
**Important:** a successful checkout clears the cart server-side. Any flow
that calls `checkout()` must also call `useCart().refresh()` afterward, or
the header badge and cart state go stale until next reload.
**Which store-item variant does "add to cart" target?**
- On the product/store-item **detail** pages, `ProductPurchasePanel` always
- **Detecting a logged-in shopper**: read the `meshkee_customer_access_token`
cookie (written by the customer dashboard with `Domain=.sanihome.ir`, so
it's readable here too) — see `isCustomerLoggedIn()` in `guestCart.ts`.
Never build a login UI or call `/auth/login` from this site.
- **Guest cart** (`guestCart.ts`): lines are
`{ id, name, slug, price, originalPrice?, image, quantity }` where `id` is
always a `storeItemVariantId` — never a product id or store-item id.
Persisted to `localStorage` (key `meshkee-guest-cart`) **and** a cookie of
the same name (`Domain=.sanihome.ir`, skipped if the encoded JSON is
>~3500 chars — rely on the URL param instead). `CartProvider`
(`src/context/CartContext.tsx`) just wraps this in React state; there is
no server round-trip, so `addItem`/`updateItem`/`removeItem` are
synchronous.
- **"Continue" in the mini-cart** (`CartPopup`) builds a URL with
`continueToCheckoutUrl()`: the guest cart, base64url-encoded (exact
algorithm from the spec) into a `guestCart` query param, pointed at
`https://customer.sanihome.ir/checkout/cart?guestCart=...` if the shopper
looks logged in, or `.../login?redirect=...` (wrapping that same cart URL)
if not. The dashboard is responsible for decoding it and syncing it into
the real server cart after login — this site's job ends at building that
URL correctly.
- **Which variant does "add to cart" target?**
- On the product/store-item **detail** pages, `ProductPurchasePanel`
resolves a `matchedVariant` from `storeVariants` (even for a single-SKU
product with no selectable variations — it just uses the one variant) and
adds `matchedVariant.id`.
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.
`normalizeProduct` from `raw.variants[0].id` (store-specials,
brand-groups). Cards from the plain `/products` list endpoint have no
variant info, so the button links to the detail page instead — never
fabricate a variant id to force a quick-add.
- The spec's fuller flow (`GET /store-items/by-product/{productId}`,
then: hide the button if no in-stock variant exists, force a picker
when more than one is in stock) isn't separately re-implemented per
card — the existing variation-picker UI on the detail page already
satisfies "shopper must choose before adding."
## Comments
`GET/POST /tenants/{domain}/comments` needs no auth on Meshkee's side
(`authorName`/`authorEmail` are plain body fields) — the login requirement is
a **product decision by this site**, not an API constraint. Gate the comment
form in `ProductTabs`' comments panel on `useAuth().user`; when posting, use
the logged-in user's name/email. `GET /comments` only returns **approved**
comments, so a freshly-posted comment won't reappear on refetch until an
admin approves it — the UI appends it optimistically to local state instead
of re-fetching, which is correct, not a bug.
`GET/POST /tenants/{domain}/comments` needs no auth on Meshkee's side —
`authorName`/`authorEmail` are plain body fields, same as the contact form.
`ProductTabs`' comments panel is a guest name+email(optional)+text form, no
login involved (this also isn't gated on the dashboard cookie — keep it
that way; there's no reason to require a customer-dashboard session just to
leave a comment). `GET /comments` only returns **approved** comments, so a
freshly-posted comment won't reappear on refetch until an admin approves it
— the UI appends it optimistically to local state instead of re-fetching,
which is correct, not a bug.
## Data quirks (verified against the live catalog)
@@ -165,6 +156,11 @@ 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`.
- Detail pages use `src/components/ui/PageShell.tsx` so the max width, page
padding, and breadcrumb position cannot drift between product and blog
detail layouts. The blog detail page also renders category-matched related
posts in the collapsible `SimilarArticles` sidebar; its DOM position follows
the article so it naturally moves below the article body on smaller screens.
- **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
@@ -189,6 +185,28 @@ persistent memory as "for all the user's sites", not just this one)
in the array — first DOM child renders rightmost under `dir="rtl"`).
- Category tile images: 110px, no border, no border-radius
(`FeaturedCategories.tsx`).
- **No emoji as icons** — `src/components/ui/icons.tsx` has the shared
light/outline SVG set (`MenuIcon`, `UserIcon`, `CartIcon`, `CloseIcon`,
`ChevronLeftIcon`), 24x24 viewBox, `stroke="currentColor"`. Use these
instead of characters like "☰"/"👤"/"🛒"/"✕". Every "view more"-style
link/button (`SectionTitle`'s `action`, the mega-menu's "مشاهده همه",
`BlogCarousel`'s "ادامه مطلب") uses `ChevronLeftIcon`, not a literal "←"
character — keep new ones consistent with that.
- **Header account/cart cluster** (`Header.tsx`, desktop only —
`hidden ... sm:flex`): a borderless `bg-surface` chip holding, in this
exact DOM order, `CartButton`, a divider, then the login link. That DOM
order is deliberate and easy to get backwards: under `dir="rtl"` the
first DOM child renders rightmost, so cart-first-in-DOM is what actually
puts the cart icon on the visual **right** and the login block on the
**left** (this was built backwards once and corrected). Same rule inside
the login link itself — the icon badge comes before the two-line text in
DOM so the icon renders right of the text. Neither `CartButton` nor this
wrapper has a border (removed on request — don't reintroduce one).
`CartButton` is a fixed 44px (`h-11 w-11`) icon-only square everywhere it
renders (also stands alone, un-wrapped, below `sm`); its unread-count
badge sits at `-top-1.5 -right-1.5`, not the product-card cart badge's
`-left-1.5` — don't copy that positioning between the two, they're
intentionally different corners for different-looking buttons.
## Static-image slots
@@ -197,34 +215,204 @@ 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
`home-hero`, `two-banner`, `three-banner-row`, `featured-categories`,
`about-us-image`. `about-us-image` is a homepage `single` slot with a `14:9`
ratio (the original 560×360 frame). `AboutSanihome` uses its first image,
prefers `titleFa`, then `titleEn`, then `subtext` for alt text, wraps the image
with `linkUrl` when present, and preserves `/images/about.svg` as the empty/error
fallback. 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).
**Static-image sizing rule:** whenever a slot's rendered image dimensions or
aspect ratio change during development, update the matching
`STATIC_IMAGE_SLOT_CATALOG` entry (`aspectRatio` and `recommendedWidth`) in the
same change so `/meshkee/static-image-slots` stays accurate for the dashboard.
## Store-item filters
`/store-items` has a desktop sidebar and a mobile filter drawer implemented by
`components/product/ProductFilters.tsx`. Categories are rendered as a nested
accordion (CMS parent categories with their children), not one long flat list.
The three currently supported filters
are category (`categoryId`), price range (`minPrice` / `maxPrice`), and in-stock
only (`inStock=true`). They are submitted as URL search params and passed to
`getStoreItems`, so filtering happens in the API before pagination. Pagination
links must preserve every active filter. Categories come from `getCategoryTree`
and therefore follow CMS data rather than a hardcoded list. On mobile the
"فیلتر محصولات" button opens a right-side modal; its submit/reset actions stay
fixed at the bottom while filter fields scroll. Desktop filters apply in real
time: category and stock changes submit immediately, while price inputs use a
short debounce; only the mobile drawer keeps an explicit apply button. Desktop
submissions use `scroll={false}` and the client component must not be keyed by
active filters, otherwise both the page and the category list jump back to the
top. When a parent category or one of its children becomes active, its matching
`details` element is opened imperatively without closing other accordions.
Do not simulate technical-property filters by fetching every product's
`technical-info`: the public API currently exposes technical schema/values only
per product, and `/store-items` does not accept technical field filters. When a
faceted category-filter endpoint and technical-field query parameters are added
to the API, render those returned fields as additional accordions in the same
component.
## Product detail tabs and technical specifications
`ProductTabs` wraps the specifications, review, and comments UI in one white,
rounded, bordered card. Technical specifications render as a responsive
two-column table (field label and submitted value), not a loose card grid.
`getProductTechnicalInfo()` must join `values[].fieldId` to
`form.fields[].id`, resolve option labels from each field's `options`, and sort
by the CMS field `sortOrder`; technical `values` do not reliably carry their
own labels. If the form or submitted values are empty, keep the existing empty
state rather than fabricating rows.
## Homepage product carousels — fully dynamic, don't hardcode a name/key
`GET /tenants/{domain}/store-specials` returns **every** admin-managed named
carousel as one flat list — e.g. "Special Sale", "پرفروش‌ها", "بهترین‌ها از
نگاه شما" all come back from this one call, each with its own `title` and
`items`. `StoreSpecialCarousels.tsx` maps over the **whole list** (sorted by
`sortOrder`, empty groups skipped) and renders one titled carousel section
per group, using `group.title` from the API as the heading — no group
id/key/title is special-cased in code. This means a brand-new carousel
created in the Meshkee dashboard (any name) appears on the homepage the next
time the page renders, with zero code changes.
**Do not**:
- Hardcode a Persian/English title pair for one of these carousels (that was
the old `SpecialSaleCarousel`/`TopSellingCarousel` mistake — two separate
components each pinned to one group, with a made-up title instead of the
API's own `title`, and `TopSellingCarousel` didn't even read from
store-specials, it re-queried the plain product list).
- Reintroduce a **brand-name carousel** (`GET /website/brand-groups` — used
to render a "سامسونگ" section). The user explicitly removed this: brand
carousels aren't wanted on this site at all. If similar per-brand curation
is wanted later, it should go through admin-managed store-specials groups
(a group can be curated by brand already), not a separate brand-groups
integration.
`SectionTitle`'s `enTitle` prop is optional for exactly this reason — these
dynamic groups only have one `title` string from the API, not a Persian/
English pair. Each carousel still shows an English caption using that same
`enTitle` slot (inline, beside the title — the same treatment as every
other section heading on the site, e.g. BlogCarousel's "آخرین مطالب وبلاگ /
LATEST BLOG"; there was a brief detour through a separate "below the title,
opacity-50, own line" `enSubtitle` prop, which the user then asked to match
the existing inline convention instead — don't reintroduce that below-title
variant). `StoreSpecialCarousels.englishLabelFromKey()` formats the group's
`key` (e.g. `top-selling` → "TOP SELLING") rather than inventing a
translation of `title`; there's no real localized-English field to
translate from, and a made-up translation would be fabricated data. Skips
rendering if the key has no letters at all (fell back to a bare numeric id).
**Banner interleaving**: the two static-image banner sections (`TwoBanners`,
`ThreeBanners`) are rendered *inside* `StoreSpecialCarousels`, one inserted
between every pair of carousels (never before the first or after the last),
cycling through the two if there end up being more than two carousels. Don't
move them back out to `page.tsx` as fixed-position siblings — that only
works for a known, fixed carousel count, which this deliberately isn't.
`SectionTitle`'s title/action row uses `items-center` (not `items-end`) —
needed once carousel titles could carry more content (the inline `enTitle`
caption) than a single line, so bottom-aligning the row left the action
button visibly offset from the title block. The `action` button itself is
styled like the site's other primary buttons (filled `bg-red`, white text,
`rounded-lg` — the same look as `ProductCard`'s "افزودن به سبد"), not a
plain text link.
**"مشاهده همه" (view all)**: each carousel's action button links to
`/store-items?specialId={group.id}`. `store-specials` groups are admin-curated,
already-complete lists (the endpoint has no pagination) — there's no
"more items than the carousel shows" to fetch, so `/store-items` with
`specialId` set just re-renders that exact group's `items` in the full grid
beside the same filter UI used by the main catalog. This is why the pattern is safe to keep
fully generic (any group id works, forever) rather than needing a
per-carousel filter mapping — there isn't a filter to map to; it's the same
list either way. The header's "فروش ویژه" link is `/store-items?special=sale`, and
the store-items page resolves the real CMS group at request time with the shared
`isSpecialSaleGroup()` matcher (`فروش ویژه` or `special-sale`) before rendering
that group's exact items. Do not hardcode a group id in the header.
`/store-items` is the one canonical catalog route. `/products` permanently
redirects there while preserving all query parameters. Product detail URLs are
also canonical under `/store-items/{variant-id|product-slug|product-id}`; the
single detail page resolves all three forms and keeps an exact variant selected
when a variant id was supplied. Legacy `/products/[slug]` and
`/products/id/[id]` routes only redirect for backwards compatibility.
## Branding: logo & favicon are dynamic, not static files
`BusinessInfo` (`getBusinessInfo()`, already fetched in `layout.tsx`) carries
`logoUrl`, `logoDarkUrl`, `faviconUrl` straight from the API — the same
values `GET /tenants/{domain}` and `GET .../website/favicon` also expose.
`Header`'s `Logo` takes a `src` prop (falls back to `public/images/logo.png`
only if the API value is null) threaded down from `layout.tsx`; `Footer`
prefers `logoDarkUrl` (falls back to `logoUrl`) since it sits on a dark
background. The favicon is set via `generateMetadata()`'s `icons` field —
**there is no `src/app/favicon.ico` file** (deliberately removed): Next.js's
static-file favicon convention and a dynamic `metadata.icons` entry both
render a `<link rel="icon">` and browsers aren't guaranteed to prefer the
second one, so keeping both was silently serving the stale static icon.
Don't add `app/favicon.ico` (or `public/favicon.ico`) back.
## Footer: light background, black text, sticky to viewport bottom
The footer is `bg-[#f1f1f1]` (exact hex given by the user, same neutral
gray as `CartButton`'s background — not swapped for a design-token color;
an earlier version used a red-tinted `#9a21291a`, since replaced) with
black text throughout (`text-black`, `/70`, `/50`, `/10`, `/20` opacity
steps) — it used to be a solid dark-red block with white text; don't revert
to that. The footer logo (`logoDarkUrl ?? logoUrl`) is `h-[72px]`, doubled
from its original size on request. Because `public/images/meshkee-logo-
white.png` (the credit-widget logo below) is a solid-white asset, it gets
`brightness-0` on this light background to render as a black silhouette
instead of invisible white-on-near-white — the same `opacity-60 →
group-hover:opacity-100` fade still applies on top of that.
`<main>` has `flex-1` in `layout.tsx` (`body` is `flex flex-col`) so the
footer sits flush at the bottom of the viewport on short pages instead of
leaving a gap of bare `background` color beneath it — this is the standard
sticky-footer flex pattern. Don't remove `flex-1` from `main` without
re-checking a short page (e.g. `/contact`) for that gap coming back.
## Footer: Meshkee credit widget
The footer's bottom-right link ("Designed And Developed By Meshkee
E-Commerce Team" → `https://meshkee.com`) intentionally matches the credit
badge Meshkee's own storefronts use elsewhere (reference: safeteb.com) —
same markup shape (frame + logo + two-line label), same animated corner
border (four 1px lines that draw in on hover, staggered L→B→R→T, and
un-draw in reverse on mouse-leave via matching `transition-delay`s on the
resting state). `public/images/meshkee-logo-white.png` is that reference
site's own logo asset, pulled down and committed here since it's the
platform's shared credit-widget logo, not something unique to safeteb.com.
If this ever needs to change, re-derive the exact hover-timing values from
a live Meshkee site rather than guessing new ones — the staggered reverse
un-draw is the distinctive part, not just "a border that appears."
## 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 |
| `/store-items`, `/store-items/[id]` | Canonical catalog and product detail; filters include category, price and stock; curated groups use `?specialId=` |
| `/products`, `/products/[slug]`, `/products/id/[id]` | Backwards-compatible redirects to the canonical `/store-items` routes |
| `/blog`, `/blog/[slug]` | Blog listing/detail |
| `/checkout` | Cart → order, cash/transfer only |
| `/contact` | Contact form → `POST /contact-submissions`, toast + reset on success |
No `/login`, `/register`, `/checkout`, `/cart`, or `/account` route exists
here on purpose — see "Auth, cart & checkout" above.
## Known gaps / explicit scope decisions
- No OTP-verification UI for a registered-but-unverified phone number — if a
returning shopper's session is lost pre-verification, password login fails
with a clear error but there's no in-app way to complete verification yet
(OTP *login* still works as a workaround).
- No online payment gateway integration (Zarinpal/Mellat/etc.) — checkout
only supports cash-on-delivery and bank transfer, by explicit user choice
over building the bank-redirect + return-URL callback flow.
- A throwaway test customer account exists in the live business database
from building/verifying this integration: `+989120000001` / "Test Dev".
Safe to delete from the Meshkee admin panel.
- Login, registration, OTP, the real cart, addresses, and payment are all
out of scope for this codebase by design — they live on
`customer.sanihome.ir`. Don't reintroduce them here.
- A throwaway test customer account was created against the live business
database while an earlier (since-reverted) pass tested a real backend
cart: `+989120000001` / "Test Dev". Safe to delete from the Meshkee admin
panel — it's not used by anything in this codebase anymore.
+1
View File
@@ -1,6 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// Leaner production runtime: deploy uses .next/standalone and drops node_modules.
output: "standalone",
allowedDevOrigins: ["sanihome.com", "localhost"],
};
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+35 -13
View File
@@ -1,12 +1,21 @@
import { notFound } from "next/navigation";
import { Breadcrumb } from "@/components/ui/Breadcrumb";
import { getBlog } from "@/lib/meshkee";
import Link from "next/link";
import { SimilarArticles } from "@/components/blog/SimilarArticles";
import { PageShell } from "@/components/ui/PageShell";
import { getBlog, getBlogs } from "@/lib/meshkee";
function formatDate(iso?: string) {
if (!iso) return "";
return new Intl.DateTimeFormat("fa-IR", { dateStyle: "long" }).format(new Date(iso));
}
function withResponsiveTables(html: string) {
return html.replace(
/(<table\b[\s\S]*?<\/table>)/gi,
'<div class="article-table-scroll" role="region" aria-label="جدول مقاله" tabindex="0">$1</div>',
);
}
export default async function BlogDetailPage({
params,
}: {
@@ -17,17 +26,26 @@ export default async function BlogDetailPage({
if (!post) notFound();
const { items: relatedCandidates } = await getBlogs({
categoryId: post.categoryId,
pageSize: post.categoryId ? 8 : 50,
});
const similarPosts = relatedCandidates
.filter((candidate) => candidate.id !== post.id)
.filter((candidate) => !post.categoryName || candidate.categoryName === post.categoryName)
.slice(0, 5);
return (
<article className="mx-auto max-w-3xl px-4 py-10">
<Breadcrumb
items={[
<PageShell
breadcrumbItems={[
{ label: "خانه", href: "/" },
{ label: "وبلاگ", href: "/blog" },
{ label: post.title },
]}
/>
<div className="mb-6 flex items-center gap-2 text-xs text-muted">
>
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_300px] lg:items-start">
<article className="min-w-0">
<div className="mb-6 flex flex-wrap items-center gap-2 text-xs text-muted">
{post.categoryName && <span>{post.categoryName}</span>}
{post.publishedAt && (
<>
@@ -43,20 +61,24 @@ export default async function BlogDetailPage({
)}
</div>
<h1 className="mb-6 text-2xl font-bold leading-relaxed text-red-dark md:text-3xl">
<h1 className="mb-6 text-xl font-bold leading-relaxed text-red-dark md:text-3xl">
{post.title}
</h1>
<div
className="prose max-w-none"
dangerouslySetInnerHTML={{ __html: post.mainTextHtml }}
className="prose article-content max-w-none"
dangerouslySetInnerHTML={{ __html: withResponsiveTables(post.mainTextHtml) }}
/>
<div className="mt-10 border-t border-border pt-6">
<a href="/blog" className="text-sm font-medium text-red hover:text-red-dark">
<Link href="/blog" className="text-sm font-medium text-red hover:text-red-dark">
→ بازگشت به وبلاگ
</a>
</Link>
</div>
</article>
<SimilarArticles posts={similarPosts} />
</div>
</PageShell>
);
}
-192
View File
@@ -1,192 +0,0 @@
"use client";
import { useState } from "react";
import { Breadcrumb } from "@/components/ui/Breadcrumb";
import { EmptyState } from "@/components/ui/EmptyState";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
import { checkout, type Order } from "@/lib/cart";
import { formatPrice } from "@/data/sample";
type PaymentType = "cash" | "transfer";
const inputClass =
"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red";
export default function CheckoutPage() {
const { user, openLoginModal } = useAuth();
const { cart, businessId, refresh } = useCart();
const [province, setProvince] = useState("");
const [city, setCity] = useState("");
const [address, setAddress] = useState("");
const [postalCode, setPostalCode] = useState("");
const [paymentType, setPaymentType] = useState<PaymentType>("cash");
const [transferRefNumber, setTransferRefNumber] = useState("");
const [customerNotes, setCustomerNotes] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [order, setOrder] = useState<Order | null>(null);
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
setBusy(true);
setError(null);
const res = await checkout(businessId, {
shippingAddress: { province, city, address, postalCode: postalCode || undefined },
customerNotes: customerNotes || undefined,
payment:
paymentType === "transfer"
? { type: "transfer", transferRefNumber: transferRefNumber || undefined }
: { type: "cash" },
});
setBusy(false);
if (!res.ok) {
setError(res.message);
return;
}
setOrder(res.data);
refresh();
};
return (
<div className="mx-auto max-w-3xl px-4 py-10">
<Breadcrumb items={[{ label: "خانه", href: "/" }, { label: "تسویه حساب" }]} />
<h1 className="mb-6 text-2xl font-bold text-red-dark">تسویه حساب</h1>
{!user ? (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-surface p-5">
<span className="text-sm text-muted">برای تسویه حساب باید وارد حساب کاربری خود شوید.</span>
<button
type="button"
onClick={openLoginModal}
className="rounded-lg bg-red px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
>
ورود
</button>
</div>
) : order ? (
<div className="rounded-xl border border-green-200 bg-green-50 p-6 text-center">
<p className="mb-2 text-lg font-bold text-green-800">سفارش شما با موفقیت ثبت شد ✓</p>
<p className="mb-1 text-sm text-green-700">شماره سفارش: {order.orderNumber}</p>
<p className="text-sm text-green-700">
مبلغ کل: {formatPrice(order.total)} تومان
</p>
<a href="/" className="mt-4 inline-block text-sm font-medium text-red hover:text-red-dark">
بازگشت به فروشگاه ←
</a>
</div>
) : !cart || cart.items.length === 0 ? (
<EmptyState message="سبد خرید شما خالی است." />
) : (
<div className="grid gap-8 md:grid-cols-3">
<form onSubmit={handleSubmit} className="space-y-4 md:col-span-2">
<div>
<h2 className="mb-3 text-sm font-bold">آدرس ارسال</h2>
<div className="grid gap-3 sm:grid-cols-2">
<input
required
placeholder="استان"
value={province}
onChange={(e) => setProvince(e.target.value)}
className={inputClass}
/>
<input
required
placeholder="شهر"
value={city}
onChange={(e) => setCity(e.target.value)}
className={inputClass}
/>
</div>
<textarea
required
rows={2}
placeholder="آدرس کامل"
value={address}
onChange={(e) => setAddress(e.target.value)}
className={`${inputClass} mt-3`}
/>
<input
placeholder="کد پستی (اختیاری)"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
className={`${inputClass} mt-3`}
/>
</div>
<div>
<h2 className="mb-3 text-sm font-bold">روش پرداخت</h2>
<div className="space-y-2">
<label className="flex items-center gap-2 rounded-lg border border-border p-3 text-sm">
<input
type="radio"
name="payment"
checked={paymentType === "cash"}
onChange={() => setPaymentType("cash")}
/>
پرداخت در محل (نقدی)
</label>
<label className="flex items-center gap-2 rounded-lg border border-border p-3 text-sm">
<input
type="radio"
name="payment"
checked={paymentType === "transfer"}
onChange={() => setPaymentType("transfer")}
/>
کارت به کارت / واریز بانکی
</label>
{paymentType === "transfer" && (
<input
placeholder="شماره پیگیری واریز (اختیاری)"
value={transferRefNumber}
onChange={(e) => setTransferRefNumber(e.target.value)}
className={inputClass}
/>
)}
</div>
</div>
<textarea
rows={2}
placeholder="توضیحات سفارش (اختیاری)"
value={customerNotes}
onChange={(e) => setCustomerNotes(e.target.value)}
className={inputClass}
/>
{error && <p className="text-sm text-red-dark">{error}</p>}
<button
type="submit"
disabled={busy}
className="w-full rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
>
{busy ? "در حال ثبت سفارش..." : "ثبت نهایی سفارش"}
</button>
</form>
<div className="rounded-xl border border-border bg-surface p-5">
<h2 className="mb-4 text-sm font-bold">خلاصه سفارش</h2>
<ul className="mb-4 space-y-2 text-sm">
{cart.items.map((item) => (
<li key={item.id} className="flex items-center justify-between gap-2">
<span className="line-clamp-1 text-muted">
{item.productNameFa ?? item.productTitle} × {item.quantity}
</span>
<span className="shrink-0 font-medium">{formatPrice(item.lineTotal)}</span>
</li>
))}
</ul>
<div className="flex items-center justify-between border-t border-border pt-3 text-sm font-bold">
<span>جمع کل</span>
<span className="text-red-dark">
{formatPrice(cart.subtotal)}
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
</span>
</div>
</div>
</div>
)}
</div>
);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

+114
View File
@@ -100,3 +100,117 @@ h6 {
height: auto;
border-radius: 1rem;
}
/* Rich-text tables arrive as raw CMS HTML. Keep every article table aligned
with the full article column while allowing a readable horizontal scroll on
narrow screens instead of squeezing several columns into tiny cells. */
.article-table-scroll {
width: 100%;
margin-block: 2rem;
overflow-x: auto;
overscroll-behavior-inline: contain;
border: 1px solid var(--border);
border-radius: 0.875rem;
background: var(--surface);
scrollbar-width: thin;
scrollbar-color: var(--red-muted) transparent;
-webkit-overflow-scrolling: touch;
}
.article-table-scroll:focus-visible {
outline: 2px solid var(--red);
outline-offset: 2px;
}
.article-content table {
width: 100% !important;
min-width: 600px;
margin: 0;
border: 0;
border-spacing: 0;
border-collapse: separate;
overflow: hidden;
border-radius: 0.875rem;
background: var(--surface);
font-size: 0.925rem;
line-height: 1.8;
}
.article-content thead {
background: var(--red-light);
}
.article-content th,
.article-content td {
padding: 0.9rem 1rem;
text-align: right;
vertical-align: middle;
border-bottom: 1px solid var(--border);
border-left: 1px solid var(--border);
}
.article-content th {
color: var(--red-dark);
font-family: var(--font-iranyekan-bold), var(--font-iranyekan), system-ui, sans-serif;
font-weight: 700;
white-space: nowrap;
}
.article-content th:last-child,
.article-content td:last-child {
border-left: 0;
}
.article-content tbody tr:nth-child(even) {
background: #fafafa;
}
.article-content tbody tr {
transition: background-color 160ms ease;
}
.article-content tbody tr:hover {
background: var(--red-light);
}
.article-content tbody tr:last-child td {
border-bottom: 0;
}
@media (max-width: 640px) {
.article-content h2 {
margin-top: 1.75rem;
margin-bottom: 0.75rem;
font-size: 1.125rem;
line-height: 1.8;
}
.article-content h3 {
margin-top: 1.5rem;
margin-bottom: 0.625rem;
font-size: 1rem;
line-height: 1.75;
}
.article-content h4 {
margin-top: 1.25rem;
margin-bottom: 0.5rem;
font-size: 0.925rem;
line-height: 1.75;
}
.article-table-scroll {
margin-inline: 0;
border-radius: 0.75rem;
}
.article-content table {
min-width: 560px;
font-size: 0.85rem;
}
.article-content th,
.article-content td {
padding: 0.75rem;
}
}
+25 -6
View File
@@ -6,7 +6,12 @@ import { TopBar } from "@/components/home/TopBar";
import { Header } from "@/components/home/Header";
import { Footer } from "@/components/home/Footer";
import { Providers } from "@/context/Providers";
import { getBusinessInfo, getCategories, getCategoryTree } from "@/lib/meshkee";
import {
getBusinessInfo,
getCategories,
getCategoryTree,
parseMetaTagHtml,
} from "@/lib/meshkee";
// Body text — headings use the bold weight instead, see globals.css.
const iranyekan = localFont({
@@ -27,10 +32,15 @@ const syne = Syne({
weight: ["600", "700", "800"],
});
export const metadata: Metadata = {
title: "سانی‌هوم | فروشگاه لوازم خانگی",
export async function generateMetadata(): Promise<Metadata> {
const businessInfo = await getBusinessInfo();
return {
title: "صنیع هوم | فروشگاه لوازم خانگی",
description: "فروشگاه آنلاین لوازم خانگی — یخچال، لباسشویی، تلویزیون و بیشتر",
icons: businessInfo?.faviconUrl ? [{ url: businessInfo.faviconUrl }] : undefined,
};
}
export default async function RootLayout({ children }: LayoutProps<"/">) {
const [categoryTree, categories, businessInfo] = await Promise.all([
@@ -39,17 +49,26 @@ export default async function RootLayout({ children }: LayoutProps<"/">) {
getBusinessInfo(),
]);
const cmsMetaTags = (businessInfo?.metaTags ?? [])
.map((tag, index) => {
const attrs = parseMetaTagHtml(tag.html ?? "");
if (!attrs) return null;
return <meta key={`cms-meta-${index}`} {...attrs} />;
})
.filter(Boolean);
return (
<html
lang="fa"
dir="rtl"
className={`${iranyekan.variable} ${iranyekanBold.variable} ${syne.variable} h-full antialiased`}
>
{cmsMetaTags.length > 0 ? <head>{cmsMetaTags}</head> : null}
<body className="min-h-full flex flex-col">
<Providers businessId={businessInfo?.id ?? "1"}>
<Providers>
<TopBar />
<Header categoryTree={categoryTree} categories={categories} />
<main>{children}</main>
<Header categoryTree={categoryTree} categories={categories} logoUrl={businessInfo?.logoUrl} />
<main className="flex-1">{children}</main>
<Footer businessInfo={businessInfo} categories={categories} />
</Providers>
</body>
+16 -30
View File
@@ -1,46 +1,30 @@
import { FeatureBar } from "@/components/home/FeatureBar";
import { HeroSlider } from "@/components/home/HeroSlider";
import { FeaturedCategories } from "@/components/home/FeaturedCategories";
import { SpecialSaleCarousel } from "@/components/home/SpecialSaleCarousel";
import { TwoBanners } from "@/components/home/TwoBanners";
import { TopSellingCarousel } from "@/components/home/TopSellingCarousel";
import { ThreeBanners } from "@/components/home/ThreeBanners";
import { BrandGroupCarousels } from "@/components/home/BrandGroupCarousels";
import { StoreSpecialCarousels } from "@/components/home/StoreSpecialCarousels";
import { AboutSanihome } from "@/components/home/AboutSanihome";
import { BlogCarousel } from "@/components/home/BlogCarousel";
import {
getBlogs,
getBusinessInfo,
getCategories,
getProducts,
getBrandGroups,
getStoreSpecials,
getStaticImageSlots,
firstImageForSlot,
imagesForSlot,
STATIC_IMAGE_KEYS,
} from "@/lib/meshkee";
export default async function Home() {
const [
categories,
storeSpecials,
productsResult,
brandGroups,
staticImageSlots,
businessInfo,
blogsResult,
] = await Promise.all([
const [categories, storeSpecials, staticImageSlots, businessInfo, blogsResult] = await Promise.all([
getCategories(),
getStoreSpecials(),
getProducts({ pageSize: 12 }),
getBrandGroups(),
getStaticImageSlots(),
getBusinessInfo(),
getBlogs({ pageSize: 8 }),
]);
const contactPhone = businessInfo?.phoneNumbers[0];
const specialSaleProducts = storeSpecials[0]?.items ?? [];
const twoBannerSlot = staticImageSlots.find((slot) => slot.key === STATIC_IMAGE_KEYS.twoBanner);
const threeBannerSlot = staticImageSlots.find(
(slot) => slot.key === STATIC_IMAGE_KEYS.threeBannerRow,
@@ -51,20 +35,22 @@ export default async function Home() {
return (
<>
<HeroSlider images={heroImages} />
<SpecialSaleCarousel products={specialSaleProducts} contactPhone={contactPhone} />
<FeatureBar />
<FeaturedCategories categories={categories} images={featuredCategoryImages} />
<TwoBanners
images={imagesForSlot(staticImageSlots, STATIC_IMAGE_KEYS.twoBanner)}
aspectRatio={twoBannerSlot?.aspectRatio}
<StoreSpecialCarousels
groups={storeSpecials}
contactPhone={contactPhone}
twoBannerImages={imagesForSlot(staticImageSlots, STATIC_IMAGE_KEYS.twoBanner)}
twoBannerAspectRatio={twoBannerSlot?.aspectRatio}
threeBannerImages={imagesForSlot(staticImageSlots, STATIC_IMAGE_KEYS.threeBannerRow)}
threeBannerAspectRatio={threeBannerSlot?.aspectRatio}
/>
<TopSellingCarousel products={productsResult.items} contactPhone={contactPhone} />
<ThreeBanners
images={imagesForSlot(staticImageSlots, STATIC_IMAGE_KEYS.threeBannerRow)}
aspectRatio={threeBannerSlot?.aspectRatio}
<FeatureBar />
<AboutSanihome
image={firstImageForSlot(staticImageSlots, STATIC_IMAGE_KEYS.aboutUsImage)}
aspectRatio={staticImageSlots.find(
(slot) => slot.key === STATIC_IMAGE_KEYS.aboutUsImage,
)?.aspectRatio}
/>
<BrandGroupCarousels brandGroups={brandGroups} contactPhone={contactPhone} />
<AboutSanihome />
<BlogCarousel posts={blogsResult.items} />
</>
);
+2 -86
View File
@@ -1,17 +1,4 @@
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,
getProduct,
getProductStoreVariants,
getProductTechnicalInfo,
getProductVariations,
} from "@/lib/meshkee";
import { permanentRedirect } from "next/navigation";
export default async function ProductDetailPage({
params,
@@ -19,76 +6,5 @@ export default async function ProductDetailPage({
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const [product, technicalInfo, variations, businessInfo] = await Promise.all([
getProduct(slug),
getProductTechnicalInfo(slug),
getProductVariations(slug),
getBusinessInfo(),
]);
if (!product) notFound();
const [storeVariants, comments] = await Promise.all([
getProductStoreVariants(product.id),
getComments("product", product.id),
]);
const contactPhone = businessInfo?.phoneNumbers[0];
const images = product.images.length > 0 ? product.images : product.image ? [product.image] : [];
return (
<div className="mx-auto max-w-7xl px-4 py-10">
<Breadcrumb
items={[
{ label: "خانه", href: "/" },
...(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}
/>
</div>
<ProductTabs
technicalInfo={technicalInfo}
descriptionHtml={product.descriptionHtml}
entityId={product.id}
initialComments={comments}
/>
<SimilarProducts
categoryId={product.categoryId}
excludeProductId={product.id}
contactPhone={contactPhone}
/>
</div>
);
permanentRedirect(`/store-items/${slug}`);
}
+1 -1
View File
@@ -11,5 +11,5 @@ export default async function ProductByIdPage({
if (!product?.slug) notFound();
redirect(`/products/${product.slug}`);
redirect(`/store-items/${product.slug}`);
}
+9 -118
View File
@@ -1,127 +1,18 @@
import { Breadcrumb } from "@/components/ui/Breadcrumb";
import { ProductCard } from "@/components/ui/ProductCard";
import { EmptyState } from "@/components/ui/EmptyState";
import {
type CategoryTreeGroup,
getBusinessInfo,
getCategoryTree,
getProducts,
productHref,
} from "@/lib/meshkee";
const PAGE_SIZE = 24;
function findCategoryLabel(tree: CategoryTreeGroup[], id: string): string | undefined {
for (const group of tree) {
for (const item of group.items) {
if (item.id === id) return item.nameFa;
const child = item.children.find((c) => c.id === id);
if (child) return child.nameFa;
}
}
return undefined;
}
import { permanentRedirect } from "next/navigation";
export default async function ProductsPage({
searchParams,
}: {
searchParams: Promise<{ categoryId?: string; q?: string; page?: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const params = await searchParams;
const page = Math.max(1, Number(params.page ?? 1) || 1);
const [{ items, total }, businessInfo, categoryTree] = await Promise.all([
getProducts({
categoryId: params.categoryId,
name: params.q,
page,
pageSize: PAGE_SIZE,
}),
getBusinessInfo(),
params.categoryId ? getCategoryTree() : Promise.resolve([]),
]);
const contactPhone = businessInfo?.phoneNumbers[0];
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const isFiltered = Boolean(params.q || params.categoryId);
const categoryLabel = params.categoryId ? findCategoryLabel(categoryTree, params.categoryId) : undefined;
const query = new URLSearchParams();
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 `/products?${sp.toString()}`;
};
for (const [key, value] of Object.entries(params)) {
if (Array.isArray(value)) value.forEach((item) => query.append(key, item));
else if (value != null) query.set(key, value);
}
return (
<div className="mx-auto max-w-7xl px-4 py-10">
<Breadcrumb
items={[
{ label: "خانه", href: "/" },
{ label: "محصولات", href: isFiltered ? "/products" : undefined },
...(params.q ? [{ label: `نتایج جستجو برای «${params.q}»` }] : []),
...(categoryLabel ? [{ label: categoryLabel }] : []),
]}
/>
<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((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)}
fluid
contactPhone={contactPhone}
variantId={product.variantId}
/>
))}
</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>
);
const suffix = query.toString();
permanentRedirect(`/store-items${suffix ? `?${suffix}` : ""}`);
}
+14 -11
View File
@@ -1,5 +1,5 @@
import { notFound } from "next/navigation";
import { Breadcrumb } from "@/components/ui/Breadcrumb";
import { PageShell } from "@/components/ui/PageShell";
import { ProductGallery } from "@/components/product/ProductGallery";
import { ProductPurchasePanel } from "@/components/product/ProductPurchasePanel";
import { ProductTabs } from "@/components/product/ProductTabs";
@@ -7,6 +7,7 @@ import { SimilarProducts } from "@/components/product/SimilarProducts";
import {
getBusinessInfo,
getComments,
getProduct,
getProductById,
getProductStoreVariants,
getProductTechnicalInfo,
@@ -21,9 +22,9 @@ export default async function StoreItemDetailPage({
}) {
const { id } = await params;
const variant = await getStoreItemVariant(id);
if (!variant) notFound();
const product = await getProductById(variant.productId);
const product = variant
? await getProductById(variant.productId)
: (await getProduct(id)) ?? (await getProductById(id));
if (!product) notFound();
const [technicalInfo, variations, businessInfo, comments] = await Promise.all([
@@ -39,21 +40,20 @@ export default async function StoreItemDetailPage({
// 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]),
(variant?.selections ?? []).map((s) => [s.variationId, s.optionId]),
);
return (
<div className="mx-auto max-w-7xl px-4 py-10">
<Breadcrumb
items={[
<PageShell
breadcrumbItems={[
{ label: "خانه", href: "/" },
{ label: "فروشگاه", href: "/store-items" },
...(product.categoryName
? [{ label: product.categoryName, href: `/products?categoryId=${product.categoryId}` }]
? [{ label: product.categoryName, href: `/store-items?categoryId=${product.categoryId}` }]
: []),
{ label: product.name },
]}
/>
>
<div className="grid gap-8 md:grid-cols-12">
<div className="md:col-span-4">
@@ -83,6 +83,9 @@ export default async function StoreItemDetailPage({
contactPhone={contactPhone}
storeName={businessInfo?.nameFa}
initialSelections={initialSelections}
productName={product.name}
productSlug={product.slug}
productImage={product.image ?? images[0] ?? ""}
/>
</div>
@@ -98,6 +101,6 @@ export default async function StoreItemDetailPage({
excludeProductId={product.id}
contactPhone={contactPhone}
/>
</div>
</PageShell>
);
}
+129 -18
View File
@@ -1,33 +1,110 @@
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";
import {
ProductFilters,
type ProductFilterCategory,
} from "@/components/product/ProductFilters";
import {
getCategoryTree,
getStoreItems,
getStoreSpecials,
isSpecialSaleGroup,
productHref,
storeItemHref,
} from "@/lib/meshkee";
const PAGE_SIZE = 24;
export default async function StoreItemsPage({
searchParams,
}: {
searchParams: Promise<{ categoryId?: string; q?: string; page?: string }>;
searchParams: Promise<{
categoryId?: string;
q?: string;
page?: string;
minPrice?: string;
maxPrice?: string;
inStock?: string;
specialId?: string;
special?: 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,
const parsePrice = (value?: string) => {
const number = Number(value);
return value && Number.isFinite(number) && number >= 0 ? number : undefined;
};
const minPrice = parsePrice(params.minPrice);
const maxPrice = parsePrice(params.maxPrice);
const inStock = params.inStock === "true";
const categoryId = params.categoryId || undefined;
const specialMode = Boolean(params.specialId || params.special === "sale");
const [categoryTree, specialGroups] = await Promise.all([
getCategoryTree(),
specialMode ? getStoreSpecials() : Promise.resolve([]),
]);
const categories: ProductFilterCategory[] = categoryTree.flatMap((group) =>
group.items.map((category) => ({
id: category.id,
label: category.nameFa,
children: category.children.map((child) => ({
id: child.id,
label: child.nameFa,
})),
})),
);
const filterValues = {
categoryId,
minPrice: minPrice != null ? String(minPrice) : undefined,
maxPrice: maxPrice != null ? String(maxPrice) : undefined,
inStock,
q: params.q,
specialId: params.specialId,
special: params.special,
};
const specialGroup = params.specialId
? specialGroups.find((group) => group.id === params.specialId)
: specialGroups.find(isSpecialSaleGroup);
const selectedCategoryIds = new Set<string>();
if (categoryId) {
selectedCategoryIds.add(categoryId);
const parent = categories.find((item) => item.id === categoryId);
parent?.children.forEach((child) => selectedCategoryIds.add(child.id));
}
const specialItems = (specialGroup?.items ?? []).filter((product) => {
const matchesCategory = !categoryId || (product.categoryId && selectedCategoryIds.has(product.categoryId));
const matchesQuery = !params.q || product.name.toLocaleLowerCase("fa").includes(params.q.toLocaleLowerCase("fa"));
const matchesMin = minPrice == null || (product.price != null && product.price >= minPrice);
const matchesMax = maxPrice == null || (product.price != null && product.price <= maxPrice);
const matchesStock = !inStock || (product.stockQuantity != null && product.stockQuantity > 0);
return matchesCategory && matchesQuery && matchesMin && matchesMax && matchesStock;
});
const storeResult = specialMode
? { items: [], total: 0 }
: await getStoreItems({
categoryId,
name: params.q,
minPrice,
maxPrice,
inStock: inStock || undefined,
page,
pageSize: PAGE_SIZE,
}),
getBusinessInfo(),
]);
const contactPhone = businessInfo?.phoneNumbers[0];
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
});
const totalPages = Math.max(1, Math.ceil(storeResult.total / PAGE_SIZE));
const pageHref = (p: number) => {
const sp = new URLSearchParams();
if (params.categoryId) sp.set("categoryId", params.categoryId);
if (categoryId) sp.set("categoryId", categoryId);
if (params.q) sp.set("q", params.q);
if (minPrice != null) sp.set("minPrice", String(minPrice));
if (maxPrice != null) sp.set("maxPrice", String(maxPrice));
if (inStock) sp.set("inStock", "true");
sp.set("page", String(p));
return `/store-items?${sp.toString()}`;
};
@@ -41,16 +118,49 @@ export default async function StoreItemsPage({
]}
/>
{params.q && (
<h1 className="mb-6 text-2xl font-bold text-red-dark">
{params.q ? `نتایج جستجو برای «${params.q}»` : "فروشگاه"}
نتایج جستجو برای «{params.q}»
</h1>
)}
{items.length === 0 ? (
<EmptyState message="کالایی یافت نشد." />
<div className="md:flex md:items-start md:gap-6">
<ProductFilters
categories={categories}
values={filterValues}
/>
<div className="min-w-0 flex-1">
{specialMode && (
<h1 className="mb-6 text-2xl font-bold text-red-dark">
{specialGroup?.title ?? "فروش ویژه"}
</h1>
)}
{(specialMode ? specialItems : storeResult.items).length === 0 ? (
<EmptyState message="کالایی با این فیلترها یافت نشد." />
) : specialMode ? (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-4">
{specialItems.map((product) => (
<ProductCard
key={`${product.id}-${product.variantId ?? "product"}`}
name={product.name}
brand={product.brand ?? ""}
price={product.price}
oldPrice={product.oldPrice}
discount={product.discount}
image={product.image ?? "/images/placeholder.svg"}
href={productHref(product)}
fluid
variantId={product.variantId}
slug={product.slug}
/>
))}
</div>
) : (
<>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
{items.map((item) => (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-4">
{storeResult.items.map((item) => (
<ProductCard
key={item.id}
name={item.name}
@@ -61,13 +171,12 @@ export default async function StoreItemsPage({
image={item.image ?? "/images/placeholder.svg"}
href={storeItemHref(item)}
fluid
contactPhone={contactPhone}
variantId={item.id}
/>
))}
</div>
{totalPages > 1 && (
{!specialMode && totalPages > 1 && (
<div className="mt-8 flex items-center justify-center gap-3">
{page > 1 ? (
<a
@@ -101,5 +210,7 @@ export default async function StoreItemsPage({
</>
)}
</div>
</div>
</div>
);
}
-262
View File
@@ -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>
);
}
+67
View File
@@ -0,0 +1,67 @@
import Link from "next/link";
import { Placeholder } from "@/components/ui/Placeholder";
import type { BlogSummary } from "@/lib/meshkee";
function formatDate(iso?: string) {
if (!iso) return "";
return new Intl.DateTimeFormat("fa-IR", { dateStyle: "medium" }).format(new Date(iso));
}
export function SimilarArticles({ posts }: { posts: BlogSummary[] }) {
if (posts.length === 0) return null;
return (
<aside className="lg:sticky lg:top-32">
<details open className="group rounded-2xl border border-border bg-surface">
<summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-4 py-4 font-bold text-red-dark">
مقالات مشابه
<svg
viewBox="0 0 24 24"
fill="none"
className="h-5 w-5 shrink-0 text-muted transition-transform group-open:rotate-180"
aria-hidden
>
<path
d="m7 10 5 5 5-5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</summary>
<div className="border-t border-border p-3">
<div className="divide-y divide-border">
{posts.map((post) => (
<Link
key={post.id}
href={`/blog/${post.slug}`}
className="group/article flex gap-3 py-3 first:pt-0 last:pb-0"
>
<Placeholder
src={post.image ?? "/images/placeholder.svg"}
alt={post.title}
width="72px"
height="72px"
fit="cover"
className="shrink-0 rounded-lg"
/>
<div className="min-w-0 flex-1">
<h3 className="line-clamp-2 text-sm font-bold leading-relaxed transition-colors group-hover/article:text-red">
{post.title}
</h3>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-muted">
{post.categoryName && <span>{post.categoryName}</span>}
{post.categoryName && post.publishedAt && <span>•</span>}
{post.publishedAt && <span>{formatDate(post.publishedAt)}</span>}
</div>
</div>
</Link>
))}
</div>
</div>
</details>
</aside>
);
}
+6 -8
View File
@@ -1,23 +1,21 @@
"use client";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
import { CartIcon } from "@/components/ui/icons";
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"
onClick={openPopup}
aria-label="سبد خرید"
className="relative flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[#f1f1f1] text-foreground transition-colors hover:text-red"
>
<span aria-hidden>🛒</span>
<span className="hidden sm:inline">سبد خرید</span>
<CartIcon className="h-5 w-5" />
{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">
<span className="absolute -top-1.5 -right-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>
)}
+21 -27
View File
@@ -4,12 +4,12 @@ import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { formatPrice } from "@/data/sample";
import { useCart } from "@/context/CartContext";
import { continueToCheckoutUrl } from "@/lib/guestCart";
import { EmptyState } from "@/components/ui/EmptyState";
export function CartPopup() {
const { cart, popupOpen, closePopup, updateItem, removeItem } = useCart();
const { items, subtotal, popupOpen, closePopup, updateItem, removeItem } = useCart();
const [mounted, setMounted] = useState(false);
const [busyId, setBusyId] = useState<string | null>(null);
useEffect(() => setMounted(true), []);
@@ -22,15 +22,6 @@ export function CartPopup() {
if (!mounted) return null;
const items = cart?.items ?? [];
const changeQty = async (itemId: string, quantity: number) => {
setBusyId(itemId);
if (quantity <= 0) await removeItem(itemId);
else await updateItem(itemId, quantity);
setBusyId(null);
};
return createPortal(
<div aria-hidden={!popupOpen}>
<div
@@ -65,22 +56,18 @@ export function CartPopup() {
<li key={item.id} className="flex gap-3 border-b border-border pb-4">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={item.productImage ?? "/images/placeholder.svg"}
alt={item.productNameFa ?? item.productTitle}
src={item.image || "/images/placeholder.svg"}
alt={item.name}
className="h-16 w-16 shrink-0 rounded-lg border border-border object-contain p-1"
/>
<div className="min-w-0 flex-1">
<p className="line-clamp-2 text-sm font-medium">
{item.productNameFa ?? item.productTitle}
</p>
{item.label && <p className="mt-0.5 text-xs text-muted">{item.label}</p>}
<p className="line-clamp-2 text-sm font-medium">{item.name}</p>
<div className="mt-2 flex items-center justify-between">
<div className="flex items-center rounded-lg border border-border">
<button
type="button"
disabled={busyId === item.id}
onClick={() => changeQty(item.id, item.quantity + 1)}
className="px-2 py-1 text-sm disabled:opacity-40"
onClick={() => updateItem(item.id, item.quantity + 1)}
className="px-2 py-1 text-sm"
aria-label="افزایش تعداد"
>
+
@@ -88,37 +75,44 @@ export function CartPopup() {
<span className="min-w-6 text-center text-xs font-medium">{item.quantity}</span>
<button
type="button"
disabled={busyId === item.id}
onClick={() => changeQty(item.id, item.quantity - 1)}
className="px-2 py-1 text-sm disabled:opacity-40"
onClick={() => updateItem(item.id, item.quantity - 1)}
className="px-2 py-1 text-sm"
aria-label="کاهش تعداد"
>
−
</button>
</div>
<span className="text-sm font-bold text-red-dark">
{formatPrice(item.lineTotal)}
{formatPrice(item.price * item.quantity)}
<span className="mr-0.5 text-[11px] font-normal text-muted">تومان</span>
</span>
</div>
</div>
<button
type="button"
onClick={() => removeItem(item.id)}
aria-label="حذف از سبد"
className="shrink-0 self-start text-muted transition-colors hover:text-red-dark"
>
✕
</button>
</li>
))}
</ul>
)}
</div>
{items.length > 0 && cart && (
{items.length > 0 && (
<div className="border-t border-border p-5">
<div className="mb-4 flex items-center justify-between text-sm">
<span className="text-muted">جمع کل</span>
<span className="text-base font-bold text-red-dark">
{formatPrice(cart.subtotal)}
{formatPrice(subtotal)}
<span className="mr-0.5 text-xs font-normal text-muted">تومان</span>
</span>
</div>
<a
href="/checkout"
href={continueToCheckoutUrl(items)}
className="block w-full rounded-xl bg-red py-3 text-center text-sm font-medium text-white transition-colors hover:bg-red-dark"
>
ادامه فرآیند خرید
+12 -12
View File
@@ -1,6 +1,13 @@
import { Placeholder } from "@/components/ui/Placeholder";
import { AboutSlotImage } from "@/components/home/AboutSlotImage";
import type { StaticImageWithUrl } from "@/lib/meshkee";
export function AboutSanihome() {
export function AboutSanihome({
image,
aspectRatio,
}: {
image?: StaticImageWithUrl;
aspectRatio?: string;
}) {
return (
<section className="border-y border-red-light bg-gradient-to-br from-red-light/40 via-surface to-background py-12 md:py-16">
<div className="mx-auto max-w-7xl px-4">
@@ -8,7 +15,7 @@ export function AboutSanihome() {
<div className="animate-fade-up">
<div className="mb-4 flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h2 className="text-2xl font-bold text-red-dark md:text-3xl">
درباره سانی‌هوم
درباره صنیع هوم
</h2>
<span
className="font-display text-sm font-semibold tracking-wide text-red-dark/30 uppercase md:text-base"
@@ -19,7 +26,7 @@ export function AboutSanihome() {
</span>
</div>
<p className="mb-4 leading-relaxed text-muted">
سانی‌هوم از سال ۱۳۹۰ به عنوان یکی از معتبرترین فروشگاه‌های آنلاین لوازم
صنیع هوم از سال ۱۳۹۰ به عنوان یکی از معتبرترین فروشگاه‌های آنلاین لوازم
خانگی در ایران فعالیت می‌کند. ما با ارائه محصولات اصل از برندهای
معتبر جهانی، گارانتی رسمی و خدمات پس از فروش، تجربه‌ای مطمئن برای
خرید لوازم خانگی فراهم کرده‌ایم.
@@ -43,14 +50,7 @@ export function AboutSanihome() {
))}
</div>
</div>
<Placeholder
src="/images/about.svg"
alt="درباره سانی‌هوم"
width="100%"
height="360px"
label="560×360"
className="w-full rounded-2xl"
/>
<AboutSlotImage image={image} aspectRatio={aspectRatio} />
</div>
</div>
</section>
+42
View File
@@ -0,0 +1,42 @@
"use client";
import { useState } from "react";
import { Placeholder } from "@/components/ui/Placeholder";
import type { StaticImageWithUrl } from "@/lib/meshkee";
export function AboutSlotImage({
image,
aspectRatio,
}: {
image?: StaticImageWithUrl;
aspectRatio?: string;
}) {
const [failed, setFailed] = useState(false);
if (!image || failed) {
return (
<Placeholder
src="/images/about.svg"
alt="درباره صنیع هوم"
width="100%"
height="360px"
label="560×360"
className="w-full rounded-2xl"
/>
);
}
const frame = (
// Meshkee slot URLs are rendered as-is; a failed remote image falls back locally.
// eslint-disable-next-line @next/next/no-img-element
<img
src={image.url}
alt={image.titleFa ?? image.titleEn ?? image.subtext ?? "درباره صنیع هوم"}
onError={() => setFailed(true)}
style={{ aspectRatio: (aspectRatio ?? "14:9").replace(":", " / ") }}
className="h-auto w-full rounded-2xl object-cover"
/>
);
return image.linkUrl ? <a href={image.linkUrl}>{frame}</a> : frame;
}
+5 -2
View File
@@ -2,6 +2,7 @@ import { Placeholder } from "@/components/ui/Placeholder";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { Carousel } from "@/components/ui/Carousel";
import { EmptyState } from "@/components/ui/EmptyState";
import { ChevronLeftIcon } from "@/components/ui/icons";
import type { BlogSummary } from "@/lib/meshkee";
function formatDate(iso?: string) {
@@ -17,6 +18,7 @@ export function BlogCarousel({ posts }: { posts: BlogSummary[] }) {
title="آخرین مطالب وبلاگ"
enTitle="Latest Blog"
action="وبلاگ"
actionHref="/blog"
/>
{posts.length === 0 ? (
<EmptyState message="هنوز مطلبی ثبت نشده است." />
@@ -49,8 +51,9 @@ export function BlogCarousel({ posts }: { posts: BlogSummary[] }) {
{post.abstract}
</p>
)}
<span className="mt-3 block text-xs font-medium text-red">
ادامه مطلب ←
<span className="mt-3 flex items-center gap-1 text-xs font-medium text-red">
ادامه مطلب
<ChevronLeftIcon className="h-3.5 w-3.5" />
</span>
</div>
</a>
@@ -1,53 +0,0 @@
import { Carousel } from "@/components/ui/Carousel";
import { ProductCard } from "@/components/ui/ProductCard";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { EmptyState } from "@/components/ui/EmptyState";
import { productHref, type ProductGroup } from "@/lib/meshkee";
export function BrandGroupCarousels({
brandGroups,
contactPhone,
}: {
brandGroups: ProductGroup[];
contactPhone?: string;
}) {
if (brandGroups.length === 0) {
return (
<section className="py-10 md:py-14">
<div className="mx-auto max-w-7xl px-4">
<SectionTitle title="محصولات برندها" enTitle="Brand Collections" />
<EmptyState message="هنوز محصولی برای برندها ثبت نشده است." />
</div>
</section>
);
}
return (
<>
{brandGroups.map((group) => (
<section key={group.id} className="py-10 md:py-14">
<div className="mx-auto max-w-7xl px-4">
<SectionTitle title={group.title} enTitle={group.title} action="مشاهده همه" />
<Carousel ariaLabel={`کاروسل ${group.title}`}>
{group.items.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"}
variant="brand"
href={productHref(product)}
contactPhone={contactPhone}
variantId={product.variantId}
/>
))}
</Carousel>
</div>
</section>
))}
</>
);
}
+1 -7
View File
@@ -4,7 +4,6 @@ import { Swiper, SwiperSlide } from "swiper/react";
import { FreeMode } from "swiper/modules";
import "swiper/css";
import "swiper/css/free-mode";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { EmptyState } from "@/components/ui/EmptyState";
import type { Category, StaticImageWithUrl } from "@/lib/meshkee";
@@ -34,13 +33,8 @@ export function FeaturedCategories({
images?: StaticImageWithUrl[];
}) {
return (
<section className="py-10 md:py-14">
<section className="py-4 md:py-6">
<div className="mx-auto max-w-7xl px-4">
<SectionTitle
title="دسته‌بندی‌های پرطرفدار"
enTitle="Featured Categories"
action="همه دسته‌ها"
/>
{images.length > 0 ? (
<Swiper
modules={[FreeMode]}
+62 -19
View File
@@ -27,29 +27,35 @@ export function Footer({
);
return (
<footer className="border-t border-red-dark/20 bg-red-dark text-white">
<div className="mx-auto max-w-7xl px-4 py-12">
<footer className="border-t border-[#dddddd] bg-[#f1f1f1] text-black">
<div className="mx-auto max-w-7xl px-4 pt-10 pb-3">
<div className="grid gap-8 md:grid-cols-4">
<div>
<div className="mb-4 flex items-center gap-2">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white text-base font-bold text-red-dark">
S
</div>
{businessInfo?.logoDarkUrl || businessInfo?.logoUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={businessInfo.logoDarkUrl ?? businessInfo.logoUrl ?? undefined}
alt={businessInfo.nameFa?.replace(/سانی[‌ ]?هوم/g, "صنیع هوم") || "صنیع هوم"}
className="h-[72px] w-auto object-contain"
/>
) : (
<span className="font-display text-lg font-bold tracking-tight">
SANIHOME
</span>
)}
</div>
{businessInfo?.about && (
<p className="text-sm leading-relaxed text-white/70">{businessInfo.about}</p>
<p className="text-sm leading-relaxed text-black/70">{businessInfo.about}</p>
)}
</div>
<div>
<h4 className="mb-3 text-sm font-bold">دسترسی سریع</h4>
<ul className="space-y-2 text-sm text-white/70">
<ul className="space-y-2 text-sm text-black/70">
{quickLinks.map((link) => (
<li key={link}>
<a href="#" className="transition-colors hover:text-white">
<a href="#" className="transition-colors hover:text-black">
{link}
</a>
</li>
@@ -60,12 +66,12 @@ export function Footer({
<div>
<h4 className="mb-3 text-sm font-bold">دسته‌بندی‌ها</h4>
{categories.length === 0 ? (
<p className="text-sm text-white/50">هنوز دسته‌بندی‌ای ثبت نشده است.</p>
<p className="text-sm text-black/50">هنوز دسته‌بندی‌ای ثبت نشده است.</p>
) : (
<ul className="space-y-2 text-sm text-white/70">
<ul className="space-y-2 text-sm text-black/70">
{categories.slice(0, 5).map((cat) => (
<li key={cat.id}>
<a href="#" className="transition-colors hover:text-white">
<a href="#" className="transition-colors hover:text-black">
{cat.name}
</a>
</li>
@@ -77,7 +83,7 @@ export function Footer({
<div>
<h4 className="mb-3 text-sm font-bold">تماس با ما</h4>
{hasContactInfo ? (
<ul className="space-y-2 text-sm text-white/70">
<ul className="space-y-2 text-sm text-black/70">
{businessInfo?.addresses.map((address) => <li key={address}>{address}</li>)}
{businessInfo?.phoneNumbers.map((phone) => (
<li key={phone}>تلفن: {phone}</li>
@@ -85,7 +91,7 @@ export function Footer({
{businessInfo?.emails.map((email) => <li key={email}>ایمیل: {email}</li>)}
</ul>
) : (
<p className="text-sm text-white/50">هنوز اطلاعات تماس ثبت نشده است.</p>
<p className="text-sm text-black/50">هنوز اطلاعات تماس ثبت نشده است.</p>
)}
{socialEntries.length > 0 && (
<div className="mt-4 flex gap-3">
@@ -95,7 +101,7 @@ export function Footer({
href={url}
target="_blank"
rel="noreferrer"
className="font-display flex h-8 w-8 items-center justify-center rounded-full border border-white/20 text-[10px] font-bold transition-colors hover:border-white hover:bg-white/10"
className="font-display flex h-8 w-8 items-center justify-center rounded-full border border-black/20 text-[10px] font-bold transition-colors hover:border-black hover:bg-black/5"
>
{socialLabels[key] ?? key.slice(0, 2).toUpperCase()}
</a>
@@ -105,11 +111,48 @@ export function Footer({
</div>
</div>
<div className="mt-10 flex flex-col items-center justify-between gap-3 border-t border-white/10 pt-6 text-xs text-white/50 md:flex-row">
<p>© ۱۴۰۵ سانی‌هوم — تمامی حقوق محفوظ است.</p>
<p className="font-display tracking-wide uppercase">
Designed for Sanihome
</p>
{businessInfo?.trustBadges && businessInfo.trustBadges.length > 0 ? (
<div className="mt-10 flex flex-wrap items-center justify-center gap-4 border-t border-black/10 pt-6">
{businessInfo.trustBadges.map((badge) => (
<div
key={badge.kind}
className="trust-badge [&_img]:max-h-16 [&_a]:inline-block"
dangerouslySetInnerHTML={{ __html: badge.embedHtml }}
/>
))}
</div>
) : null}
<div className="mt-10 flex flex-col items-center justify-between gap-3 border-t border-black/10 pt-6 text-xs text-black/50 md:flex-row">
<p>© ۱۴۰۵ صنیع هوم — تمامی حقوق محفوظ است.</p>
<a
href="https://meshkee.com"
target="_blank"
rel="noopener noreferrer"
dir="ltr"
className="group relative inline-flex items-center gap-2.5 px-2.5 py-1.5 text-black/50 transition-colors duration-300 hover:text-black"
>
<span className="pointer-events-none absolute inset-0" aria-hidden="true">
<span className="absolute top-0 left-0 h-full w-px origin-top scale-y-0 bg-black/40 transition-transform duration-[280ms] delay-[420ms] group-hover:scale-y-100 group-hover:delay-0" />
<span className="absolute bottom-0 left-0 h-px w-full origin-left scale-x-0 bg-black/40 transition-transform duration-[280ms] delay-[280ms] group-hover:scale-x-100 group-hover:delay-[140ms]" />
<span className="absolute top-0 right-0 h-full w-px origin-bottom scale-y-0 bg-black/40 transition-transform duration-[280ms] delay-[140ms] group-hover:scale-y-100 group-hover:delay-[280ms]" />
<span className="absolute top-0 left-0 h-px w-full origin-right scale-x-0 bg-black/40 transition-transform duration-[280ms] delay-0 group-hover:scale-x-100 group-hover:delay-[420ms]" />
</span>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/images/meshkee-logo-white.png"
alt="Meshkee"
width={42}
height={42}
className="relative block h-[42px] w-auto shrink-0 object-contain opacity-60 brightness-0 transition-opacity duration-300 group-hover:opacity-100"
/>
<span className="relative flex min-h-[42px] flex-col justify-center leading-[1.25]">
<span className="text-[11px]">Designed And Developed By</span>
<span className="text-[13px] font-semibold text-black/70 transition-colors duration-300 group-hover:text-black">
Meshkee E-Commerce Team
</span>
</span>
</a>
</div>
</div>
</footer>
+47 -27
View File
@@ -5,11 +5,12 @@ import { createPortal } from "react-dom";
import type { Category, CategoryNode, CategoryTreeGroup } from "@/lib/meshkee";
import { EmptyState } from "@/components/ui/EmptyState";
import { CartButton } from "@/components/cart/CartButton";
import { ChevronLeftIcon, CloseIcon, MenuIcon, UserIcon } from "@/components/ui/icons";
import { SearchBar } from "./SearchBar";
const navLinks = [
{ label: "فروشگاه", href: "/store-items" },
{ label: "فروش ویژه", href: "#" },
{ label: "فروش ویژه", href: "/store-items?special=sale" },
{ label: "درباره ما", href: "#" },
{ label: "سوالات متداول", href: "#" },
{ label: "تماس با ما", href: "/contact" },
@@ -17,17 +18,17 @@ const navLinks = [
const LOGIN_URL = "https://customer.sanihome.ir";
function Logo({ large = false }: { large?: boolean }) {
function Logo({ src, large = false }: { src?: string | null; large?: boolean }) {
return (
<a href="/" className="flex shrink-0 items-center">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/images/logo.png"
alt="سانی‌هوم"
src={src || "/images/logo.png"}
alt="صنیع هوم"
className={
large
? "h-[42px] w-auto object-contain md:h-[46px]"
: "h-8 w-auto md:h-9"
? "h-[65px] w-auto object-contain"
: "h-[65px] w-auto object-contain"
}
/>
</a>
@@ -56,10 +57,12 @@ function MobileDrawer({
open,
onClose,
categoryTree,
logoUrl,
}: {
open: boolean;
onClose: () => void;
categoryTree: CategoryTreeGroup[];
logoUrl?: string | null;
}) {
const [categoriesOpen, setCategoriesOpen] = useState(false);
const [mounted, setMounted] = useState(false);
@@ -100,14 +103,14 @@ function MobileDrawer({
}`}
>
<div className="flex items-center justify-between border-b border-border p-5">
<Logo />
<Logo src={logoUrl} />
<button
type="button"
onClick={onClose}
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"
>
✕
<CloseIcon className="h-5 w-5" />
</button>
</div>
@@ -145,7 +148,7 @@ function MobileDrawer({
{level2.map((node) => (
<li key={node.id}>
<a
href={`/products?categoryId=${node.id}`}
href={`/store-items?categoryId=${node.id}`}
className="block rounded-lg px-3 py-1.5 font-medium text-foreground transition-colors hover:bg-red-light hover:text-red"
>
{node.nameFa}
@@ -155,7 +158,7 @@ function MobileDrawer({
{node.children.map((child) => (
<li key={child.id}>
<a
href={`/products?categoryId=${child.id}`}
href={`/store-items?categoryId=${child.id}`}
className="block rounded-lg px-3 py-1 text-muted transition-colors hover:bg-red-light hover:text-red"
>
{child.nameFa}
@@ -186,7 +189,7 @@ function MobileDrawer({
href={LOGIN_URL}
className="flex items-center gap-2 px-5 py-4 text-right font-medium transition-colors hover:bg-red-light/40 hover:text-red"
>
<span aria-hidden>👤</span>
<UserIcon className="h-4 w-4" />
ورود
</a>
</nav>
@@ -199,9 +202,11 @@ function MobileDrawer({
export function Header({
categoryTree,
categories,
logoUrl,
}: {
categoryTree: CategoryTreeGroup[];
categories: Category[];
logoUrl?: string | null;
}) {
const [menuOpen, setMenuOpen] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
@@ -221,24 +226,24 @@ export function Header({
return (
<header className="sticky top-0 z-50 border-b border-border bg-surface/95 backdrop-blur-sm">
<div className="mx-auto max-w-7xl px-4">
<div className="grid grid-cols-3 items-center gap-4 py-4 min-[1200px]:flex min-[1200px]:justify-between">
<div className="grid grid-cols-3 items-center gap-4 py-2 min-[1200px]:flex min-[1200px]:justify-between">
<div className="flex items-center justify-start">
<button
type="button"
onClick={() => setDrawerOpen(true)}
aria-label="منو"
className="flex h-10 w-10 items-center justify-center rounded-lg border border-border text-xl transition-colors hover:border-red hover:text-red min-[1200px]:hidden"
className="flex h-10 w-10 items-center justify-center rounded-lg border border-border transition-colors hover:border-red hover:text-red min-[1200px]:hidden"
>
<span aria-hidden>☰</span>
<MenuIcon className="h-5 w-5" />
</button>
<div className="hidden min-[1200px]:block">
<Logo />
<Logo src={logoUrl} />
</div>
</div>
<div className="flex items-center justify-center min-[1200px]:flex-1 min-[1200px]:px-6">
<div className="min-[1200px]:hidden">
<Logo large />
<Logo src={logoUrl} large />
</div>
<div className="hidden w-full min-[1200px]:block">
<SearchBar />
@@ -246,16 +251,29 @@ export function Header({
</div>
<div className="flex items-center justify-end gap-3 text-sm">
<div className="hidden items-center gap-2 rounded-2xl bg-surface p-1.5 sm:flex">
<CartButton />
<span className="h-8 w-px bg-border" aria-hidden />
<a
href={LOGIN_URL}
className="hidden items-center gap-1.5 text-muted transition-colors hover:text-red sm:flex"
className="flex items-center gap-2 rounded-xl py-1 pr-1 transition-opacity hover:opacity-80"
>
<span>👤</span>
<span>ورود</span>
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-red text-white">
<UserIcon className="h-5 w-5" />
</span>
<span className="text-right leading-tight">
<span className="block text-sm font-bold whitespace-nowrap text-foreground">
حساب کاربری
</span>
<span className="block text-xs whitespace-nowrap text-muted">ورود/ثبت‌نام</span>
</span>
</a>
</div>
<div className="sm:hidden">
<CartButton />
</div>
</div>
</div>
<div className="border-t border-border py-3 min-[1200px]:hidden">
<SearchBar />
@@ -275,7 +293,7 @@ export function Header({
aria-haspopup="true"
className="flex shrink-0 items-center gap-2 rounded-lg bg-red px-4 py-2 font-medium text-white transition-colors hover:bg-red-dark"
>
<span aria-hidden>☰</span>
<MenuIcon className="h-4 w-4" />
دسته‌بندی‌ها
</button>
@@ -289,10 +307,11 @@ export function Header({
</p>
</div>
<a
href="/products"
className="text-xs font-medium text-red hover:text-red-dark"
href="/store-items"
className="flex items-center gap-1 text-xs font-medium text-red hover:text-red-dark"
>
مشاهده همه ←
مشاهده همه
<ChevronLeftIcon className="h-3.5 w-3.5" />
</a>
</div>
@@ -303,7 +322,7 @@ export function Header({
{level2.map((node) => (
<div key={node.id} className="mb-4 break-inside-avoid">
<a
href={`/products?categoryId=${node.id}`}
href={`/store-items?categoryId=${node.id}`}
className="text-sm font-bold text-red-dark transition-colors hover:text-red"
>
{node.nameFa}
@@ -313,7 +332,7 @@ export function Header({
{node.children.map((child) => (
<li key={child.id}>
<a
href={`/products?categoryId=${child.id}`}
href={`/store-items?categoryId=${child.id}`}
className="text-sm text-muted transition-colors hover:text-red"
>
{child.nameFa}
@@ -332,7 +351,7 @@ export function Header({
{categories.slice(0, 4).map((cat) => (
<a
key={cat.id}
href={`/products?categoryId=${cat.id}`}
href={`/store-items?categoryId=${cat.id}`}
className="rounded-lg bg-red-light/50 px-3 py-2 text-center text-xs font-medium text-red-dark transition-colors hover:bg-red-light"
>
{cat.name}
@@ -360,6 +379,7 @@ export function Header({
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
categoryTree={categoryTree}
logoUrl={logoUrl}
/>
</header>
);
+12 -5
View File
@@ -1,11 +1,13 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Placeholder } from "@/components/ui/Placeholder";
import { formatPrice } from "@/data/sample";
import type { Product } from "@/lib/meshkee";
export function SearchBar() {
const router = useRouter();
const [query, setQuery] = useState("");
const [results, setResults] = useState<Product[]>([]);
const [open, setOpen] = useState(false);
@@ -15,8 +17,6 @@ export function SearchBar() {
useEffect(() => {
const trimmed = query.trim();
if (trimmed.length <= 2) {
setResults([]);
setOpen(false);
return;
}
@@ -56,7 +56,7 @@ export function SearchBar() {
const submit = () => {
const trimmed = query.trim();
if (trimmed) window.location.href = `/products?q=${encodeURIComponent(trimmed)}`;
if (trimmed) router.push(`/store-items?q=${encodeURIComponent(trimmed)}`);
};
return (
@@ -64,7 +64,14 @@ export function SearchBar() {
<input
type="search"
value={query}
onChange={(event) => setQuery(event.target.value)}
onChange={(event) => {
const value = event.target.value;
setQuery(value);
if (value.trim().length <= 2) {
setResults([]);
setOpen(false);
}
}}
onFocus={() => results.length > 0 && setOpen(true)}
onKeyDown={(event) => event.key === "Enter" && submit()}
placeholder="جستجوی محصول، برند یا دسته‌بندی..."
@@ -89,7 +96,7 @@ export function SearchBar() {
{results.map((product) => (
<li key={product.id}>
<a
href={`/products/${product.slug}`}
href={`/store-items/${product.slug}`}
className="flex items-center gap-3 p-3 transition-colors hover:bg-red-light/40"
>
<Placeholder
@@ -1,64 +0,0 @@
import { Carousel } from "@/components/ui/Carousel";
import { Placeholder } from "@/components/ui/Placeholder";
import { ProductCard } from "@/components/ui/ProductCard";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { EmptyState } from "@/components/ui/EmptyState";
import { productHref, type Product } from "@/lib/meshkee";
function SpecialSaleBanner() {
return (
<a
href="#"
className="relative w-[220px] shrink-0 self-stretch overflow-hidden rounded-xl border border-border md:w-[240px]"
>
<Placeholder
src="/images/sale-banner.svg"
alt="فروش ویژه"
width="100%"
className="h-full min-h-[380px] w-full rounded-none border-0"
/>
</a>
);
}
export function SpecialSaleCarousel({
products,
contactPhone,
}: {
products: Product[];
contactPhone?: string;
}) {
return (
<section className="border-y border-red-light bg-red-light/30 py-10 md:py-14">
<div className="mx-auto max-w-7xl px-4">
<SectionTitle
title="فروش ویژه"
enTitle="Special Sale"
action="مشاهده همه"
/>
{products.length === 0 ? (
<EmptyState message="هنوز محصولی برای فروش ویژه ثبت نشده است." />
) : (
<Carousel ariaLabel="کاروسل فروش ویژه">
<SpecialSaleBanner />
{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"}
variant="sale"
href={productHref(product)}
contactPhone={contactPhone}
variantId={product.variantId}
/>
))}
</Carousel>
)}
</div>
</section>
);
}
@@ -0,0 +1,50 @@
"use client";
import { useEffect, useState } from "react";
type RemainingTime = {
hours: number;
minutes: number;
seconds: number;
};
function getRemainingTime(): RemainingTime {
const now = new Date();
const endOfDay = new Date(now);
endOfDay.setHours(23, 59, 59, 999);
const totalSeconds = Math.max(0, Math.floor((endOfDay.getTime() - now.getTime()) / 1000));
return {
hours: Math.floor(totalSeconds / 3600),
minutes: Math.floor((totalSeconds % 3600) / 60),
seconds: totalSeconds % 60,
};
}
function TimeBox({ value, label }: { value: number; label: string }) {
return (
<div className="flex min-w-0 flex-1 flex-col items-center rounded-xl bg-white/15 px-1 py-2.5 md:py-3">
<strong className="text-lg leading-none tabular-nums md:text-2xl" suppressHydrationWarning>
{String(value).padStart(2, "0")}
</strong>
<span className="mt-2 text-[10px] text-white/80 md:text-xs">{label}</span>
</div>
);
}
export function SpecialSaleCountdown() {
const [remaining, setRemaining] = useState(getRemainingTime);
useEffect(() => {
const timer = window.setInterval(() => setRemaining(getRemainingTime()), 1000);
return () => window.clearInterval(timer);
}, []);
return (
<div className="grid w-full grid-cols-3 gap-1.5 md:gap-2" dir="ltr">
<TimeBox value={remaining.hours} label="ساعت" />
<TimeBox value={remaining.minutes} label="دقیقه" />
<TimeBox value={remaining.seconds} label="ثانیه" />
</div>
);
}
@@ -0,0 +1,157 @@
import { Fragment } from "react";
import { Carousel } from "@/components/ui/Carousel";
import { ProductCard } from "@/components/ui/ProductCard";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { ChevronLeftIcon } from "@/components/ui/icons";
import { TwoBanners } from "@/components/home/TwoBanners";
import { ThreeBanners } from "@/components/home/ThreeBanners";
import { SpecialSaleCountdown } from "@/components/home/SpecialSaleCountdown";
import {
isSpecialSaleGroup,
productHref,
type ProductGroup,
type StaticImageWithUrl,
} from "@/lib/meshkee";
// The API only gives one `title` string per group (sometimes already
// English, e.g. "Special Sale", sometimes Persian) — there's no separate
// localized English field to pull a real translation from, and inventing
// one would be fabricated data. `key` is real data and usually a readable
// English slug (e.g. "top-selling"), so it's what gets formatted into the
// English caption beside the title (same inline treatment as every other
// section heading on the site, e.g. BlogCarousel's "LATEST BLOG"). Skip it
// if the key has no letters at all (e.g. it fell back to a bare numeric id).
function englishLabelFromKey(key: string): string | undefined {
const label = key.replace(/[-_]+/g, " ").trim();
return /[a-zA-Z]/.test(label) ? label.toUpperCase() : undefined;
}
function SpecialSaleSection({ group }: { group: ProductGroup }) {
return (
<section className="bg-red py-6 md:py-8">
<div className="mx-auto flex max-w-7xl items-stretch gap-3 px-4 md:gap-5">
<aside className="my-2 flex w-[calc(50%-1rem)] shrink-0 flex-col items-center justify-center rounded-2xl bg-red-dark/35 p-3 text-center text-white md:w-[240px] md:p-6">
<svg
viewBox="0 0 32 32"
className="mb-3 h-11 w-11 md:h-14 md:w-14"
aria-hidden="true"
>
<g transform="matrix(1.05 0 0 1.05 -.8 -.8006)">
<path
fill="currentColor"
d="m30.25 14.182-.876-.876c-.36-.36-.577-1.168-.445-1.661l.32-1.197a2.54 2.54 0 0 0-.259-1.949 2.55 2.55 0 0 0-1.559-1.198l-1.196-.321c-.492-.132-1.084-.724-1.217-1.215l-.32-1.197C24.34 3.232 22.899 2.39 21.55 2.75l-1.196.321c-.459.122-1.316-.101-1.66-.445l-.877-.876c-.969-.969-2.666-.969-3.635 0l-.877.877c-.344.344-1.201.567-1.661.445l-1.195-.321c-1.349-.361-2.79.481-3.148 1.818l-.32 1.195c-.132.494-.724 1.085-1.216 1.217l-1.197.321c-.662.177-1.216.603-1.56 1.199s-.435 1.288-.257 1.947l.319 1.198c.132.493-.084 1.3-.444 1.661l-.876.876C1.267 14.667 1 15.313 1 16s.267 1.333.751 1.817l.876.876c.36.36.577 1.168.445 1.661l-.32 1.197a2.54 2.54 0 0 0 .259 1.949 2.55 2.55 0 0 0 1.559 1.198l1.195.32c.493.132 1.085.724 1.218 1.215l.319 1.197c.358 1.336 1.804 2.175 3.147 1.817l1.197-.32c.46-.122 1.317.101 1.661.445l.876.875c.484.486 1.13.753 1.818.753s1.334-.267 1.817-.75l.877-.876c.345-.344 1.205-.565 1.661-.445l1.195.32q.326.087.662.087h.001a2.575 2.575 0 0 0 2.485-1.905l.319-1.194c.133-.494.725-1.085 1.217-1.218l1.196-.32c.662-.177 1.216-.604 1.56-1.2s.435-1.288.257-1.947l-.319-1.198c-.132-.493.084-1.3.444-1.661l.876-.876c.484-.484.751-1.13.751-1.817a2.55 2.55 0 0 0-.75-1.818M9 12c0-1.654 1.346-3 3-3s3 1.346 3 3-1.346 3-3 3-3-1.346-3-3m3.707 8.707a.997.997 0 0 1-1.414 0 1 1 0 0 1 0-1.414l8-8a.999.999 0 1 1 1.414 1.414zM20 23c-1.654 0-3-1.346-3-3s1.346-3 3-3 3 1.346 3 3-1.346 3-3 3"
/>
<circle cx="20" cy="20" r="1" fill="currentColor" />
<circle cx="12" cy="12" r="1" fill="currentColor" />
</g>
</svg>
<h2 className="text-lg font-bold md:text-2xl">{group.title}</h2>
<p className="mt-1.5 mb-4 text-xs text-white/80 md:text-sm">تا پایان فروش ویژه</p>
<SpecialSaleCountdown />
<a
href={`/store-items?specialId=${group.id}`}
className="mt-4 flex shrink-0 items-center gap-1.5 rounded-lg bg-white px-4 py-2 text-sm font-medium text-black transition-colors hover:bg-white/90"
>
مشاهده همه
<ChevronLeftIcon className="h-4 w-4" />
</a>
</aside>
<div className="min-w-0 flex-1">
<Carousel
ariaLabel={`کاروسل ${group.title}`}
slideClassName="!w-full md:!w-[240px]"
>
{group.items.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)}
variant="sale"
fluid
/>
))}
</Carousel>
</div>
</div>
</section>
);
}
// Renders every admin-managed carousel from GET /store-specials — whatever
// groups exist there, in their configured order. Nothing here is keyed off
// a specific group id/key/title, so a new carousel created in the Meshkee
// dashboard (any name) shows up on the homepage automatically, with no code
// change. Groups with no items are skipped (honest empty state — no heading
// over nothing).
//
// One of the two banner sections is inserted between every pair of
// carousels (never before the first or after the last), cycling if there
// end up being more than two carousels.
export function StoreSpecialCarousels({
groups,
contactPhone,
twoBannerImages,
twoBannerAspectRatio,
threeBannerImages,
threeBannerAspectRatio,
}: {
groups: ProductGroup[];
contactPhone?: string;
twoBannerImages?: StaticImageWithUrl[];
twoBannerAspectRatio?: string;
threeBannerImages?: StaticImageWithUrl[];
threeBannerAspectRatio?: string;
}) {
const visibleGroups = groups.filter((group) => group.items.length > 0);
const banners = [
<TwoBanners key="two" images={twoBannerImages} aspectRatio={twoBannerAspectRatio} />,
<ThreeBanners key="three" images={threeBannerImages} aspectRatio={threeBannerAspectRatio} />,
];
return (
<>
{visibleGroups.map((group, i) => (
<Fragment key={group.id}>
{i > 0 && banners[(i - 1) % banners.length]}
{isSpecialSaleGroup(group) ? (
<SpecialSaleSection group={group} />
) : (
<section className="py-10 md:py-14">
<div className="mx-auto max-w-7xl px-4">
<SectionTitle
title={group.title}
enTitle={englishLabelFromKey(group.key)}
action="مشاهده همه"
actionHref={`/store-items?specialId=${group.id}`}
/>
<Carousel ariaLabel={`کاروسل ${group.title}`}>
{group.items.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}
slug={product.slug}
/>
))}
</Carousel>
</div>
</section>
)}
</Fragment>
))}
</>
);
}
@@ -1,45 +0,0 @@
import { Carousel } from "@/components/ui/Carousel";
import { ProductCard } from "@/components/ui/ProductCard";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { EmptyState } from "@/components/ui/EmptyState";
import { productHref, type Product } from "@/lib/meshkee";
export function TopSellingCarousel({
products,
contactPhone,
}: {
products: Product[];
contactPhone?: string;
}) {
return (
<section className="py-10 md:py-14">
<div className="mx-auto max-w-7xl px-4">
<SectionTitle
title="پرفروش‌ترین‌ها"
enTitle="Top Selling"
action="مشاهده همه"
/>
{products.length === 0 ? (
<EmptyState message="هنوز محصولی ثبت نشده است." />
) : (
<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>
</section>
);
}
+360
View File
@@ -0,0 +1,360 @@
"use client";
import { useEffect, useRef, useState } from "react";
import Form from "next/form";
import { CloseIcon } from "@/components/ui/icons";
export type ProductFilterCategory = {
id: string;
label: string;
children: { id: string; label: string }[];
};
export type ProductFilterValues = {
categoryId?: string;
minPrice?: string;
maxPrice?: string;
inStock: boolean;
q?: string;
specialId?: string;
special?: string;
};
function FilterIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
<path
d="M4 6h16M7 12h10M10 18h4"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
/>
</svg>
);
}
function FilterFields({
categories,
values,
}: {
categories: ProductFilterCategory[];
values: ProductFilterValues;
}) {
const categoryListRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (!values.categoryId) return;
const activeParent = categories.find(
(category) =>
category.id === values.categoryId ||
(category.children ?? []).some((child) => child.id === values.categoryId),
);
if (!activeParent) return;
const accordion = categoryListRef.current?.querySelector<HTMLDetailsElement>(
`[data-category-id="${CSS.escape(activeParent.id)}"]`,
);
if (accordion) accordion.open = true;
}, [categories, values.categoryId]);
return (
<div className="divide-y divide-border">
{values.q && <input type="hidden" name="q" value={values.q} />}
{values.specialId && <input type="hidden" name="specialId" value={values.specialId} />}
{values.special && <input type="hidden" name="special" value={values.special} />}
<details className="group py-4" open>
<summary className="flex cursor-pointer list-none items-center justify-between font-medium">
دسته‌بندی
<span className="text-lg text-muted transition-transform group-open:rotate-45">+</span>
</summary>
<div ref={categoryListRef} className="mt-3 max-h-72 overflow-y-auto pl-1">
<label className="mb-2 flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm transition-colors hover:bg-red-light">
<input
type="radio"
name="categoryId"
value=""
defaultChecked={!values.categoryId}
className="accent-red"
/>
همه دسته‌بندی‌ها
</label>
{categories.map((category) => (
(category.children ?? []).length > 0 ? (
<details
key={category.id}
data-category-id={category.id}
className="group/category border-t border-border/70"
>
<summary className="flex cursor-pointer list-none items-center justify-between gap-2 rounded-lg px-2 py-2.5 text-sm transition-colors hover:bg-red-light">
<label
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2"
onClick={(event) => event.stopPropagation()}
>
<input
type="radio"
name="categoryId"
value={category.id}
defaultChecked={values.categoryId === category.id}
className="accent-red"
/>
<span className="truncate">{category.label}</span>
</label>
<svg
viewBox="0 0 24 24"
fill="none"
className="h-4 w-4 shrink-0 text-muted transition-transform group-open/category:rotate-180"
aria-hidden
>
<path
d="m7 10 5 5 5-5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</summary>
<div className="mb-2 mr-5 space-y-0.5 border-r border-border pr-3">
{(category.children ?? []).map((child) => (
<label
key={child.id}
className="flex cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-sm text-muted transition-colors hover:bg-red-light hover:text-foreground"
>
<input
type="radio"
name="categoryId"
value={child.id}
defaultChecked={values.categoryId === child.id}
className="accent-red"
/>
{child.label}
</label>
))}
</div>
</details>
) : (
<label
key={category.id}
className="flex cursor-pointer items-center gap-2 border-t border-border/70 px-2 py-2.5 text-sm transition-colors hover:bg-red-light"
>
<input
type="radio"
name="categoryId"
value={category.id}
defaultChecked={values.categoryId === category.id}
className="accent-red"
/>
{category.label}
</label>
)
))}
</div>
</details>
<details className="group py-4" open>
<summary className="flex cursor-pointer list-none items-center justify-between font-medium">
محدوده قیمت
<span className="text-lg text-muted transition-transform group-open:rotate-45">+</span>
</summary>
<div className="mt-3 grid grid-cols-2 gap-2">
<label className="text-xs text-muted">
از قیمت
<input
type="number"
name="minPrice"
min="0"
inputMode="numeric"
defaultValue={values.minPrice}
placeholder="۰"
className="mt-1 w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-foreground outline-none transition-colors focus:border-red"
/>
</label>
<label className="text-xs text-muted">
تا قیمت
<input
type="number"
name="maxPrice"
min="0"
inputMode="numeric"
defaultValue={values.maxPrice}
placeholder="بدون محدودیت"
className="mt-1 w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-foreground outline-none transition-colors focus:border-red"
/>
</label>
</div>
<p className="mt-2 text-[11px] text-muted">مبالغ به تومان هستند.</p>
</details>
<div className="py-4">
<label className="flex cursor-pointer items-center justify-between gap-3 text-sm font-medium">
فقط کالاهای موجود
<input
type="checkbox"
name="inStock"
value="true"
defaultChecked={values.inStock}
className="h-4 w-4 accent-red"
/>
</label>
</div>
</div>
);
}
function FilterActions({ resetHref }: { resetHref: string }) {
return (
<div className="grid grid-cols-[1fr_auto] gap-2">
<button
type="submit"
className="rounded-lg bg-red px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-red-dark"
>
اعمال فیلترها
</button>
<a
href={resetHref}
className="rounded-lg border border-border px-3 py-2.5 text-center text-sm text-muted transition-colors hover:border-red hover:text-red"
>
پاک کردن
</a>
</div>
);
}
export function ProductFilters({
categories,
values,
}: {
categories: ProductFilterCategory[];
values: ProductFilterValues;
}) {
const [open, setOpen] = useState(false);
const desktopPriceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const activeCount = [values.categoryId, values.minPrice || values.maxPrice, values.inStock].filter(
Boolean,
).length;
const resetParams = new URLSearchParams();
if (values.q) resetParams.set("q", values.q);
if (values.specialId) resetParams.set("specialId", values.specialId);
if (values.special) resetParams.set("special", values.special);
const resetQuery = resetParams.toString();
const resetHref = `/store-items${resetQuery ? `?${resetQuery}` : ""}`;
useEffect(() => {
if (!open) return;
const previousOverflow = document.body.style.overflow;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") setOpen(false);
};
document.body.style.overflow = "hidden";
document.addEventListener("keydown", onKeyDown);
return () => {
document.body.style.overflow = previousOverflow;
document.removeEventListener("keydown", onKeyDown);
};
}, [open]);
useEffect(
() => () => {
if (desktopPriceTimer.current) clearTimeout(desktopPriceTimer.current);
},
[],
);
const submitDesktopFilters = (event: React.ChangeEvent<HTMLFormElement>) => {
const form = event.currentTarget;
const target = event.target;
if (!(target instanceof HTMLInputElement)) return;
if (desktopPriceTimer.current) clearTimeout(desktopPriceTimer.current);
if (target.type === "number") {
desktopPriceTimer.current = setTimeout(() => form.requestSubmit(), 600);
return;
}
form.requestSubmit();
};
return (
<>
<aside className="hidden w-64 shrink-0 md:block">
<Form
action="/store-items"
scroll={false}
onChange={submitDesktopFilters}
className="sticky top-32 rounded-2xl border border-border bg-surface p-4"
>
<div className="mb-1 flex items-center gap-2 border-b border-border pb-4">
<FilterIcon className="h-5 w-5 text-red" />
<h2 className="font-bold">فیلتر محصولات</h2>
</div>
<FilterFields categories={categories} values={values} />
{activeCount > 0 && (
<a
href={resetHref}
className="block w-full rounded-lg border border-border px-3 py-2.5 text-center text-sm text-muted transition-colors hover:border-red hover:text-red"
>
پاک کردن فیلترها
</a>
)}
</Form>
</aside>
<button
type="button"
onClick={() => setOpen(true)}
className="mb-5 flex w-full items-center justify-center gap-2 rounded-xl border border-border bg-surface px-4 py-3 text-sm font-medium md:hidden"
>
<FilterIcon className="h-5 w-5 text-red" />
فیلتر محصولات
{activeCount > 0 && (
<span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-red px-1.5 text-[11px] text-white">
{activeCount}
</span>
)}
</button>
{open && (
<div
className="fixed inset-0 z-[70] bg-black/45 md:hidden"
role="presentation"
onMouseDown={(event) => {
if (event.target === event.currentTarget) setOpen(false);
}}
>
<div
role="dialog"
aria-modal="true"
aria-labelledby="mobile-filter-title"
className="ml-auto flex h-full w-[min(90vw,380px)] flex-col bg-surface shadow-2xl"
>
<div className="flex items-center justify-between border-b border-border px-4 py-3">
<h2 id="mobile-filter-title" className="font-bold">
فیلتر محصولات
</h2>
<button
type="button"
onClick={() => setOpen(false)}
aria-label="بستن فیلترها"
className="flex h-10 w-10 items-center justify-center rounded-lg text-muted transition-colors hover:bg-red-light hover:text-red"
>
<CloseIcon className="h-5 w-5" />
</button>
</div>
<Form
action="/store-items"
onSubmit={() => setOpen(false)}
className="flex min-h-0 flex-1 flex-col"
>
<div className="min-h-0 flex-1 overflow-y-auto px-4">
<FilterFields categories={categories} values={values} />
</div>
<div className="shrink-0 border-t border-border bg-surface p-4 shadow-[0_-8px_24px_rgba(0,0,0,0.06)]">
<FilterActions resetHref={resetHref} />
</div>
</Form>
</div>
</div>
)}
</>
);
}
+4 -9
View File
@@ -33,11 +33,8 @@ function Lightbox({
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) => {
@@ -52,8 +49,6 @@ function Lightbox({
};
}, [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
@@ -77,7 +72,7 @@ function Lightbox({
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" />
<ChevronIcon direction="next" className="h-6 w-6" />
</button>
<button
type="button"
@@ -85,7 +80,7 @@ function Lightbox({
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" />
<ChevronIcon direction="prev" className="h-6 w-6" />
</button>
</>
)}
@@ -164,7 +159,7 @@ export function ProductGallery({ images, alt }: { images: string[]; alt: string
aria-label="تصویر بعدی"
className="absolute top-1/2 right-3 z-10 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-border bg-surface/90 text-foreground shadow-sm transition-colors hover:border-red hover:text-red"
>
<ChevronIcon direction="prev" className="h-5 w-5" />
<ChevronIcon direction="next" className="h-5 w-5" />
</button>
<button
type="button"
@@ -172,7 +167,7 @@ export function ProductGallery({ images, alt }: { images: string[]; alt: string
aria-label="تصویر قبلی"
className="absolute top-1/2 left-3 z-10 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-border bg-surface/90 text-foreground shadow-sm transition-colors hover:border-red hover:text-red"
>
<ChevronIcon direction="next" className="h-5 w-5" />
<ChevronIcon direction="prev" className="h-5 w-5" />
</button>
</>
)}
+20 -21
View File
@@ -3,7 +3,6 @@
import { type ReactNode, useMemo, useState } from "react";
import { formatPrice } from "@/data/sample";
import type { ProductStoreVariant, ProductVariation } from "@/lib/meshkee";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
function CheckIcon({ className }: { className?: string }) {
@@ -29,6 +28,9 @@ export function ProductPurchasePanel({
contactPhone,
storeName,
initialSelections,
productName,
productSlug,
productImage,
}: {
header: ReactNode;
variations: ProductVariation[];
@@ -46,8 +48,11 @@ export function ProductPurchasePanel({
// detail page for one specific variant), instead of defaulting to the
// first option of every variation.
initialSelections?: Record<string, string>;
// For the guest-cart line (id alone isn't enough to render a mini-cart row).
productName: string;
productSlug: string;
productImage: string;
}) {
const { user, openLoginModal } = useAuth();
const { addItem } = useCart();
const [selected, setSelected] = useState<Record<string, string>>(() => {
if (initialSelections && Object.keys(initialSelections).length > 0) return initialSelections;
@@ -58,8 +63,7 @@ export function ProductPurchasePanel({
return initial;
});
const [quantity, setQuantity] = useState(1);
const [cartStatus, setCartStatus] = useState<"idle" | "busy" | "done">("idle");
const [cartError, setCartError] = useState<string | null>(null);
const [cartStatus, setCartStatus] = useState<"idle" | "done">("idle");
const matchedVariant = useMemo(() => {
if (storeVariants.length === 0) return null;
@@ -101,22 +105,19 @@ export function ProductPurchasePanel({
const available = matchedVariant ? stockQuantity! > 0 : inStock;
const maxQty = stockQuantity && stockQuantity > 0 ? stockQuantity : 99;
const handleAddToCart = async () => {
if (!matchedVariant) return;
if (!user) {
openLoginModal();
return;
}
setCartError(null);
setCartStatus("busy");
const res = await addItem(matchedVariant.id, quantity);
if (res.ok) {
const handleAddToCart = () => {
if (!matchedVariant || price == null) return;
addItem({
id: matchedVariant.id,
name: productName,
slug: productSlug,
price,
originalPrice: oldPrice ?? undefined,
image: productImage,
quantity,
});
setCartStatus("done");
setTimeout(() => setCartStatus("idle"), 1500);
} else {
setCartStatus("idle");
setCartError(res.message ?? "افزودن به سبد ناموفق بود.");
}
};
return (
@@ -226,12 +227,10 @@ export function ProductPurchasePanel({
</div>
</div>
{cartError && <p className="mb-3 text-xs text-red-dark">{cartError}</p>}
<button
type="button"
onClick={handleAddToCart}
disabled={!available || cartStatus === "busy"}
disabled={!available}
className="w-full rounded-xl bg-red py-3 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:bg-red/60"
>
{cartStatus === "done" ? "به سبد اضافه شد ✓" : "افزودن به سبد خرید"}
+47 -31
View File
@@ -2,7 +2,6 @@
import { useState } from "react";
import { EmptyState } from "@/components/ui/EmptyState";
import { useAuth } from "@/context/AuthContext";
import { postComment, type EntityComment, type TechnicalInfoField } from "@/lib/meshkee";
type Tab = "specs" | "review" | "comments";
@@ -19,23 +18,23 @@ function formatDate(iso?: string) {
}
function CommentsPanel({ entityId, initialComments }: { entityId: string; initialComments: EntityComment[] }) {
const { user, openLoginModal } = useAuth();
const [comments, setComments] = useState(initialComments);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [text, setText] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
if (!user || !text.trim()) return;
if (!name.trim() || !text.trim()) return;
setBusy(true);
setError(null);
const authorName = [user.firstName, user.lastName].filter(Boolean).join(" ") || "کاربر";
const res = await postComment({
entityType: "product",
entityId,
authorName,
authorEmail: user.email,
authorName: name.trim(),
authorEmail: email.trim() || undefined,
text: text.trim(),
});
setBusy(false);
@@ -43,14 +42,29 @@ function CommentsPanel({ entityId, initialComments }: { entityId: string; initia
setError(res.message ?? "ثبت نظر ناموفق بود.");
return;
}
setComments((prev) => [{ id: `local-${Date.now()}`, authorName, text: text.trim() }, ...prev]);
setComments((prev) => [{ id: `local-${Date.now()}`, authorName: name.trim(), text: text.trim() }, ...prev]);
setText("");
};
return (
<div>
{user ? (
<form onSubmit={handleSubmit} className="mb-6 space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<input
required
placeholder="نام شما"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red"
/>
<input
type="email"
placeholder="ایمیل (اختیاری)"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus:border-red"
/>
</div>
<textarea
required
rows={3}
@@ -62,24 +76,12 @@ function CommentsPanel({ entityId, initialComments }: { entityId: string; initia
{error && <p className="text-xs text-red-dark">{error}</p>}
<button
type="submit"
disabled={busy || !text.trim()}
disabled={busy || !name.trim() || !text.trim()}
className="rounded-lg bg-red px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-60"
>
{busy ? "در حال ثبت..." : "ثبت نظر"}
</button>
</form>
) : (
<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="هنوز نظری برای این محصول ثبت نشده است." />
@@ -117,8 +119,8 @@ export function ProductTabs({
const activeLabel = TABS.find((t) => t.id === active)?.label ?? "";
return (
<div className="mt-10">
<div className="flex items-center gap-8 border-b border-border">
<section className="mt-10 overflow-hidden rounded-2xl border border-border bg-surface">
<div className="flex flex-wrap items-center gap-x-7 border-b border-border px-5 pt-5 md:gap-x-10 md:px-7">
{TABS.map((tab) => (
<button
key={tab.id}
@@ -136,7 +138,7 @@ export function ProductTabs({
))}
</div>
<div className="pt-8">
<div className="p-5 md:p-7">
<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 />
{activeLabel}
@@ -146,13 +148,27 @@ export function ProductTabs({
(technicalInfo.length === 0 ? (
<EmptyState message="هنوز مشخصات فنی‌ای برای این محصول ثبت نشده است." />
) : (
<div className="grid gap-3 sm:grid-cols-2">
{technicalInfo.map((field) => (
<div key={field.label} className="rounded-xl bg-background p-4">
<p className="mb-1 text-sm font-bold">{field.label} :</p>
<p className="text-sm text-muted">{field.value}</p>
</div>
<div className="overflow-hidden rounded-xl border border-border">
<table className="w-full border-collapse text-right text-sm">
<tbody>
{technicalInfo.map((field, index) => (
<tr
key={`${field.label}-${index}`}
className="border-b border-border last:border-b-0 odd:bg-background/60"
>
<th
scope="row"
className="w-[30%] px-4 py-3.5 align-top font-bold text-foreground md:w-[22%] md:px-5"
>
{field.label}
</th>
<td className="px-4 py-3.5 leading-7 text-muted md:px-5">
{field.value}
</td>
</tr>
))}
</tbody>
</table>
</div>
))}
@@ -168,6 +184,6 @@ export function ProductTabs({
{active === "comments" && <CommentsPanel entityId={entityId} initialComments={initialComments} />}
</div>
</div>
</section>
);
}
@@ -37,6 +37,7 @@ export async function SimilarProducts({
href={productHref(product)}
contactPhone={contactPhone}
variantId={product.variantId}
slug={product.slug}
/>
))}
</Carousel>
+20 -4
View File
@@ -1,6 +1,6 @@
"use client";
import { Children, useRef } from "react";
import { Children, useRef, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { FreeMode } from "swiper/modules";
import type { Swiper as SwiperClass } from "swiper";
@@ -10,6 +10,7 @@ import "swiper/css/free-mode";
type CarouselProps = {
children: React.ReactNode;
ariaLabel: string;
slideClassName?: string;
};
function ChevronLeftIcon() {
@@ -40,11 +41,12 @@ function ChevronRightIcon() {
);
}
export function Carousel({ children, ariaLabel }: CarouselProps) {
export function Carousel({ children, ariaLabel, slideClassName }: CarouselProps) {
const swiperRef = useRef<SwiperClass | null>(null);
const [isLocked, setIsLocked] = useState(false);
const btnClass =
"absolute top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-white/40 bg-white/40 text-red shadow-sm backdrop-blur-md transition-colors hover:border-red/40 hover:bg-white/60 hover:text-red-dark";
"absolute top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-white/40 bg-white/40 text-red shadow-sm backdrop-blur-md transition-colors hover:border-red/40 hover:bg-white/60 hover:text-red-dark disabled:pointer-events-none disabled:opacity-0";
return (
<div className="relative">
@@ -52,6 +54,7 @@ export function Carousel({ children, ariaLabel }: CarouselProps) {
type="button"
onClick={() => swiperRef.current?.slidePrev()}
aria-label="قبلی"
disabled={isLocked}
className={`${btnClass} right-1`}
>
<ChevronRightIcon />
@@ -60,6 +63,7 @@ export function Carousel({ children, ariaLabel }: CarouselProps) {
type="button"
onClick={() => swiperRef.current?.slideNext()}
aria-label="بعدی"
disabled={isLocked}
className={`${btnClass} left-1`}
>
<ChevronLeftIcon />
@@ -68,10 +72,17 @@ export function Carousel({ children, ariaLabel }: CarouselProps) {
modules={[FreeMode]}
onSwiper={(swiper) => {
swiperRef.current = swiper;
setIsLocked(swiper.isLocked);
}}
onLock={(swiper) => {
swiper.slideTo(0, 0);
setIsLocked(true);
}}
onUnlock={() => setIsLocked(false)}
dir="rtl"
slidesPerView="auto"
spaceBetween={16}
watchOverflow
freeMode={{ enabled: true, momentum: true, sticky: true }}
grabCursor
role="region"
@@ -83,7 +94,12 @@ export function Carousel({ children, ariaLabel }: CarouselProps) {
// wrapper height — resolves per-slide instead of stretching to match
// the tallest sibling. height:auto (inline, so it wins) lets normal
// flex stretch equalize card heights across a row.
<SwiperSlide style={{ width: "auto", height: "auto" }}>{child}</SwiperSlide>
<SwiperSlide
className={slideClassName}
style={slideClassName ? { height: "auto" } : { width: "auto", height: "auto" }}
>
{child}
</SwiperSlide>
))}
</Swiper>
</div>
+19
View File
@@ -0,0 +1,19 @@
import type { ReactNode } from "react";
import { Breadcrumb } from "./Breadcrumb";
type PageShellBreadcrumbItem = { label: string; href?: string };
export function PageShell({
breadcrumbItems,
children,
}: {
breadcrumbItems: PageShellBreadcrumbItem[];
children: ReactNode;
}) {
return (
<main className="mx-auto max-w-7xl px-4 py-10">
<Breadcrumb items={breadcrumbItems} />
{children}
</main>
);
}
+9 -67
View File
@@ -1,10 +1,5 @@
"use client";
import { useState } from "react";
import { Placeholder } from "./Placeholder";
import { formatPrice } from "@/data/sample";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
type ProductCardProps = {
name: string;
@@ -17,10 +12,8 @@ type ProductCardProps = {
href?: string;
fluid?: boolean;
contactPhone?: string;
// When known (store-specials/brand-groups/store-items cards already point
// at one purchasable variant), the button adds straight to cart. Otherwise
// it just links to the detail page, where a variant can be picked first.
variantId?: string;
slug?: string;
};
export function ProductCard({
@@ -33,25 +26,7 @@ export function ProductCard({
variant = "default",
href,
fluid = false,
contactPhone,
variantId,
}: 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 = (
<>
<div className="relative p-[10px]">
@@ -68,19 +43,21 @@ export function ProductCard({
</span>
)}
</div>
<div className="p-4 pb-0">
<p className="font-display mb-1 text-[11px] tracking-wide text-muted uppercase">
<div className="px-4 pb-4">
{brand && (
<p className="font-display mb-1 line-clamp-2 h-8 text-[11px] leading-4 tracking-wide text-muted uppercase">
{brand}
</p>
<h3 className="mb-3 line-clamp-2 min-h-[2.75rem] text-sm leading-relaxed font-medium">
)}
<h3 className="mb-2 line-clamp-2 h-11 text-sm leading-6 font-medium">
{name}
</h3>
<div className="space-y-1">
<div className="flex h-12 flex-col items-end justify-end space-y-1 text-left">
{oldPrice != null && (
<div className="flex items-center gap-2">
<span className="text-xs text-muted line-through">{formatPrice(oldPrice)}</span>
<span className="text-sm text-muted line-through">{formatPrice(oldPrice)}</span>
{discount != null && (
<span className="rounded-md bg-green-50 px-1.5 py-0.5 text-[11px] font-bold text-green-700">
<span className="rounded-md bg-red px-1.5 py-0.5 text-[11px] font-bold text-white">
{discount}٪
</span>
)}
@@ -112,41 +89,6 @@ export function ProductCard({
) : (
<div className="flex-1">{info}</div>
)}
<div className="p-4">
{price != null && variantId ? (
<button
type="button"
onClick={handleAddToCart}
disabled={status === "busy"}
className="w-full rounded-lg bg-red py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark disabled:cursor-not-allowed disabled:opacity-70"
>
{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>
) : contactPhone ? (
<a
href={`tel:${contactPhone}`}
className="flex w-full items-center justify-center gap-1.5 rounded-lg bg-red py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
>
<span aria-hidden>📞</span>
تماس با فروشگاه
</a>
) : (
<button
type="button"
disabled
className="w-full cursor-not-allowed rounded-lg bg-red/60 py-2 text-sm font-medium text-white"
>
تماس با فروشگاه
</button>
)}
</div>
</article>
);
}
+15 -9
View File
@@ -1,16 +1,20 @@
import { ChevronLeftIcon } from "@/components/ui/icons";
type SectionTitleProps = {
title: string;
enTitle: string;
enTitle?: string;
subtitle?: string;
action?: string;
actionHref?: string;
};
export function SectionTitle({ title, enTitle, subtitle, action }: SectionTitleProps) {
export function SectionTitle({ title, enTitle, subtitle, action, actionHref }: SectionTitleProps) {
return (
<div className="mb-6 flex items-end justify-between gap-4">
<div className="mb-6 flex items-center justify-between gap-4">
<div>
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h2 className="text-xl font-bold text-red-dark md:text-2xl">{title}</h2>
{enTitle && (
<span
className="font-display text-sm font-semibold tracking-wide text-red-dark/30 uppercase md:text-base"
lang="en"
@@ -18,18 +22,20 @@ export function SectionTitle({ title, enTitle, subtitle, action }: SectionTitleP
>
{enTitle}
</span>
)}
</div>
{subtitle && (
<p className="mt-1 text-sm text-muted">{subtitle}</p>
)}
</div>
{action && (
<button
type="button"
className="shrink-0 text-sm font-medium text-red transition-colors hover:text-red-dark"
{action && actionHref && (
<a
href={actionHref}
className="flex shrink-0 items-center gap-1.5 rounded-lg bg-red px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-dark"
>
{action} ←
</button>
{action}
<ChevronLeftIcon className="h-4 w-4" />
</a>
)}
</div>
);
+76
View File
@@ -0,0 +1,76 @@
type IconProps = { className?: string };
// Shared light/outline icon set — thin stroke (1.75), rounded caps/joins,
// 24x24 viewBox, matching the chevrons already used in Carousel/ProductGallery.
// Prefer these over emoji anywhere in the UI.
export function MenuIcon({ className }: IconProps) {
return (
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
<path
d="M4 7h16M4 12h16M4 17h16"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
export function UserIcon({ className }: IconProps) {
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="M4.75 19.25c0-3.45 3.24-6.25 7.25-6.25s7.25 2.8 7.25 6.25"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
/>
</svg>
);
}
export function CartIcon({ className }: IconProps) {
return (
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
<path
d="M3.5 4.5h1.6l1.1 2M6.2 6.5l1.65 7.3a1.5 1.5 0 0 0 1.46 1.17h6.9a1.5 1.5 0 0 0 1.46-1.15l1.23-5.32H6.2Z"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
<circle cx="10" cy="19.5" r="1.15" stroke="currentColor" strokeWidth="1.6" />
<circle cx="16.5" cy="19.5" r="1.15" stroke="currentColor" strokeWidth="1.6" />
</svg>
);
}
export function CloseIcon({ className }: IconProps) {
return (
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
<path
d="M6 6l12 12M18 6 6 18"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
/>
</svg>
);
}
export function ChevronLeftIcon({ className }: IconProps) {
return (
<svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
<path
d="M14.5 6.5 9 12l5.5 5.5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
-147
View File
@@ -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;
}
+34 -81
View File
@@ -1,114 +1,67 @@
"use client";
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { addCartItem, type Cart, getCart, removeCartItem, updateCartItem } from "@/lib/cart";
type ActionResult = { ok: boolean; message?: string };
import {
addToGuestCart,
type GuestCartLine,
getGuestCart,
removeFromGuestCart,
setGuestCartQuantity,
} from "@/lib/guestCart";
type CartContextValue = {
cart: Cart | null;
items: GuestCartLine[];
itemCount: number;
loading: boolean;
subtotal: number;
popupOpen: boolean;
openPopup: () => void;
closePopup: () => void;
businessId: string;
addItem: (storeItemVariantId: string, quantity: number) => Promise<ActionResult>;
updateItem: (itemId: string, quantity: number) => Promise<ActionResult>;
removeItem: (itemId: string) => Promise<ActionResult>;
refresh: () => Promise<void>;
addItem: (line: Omit<GuestCartLine, "quantity"> & { quantity?: number }) => void;
updateItem: (id: string, quantity: number) => void;
removeItem: (id: string) => void;
};
const CartContext = createContext<CartContextValue | null>(null);
export function CartProvider({ businessId, children }: { businessId: string; children: React.ReactNode }) {
const { user, logout } = useAuth();
const [cart, setCart] = useState<Cart | null>(null);
const [loading, setLoading] = useState(false);
export function CartProvider({ children }: { children: React.ReactNode }) {
const [items, setItems] = useState<GuestCartLine[]>([]);
const [popupOpen, setPopupOpen] = useState(false);
// cart.ts always reads the freshest token from storage (and self-refreshes
// on expiry) — gate here only on "is someone logged in at all".
const handleUnauthorized = useCallback(() => {
setCart(null);
logout();
}, [logout]);
const refresh = useCallback(async () => {
if (!user) {
setCart(null);
return;
}
setLoading(true);
const res = await getCart(businessId);
if (res.ok) setCart(res.data);
else if (res.unauthorized) handleUnauthorized();
setLoading(false);
}, [user, businessId, handleUnauthorized]);
// Guest cart lives in localStorage/cookies only — nothing to fetch from a
// server, just read what's already there once mounted in the browser.
useEffect(() => {
refresh();
}, [refresh]);
setItems(getGuestCart());
}, []);
const addItem = useCallback(
async (storeItemVariantId: string, quantity: number): Promise<ActionResult> => {
if (!user) return { ok: false, message: "برای افزودن به سبد باید وارد شوید." };
const res = await addCartItem(businessId, storeItemVariantId, quantity);
if (res.ok) {
setCart(res.data);
const addItem = useCallback((line: Omit<GuestCartLine, "quantity"> & { quantity?: number }) => {
setItems(addToGuestCart(line));
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 updateItem = useCallback((id: string, quantity: number) => {
setItems(setGuestCartQuantity(id, quantity));
}, []);
const removeItem = useCallback(
async (itemId: string): Promise<ActionResult> => {
if (!user) return { ok: false, message: "برای این کار باید وارد شوید." };
const res = await removeCartItem(businessId, itemId);
if (res.ok) {
setCart(res.data);
return { ok: true };
}
if (res.unauthorized) handleUnauthorized();
return { ok: false, message: res.message };
},
[user, businessId, handleUnauthorized],
);
const removeItem = useCallback((id: string) => {
setItems(removeFromGuestCart(id));
}, []);
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const value = useMemo<CartContextValue>(
() => ({
cart,
itemCount: cart?.itemCount ?? 0,
loading,
items,
itemCount,
subtotal,
popupOpen,
openPopup: () => setPopupOpen(true),
closePopup: () => setPopupOpen(false),
businessId,
addItem,
updateItem,
removeItem,
refresh,
}),
[cart, loading, popupOpen, businessId, addItem, updateItem, removeItem, refresh],
[items, itemCount, subtotal, popupOpen, addItem, updateItem, removeItem],
);
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
+2 -7
View File
@@ -1,18 +1,13 @@
"use client";
import { AuthProvider } from "@/context/AuthContext";
import { CartProvider } from "@/context/CartContext";
import { LoginModal } from "@/components/auth/LoginModal";
import { CartPopup } from "@/components/cart/CartPopup";
export function Providers({ businessId, children }: { businessId: string; children: React.ReactNode }) {
export function Providers({ children }: { children: React.ReactNode }) {
return (
<AuthProvider>
<CartProvider businessId={businessId}>
<CartProvider>
{children}
<LoginModal />
<CartPopup />
</CartProvider>
</AuthProvider>
);
}
-211
View File
@@ -1,211 +0,0 @@
// Client-side session storage for Meshkee customer auth. Tokens live in
// localStorage (per-browser, never sent anywhere but api.meshkee.com).
const ACCESS_KEY = "sanihome_access_token";
const REFRESH_KEY = "sanihome_refresh_token";
export type AuthUser = {
id: string;
firstName?: string;
lastName?: string;
cellNumber?: string;
email?: string;
};
export function getStoredTokens(): { accessToken: string; refreshToken: string | null } | null {
if (typeof window === "undefined") return null;
try {
const accessToken = window.localStorage.getItem(ACCESS_KEY);
if (!accessToken) return null;
return { accessToken, refreshToken: window.localStorage.getItem(REFRESH_KEY) };
} catch {
return null;
}
}
export function storeTokens(accessToken: string, refreshToken?: string | null): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(ACCESS_KEY, accessToken);
if (refreshToken) window.localStorage.setItem(REFRESH_KEY, refreshToken);
} catch {
// Private browsing / storage disabled — session just won't persist.
}
}
// Access tokens are short-lived (~15 min). Call this whenever a request
// comes back 401 so the shopper doesn't get silently logged out mid-session.
// Returns the fresh access token, or null if the refresh token is also gone/invalid
// (caller should then clear the session and prompt login again).
//
// AuthContext and CartContext each independently notice an expired token and
// call this — without coordination they'd fire two concurrent /auth/refresh
// requests. If the backend rotates the refresh token on use, the second
// request then fails (observed as a 500/400). This in-flight guard makes
// every concurrent caller share the same single request instead of racing.
let inFlightRefresh: Promise<string | null> | null = null;
export async function refreshAccessToken(): Promise<string | null> {
if (inFlightRefresh) return inFlightRefresh;
inFlightRefresh = (async () => {
const stored = getStoredTokens();
if (!stored?.refreshToken) return null;
try {
const res = await fetch(`${AUTH_API_BASE}/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: stored.refreshToken }),
});
if (!res.ok) {
clearTokens();
return null;
}
const data = (await res.json()) as RawAuthResponse;
const accessToken = data.accessToken ?? data.token ?? data.access_token;
if (!accessToken) return null;
storeTokens(accessToken, data.refreshToken ?? data.refresh_token ?? stored.refreshToken);
return accessToken;
} catch {
return null;
}
})();
try {
return await inFlightRefresh;
} finally {
inFlightRefresh = null;
}
}
export function clearTokens(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.removeItem(ACCESS_KEY);
window.localStorage.removeItem(REFRESH_KEY);
} catch {
// ignore
}
}
const AUTH_API_BASE = "https://api.meshkee.com/api/v1";
export const WEBSITE_DOMAIN = "sanihome.ir";
async function authFetch<T>(
path: string,
options: { method?: string; body?: unknown; token?: string } = {},
): Promise<{ ok: true; data: T } | { ok: false; status: number; message: string }> {
try {
const res = await fetch(`${AUTH_API_BASE}${path}`, {
method: options.method ?? "GET",
headers: {
"Content-Type": "application/json",
...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),
},
body: options.body != null ? JSON.stringify(options.body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return {
ok: false,
status: res.status,
message: (data as { message?: string })?.message ?? "خطایی رخ داد. دوباره تلاش کنید.",
};
}
return { ok: true, data: data as T };
} catch {
return { ok: false, status: 0, message: "ارتباط با سرور برقرار نشد." };
}
}
// The API doesn't document the exact success-response field names for
// login/register/login-otp — accessToken/refreshToken/user is the standard
// shape (confirmed accessToken+refreshToken naming via /auth/refresh's own
// request body, and a `user` wrapper via /auth/me's documented description).
// Read defensively in case a field is nested or named slightly differently.
type RawAuthResponse = {
accessToken?: string;
token?: string;
access_token?: string;
refreshToken?: string;
refresh_token?: string;
user?: Record<string, unknown>;
customer?: Record<string, unknown>;
};
function extractSession(raw: RawAuthResponse): { accessToken: string; refreshToken: string | null; user: AuthUser } | null {
const accessToken = raw.accessToken ?? raw.token ?? raw.access_token;
if (!accessToken) return null;
const refreshToken = raw.refreshToken ?? raw.refresh_token ?? null;
const rawUser = raw.user ?? raw.customer ?? {};
return {
accessToken,
refreshToken,
user: {
id: String(rawUser.id ?? ""),
firstName: rawUser.firstName as string | undefined,
lastName: rawUser.lastName as string | undefined,
cellNumber: rawUser.cellNumber as string | undefined,
email: rawUser.email as string | undefined,
},
};
}
export async function loginWithPassword(cellNumber: string, password: string) {
const res = await authFetch<RawAuthResponse>("/auth/login", {
method: "POST",
body: { cellNumber, password },
});
if (!res.ok) return res;
const session = extractSession(res.data);
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
return { ok: true as const, data: session };
}
export async function loginWithOtp(cellNumber: string, code: string) {
const res = await authFetch<RawAuthResponse>("/auth/login-otp", {
method: "POST",
body: { cellNumber, code },
});
if (!res.ok) return res;
const session = extractSession(res.data);
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
return { ok: true as const, data: session };
}
export async function sendOtp(cellNumber: string) {
return authFetch<{ message?: string }>("/auth/send-otp", {
method: "POST",
body: { cellNumber, domain: WEBSITE_DOMAIN },
});
}
export async function register(input: {
cellNumber: string;
password: string;
firstName: string;
lastName: string;
email?: string;
}) {
const res = await authFetch<RawAuthResponse>("/auth/register", {
method: "POST",
body: { ...input, domain: WEBSITE_DOMAIN },
});
if (!res.ok) return res;
const session = extractSession(res.data);
if (!session) return { ok: false as const, status: 200, message: "پاسخ سرور نامعتبر بود." };
return { ok: true as const, data: session };
}
export async function fetchMe(accessToken: string) {
const res = await authFetch<{ user?: Record<string, unknown> }>("/auth/me", { token: accessToken });
if (!res.ok) return res;
const rawUser = res.data.user ?? {};
const user: AuthUser = {
id: String(rawUser.id ?? ""),
firstName: rawUser.firstName as string | undefined,
lastName: rawUser.lastName as string | undefined,
cellNumber: rawUser.cellNumber as string | undefined,
email: rawUser.email as string | undefined,
};
return { ok: true as const, data: user };
}
-171
View File
@@ -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),
},
};
}
+126
View File
@@ -0,0 +1,126 @@
// Storefront mini-cart per Meshkee's contract (api.meshkee.com/docs/website/AI_PROMPT.md
// — "Shopping cart on the storefront"). This site never calls the real cart/checkout
// API (/businesses/{id}/cart...) — that's the customer dashboard's job. This is a
// local, guest-only cart that gets handed off to customer.<domain> on "Continue".
const STORAGE_KEY = "meshkee-guest-cart";
const DOMAIN = "sanihome.ir";
const MAX_COOKIE_LEN = 3500;
const THIRTY_DAYS = 30 * 24 * 60 * 60;
export type GuestCartLine = {
id: string; // storeItemVariantId — never a product id or store-item id
name: string;
slug: string;
price: number;
originalPrice?: number;
image: string;
quantity: number;
};
function readCart(): GuestCartLine[] {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
return raw ? (JSON.parse(raw) as GuestCartLine[]) : [];
} catch {
return [];
}
}
function writeCart(items: GuestCartLine[]): void {
if (typeof window === "undefined") return;
const json = JSON.stringify(items);
try {
window.localStorage.setItem(STORAGE_KEY, json);
} catch {
// ignore — private browsing / storage disabled
}
try {
const encoded = encodeURIComponent(json);
// Skip the cookie (rely on localStorage + the URL param on Continue)
// when it would blow past a sane cookie size.
if (encoded.length <= MAX_COOKIE_LEN) {
const secure = window.location.protocol === "https:" ? "; Secure" : "";
document.cookie = `${STORAGE_KEY}=${encoded}; Domain=.${DOMAIN}; Path=/; SameSite=Lax; Max-Age=${THIRTY_DAYS}${secure}`;
}
} catch {
// Domain=.sanihome.ir is rejected on hosts that don't match (e.g. local
// dev on localhost) — localStorage still works, cross-domain handoff
// just isn't testable outside the real domain.
}
}
export function getGuestCart(): GuestCartLine[] {
return readCart();
}
export function addToGuestCart(line: Omit<GuestCartLine, "quantity"> & { quantity?: number }): GuestCartLine[] {
const items = readCart();
const quantity = line.quantity ?? 1;
const existing = items.findIndex((i) => i.id === line.id);
if (existing >= 0) {
items[existing] = { ...items[existing], quantity: items[existing].quantity + quantity };
} else {
items.push({
id: line.id,
name: line.name,
slug: line.slug,
price: line.price,
originalPrice: line.originalPrice,
image: line.image,
quantity,
});
}
writeCart(items);
return items;
}
export function setGuestCartQuantity(id: string, quantity: number): GuestCartLine[] {
let items = readCart();
items = quantity <= 0 ? items.filter((i) => i.id !== id) : items.map((i) => (i.id === id ? { ...i, quantity } : i));
writeCart(items);
return items;
}
export function removeFromGuestCart(id: string): GuestCartLine[] {
return setGuestCartQuantity(id, 0);
}
// Base64url-encode the cart for the `guestCart` query param — exact algorithm
// from the AI_PROMPT.md spec so the customer dashboard can decode it.
export function encodeGuestCart(items: GuestCartLine[]): string {
const json = JSON.stringify(items);
return btoa(unescape(encodeURIComponent(json)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
function readCookie(name: string): string | undefined {
if (typeof document === "undefined") return undefined;
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return match?.[1];
}
// The customer dashboard writes this on login (Domain=.sanihome.ir), so it's
// readable here too — chunked as `_0`, `_1`, ... when long.
export function isCustomerLoggedIn(): boolean {
return (
readCookie("meshkee_customer_access_token") != null ||
readCookie("meshkee_customer_access_token_0") != null
);
}
export function customerDashboardOrigin(): string {
return `https://customer.${DOMAIN}`;
}
// Where the mini-cart's "Continue" button sends the shopper: the dashboard's
// cart page carrying the guest cart, or its login page (redirecting back to
// that same cart page) when no session cookie is present yet.
export function continueToCheckoutUrl(items: GuestCartLine[]): string {
const encoded = encodeGuestCart(items);
const cartPath = `/checkout/cart?guestCart=${encoded}`;
if (isCustomerLoggedIn()) return `${customerDashboardOrigin()}${cartPath}`;
return `${customerDashboardOrigin()}/login?redirect=${encodeURIComponent(cartPath)}`;
}
+107 -21
View File
@@ -21,10 +21,9 @@ async function apiGet<T>(
}
}
// POST helper for the handful of public, unauthenticated write endpoints
// (contact form, comments) — distinct from the cart/auth flows in
// lib/cart.ts and lib/auth.ts, which need a Bearer token and browser-only
// APIs (localStorage) this module (used from Server Components too) avoids.
// POST helper for the public, unauthenticated write endpoints this storefront
// is allowed to call directly (contact form, comments). Cart/checkout/auth
// are the customer dashboard's job, not this site's — see lib/guestCart.ts.
async function apiPost<T>(
path: string,
body: Record<string, unknown>,
@@ -45,6 +44,31 @@ async function apiPost<T>(
}
}
/** Full sanitized `<meta …>` HTML from business-info. */
export type BusinessMetaTag = {
html: string;
};
/** Parse a single `<meta …>` tag into React/Next attribute props. */
export function parseMetaTagHtml(html: string): Record<string, string> | null {
const match = html.trim().match(/^<meta\b([^>]*)\/?\s*>$/i);
if (!match) return null;
const attrs: Record<string, string> = {};
const attrRe = /([:\w.-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
let m: RegExpExecArray | null;
while ((m = attrRe.exec(match[1]))) {
const key = m[1].toLowerCase();
if (key === '/') continue;
attrs[key] = m[2] ?? m[3] ?? m[4] ?? '';
}
return Object.keys(attrs).length > 0 ? attrs : null;
}
export type BusinessTrustBadge = {
kind: "enamad" | "samandehi";
embedHtml: string;
};
export type BusinessInfo = {
id: string;
name: string;
@@ -52,6 +76,7 @@ export type BusinessInfo = {
about: string;
vision: string;
logoUrl: string | null;
logoDarkUrl: string | null;
faviconUrl: string | null;
emails: string[];
phoneNumbers: string[];
@@ -64,6 +89,8 @@ export type BusinessInfo = {
aparat?: string;
};
addresses: string[];
metaTags?: BusinessMetaTag[];
trustBadges?: BusinessTrustBadge[];
};
export async function getBusinessInfo(): Promise<BusinessInfo | null> {
@@ -145,6 +172,7 @@ export type Product = {
// brand-groups, store-items — lets "add to cart" skip a variant picker).
variantId?: string;
stockQuantity?: number;
categoryId?: string;
};
function normalizeProduct(raw: Record<string, unknown>): Product {
@@ -195,6 +223,12 @@ function normalizeProduct(raw: Record<string, unknown>): Product {
variantId: firstVariant?.id != null ? String(firstVariant.id) : undefined,
stockQuantity:
firstVariant?.stockQuantity != null ? Number(firstVariant.stockQuantity) : undefined,
categoryId:
raw.categoryId != null
? String(raw.categoryId)
: (raw.category as Record<string, unknown> | undefined)?.id != null
? String((raw.category as Record<string, unknown>).id)
: undefined,
price: numericPrice,
oldPrice: numericOldPrice,
discount,
@@ -211,11 +245,12 @@ function normalizeProduct(raw: Record<string, unknown>): Product {
}
export function productHref(product: Product): string {
if (product.slug) return `/products/${product.slug}`;
if (product.variantId) return `/store-items/${product.variantId}`;
if (product.slug) return `/store-items/${product.slug}`;
// No slug (store-specials/brand-groups/store-items don't return one) — route
// through the id-based resolver, which redirects to the canonical slug page.
if (product.id) return `/products/id/${product.id}`;
return `/products?q=${encodeURIComponent(product.name)}`;
if (product.id) return `/store-items/${product.id}`;
return `/store-items?q=${encodeURIComponent(product.name)}`;
}
export async function getProducts(params?: {
@@ -344,13 +379,47 @@ export async function getProductStoreVariants(productId: string): Promise<Produc
export type TechnicalInfoField = { label: string; value: string };
export async function getProductTechnicalInfo(slug: string): Promise<TechnicalInfoField[]> {
const res = await apiGet<{ form: unknown; values: Record<string, unknown>[] }>(
const res = await apiGet<{
form: { fields?: Record<string, unknown>[] } | null;
values: Record<string, unknown>[];
}>(
`/tenants/${DOMAIN}/products/${slug}/technical-info`,
);
return (res?.values ?? []).map((v) => ({
label: String(v.label ?? v.name ?? v.key ?? ""),
value: String(v.value ?? ""),
}));
const submittedValues = res?.values ?? [];
const valuesByFieldId = new Map(
submittedValues
.filter((value) => value.fieldId != null)
.map((value) => [String(value.fieldId), value]),
);
const valuesByFieldKey = new Map(
submittedValues
.filter((value) => value.fieldKey != null)
.map((value) => [String(value.fieldKey), value]),
);
return [...(res?.form?.fields ?? [])]
.sort((a, b) => Number(a.sortOrder ?? 0) - Number(b.sortOrder ?? 0))
.map((field) => {
const fieldId = String(field.id ?? "");
const fieldKey = String(field.key ?? "");
const submitted = valuesByFieldId.get(fieldId) ?? valuesByFieldKey.get(fieldKey);
if (!submitted) return null;
const options = (field.options as Record<string, unknown>[] | undefined) ?? [];
const optionLabel = (optionId: unknown) => {
const option = options.find((item) => String(item.id ?? "") === String(optionId ?? ""));
return option ? String(option.label ?? option.value ?? option.name ?? "") : "";
};
const selectedOptionIds = Array.isArray(submitted.optionIds) ? submitted.optionIds : [];
const value =
String(submitted.textValue ?? submitted.value ?? "").trim() ||
optionLabel(submitted.optionId) ||
selectedOptionIds.map(optionLabel).filter(Boolean).join("، ");
const label = String(field.label ?? field.labelFa ?? field.name ?? field.key ?? "").trim();
return label && value ? { label, value } : null;
})
.filter((field): field is TechnicalInfoField => field !== null);
}
export type StoreItem = {
@@ -440,6 +509,7 @@ export type BlogSummary = {
image?: string | null;
publishedAt?: string;
categoryName?: string;
categoryId?: string;
};
function normalizeBlog(raw: Record<string, unknown>): BlogSummary {
@@ -451,6 +521,7 @@ function normalizeBlog(raw: Record<string, unknown>): BlogSummary {
image: (raw.titleImageUrl as string | undefined) ?? null,
publishedAt: raw.publishedAt as string | undefined,
categoryName: raw.categoryName as string | undefined,
categoryId: raw.categoryId != null ? String(raw.categoryId) : undefined,
};
}
@@ -491,27 +562,32 @@ export type ProductGroup = {
id: string;
key: string;
title: string;
sortOrder: number;
items: Product[];
};
export function isSpecialSaleGroup(group: Pick<ProductGroup, "title" | "key">): boolean {
return /فروش\s*ویژه|special[\s_-]*sale/i.test(`${group.title} ${group.key}`);
}
function normalizeProductGroups(items: Record<string, unknown>[] | undefined): ProductGroup[] {
return (items ?? []).map((group) => ({
return (items ?? [])
.map((group) => ({
id: String(group.id ?? group.key ?? ""),
key: String(group.key ?? group.id ?? ""),
title: String(group.title ?? ""),
sortOrder: Number(group.sortOrder ?? 0),
items: Array.isArray(group.items)
? (group.items as Record<string, unknown>[]).map(normalizeProduct)
: [],
}));
}
export async function getBrandGroups(): Promise<ProductGroup[]> {
const res = await apiGet<{ items: Record<string, unknown>[] }>(
`/tenants/${DOMAIN}/website/brand-groups`,
);
return normalizeProductGroups(res?.items);
}))
.sort((a, b) => a.sortOrder - b.sortOrder);
}
// Admin-managed, named product carousels ("Special Sale", "پرفروش‌ها",
// "بهترین‌ها از نگاه شما", ...) — the whole list, not a fixed set of known
// keys, so a new one created in the dashboard shows up on the homepage
// automatically. See StoreSpecialCarousels.tsx.
export async function getStoreSpecials(): Promise<ProductGroup[]> {
const res = await apiGet<{ items: Record<string, unknown>[] }>(
`/tenants/${DOMAIN}/store-specials`,
@@ -582,6 +658,7 @@ export const STATIC_IMAGE_KEYS = {
twoBanner: "two-banner",
threeBannerRow: "three-banner-row",
featuredCategories: "featured-categories",
aboutUsImage: "about-us-image",
} as const;
export const STATIC_IMAGE_SLOT_CATALOG = [
@@ -621,6 +698,15 @@ export const STATIC_IMAGE_SLOT_CATALOG = [
itemCount: null,
recommendedWidth: 300,
},
{
key: STATIC_IMAGE_KEYS.aboutUsImage,
label: "Homepage about-us image",
kind: "single" as const,
pageKey: "home",
aspectRatio: "14:9",
itemCount: 1,
recommendedWidth: 560,
},
];
export async function getStaticImageSlots(): Promise<StaticImageSlot[]> {