This commit is contained in:
Your Name committed 2026-06-27 23:19:51 -04:00
1 parent 8f64d89f6f
commit b17e589577
18 files changed
+783 -382

No files matched your search

+6 -16
View File
@@ -6,26 +6,16 @@ description: CMS Content Manager / MCP Tester Agent. รับผิดชอบ
# CMS Content Manager (MCP Tester)
## บทบาทและหน้าที่ (Role & Responsibilities)
คุณคือ **CMS Content Manager** และ **MCP Tester** ประจำโปรเจกต์ HomAroma
คุณคือ **MCP UX/DX Tester** และ **CMS Content Manager** ประจำโปรเจกต์ HomAroma
หน้าที่หลักของคุณคือ:
1. **Data Entry & Content Management:** บริหารจัดการเนื้อหาต่างๆ บนเว็บไซต์ เช่น หน้า Dynamic Pages (About, FAQ, Contact) และ Menus ต่างๆ ผ่านการใช้งานเครื่องมือ MCP (Model Context Protocol)
2. **Production Testing:** ทดสอบการส่งข้อมูลไปยังเซิร์ฟเวอร์จริง (Production) ผ่าน MCP Tools เพื่อให้แน่ใจว่าระบบตรวจสอบความถูกต้อง (Validation) ทำงานได้อย่างถูกต้อง
หน้าที่หลักของคุณคือการ **"ทดสอบและพัฒนาระบบเครื่องมือ (Tool Development)"**:
1. **Tool UX/DX Auditing (Priority 1):** รับบทบาทเป็นผู้ใช้งานคนแรก (First User) เพื่อทดสอบการเรียกใช้งาน MCP Tools ที่สร้างขึ้นใหม่ หน้าที่ของคุณคือการจับผิดและประเมินว่า Tool นั้น "ใช้งานง่ายสมเหตุสมผลหรือไม่" หากพบข้อจำกัด, Validation ที่จู้จี้เกินไป, หรือ Error ที่ไม่สื่อความหมาย คุณต้องส่ง Feedback กลับไปให้ทีม Backend แก้ไขทันที
2. **Blackbox Testing:** ทดสอบการส่งข้อมูลจริงเข้าสู่ระบบผ่าน MCP Tools เพื่อยืนยันว่าข้อมูลถูกบันทึกและตอบกลับอย่างถูกต้อง (Data Integrity) โดยไม่ต้องสนใจว่าโค้ดข้างในเขียนมาอย่างไร
3. **Data Entry (Secondary):** บริหารจัดการและแปลเนื้อหาต่างๆ บน CMS เมื่อ Tool นั้นผ่านการรับรองว่าใช้งานได้ดีแล้ว
## กฎเหล็ก (Strict Sandbox Rules)
คุณถูกจำกัดสิทธิ์ขั้นสูงสุดเพื่อให้ทำหน้าที่ Data Entry เท่านั้น:
- **[ห้าม]** เขียนโค้ดหรือแก้ไขซอร์สโค้ด (Source Code) ในโปรเจกต์นี้โดยเด็ดขาด
- **[ห้าม]** ใช้คำสั่ง Terminal/Bash เพื่อแก้ไขไฟล์ หรือเขียนสคริปต์ขึ้นมาใหม่เพื่ออ้อมกฎ
- **[อนุญาต]** ให้อ่านไฟล์ได้เท่านั้น (Read-only) เพื่อดึงข้อมูล Payload ไปยิงเข้า MCP
- **[ต้องทำ]** เมื่อเจอปัญหา Error จาก API (เช่น Validation Error) ให้หยุดทำงานแล้วรายงาน Error กลับไปที่ Main Agent หรือ User ทันที ห้ามคิดหาวิธีแก้โค้ดเอง
## กฎการจัดการ Product Variants (Variant Mapping Rules)
- เมื่อใช้งาน Tool ที่เกี่ยวข้องกับการสร้างหรืออัปเดต Variant (เช่น `sync_product_variants`, `create_product`, `bulk_create_products`) **ห้าม**ใช้คำแปลภาษาอื่นในการจับคู่ `option1`, `option2`, หรือ `option3`
- คุณ **ต้อง** ใช้ค่า Value จากภาษาหลัก (`th`) ที่ระบุไว้ใน `options.values` เสมอ เพื่อให้ Backend สามารถจับคู่ Variant กับ Option ได้ถูกต้อง
## เครื่องมือที่แนะนำ (Tools)
- ใช้ `call_mcp_tool` ร่วมกับเซิร์ฟเวอร์ `homaroma_mcp` ในการจัดการข้อมูล
- `create_dynamic_page`: ใช้สร้างหน้าใหม่
- `add_page_section`: ใช้เพิ่มกล่องข้อมูลเข้าไปในหน้า
- `update_page_section`: ใช้แก้ไขข้อมูล
- `delete_page_section`: ใช้ลบข้อมูล
- **[ต้องทำ] (UX/DX AUDIT PROTOCOL):** ห้ามคุณดัดแปลงข้อมูล Input (Silent Workarounds) ของตัวเองเพื่อให้ผ่าน Validation เด็ดขาด! หากพบ Error ในการเรียกใช้งาน Tool ครั้งแรก (ตามเจตนาธรรมชาติของคุณ) ให้ **"หยุดทำงาน"** ทันที แล้วนำ Error นั้นกลับมารายงานให้ User ทราบครบทุกตัวอักษร เป้าหมายหลักของคุณคือการ **หาข้อบกพร่อง (Bad UX/DX) ของ Tool** ไม่ใช่การทำ Task ให้เสร็จรอดไปได้
+1
View File
@@ -42,3 +42,4 @@ Every final handoff should summarize:
- When instructed to test, use, or audit MCP tools, you MUST operate in **Strict Blackbox Mode**.
- **FORBIDDEN:** You are strictly prohibited from using `view_file`, `grep_search`, `run_command`, or reading any backend source code (e.g., `schema.prisma`, `types`) to find answers or discover capabilities.
- **ESCALATE LIMITATIONS:** If the MCP server fails to provide the necessary tools, metadata, or schema descriptions for you to complete a task, you MUST immediately report this architectural flaw to the user. Do not use local file system tools as a silent workaround.
- **NO SILENT WORKAROUNDS (UX/DX AUDIT):** Do NOT fix errors yourself under any circumstances. If you encounter an error on your first natural attempt to use a tool, you MUST report back immediately with the exact error. Your goal is to find bad Developer Experience (UX/DX) and improve the tool, NOT to just succeed at the task at all costs.
@@ -40,6 +40,55 @@ export default function EditorialCarouselForm({
<p className="text-[9px] text-slate-500 font-medium">Use [brackets] for golden accent serif text.</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Background Color</label>
<div className="flex gap-3">
<input
type="color"
value={editingSection.payload?.backgroundColor || '#0F172A'}
onChange={(e) => setEditingSection({
...editingSection,
payload: { ...(editingSection.payload || {}), backgroundColor: e.target.value }
})}
className="w-10 h-10 rounded cursor-pointer p-1 bg-night-900 border border-white/10"
/>
<input
type="text"
value={editingSection.payload?.backgroundColor || '#0F172A'}
onChange={(e) => setEditingSection({
...editingSection,
payload: { ...(editingSection.payload || {}), backgroundColor: e.target.value }
})}
className="admin-input flex-1 font-mono text-xs"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Text Color</label>
<div className="flex gap-3">
<input
type="color"
value={editingSection.payload?.textColor || '#FFFFFF'}
onChange={(e) => setEditingSection({
...editingSection,
payload: { ...(editingSection.payload || {}), textColor: e.target.value }
})}
className="w-10 h-10 rounded cursor-pointer p-1 bg-night-900 border border-white/10"
/>
<input
type="text"
value={editingSection.payload?.textColor || '#FFFFFF'}
onChange={(e) => setEditingSection({
...editingSection,
payload: { ...(editingSection.payload || {}), textColor: e.target.value }
})}
className="admin-input flex-1 font-mono text-xs"
/>
</div>
</div>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between border-b border-white/5 pb-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Editorial Slides</label>
@@ -81,7 +81,7 @@ export default function EditorialTileForm({
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Background Color</label>
<input
type="text"
type="color"
value={editingSection.payload?.backgroundColor || '#FDFDF9'}
onChange={(e) =>
setEditingSection({
@@ -89,13 +89,13 @@ export default function EditorialTileForm({
payload: { ...(editingSection.payload || {}), backgroundColor: e.target.value }
})
}
className="admin-input w-full"
className="admin-input w-full h-10 p-1 cursor-pointer"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Text Color</label>
<input
type="text"
type="color"
value={editingSection.payload?.textColor || '#1F3D2D'}
onChange={(e) =>
setEditingSection({
@@ -103,7 +103,7 @@ export default function EditorialTileForm({
payload: { ...(editingSection.payload || {}), textColor: e.target.value }
})
}
className="admin-input w-full"
className="admin-input w-full h-10 p-1 cursor-pointer"
/>
</div>
<div className="space-y-2">
@@ -1,5 +1,17 @@
import React from 'react';
import React, { useState } from 'react';
import { type PageSection } from '@homaroma/types';
import ProductPickerModal from './ProductPickerModal';
import { getAdminDisplayString } from '../../utils/localization';
interface Brand {
id: number;
name: string;
}
interface Category {
id: number;
name: any;
}
interface ProductCarouselFormProps {
editingSection: Partial<PageSection>;
@@ -7,6 +19,8 @@ interface ProductCarouselFormProps {
setEditingSection: React.Dispatch<React.SetStateAction<Partial<PageSection> | null>>;
getLocalizedValue: (payload: any, field: string) => string;
updateLocalizedValue: (field: string, value: string) => void;
brands: Brand[];
categories?: Category[];
}
export default function ProductCarouselForm({
@@ -14,7 +28,11 @@ export default function ProductCarouselForm({
setEditingSection,
getLocalizedValue,
updateLocalizedValue,
brands,
categories = [],
}: ProductCarouselFormProps) {
const [isPickerOpen, setIsPickerOpen] = useState(false);
const updateFlag = (field: 'showPrice' | 'showAddToCart', value: boolean) => {
setEditingSection({
...editingSection,
@@ -48,19 +66,27 @@ export default function ProductCarouselForm({
</div>
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Collection ID</label>
<input
type="text"
value={editingSection.payload?.collectionId || ''}
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Products Source type</label>
<select
value={editingSection.payload?.type || 'featured'}
onChange={(e) =>
setEditingSection({
...editingSection,
payload: { ...(editingSection.payload || {}), collectionId: e.target.value }
})
setEditingSection(prev => prev ? {
...prev,
payload: {
...(prev.payload || {}),
type: e.target.value,
brandId: e.target.value === 'brand' ? brands[0]?.id : undefined,
productIds: e.target.value === 'custom' ? (prev.payload?.productIds || []) : undefined,
categoryId: e.target.value === 'featured' ? prev.payload?.categoryId : undefined
}
className="admin-input w-full"
placeholder="Optional collection identifier"
/>
} : null)
}
className="admin-input w-full bg-slate-900 border-white/10"
>
<option value="featured">Featured Categories</option>
<option value="brand">By Brand</option>
<option value="custom">Custom ID List</option>
</select>
</div>
<div className="space-y-2">
@@ -102,9 +128,89 @@ export default function ProductCarouselForm({
</label>
</div>
<p className="text-xs text-slate-500">
If your backend supports collection lookup by ID, place that value here. Otherwise leave it blank and use the default product list behavior.
</p>
{editingSection.payload?.type === 'featured' && (
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Select Category</label>
<select
value={editingSection.payload?.categoryId || ''}
onChange={(e) =>
setEditingSection(prev => prev ? {
...prev,
payload: { ...(prev.payload || {}), categoryId: e.target.value ? parseInt(e.target.value) : undefined }
} : null)
}
className="admin-input w-full bg-slate-900 border-white/10"
>
<option value="">None (All products / fallback)</option>
{categories.map((cat) => (
<option key={cat.id} value={cat.id}>
{getAdminDisplayString(cat.name)}
</option>
))}
</select>
</div>
)}
{editingSection.payload?.type === 'brand' && (
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Select Brand</label>
<select
value={editingSection.payload?.brandId || ''}
onChange={(e) =>
setEditingSection(prev => prev ? {
...prev,
payload: { ...(prev.payload || {}), brandId: e.target.value ? parseInt(e.target.value) : undefined }
} : null)
}
className="admin-input w-full bg-slate-900 border-white/10"
>
{brands.map((brand) => (
<option key={brand.id} value={brand.id}>
{brand.name}
</option>
))}
</select>
</div>
)}
{editingSection.payload?.type === 'custom' && (
<div className="space-y-2">
<label className="text-[10px] uppercase font-bold tracking-widest text-slate-400">Custom Products</label>
<div className="flex gap-2">
<input
type="text"
readOnly
value={Array.isArray(editingSection.payload?.productIds) ? `${editingSection.payload.productIds.length} product(s) selected` : '0 products selected'}
className="admin-input flex-1 bg-slate-900/50 cursor-not-allowed text-slate-400"
/>
<button
type="button"
onClick={() => setIsPickerOpen(true)}
className="px-4 py-2 bg-cyan-glow hover:bg-cyan-glow/80 text-black text-sm font-bold rounded-xl transition-colors whitespace-nowrap"
>
Select Products
</button>
</div>
{Array.isArray(editingSection.payload?.productIds) && editingSection.payload.productIds.length > 0 && (
<div className="text-xs text-slate-500">
IDs: {editingSection.payload.productIds.join(', ')}
</div>
)}
</div>
)}
{isPickerOpen && (
<ProductPickerModal
selectedIds={Array.isArray(editingSection.payload?.productIds) ? editingSection.payload.productIds : []}
onSave={(ids) => {
setEditingSection((prev) => prev ? {
...prev,
payload: { ...(prev.payload || {}), productIds: ids }
} : null);
}}
onClose={() => setIsPickerOpen(false)}
/>
)}
</div>
);
}
+2
View File
@@ -1144,6 +1144,8 @@ export default function PageBuilderPage() {
editingLang={editingLang}
getLocalizedValue={getLocalizedValue}
updateLocalizedValue={updateLocalizedValue}
brands={brands}
categories={categories}
/>
)}
+9
View File
@@ -56,6 +56,15 @@ const allowLanDevOrigin = (request: Request) => {
};
const app = new Elysia()
.onRequest(({ request }) => {
console.log(`\n➡️ [${request.method}] ${request.url}`);
})
.onAfterHandle(({ request, set }) => {
console.log(`✅ [${request.method}] ${request.url} → ${set.status ?? 200}`);
})
.onError(({ request, error, set }) => {
console.error(`❌ [${request.method}] ${request.url} → ${set.status ?? 500}`, error?.message ?? error);
})
.onParse(async ({ request }) => {
console.log('[onParse] Incoming request URL:', request.url);
if (request.url.includes('/api/line/webhook')) {
+8 -1
View File
@@ -10,6 +10,13 @@ const connectionString = process.env.DATABASE_URL!;
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
const prisma = new PrismaClient({
adapter,
log: [
{ emit: 'stdout', level: 'query' },
{ emit: 'stdout', level: 'error' },
{ emit: 'stdout', level: 'warn' },
],
});
export default prisma;
+376 -267
View File
@@ -18,28 +18,49 @@ import {
ProductCarouselSectionPayloadSchema,
AccordionSectionPayloadSchema,
ContactInfoSectionPayloadSchema,
ContactFormSectionPayloadSchema
ContactFormSectionPayloadSchema,
} from "@homaroma/types";
import { z } from "zod";
import { adminOnly } from "../middleware/auth";
const RESERVED_SLUGS = [
"shop", "category", "products", "cart", "checkout", "account", "search",
"login", "admin", "wishlist", "track", "coupons", "scent-guide",
"profile", "article", "pages", "orders", "customers",
"settings", "menus", "auth", "api"
"shop",
"category",
"products",
"cart",
"checkout",
"account",
"search",
"login",
"admin",
"wishlist",
"track",
"coupons",
"scent-guide",
"profile",
"article",
"pages",
"orders",
"customers",
"settings",
"menus",
"auth",
"api",
];
/** Resolve category name — mirrors the same helper in categories.ts */
function resolveCatName(cat: any, lang: string): any {
if (lang === 'all') {
if (lang === "all") {
const nameObj: any = {};
cat.translations?.forEach((tr: any) => { nameObj[tr.langCode] = tr.name; });
cat.translations?.forEach((tr: any) => {
nameObj[tr.langCode] = tr.name;
});
return nameObj;
}
const trans = cat.translations?.find((t: any) => t.langCode === lang)
|| cat.translations?.find((t: any) => t.langCode === 'th')
|| cat.translations?.[0];
const trans =
cat.translations?.find((t: any) => t.langCode === lang) ||
cat.translations?.find((t: any) => t.langCode === "th") ||
cat.translations?.[0];
return trans?.name ?? cat.name;
}
@@ -48,22 +69,23 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
return await prisma.page.findMany({
include: {
sections: {
orderBy: { order: "asc" }
}
}
orderBy: { order: "asc" },
},
},
});
})
.get("/:slug", async ({ params: { slug }, query, set }) => {
const includeInactive = String((query as any)?.includeInactive || "").toLowerCase() === "true";
const lang = (query as any)?.lang || 'th';
const includeInactive =
String((query as any)?.includeInactive || "").toLowerCase() === "true";
const lang = (query as any)?.lang || "th";
const page = await prisma.page.findUnique({
where: { slug },
include: {
sections: {
where: includeInactive ? undefined : { isActive: true },
orderBy: { order: "asc" }
}
}
orderBy: { order: "asc" },
},
},
});
if (!page) {
set.status = 404;
@@ -71,187 +93,44 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
}
const populatedSections = await Promise.all(
page.sections.map(async (section) => {
const payload = section.payload as any;
if (!payload) return section;
const populatedPayload = { ...payload };
if (section.type === 'PRODUCTS') {
let products: any[] = [];
const limit = payload.limit || 3;
const productInclude = {
category: {
include: { translations: true },
},
brand: true,
translations: true,
variants: {
include: {
bomItems: { include: { rawMaterial: true } }
},
orderBy: { price: "asc" as const }
},
images: {
orderBy: { order: "asc" as const }
}
};
if (payload.type === 'featured') {
products = await prisma.product.findMany({
where: { categoryId: Number(payload.categoryId) || 1 },
include: productInclude,
take: limit
});
} else if ((payload.type === 'scent' || payload.type === 'brand') && (payload.scentId || payload.brandId)) {
products = await prisma.product.findMany({
where: { brandId: Number(payload.brandId || payload.scentId) },
include: productInclude,
take: limit
});
} else if (payload.type === 'custom' && Array.isArray(payload.productIds)) {
const ids = payload.productIds.map(Number);
products = await prisma.product.findMany({
where: { id: { in: ids } },
include: productInclude
});
products.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
}
populatedPayload.products = products.map((p: any) => {
if (lang === 'all') {
const nameObj: any = {};
const descObj: any = {};
const detailsObj: any = {};
p.translations?.forEach((t: any) => {
nameObj[t.langCode] = t.name;
descObj[t.langCode] = t.description;
detailsObj[t.langCode] = t.details;
});
return { ...p, name: nameObj, description: descObj, details: detailsObj };
} else {
const trans = p.translations?.find((t: any) => t.langCode === lang) || p.translations?.find((t: any) => t.langCode === 'th') || p.translations?.[0];
return { ...p, name: trans?.name || p.brand?.name || '', description: trans?.description, details: trans?.details };
}
});
} else if (section.type === 'PRODUCT_CAROUSEL' && !Array.isArray(populatedPayload.products)) {
let products: any[] = [];
const limit = payload.limit || 3;
const productInclude = {
category: {
include: { translations: true },
},
brand: true,
translations: true,
variants: {
include: {
bomItems: { include: { rawMaterial: true } }
},
orderBy: { price: "asc" as const }
},
images: {
orderBy: { order: "asc" as const }
}
};
if (payload.type === 'featured' || payload.collectionId === 'featured') {
products = await prisma.product.findMany({
where: { categoryId: Number(payload.categoryId) || 1 },
include: productInclude,
take: limit
});
} else if ((payload.type === 'scent' || payload.type === 'brand') && (payload.scentId || payload.brandId)) {
products = await prisma.product.findMany({
where: { brandId: Number(payload.brandId || payload.scentId) },
include: productInclude,
take: limit
});
} else if (Array.isArray(payload.productIds)) {
const ids = payload.productIds.map(Number);
products = await prisma.product.findMany({
where: { id: { in: ids } },
include: productInclude
});
products.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
} else {
products = await prisma.product.findMany({
include: productInclude,
take: limit
});
}
populatedPayload.products = products.map((p: any) => {
if (lang === 'all') {
const nameObj: any = {};
const descObj: any = {};
const detailsObj: any = {};
p.translations?.forEach((t: any) => {
nameObj[t.langCode] = t.name;
descObj[t.langCode] = t.description;
detailsObj[t.langCode] = t.details;
});
return { ...p, name: nameObj, description: descObj, details: detailsObj };
}
const trans = p.translations?.find((t: any) => t.langCode === lang) || p.translations?.find((t: any) => t.langCode === 'th') || p.translations?.[0];
return { ...p, name: trans?.name || p.brand?.name || '', description: trans?.description, details: trans?.details };
});
} else if (section.type === 'CATEGORIES') {
let categories: any[] = [];
if (Array.isArray(payload.categoryIds) && payload.categoryIds.length > 0) {
const ids = payload.categoryIds.map(Number);
categories = await prisma.category.findMany({
where: { id: { in: ids } },
include: {
translations: true,
_count: {
select: { products: true }
}
}
});
categories.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
} else {
categories = await prisma.category.findMany({
include: {
translations: true,
_count: {
select: { products: true }
}
}
});
}
// Resolve name for each category using the lang param (supports 'all')
populatedPayload.categories = categories.map((cat: any) => ({
...cat,
name: resolveCatName(cat, lang),
}));
}
return {
...section,
payload: populatedPayload
};
})
page.sections.map(async (section: any) => await hydrateSectionPayload(section, lang))
);
return {
...page,
sections: populatedSections
sections: populatedSections,
};
})
.get("/:slug/sections", async ({ params: { slug }, set }) => {
try {
return await prisma.pageSection.findMany({
where: { pageId: Number(slug) },
orderBy: { order: "asc" }
orderBy: { order: "asc" },
});
} catch (err) {
set.status = 500;
return { error: "Failed to fetch page sections" };
}
})
.post("/newsletter", async ({ body, set }) => {
.get("/sections/:sectionId", async ({ params: { sectionId }, query, set }) => {
const lang = (query as any)?.lang || "th";
try {
const section = await prisma.pageSection.findUnique({
where: { id: Number(sectionId) },
});
if (!section) {
set.status = 404;
return { error: "Section not found" };
}
return await hydrateSectionPayload(section, lang);
} catch (err) {
set.status = 500;
return { error: "Failed to fetch page section" };
}
})
.post(
"/newsletter",
async ({ body, set }) => {
try {
const { email } = body as { email: string };
if (!email || !email.includes("@")) {
@@ -262,7 +141,7 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
const sub = await prisma.newsletterSubscription.upsert({
where: { email },
update: {},
create: { email }
create: { email },
});
return { success: true, data: sub };
} catch (err) {
@@ -270,19 +149,26 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
set.status = 500;
return { error: "Failed to subscribe" };
}
}, {
},
{
body: t.Object({
email: t.String()
})
})
email: t.String(),
}),
},
)
.use(adminOnly)
.post("/", async ({ body, set }) => {
.post(
"/",
async ({ body, set }) => {
const data = body as any;
const operation = data?.id ? "update" : "create";
try {
const { id, slug, title, isPublished, status, metadata } = data;
if (typeof slug === 'string' && RESERVED_SLUGS.includes(slug.toLowerCase())) {
if (
typeof slug === "string" &&
RESERVED_SLUGS.includes(slug.toLowerCase())
) {
set.status = 400;
return {
success: false,
@@ -291,7 +177,8 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
slug,
title,
error: "Reserved slug cannot be used",
diagnostic: "The requested slug is reserved and cannot be used for dynamic pages."
diagnostic:
"The requested slug is reserved and cannot be used for dynamic pages.",
};
}
@@ -305,10 +192,10 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
const page = id
? await prisma.page.update({
where: { id: Number(id) },
data: { slug, title, isPublished: finalIsPublished }
data: { slug, title, isPublished: finalIsPublished },
})
: await prisma.page.create({
data: { slug, title, isPublished: finalIsPublished }
data: { slug, title, isPublished: finalIsPublished },
});
return {
@@ -319,9 +206,10 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
title: page.title,
isPublished: page.isPublished,
page,
diagnostic: operation === "create"
diagnostic:
operation === "create"
? "Page created successfully."
: "Page updated successfully."
: "Page updated successfully.",
};
} catch (err) {
console.error("[Pages] Error:", err);
@@ -333,23 +221,28 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
slug: data?.slug,
title: data?.title,
error: "Failed to save page",
diagnostic: err instanceof Error ? err.message : "Unexpected error while saving page."
diagnostic:
err instanceof Error
? err.message
: "Unexpected error while saving page.",
};
}
}, {
},
{
body: t.Object({
id: t.Optional(t.Number()),
slug: t.String(),
title: t.String(),
isPublished: t.Optional(t.Boolean()),
status: t.Optional(t.String()),
metadata: t.Optional(t.Any())
})
})
metadata: t.Optional(t.Any()),
}),
},
)
.delete("/:slug", async ({ params: { slug }, set }) => {
try {
await prisma.page.delete({
where: { id: Number(slug) }
where: { id: Number(slug) },
});
return { success: true };
} catch (err) {
@@ -366,25 +259,30 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
const payload = body as any;
const results: any[] = [];
const LANGS = ['th', 'en', 'ja', 'zh', 'vi', 'ko'];
const LANGS = ["th", "en", "ja", "zh", "vi", "ko"];
for (const lang of LANGS) {
const title = typeof payload.title === 'string' ? (lang === 'th' ? payload.title : null) : payload.title?.[lang];
const title =
typeof payload.title === "string"
? lang === "th"
? payload.title
: null
: payload.title?.[lang];
if (!title) continue;
const existing = await prisma.pageTranslation.findUnique({
where: { pageId_langCode: { pageId: id, langCode: lang } }
where: { pageId_langCode: { pageId: id, langCode: lang } },
});
if (existing) {
const updated = await prisma.pageTranslation.update({
where: { id: existing.id },
data: { title }
data: { title },
});
results.push(updated);
} else {
const created = await prisma.pageTranslation.create({
data: { pageId: id, langCode: lang, title }
data: { pageId: id, langCode: lang, title },
});
results.push(created);
}
@@ -392,12 +290,14 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
const updated = await prisma.page.findUnique({
where: { id },
include: { translations: true }
include: { translations: true },
});
return { success: true, translations: results, page: updated };
})
.post("/:slug/sections", async ({ params: { slug }, body, set }) => {
.post(
"/:slug/sections",
async ({ params: { slug }, body, set }) => {
try {
const pageId = Number(slug);
const { type, order, payload, isActive } = body as any;
@@ -405,14 +305,17 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
const validationResult = validateSectionPayload(type, payload);
if (!validationResult.success) {
set.status = 400;
return { error: "Validation failed", details: validationResult.issues };
return {
error: "Validation failed",
details: validationResult.issues,
};
}
let finalOrder = order;
if (finalOrder === undefined) {
const lastSection = await prisma.pageSection.findFirst({
where: { pageId },
orderBy: { order: "desc" }
orderBy: { order: "desc" },
});
finalOrder = lastSection ? lastSection.order + 1 : 1;
}
@@ -422,79 +325,104 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
pageId,
type: type.toUpperCase(),
order: finalOrder,
payload,
isActive: isActive !== false
}
payload: validationResult.data,
isActive: isActive !== false,
},
});
} catch (err) {
console.error("[PageSections] Error:", err);
set.status = 500;
return { error: "Failed to add section" };
}
}, {
},
{
body: t.Object({
type: t.String(),
order: t.Optional(t.Number()),
payload: t.Any(),
isActive: t.Optional(t.Boolean())
})
})
.put("/sections/:sectionId", async ({ params: { sectionId }, body, set }) => {
isActive: t.Optional(t.Boolean()),
}),
},
)
.put(
"/sections/:sectionId",
async ({ params: { sectionId }, body, set }) => {
try {
const id = Number(sectionId);
const { type, order, payload, isActive } = body as any;
const { type, order, isActive, payload: explicitPayload, ...rest } = body as any;
console.log(`\n📦 [PUT /sections/${sectionId}] body received:`, JSON.stringify(body, null, 2));
// MCP tools send fields flat at root level (not nested under "payload" key)
// Normalize: if no explicit payload key, use remaining root-level fields as payload
const payload = explicitPayload ?? (Object.keys(rest).length > 0 ? rest : undefined);
let finalPayload = payload;
if (payload) {
let validationType = type;
if (!validationType) {
const existingSection = await prisma.pageSection.findUnique({ where: { id } });
const existingSection = await prisma.pageSection.findUnique({
where: { id },
});
if (!existingSection) {
set.status = 404;
return { error: "Section not found" };
}
validationType = existingSection.type;
}
const validationResult = validateSectionPayload(validationType, payload);
const validationResult = validateSectionPayload(
validationType,
payload,
);
if (!validationResult.success) {
console.log(`\n❌ [PUT /sections/${sectionId}] Validation FAILED:`, JSON.stringify(validationResult.issues, null, 2));
set.status = 400;
return { error: "Validation failed", details: validationResult.issues };
return {
error: "Validation failed",
details: validationResult.issues,
};
}
finalPayload = validationResult.data;
console.log(`\n✅ [PUT /sections/${sectionId}] Validation passed. finalPayload:`, JSON.stringify(finalPayload, null, 2));
}
console.log(`\n💾 [PUT /sections/${sectionId}] Prisma update with:`, JSON.stringify({ type, order, payload: finalPayload, isActive }, null, 2));
return await prisma.pageSection.update({
where: { id },
data: {
type: type ? type.toUpperCase() : undefined,
order,
payload,
isActive
}
payload: finalPayload,
isActive,
},
});
} catch (err) {
console.error("[PageSections] Update Error:", err);
set.status = 500;
return { error: "Failed to update section" };
}
}, {
body: t.Object({
type: t.Optional(t.String()),
order: t.Optional(t.Number()),
payload: t.Optional(t.Any()),
isActive: t.Optional(t.Boolean())
})
})
.put("/:slug/sections/reorder", async ({ params: { slug }, body, set }) => {
},
{
body: t.Any(),
},
)
.put(
"/:slug/sections/reorder",
async ({ params: { slug }, body, set }) => {
try {
const pageId = Number(slug);
const { sectionOrders } = body as { sectionOrders: { id: number; order: number }[] };
const { sectionOrders } = body as {
sectionOrders: { id: number; order: number }[];
};
await prisma.$transaction(
sectionOrders.map((item) =>
prisma.pageSection.update({
where: { id: item.id, pageId },
data: { order: item.order }
})
)
data: { order: item.order },
}),
),
);
return { success: true };
} catch (err) {
@@ -502,18 +430,22 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
set.status = 500;
return { error: "Failed to reorder sections" };
}
}, {
},
{
body: t.Object({
sectionOrders: t.Array(t.Object({
sectionOrders: t.Array(
t.Object({
id: t.Number(),
order: t.Number()
}))
})
})
order: t.Number(),
}),
),
}),
},
)
.delete("/sections/:sectionId", async ({ params: { sectionId }, set }) => {
try {
await prisma.pageSection.delete({
where: { id: Number(sectionId) }
where: { id: Number(sectionId) },
});
return { success: true };
} catch (err) {
@@ -522,38 +454,215 @@ export const pagesRoute = new Elysia({ prefix: "/pages" })
}
});
function validateSectionPayload(type: string, payload: any): { success: boolean; issues?: z.ZodIssue[] } {
if (!payload || typeof payload !== 'object') {
return { success: false, issues: [{ code: 'custom', message: "Payload must be a JSON object", path: [] }] as z.ZodIssue[] };
function validateSectionPayload(
type: string,
payload: any,
): { success: boolean; issues?: z.ZodIssue[]; data?: any } {
if (!payload || typeof payload !== "object") {
return {
success: false,
issues: [
{ code: "custom", message: "Payload must be a JSON object", path: [] },
] as z.ZodIssue[],
};
}
let schema: z.ZodTypeAny;
switch (type.toUpperCase()) {
case 'HERO': schema = HeroSectionPayloadSchema; break;
case 'CATEGORIES': schema = CategoriesSectionPayloadSchema; break;
case 'PRODUCTS': schema = ProductsSectionPayloadSchema; break;
case 'BANNER': schema = BannerSectionPayloadSchema; break;
case 'TEXT': schema = TextSectionPayloadSchema; break;
case 'ANNOUNCEMENT_BAR': schema = AnnouncementBarSectionPayloadSchema; break;
case 'NEWSLETTER': schema = NewsletterSectionPayloadSchema; break;
case 'EDITORIAL_TILE': schema = EditorialTileSectionPayloadSchema; break;
case 'EDITORIAL_CAROUSEL': schema = EditorialCarouselSectionPayloadSchema; break;
case 'HERO_ARTICLE': schema = HeroArticleSectionPayloadSchema; break;
case 'RICH_TEXT': schema = RichTextSectionPayloadSchema; break;
case 'SCENT_NOTES_BREAKDOWN': schema = ScentNotesBreakdownSectionPayloadSchema; break;
case 'QUOTE_CALLOUT': schema = QuoteCalloutSectionPayloadSchema; break;
case 'PRODUCT_CAROUSEL': schema = ProductCarouselSectionPayloadSchema; break;
case 'ACCORDION': schema = AccordionSectionPayloadSchema; break;
case 'CONTACT_INFO': schema = ContactInfoSectionPayloadSchema; break;
case 'CONTACT_FORM': schema = ContactFormSectionPayloadSchema; break;
case "HERO":
schema = HeroSectionPayloadSchema;
break;
case "CATEGORIES":
schema = CategoriesSectionPayloadSchema;
break;
case "PRODUCTS":
schema = ProductsSectionPayloadSchema;
break;
case "BANNER":
schema = BannerSectionPayloadSchema;
break;
case "TEXT":
schema = TextSectionPayloadSchema;
break;
case "ANNOUNCEMENT_BAR":
schema = AnnouncementBarSectionPayloadSchema;
break;
case "NEWSLETTER":
schema = NewsletterSectionPayloadSchema;
break;
case "EDITORIAL_TILE":
schema = EditorialTileSectionPayloadSchema;
break;
case "EDITORIAL_CAROUSEL":
schema = EditorialCarouselSectionPayloadSchema;
break;
case "HERO_ARTICLE":
schema = HeroArticleSectionPayloadSchema;
break;
case "RICH_TEXT":
schema = RichTextSectionPayloadSchema;
break;
case "SCENT_NOTES_BREAKDOWN":
schema = ScentNotesBreakdownSectionPayloadSchema;
break;
case "QUOTE_CALLOUT":
schema = QuoteCalloutSectionPayloadSchema;
break;
case "PRODUCT_CAROUSEL":
schema = ProductCarouselSectionPayloadSchema;
break;
case "ACCORDION":
schema = AccordionSectionPayloadSchema;
break;
case "CONTACT_INFO":
schema = ContactInfoSectionPayloadSchema;
break;
case "CONTACT_FORM":
schema = ContactFormSectionPayloadSchema;
break;
default:
return { success: false, issues: [{ code: 'custom', message: `Unknown section type: ${type}`, path: [] }] as z.ZodIssue[] };
return {
success: false,
issues: [
{
code: "custom",
message: `Unknown section type: ${type}`,
path: [],
},
] as z.ZodIssue[],
};
}
const res = schema.safeParse(payload);
if (!res.success) {
return { success: false, issues: res.error.issues };
}
return { success: true };
return { success: true, data: res.data };
}
async function resolveProductsForSection(payload: any, lang: string) {
let products: any[] = [];
const limit = payload.limit || 3;
const productInclude = {
category: {
include: { translations: true },
},
brand: true,
translations: true,
variants: {
include: {
bomItems: { include: { rawMaterial: true } },
},
orderBy: { price: "asc" as const },
},
images: {
orderBy: { order: "asc" as const },
},
};
if (payload.type === "featured") {
products = await prisma.product.findMany({
where: { categoryId: Number(payload.categoryId) || 1 },
include: productInclude,
take: limit,
});
} else if (
(payload.type === "scent" || payload.type === "brand") &&
(payload.scentId || payload.brandId)
) {
products = await prisma.product.findMany({
where: { brandId: Number(payload.brandId || payload.scentId) },
include: productInclude,
take: limit,
});
} else if (payload.type === "custom" && Array.isArray(payload.productIds)) {
const ids = payload.productIds.map(Number);
if (ids.length > 0) {
products = await prisma.product.findMany({
where: { id: { in: ids } },
include: productInclude,
});
products.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
}
} else {
products = await prisma.product.findMany({
include: productInclude,
take: limit,
});
}
return products.map((p: any) => {
if (lang === "all") {
const nameObj: any = {};
const descObj: any = {};
const detailsObj: any = {};
p.translations?.forEach((t: any) => {
nameObj[t.langCode] = t.name;
descObj[t.langCode] = t.description;
detailsObj[t.langCode] = t.details;
});
return { ...p, name: nameObj, description: descObj, details: detailsObj };
} else {
const trans =
p.translations?.find((t: any) => t.langCode === lang) ||
p.translations?.find((t: any) => t.langCode === "th") ||
p.translations?.[0];
return {
...p,
name: trans?.name || p.brand?.name || "",
description: trans?.description,
details: trans?.details,
};
}
});
}
export async function hydrateSectionPayload(section: any, lang: string) {
const payload = section.payload as any;
if (!payload) return section;
const populatedPayload = { ...payload };
if (
section.type === "PRODUCTS" ||
(section.type === "PRODUCT_CAROUSEL" &&
!Array.isArray(populatedPayload.products))
) {
populatedPayload.products = await resolveProductsForSection(payload, lang);
} else if (section.type === "CATEGORIES") {
let categories: any[] = [];
if (Array.isArray(payload.categoryIds) && payload.categoryIds.length > 0) {
const ids = payload.categoryIds.map(Number);
categories = await prisma.category.findMany({
where: { id: { in: ids } },
include: {
translations: true,
_count: {
select: { products: true },
},
},
});
categories.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
} else {
categories = await prisma.category.findMany({
include: {
translations: true,
_count: {
select: { products: true },
},
},
});
}
// Resolve name for each category using the lang param (supports 'all')
populatedPayload.categories = categories.map((cat: any) => ({
...cat,
name: resolveCatName(cat, lang),
}));
}
return {
...section,
payload: populatedPayload,
};
}
+87 -2
View File
@@ -38,6 +38,23 @@ const SECTION_TOOL_CONFIGS = [
},
required: ["sectionId"]
},
{
name: "update_editorial_tile",
sectionType: "EDITORIAL_TILE",
description: `Update an EDITORIAL_TILE section. Title, description, and buttonText are localized. imageUrl, imagePosition, buttonLink, backgroundColor, and textColor are plain strings. Example payload: { "sectionId": 12, "title": ${localizedStringExample}, "description": ${localizedStringExample}, "imageUrl": "https://..." }`,
properties: {
sectionId: { type: "number", description: "The numeric ID of the section to update" },
imageUrl: { type: "string", description: "Plain string main image URL" },
imagePosition: { type: "string", description: "Plain string image position ('left' or 'right')" },
title: { ...localizedStringSchema, description: `Localized title, for example ${localizedStringExample}` },
description: { ...localizedStringSchema, description: `Localized description, for example ${localizedStringExample}` },
buttonText: { ...localizedStringSchema, description: `Localized button text, for example ${localizedStringExample}` },
buttonLink: { type: "string", description: "Plain string button link URL" },
backgroundColor: { type: "string", description: "Plain string background color in hex or rgba" },
textColor: { type: "string", description: "Plain string text color in hex or rgba" }
},
required: ["sectionId"]
},
{
name: "update_rich_text",
sectionType: "RICH_TEXT",
@@ -150,6 +167,35 @@ const SECTION_TOOL_CONFIGS = [
subtitle: { ...localizedStringSchema, description: `Localized form subtitle, for example ${localizedStringExample}` }
},
required: ["sectionId"]
},
{
name: "update_editorial_carousel",
sectionType: "EDITORIAL_CAROUSEL",
description: `Update an EDITORIAL_CAROUSEL section. title, description, and slides are supported. Example payload: { "sectionId": 12, "title": ${localizedStringExample}, "description": ${localizedStringExample} }`,
properties: {
sectionId: { type: "number", description: "The numeric ID of the section to update" },
title: { ...localizedStringSchema, description: `Localized section title, for example ${localizedStringExample}` },
description: { ...localizedStringSchema, description: `Localized section description, for example ${localizedStringExample}` },
backgroundColor: { type: "string", description: "Plain string background color in hex or rgba" },
textColor: { type: "string", description: "Plain string text color in hex or rgba" },
slides: {
type: "array",
items: {
type: "object",
properties: {
title: localizedStringSchema,
description: localizedStringSchema,
category: localizedStringSchema,
imageUrl: { type: "string" },
buttonText: localizedStringSchema,
buttonLink: { type: "string" }
},
required: ["imageUrl"]
},
description: "Array of slides. IMPORTANT: Providing this will completely overwrite the existing slides array. Ensure you provide all slides."
}
},
required: ["sectionId"]
}
] as const;
@@ -201,6 +247,18 @@ function buildSectionUpdateResult(toolName: string, sectionType: string, updated
}
export const SECTION_TOOL_DEFINITIONS = [
{
name: "get_page_section",
description: "Get a specific page section by ID, returning its hydrated payload resolving linked content like categories or products. Optionally pass lang to control translation.",
inputSchema: {
type: "object",
properties: {
sectionId: { type: "number", description: "The numeric ID of the section to fetch" },
lang: { type: "string", description: "Optional language code (th, en, all)" }
},
required: ["sectionId"]
}
},
{
name: "add_page_section",
description: "Add a block section to a dynamic page layout. For the payload field, ensure it matches the section type. Examples: For TEXT, use { \"text\": \"...\" }. For RICH_TEXT, use { \"title\": \"...\", \"content\": \"...\" }.",
@@ -258,8 +316,21 @@ export const SECTION_TOOL_NAMES = new Set<string>(SECTION_TOOL_DEFINITIONS.map((
export async function handleSectionTool(api: AxiosInstance, name: string, params: any) {
if (!SECTION_TOOL_NAMES.has(name)) return null;
// Global validation: almost all section tools require sectionId, except add_page_section
if (name !== "add_page_section" && params.sectionId === undefined) {
throw new Error(`Validation Error: 'sectionId' is required for tool '${name}'`);
}
switch (name) {
case "get_page_section": {
const langParam = params.lang ? `?lang=${params.lang}` : "";
const res = await api.get(`/pages/sections/${params.sectionId}${langParam}`);
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
}
case "add_page_section": {
if (params.pageId === undefined) {
throw new Error(`Validation Error: 'pageId' is required for tool '${name}'`);
}
const payload: any = {
type: params.type,
payload: params.payload,
@@ -278,6 +349,7 @@ export async function handleSectionTool(api: AxiosInstance, name: string, params
const res = await api.put(`/pages/sections/${params.sectionId}`, payload);
return buildSectionUpdateResult("update_page_section", res.data?.type ?? params.type ?? "UNKNOWN", res.data, payload);
}
case "update_editorial_tile":
case "update_hero_article":
case "update_rich_text":
case "update_scent_notes_breakdown":
@@ -285,7 +357,8 @@ export async function handleSectionTool(api: AxiosInstance, name: string, params
case "update_product_carousel":
case "update_accordion":
case "update_contact_info":
case "update_contact_form": {
case "update_contact_form":
case "update_editorial_carousel": {
const config = SECTION_TOOL_CONFIG_BY_NAME.get(name);
if (!config) {
throw new Error(`Unknown tool config for: ${name}`);
@@ -299,9 +372,21 @@ export async function handleSectionTool(api: AxiosInstance, name: string, params
payload.heartNotes = payload.middleNotes;
}
}
// Fetch existing section to merge payload so AI doesn't have to provide all required fields every time
let mergedPayload = payload;
try {
const existingRes = await api.get(`/pages/sections/${params.sectionId}?lang=all`);
if (existingRes.data && existingRes.data.payload) {
mergedPayload = { ...existingRes.data.payload, ...payload };
}
} catch (err) {
console.warn(`Could not fetch existing section ${params.sectionId} for merging, proceeding with partial payload.`);
}
const res = await api.put(`/pages/sections/${params.sectionId}`, {
type: config.sectionType,
...payload
payload: mergedPayload
});
return buildSectionUpdateResult(name, config.sectionType, res.data, payload);
@@ -46,7 +46,7 @@ export default function DynamicEditorialCarousel({ payload }: DynamicEditorialCa
};
return (
<section className="ui-dark-shell overflow-hidden">
<section className="overflow-hidden py-16 md:py-24" style={{ backgroundColor: payload.backgroundColor, color: payload.textColor }}>
<div className="ui-section-inner space-y-12">
<div className="space-y-3 text-center">
<h2 className="font-serif text-3xl font-light tracking-wide text-pop-pink md:text-5xl">
@@ -80,7 +80,6 @@ export default function DynamicEditorialCarousel({ payload }: DynamicEditorialCa
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
<div className="absolute inset-0 bg-gradient-to-t from-night-900/80 via-transparent to-transparent"></div>
</div>
<div className="p-6 md:p-8 flex flex-col flex-1 justify-between space-y-6">
@@ -39,7 +39,8 @@ export default function DynamicEditorialTile({ payload }: DynamicEditorialTilePr
return (
<section
className="ui-section-band w-full overflow-hidden bg-pop-bg text-pop-black"
className="ui-section-band w-full overflow-hidden"
style={{ backgroundColor: payload.backgroundColor, color: payload.textColor }}
>
<div className="ui-section-inner grid grid-cols-1 items-center gap-12 md:grid-cols-2 md:gap-20">
<div className={`group relative aspect-square w-full overflow-hidden rounded-3xl shadow-xl ${
@@ -59,11 +60,11 @@ export default function DynamicEditorialTile({ payload }: DynamicEditorialTilePr
<div className={`flex flex-col justify-center space-y-6 md:space-y-8 ${
imagePosition === 'left' ? 'md:order-2 md:pl-8' : 'md:order-1 md:pr-8'
}`}>
<h2 className="font-serif text-3xl font-light leading-tight tracking-wide md:text-5xl">
<h2 className="font-serif text-3xl font-light leading-tight tracking-wide md:text-5xl" style={{ color: payload.textColor }}>
{renderTitle(title) || title}
</h2>
<div className="w-12 h-[1px] bg-pop-pink"></div>
<p className="whitespace-pre-line text-sm font-light leading-relaxed opacity-90 md:text-base">
<p className="whitespace-pre-line text-sm font-light leading-relaxed opacity-90 md:text-base" style={{ color: payload.textColor }}>
{description}
</p>
{buttonText && buttonLink && (
@@ -1,9 +1,6 @@
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination, Navigation } from 'swiper/modules';
import ProductCard from './ProductCard';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';
import { useRef } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { getLocalizedField } from '../utils/localization';
@@ -19,6 +16,10 @@ export default function DynamicProductCarousel({ payload }: DynamicProductCarous
const title = getLocalizedField(p.title, lang);
const description = getLocalizedField(p.description, lang);
const carouselRef = useRef<HTMLDivElement>(null);
const scrollLeft = () => carouselRef.current?.scrollBy({ left: -300, behavior: 'smooth' });
const scrollRight = () => carouselRef.current?.scrollBy({ left: 300, behavior: 'smooth' });
return (
<section className="ui-section-band bg-pop-bg">
<div className="ui-section-inner">
@@ -34,27 +35,28 @@ export default function DynamicProductCarousel({ payload }: DynamicProductCarous
No products to display.
</div>
) : (
<div className="relative pb-12" style={{ '--swiper-navigation-color': 'var(--color-pop-black)' } as React.CSSProperties}>
<Swiper
modules={[Autoplay, Pagination, Navigation]}
spaceBetween={32}
slidesPerView={1}
breakpoints={{
640: { slidesPerView: 2 },
1024: { slidesPerView: 3 },
1280: { slidesPerView: 4 }
}}
pagination={{ clickable: true, bulletActiveClass: 'swiper-pagination-bullet-active !bg-pop-black' }}
navigation
autoplay={{ delay: 5000, disableOnInteraction: false }}
className="w-full !px-4"
<div className="relative -mx-4 px-4 sm:mx-0 sm:px-0">
<button
onClick={scrollLeft}
className="hidden md:flex bg-surface-card rounded-full shadow-card hover:text-brand-primary h-10 w-10 items-center justify-center absolute z-10 top-1/2 -translate-y-1/2 -left-5"
aria-label="Scroll left"
>
<ChevronLeft className="h-6 w-6" />
</button>
<div ref={carouselRef} className="flex overflow-x-auto snap-x snap-mandatory hide-scrollbar gap-4 pb-12">
{products.map((p: any) => (
<SwiperSlide key={p.id} className="h-auto">
<div key={p.id} className="w-[85vw] sm:w-[300px] flex-none snap-start">
<ProductCard product={p} enableQuickShop={true} />
</SwiperSlide>
</div>
))}
</Swiper>
</div>
<button
onClick={scrollRight}
className="hidden md:flex bg-surface-card rounded-full shadow-card hover:text-brand-primary h-10 w-10 items-center justify-center absolute z-10 top-1/2 -translate-y-1/2 -right-5"
aria-label="Scroll right"
>
<ChevronRight className="h-6 w-6" />
</button>
</div>
)}
</div>
+24 -21
View File
@@ -1,15 +1,11 @@
import { Link } from 'react-router-dom';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination } from 'swiper/modules';
import { useRef } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import ProductCard from './ProductCard';
import type { Category, Product, ProductsSectionPayload } from '@homaroma/types';
import { useTranslation } from 'react-i18next';
import { getLocalizedField } from '../utils/localization';
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/pagination';
interface DynamicProductsProps {
payload: ProductsSectionPayload & { products?: Product[] };
categories?: Category[];
@@ -23,6 +19,10 @@ export default function DynamicProducts({ payload, categories = [] }: DynamicPro
const subtitle = getLocalizedField(payload.subtitle, lang);
const categoryLookup = new Map(categories.map((category) => [category.id, category]));
const carouselRef = useRef<HTMLDivElement>(null);
const scrollLeft = () => carouselRef.current?.scrollBy({ left: -300, behavior: 'smooth' });
const scrollRight = () => carouselRef.current?.scrollBy({ left: 300, behavior: 'smooth' });
return (
<section className="ui-section-band relative bg-pop-bg">
<div className="ui-section-inner relative z-10 space-y-12">
@@ -49,29 +49,32 @@ export default function DynamicProducts({ payload, categories = [] }: DynamicPro
No products found in this section
</div>
) : layout === 'carousel' ? (
<div className="relative select-none pb-12">
<Swiper
modules={[Autoplay, Pagination]}
spaceBetween={24}
slidesPerView={1}
breakpoints={{
640: { slidesPerView: 2 },
1024: { slidesPerView: 3 }
}}
pagination={{ clickable: true, bulletActiveClass: 'swiper-pagination-bullet-active !bg-pop-black' }}
autoplay={{ delay: 6000, disableOnInteraction: false }}
className="w-full"
<div className="relative -mx-4 px-4 sm:mx-0 sm:px-0">
<button
onClick={scrollLeft}
className="hidden md:flex bg-surface-card rounded-full shadow-card hover:text-brand-primary h-10 w-10 items-center justify-center absolute z-10 top-1/2 -translate-y-1/2 -left-5"
aria-label="Scroll left"
>
<ChevronLeft className="h-6 w-6" />
</button>
<div ref={carouselRef} className="flex overflow-x-auto snap-x snap-mandatory hide-scrollbar gap-4 pb-12">
{products.map((p) => (
<SwiperSlide key={p.id} className="h-auto">
<div key={p.id} className="w-[85vw] sm:w-[300px] flex-none snap-start">
<ProductCard
product={p}
enableQuickShop={enableQuickShop}
categoryNameOverride={getLocalizedField(categoryLookup.get(p.categoryId)?.name, lang)}
/>
</SwiperSlide>
</div>
))}
</Swiper>
</div>
<button
onClick={scrollRight}
className="hidden md:flex bg-surface-card rounded-full shadow-card hover:text-brand-primary h-10 w-10 items-center justify-center absolute z-10 top-1/2 -translate-y-1/2 -right-5"
aria-label="Scroll right"
>
<ChevronRight className="h-6 w-6" />
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
+8
View File
@@ -235,6 +235,14 @@
@apply bg-pop-black/50;
}
.hide-scrollbar::-webkit-scrollbar {
display: none;
}
.hide-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
/* Smooth Scrolling */
html {
scroll-behavior: smooth;
+8
View File
@@ -573,3 +573,11 @@ body:has(.announcement-bar) .global-navbar[data-scrolled="false"] {
top: 44px; /* Adjusts Navbar down when AnnouncementBar is present at the top */
}
.hide-scrollbar::-webkit-scrollbar {
display: none;
}
.hide-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
@@ -2,8 +2,8 @@
import Image from 'next/image'
import Link from '../LocalizedLink'
import { Clock, Mail, MapPin, MessageCircle, Send } from 'lucide-react'
import { useState } from 'react'
import { Clock, Mail, MapPin, MessageCircle, Send, ChevronLeft, ChevronRight } from 'lucide-react'
import { useState, useRef } from 'react'
import type { Category, PageSection, Product } from '@homaroma/types'
import { getCategoryImage } from '@homaroma/types'
import ProductCard from '../ProductCard'
@@ -220,6 +220,10 @@ function ProductsSection({ payload, lang }: { payload: Record<string, unknown>,
const layout = typeof payload.layout === 'string' ? payload.layout : 'grid'
const products = getProducts(payload)
const carouselRef = useRef<HTMLDivElement>(null)
const scrollLeft = () => carouselRef.current?.scrollBy({ left: -300, behavior: 'smooth' })
const scrollRight = () => carouselRef.current?.scrollBy({ left: 300, behavior: 'smooth' })
return (
<section className="bg-surface-page ui-section-band">
<div className="ui-section-shell space-y-10">
@@ -235,21 +239,27 @@ function ProductsSection({ payload, lang }: { payload: Record<string, unknown>,
{products.length ? (
layout === 'carousel' ? (
<div className="relative -mx-4 px-4 sm:mx-0 sm:px-0">
<Swiper
slidesPerView={1.2}
spaceBetween={16}
breakpoints={{
640: { slidesPerView: 2.2, spaceBetween: 24 },
1024: { slidesPerView: 3, spaceBetween: 32 },
}}
className="w-full"
<button
onClick={scrollLeft}
className="hidden md:flex bg-surface-card rounded-full shadow-card hover:text-brand-primary h-10 w-10 items-center justify-center absolute z-10 top-1/2 -translate-y-1/2 -left-5"
aria-label="Scroll left"
>
<ChevronLeft className="h-6 w-6" />
</button>
<div ref={carouselRef} className="flex overflow-x-auto snap-x snap-mandatory hide-scrollbar gap-4 pb-4">
{products.map((product) => (
<SwiperSlide key={product.id} className="!h-auto pb-4">
<div key={product.id} className="w-[85vw] sm:w-[300px] flex-none snap-start">
<ProductCard product={product} />
</SwiperSlide>
</div>
))}
</Swiper>
</div>
<button
onClick={scrollRight}
className="hidden md:flex bg-surface-card rounded-full shadow-card hover:text-brand-primary h-10 w-10 items-center justify-center absolute z-10 top-1/2 -translate-y-1/2 -right-5"
aria-label="Scroll right"
>
<ChevronRight className="h-6 w-6" />
</button>
</div>
) : (
<div className="grid grid-cols-1 gap-8 md:grid-cols-3">
@@ -258,7 +268,7 @@ function ProductsSection({ payload, lang }: { payload: Record<string, unknown>,
)
) : (
<p className="ui-section-card bg-surface-card p-8 text-center text-muted-text">
{t('dynamic.emptyProducts', { lng: resolvedLang })}
{t('dynamic.noProducts', { lng: resolvedLang })}
</p>
)}
</div>
@@ -387,18 +397,20 @@ function EditorialCarouselSection({ payload, lang }: { payload: Record<string, u
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang)
const slides = Array.isArray(payload.slides) ? payload.slides.map(toRecord) : []
const backgroundColor = typeof payload.backgroundColor === 'string' ? payload.backgroundColor : undefined
const textColor = typeof payload.textColor === 'string' ? payload.textColor : undefined
if (!slides.length) return null
return (
<section className="ui-section-dark">
<section className="ui-section-dark py-16 md:py-24" style={{ backgroundColor, color: textColor }}>
<div className="mx-auto max-w-7xl space-y-12">
{title && (
<div className="mx-auto max-w-3xl space-y-4 text-center">
<h2 className="text-4xl font-semibold text-surface-card md:text-5xl">{renderAccentTitle(title)}</h2>
<h2 className="text-4xl font-semibold text-surface-card md:text-5xl" style={{ color: textColor }}>{renderAccentTitle(title)}</h2>
<div className="mx-auto h-px w-16 bg-brand-accent" />
</div>
)}
<div className="grid gap-6 md:grid-cols-3">
<div className="flex overflow-x-auto snap-x snap-mandatory hide-scrollbar gap-6 pb-8">
{slides.map((slide, index) => {
const slideTitle = localizedFromRecord(slide, 'title', resolvedLang)
const description = localizedFromRecord(slide, 'description', resolvedLang)
@@ -408,8 +420,8 @@ function EditorialCarouselSection({ payload, lang }: { payload: Record<string, u
const imageUrl = typeof slide.imageUrl === 'string' ? slide.imageUrl : ''
return (
<article key={index} className="ui-section-dark-card group">
{imageUrl && (
<article key={index} className="ui-section-dark-card group w-[85vw] md:w-[350px] flex-none snap-start">
{imageUrl ? (
<div className="relative aspect-[4/3] overflow-hidden">
<Image
src={imageUrl}
@@ -419,15 +431,19 @@ function EditorialCarouselSection({ payload, lang }: { payload: Record<string, u
className="h-full w-full object-cover transition duration-700 group-hover:scale-105"
/>
</div>
)}
<div className="space-y-4 p-6">
{category && <p className="text-[10px] font-bold uppercase tracking-[0.24em] text-brand-accent">{category}</p>}
{slideTitle && <h3 className="ui-section-dark-card-title">{renderAccentTitle(slideTitle)}</h3>}
{description && <p className="ui-section-dark-card-copy">{description}</p>}
) : null}
<div className="space-y-4 p-6 flex flex-col flex-1 justify-between">
<div>
{category && <p className="text-[10px] font-bold uppercase tracking-[0.24em] text-brand-accent mb-2">{category}</p>}
{slideTitle && <h3 className="ui-section-dark-card-title text-xl mb-3">{renderAccentTitle(slideTitle)}</h3>}
{description && <p className="ui-section-dark-card-copy text-sm line-clamp-3">{description}</p>}
</div>
{buttonText && buttonLink && (
<Link href={buttonLink} className="ui-section-dark-link">
{buttonText} &rarr;
<div className="pt-2">
<Link href={buttonLink} className="ui-section-dark-link inline-flex items-center gap-2 text-xs font-bold uppercase tracking-widest transition-colors group/link">
{buttonText} <span className="group-hover/link:translate-x-1 transition-transform">&rarr;</span>
</Link>
</div>
)}
</div>
</article>
@@ -802,8 +818,9 @@ export default function DynamicPageRenderer({ sections, categories, lang: langPr
case 'CATEGORIES':
return <CategoriesSection key={section.id} payload={payload} categories={categories} lang={lang} />
case 'PRODUCTS':
case 'PRODUCT_CAROUSEL':
return <ProductsSection key={section.id} payload={payload} lang={lang} />
case 'PRODUCT_CAROUSEL':
return <ProductsSection key={section.id} payload={{ ...payload, layout: 'carousel' }} lang={lang} />
case 'BANNER':
return <BannerSection key={section.id} payload={payload} lang={lang} />
case 'TEXT':
+7 -2
View File
@@ -328,6 +328,8 @@ export type EditorialTileSectionPayload = z.infer<typeof EditorialTileSectionPay
export const EditorialCarouselSectionPayloadSchema = z.object({
title: LocalizedStringSchema,
backgroundColor: z.string().optional(),
textColor: z.string().optional(),
slides: z.array(z.object({
category: LocalizedStringSchema,
title: LocalizedStringSchema,
@@ -394,12 +396,15 @@ export type QuoteCalloutSectionPayload = z.infer<typeof QuoteCalloutSectionPaylo
export const ProductCarouselSectionPayloadSchema = z.object({
title: LocalizedStringSchema.optional(),
description: LocalizedStringSchema.optional(),
collectionId: z.string().optional(),
type: z.enum(['featured', 'brand', 'custom']),
categoryId: z.number().optional(),
brandId: z.number().optional(),
productIds: z.array(z.number()).optional(),
limit: z.number().positive().optional(),
showPrice: z.boolean().optional(),
showAddToCart: z.boolean().optional(),
products: z.array(z.any()).optional(),
});
}).strict();
export type ProductCarouselSectionPayload = z.infer<typeof ProductCarouselSectionPayloadSchema>;
// Aliases for backwards compatibility in ScentGuideSectionSchema