Author SHA1 Message Date
Your Name cf4546422d feat(website): implement PDPA cookie consent banner and script manager
- Add cookieConsentStore using Zustand with localStorage persistence and skipHydration
- Implement responsive CookieBanner with Quiet Luxury design and PDPA compliance
- Implement CookiePreferencesModal with category toggles (Necessary, Analytics, Marketing)
- Implement ScriptManager for Google Consent Mode v2, GA4, Meta Pixel, and TikTok Pixel orchestration
- Add Cookie Preferences trigger in Footer support column
- Add multilingual translation keys for Thai, English, Japanese, and Chinese
2026-10-19 05:45:36 +07:00
Your Name 9a18463bda feat(profitability): set default period to this_month on omnichannel margin page 2026-10-18 22:00:42 +07:00
adminandYour Name dbc6c513db feat(profitability): hybrid actual fees for Shopee/TikTok with conservative 30% fallback (#13)
Co-authored-by: Your Name <you@example.com>
Reviewed-on: #13
2026-10-18 14:53:31 +00:00
13 changed files with 969 additions and 63 deletions

No files matched your search

@@ -8,6 +8,8 @@ import {
Coins,
RefreshCw,
Calendar,
Receipt,
ShieldCheck,
} from 'lucide-react';
import { API_BASE } from '@homaroma/types';
import ProfitabilityHeaderTabs from './ProfitabilityHeaderTabs';
@@ -50,8 +52,9 @@ interface OmnichannelItem {
categoryName: string;
unitBomCost: number;
totalBomCost: number;
totalFeePercent: number;
estPlatformFee: number;
platformFee: number;
effectiveFeePercent: number;
feeSource: 'actual' | 'hybrid' | 'fallback_30pct';
netRevenue: number;
netProfit: number;
netMarginPercent: number;
@@ -62,6 +65,7 @@ interface OmnichannelItem {
interface ChannelStat {
soldQty: number;
revenue: number;
platformFee: number;
bomCost: number;
netProfit: number;
}
@@ -78,10 +82,16 @@ interface OmnichannelKpis {
totalMappedProducts: number;
totalUnitsSold: number;
totalGrossRevenue: number;
totalPlatformFee: number;
totalEstNetRevenue: number;
totalBOMCost: number;
totalEstNetProfit: number;
overallNetMargin: number;
effectiveFeeRate: number;
actualFeeAmount: number;
fallbackFeeAmount: number;
actualOrdersCount: number;
fallbackOrdersCount: number;
channelStats: Record<string, ChannelStat>;
}
@@ -89,6 +99,7 @@ export default function OmnichannelMarginPage() {
const [loading, setLoading] = useState(true);
const [data, setData] = useState<{
periodInfo: PeriodInfo;
feePolicy?: { mode: string; fallbackPercent: number; description: string };
kpis: OmnichannelKpis;
items: OmnichannelItem[];
} | null>(null);
@@ -96,7 +107,7 @@ export default function OmnichannelMarginPage() {
// Filters
const [search, setSearch] = useState('');
const [channelFilter, setChannelFilter] = useState<'all' | 'shopee' | 'lazada' | 'tiktok'>('all');
const [dateFilter, setDateFilter] = useState<DateFilterState>({ period: 'all' });
const [dateFilter, setDateFilter] = useState<DateFilterState>({ period: 'this_month' });
const [sortBy, setSortBy] = useState('revenue_desc');
const fetchData = async () => {
@@ -163,9 +174,11 @@ export default function OmnichannelMarginPage() {
'Units Sold',
'Avg Price',
'Total Revenue',
'Platform Fee (THB)',
'Effective Fee %',
'Fee Source',
'Unit BOM Cost',
'Total BOM Cost',
'Platform Fee %',
'Net Revenue',
'Net Profit',
'Net Margin %',
@@ -184,9 +197,11 @@ export default function OmnichannelMarginPage() {
i.totalSoldQty,
i.avgSellingPrice,
i.totalRevenue,
i.platformFee,
`${i.effectiveFeePercent}%`,
i.feeSource,
i.unitBomCost,
i.totalBomCost,
`${i.totalFeePercent}%`,
i.netRevenue,
i.netProfit,
`${i.netMarginPercent}%`,
@@ -288,19 +303,58 @@ export default function OmnichannelMarginPage() {
</div>
</div>
{/* ── Executive KPI Cards ────────────────────────────────────────── */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* ── Fee Policy Notice Banner ─────────────────────────────────── */}
<div className="flex flex-wrap items-center justify-between gap-3 p-4 rounded-2xl bg-slate-900/90 border border-white/10 shadow-lg backdrop-blur-sm text-xs text-slate-300">
<div className="flex items-center gap-2.5">
<div className="p-1.5 rounded-lg bg-emerald-500/10 text-emerald-400">
<ShieldCheck className="w-5 h-5 shrink-0" />
</div>
<div>
<span className="font-bold text-white">Hybrid Fee Policy (Actual + 30% Fallback):</span>{' '}
<span className="text-slate-400">
Shopee ดึงค่าธรรมเนียมจริงจากรายงานคำสั่งซื้อ, TikTok คำนวณจากยอดโอนจริง (Settlement)
สำหรับออเดอร์ที่ยังไม่มีข้อมูลค่าธรรมเนียม จะใช้ตัวคูณปลอดภัย{' '}
<strong className="text-amber-400">30% Fallback</strong>
</span>
</div>
</div>
<div className="flex items-center gap-2 text-[11px] font-mono shrink-0">
<span className="px-2.5 py-1 rounded-lg bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 font-bold">
Actual: {fmtNum(kpis?.actualOrdersCount)} ออเดอร์ ({fmtMoney(kpis?.actualFeeAmount)})
</span>
<span className="px-2.5 py-1 rounded-lg bg-amber-500/15 text-amber-300 border border-amber-500/30 font-bold">
30% Fallback: {fmtNum(kpis?.fallbackOrdersCount)} ออเดอร์ ({fmtMoney(kpis?.fallbackFeeAmount)})
</span>
</div>
</div>
{/* ── Executive KPI Cards (5 Cards) ──────────────────────────────── */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
{/* Total Gross Revenue */}
<div className="bg-slate-900/90 border border-white/10 rounded-2xl p-5 shadow-lg backdrop-blur-sm">
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Gross Revenue ({periodInfo?.label || 'All'})</span>
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Gross Revenue</span>
<div className="p-2 rounded-xl bg-cyan-500/10 text-cyan-400">
<Coins className="w-5 h-5" />
</div>
</div>
<div className="text-2xl font-extrabold text-white">{fmtMoney(kpis?.totalGrossRevenue)}</div>
<p className="text-[11px] text-slate-400 mt-2 font-mono">
{fmtNum(kpis?.totalUnitsSold)} ชิ้น ({fmtNum(kpis?.totalMappedProducts)} รายการ SKU)
{fmtNum(kpis?.totalUnitsSold)} ชิ้น ({fmtNum(kpis?.totalMappedProducts)} SKU)
</p>
</div>
{/* Total Platform Fee */}
<div className="bg-slate-900/90 border border-white/10 rounded-2xl p-5 shadow-lg backdrop-blur-sm">
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Platform Deductions</span>
<div className="p-2 rounded-xl bg-amber-500/10 text-amber-400">
<Receipt className="w-5 h-5" />
</div>
</div>
<div className="text-2xl font-extrabold text-amber-400">{fmtMoney(kpis?.totalPlatformFee)}</div>
<p className="text-[11px] text-slate-400 mt-2 font-mono">
เฉลี่ยหัก <strong className="text-amber-300 font-bold">~{kpis?.effectiveFeeRate ?? 30}%</strong> ของยอดขาย
</p>
</div>
@@ -314,28 +368,28 @@ export default function OmnichannelMarginPage() {
</div>
<div className="text-2xl font-extrabold text-rose-400">{fmtMoney(kpis?.totalBOMCost)}</div>
<p className="text-[11px] text-slate-400 mt-2">
ต้นทุนวัตถุดิบจริงสะสมของสินค้าที่ขายได้ในช่วงเวลานี้
ต้นทุนวัตถุดิบจริงสะสมของสินค้า
</p>
</div>
{/* Total Est Net Profit */}
<div className="bg-slate-900/90 border border-white/10 rounded-2xl p-5 shadow-lg backdrop-blur-sm">
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Est. Net Profit (หลังหัก Fee)</span>
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Est. Net Profit</span>
<div className="p-2 rounded-xl bg-emerald-500/10 text-emerald-400">
<TrendingUp className="w-5 h-5" />
</div>
</div>
<div className="text-2xl font-extrabold text-emerald-400">{fmtMoney(kpis?.totalEstNetProfit)}</div>
<p className="text-[11px] text-slate-400 mt-2">
หักทั้งค่าธรรมเนียม Platform และต้นทุน BOM
หักค่า Platform และต้นทุน BOM แล้ว
</p>
</div>
{/* Overall Net Margin % */}
<div className="bg-slate-900/90 border border-white/10 rounded-2xl p-5 shadow-lg backdrop-blur-sm">
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Net Margin % ({periodInfo?.label || 'All'})</span>
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Net Margin %</span>
<div className="p-2 rounded-xl bg-purple-500/10 text-purple-400">
<Percent className="w-5 h-5" />
</div>
@@ -380,6 +434,12 @@ export default function OmnichannelMarginPage() {
</span>
</div>
<div className="flex items-baseline justify-between mt-1">
<span className="text-xs text-slate-400">Platform Fee:</span>
<span className="text-xs font-mono text-amber-400">
{fmtMoney(kpis.channelStats.shopee?.platformFee)}
</span>
</div>
<div className="flex items-baseline justify-between mt-1 pt-1 border-t border-white/5">
<span className="text-xs text-slate-400">Net Profit:</span>
<span className="text-base font-bold text-emerald-400 font-mono">
{fmtMoney(kpis.channelStats.shopee?.netProfit)}
@@ -414,6 +474,12 @@ export default function OmnichannelMarginPage() {
</span>
</div>
<div className="flex items-baseline justify-between mt-1">
<span className="text-xs text-slate-400">Platform Fee:</span>
<span className="text-xs font-mono text-amber-400">
{fmtMoney(kpis.channelStats.lazada?.platformFee)}
</span>
</div>
<div className="flex items-baseline justify-between mt-1 pt-1 border-t border-white/5">
<span className="text-xs text-slate-400">Net Profit:</span>
<span className="text-base font-bold text-emerald-400 font-mono">
{fmtMoney(kpis.channelStats.lazada?.netProfit)}
@@ -448,6 +514,12 @@ export default function OmnichannelMarginPage() {
</span>
</div>
<div className="flex items-baseline justify-between mt-1">
<span className="text-xs text-slate-400">Platform Fee:</span>
<span className="text-xs font-mono text-amber-400">
{fmtMoney(kpis.channelStats.tiktok?.platformFee)}
</span>
</div>
<div className="flex items-baseline justify-between mt-1 pt-1 border-t border-white/5">
<span className="text-xs text-slate-400">Net Profit:</span>
<span className="text-base font-bold text-emerald-400 font-mono">
{fmtMoney(kpis.channelStats.tiktok?.netProfit)}
@@ -469,7 +541,7 @@ export default function OmnichannelMarginPage() {
<th className="py-4 px-4 text-center">ขายได้ ({periodInfo?.label || 'All'})</th>
<th className="py-4 px-4 text-right">ราคาขายเฉลี่ย</th>
<th className="py-4 px-4 text-right">ต้นทุน BOM (Unit)</th>
<th className="py-4 px-4 text-right">หัก Fee (%)</th>
<th className="py-4 px-4 text-right">หัก Fee (%) &amp; ที่มา</th>
<th className="py-4 px-4 text-right">Net Rev / Unit</th>
<th className="py-4 px-4 text-right bg-white/5">Net Profit / Unit</th>
<th className="py-4 px-4 text-right">Net Margin %</th>
@@ -528,8 +600,25 @@ export default function OmnichannelMarginPage() {
<td className="py-3.5 px-4 text-right font-mono text-rose-300">
{fmtMoney(item.unitBomCost)}
</td>
<td className="py-3.5 px-4 text-right font-mono text-slate-400">
~{item.totalFeePercent}%
<td className="py-3.5 px-4 text-right">
<div className="font-mono text-slate-200">
~{item.effectiveFeePercent}%
</div>
<div className="text-[10px] mt-0.5">
{item.feeSource === 'actual' ? (
<span className="px-1.5 py-0.5 rounded font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
Actual
</span>
) : item.feeSource === 'hybrid' ? (
<span className="px-1.5 py-0.5 rounded font-bold bg-indigo-500/20 text-indigo-400 border border-indigo-500/30">
Hybrid
</span>
) : (
<span className="px-1.5 py-0.5 rounded font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30">
30% Fallback
</span>
)}
</div>
</td>
<td className="py-3.5 px-4 text-right font-mono text-slate-200">
{fmtMoney(unitNetRevenue)}
+172 -40
View File
@@ -60,6 +60,15 @@ function parseOrderDate(dateStr: string | Date | null | undefined): Date | null
return isNaN(d.getTime()) ? null : d;
}
const toNum = (val: any): number => {
if (val === null || val === undefined || val === "") return 0;
const s = String(val).replace(/[^0-9.\-]/g, "");
const n = parseFloat(s);
return isNaN(n) ? 0 : n;
};
const DEFAULT_FALLBACK_FEE_PERCENT = 30.0; // 30% conservative platform deduction fallback
export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
// ─────────────────────────────────────────────────────────────────────────────
@@ -286,7 +295,7 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
.get("/omnichannel", async ({ query }) => {
const search = (query.search || "").trim().toLowerCase();
const channel = (query.channel || "all").trim().toLowerCase();
const dateRange = resolveDateRange(query.period, query.startDate, query.endDate);
const dateRange = resolveDateRange(query.period || "this_month", query.startDate, query.endDate);
// 1. Fetch mapped marketplace products with master variants & BOM
const mpProducts = await prisma.marketplaceProduct.findMany({
@@ -313,20 +322,6 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
orderBy: { totalRevenue: "desc" },
});
const CHANNEL_FEES: Record<string, { commissionPercent: number; servicePercent: number; paymentPercent: number }> = {
shopee: { commissionPercent: 8.0, servicePercent: 5.0, paymentPercent: 3.21 }, // ~16.21%
lazada: { commissionPercent: 6.0, servicePercent: 4.0, paymentPercent: 3.21 }, // ~13.21%
tiktok: { commissionPercent: 6.0, servicePercent: 4.5, paymentPercent: 3.0 }, // ~13.5%
};
// 2. If a specific Date Range is selected, calculate dynamic sales from Orders
let dynamicSalesMap: Map<number, { soldQty: number; revenue: number }> | null = null;
if (dateRange.start) {
dynamicSalesMap = new Map();
const start = dateRange.start;
const end = dateRange.end || new Date();
// Look up helper: map marketplace item keys to marketplaceProduct.id
const mpLookup = new Map<string, number>();
for (const mp of mpProducts) {
@@ -337,13 +332,33 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
}
}
// A. TikTok Orders in Range
// 2. Dynamic Order Aggregator (Actual Fee Extraction with 30% Fallback)
interface DynamicSalesEntry {
soldQty: number;
revenue: number;
actualFeeSum: number;
fallbackFeeSum: number;
actualCount: number;
fallbackCount: number;
}
const dynamicSalesMap = new Map<number, DynamicSalesEntry>();
const start = dateRange.start;
const end = dateRange.end || new Date();
// A. TikTok Orders
if (channel === "all" || channel === "tiktok") {
const ttOrders = await prisma.tiktokOrder.findMany({
where: { createdTime: { not: null } },
select: {
orderId: true,
createdTime: true,
shop: true,
orderAmount: true,
commissionFee: true,
affiliateFee: true,
netSettlement: true,
isSettled: true,
items: {
select: {
sellerSku: true,
@@ -360,7 +375,15 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
for (const order of ttOrders) {
const orderDate = parseOrderDate(order.createdTime);
if (!orderDate || orderDate < start || orderDate > end) continue;
if (start && (!orderDate || orderDate < start || orderDate > end)) continue;
const orderAmount = order.orderAmount || 0;
// Check actual deduction from settlement or commission
const hasSettlement = order.isSettled && order.netSettlement > 0;
const actualOrderFee = hasSettlement
? Math.max(0, orderAmount - order.netSettlement)
: ((order.commissionFee || 0) + (order.affiliateFee || 0));
const isActual = actualOrderFee > 0;
for (const item of order.items) {
const sku = item.sellerSku || item.skuId || "";
@@ -371,21 +394,42 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
const qty = item.quantity || 1;
const rev = item.subtotalAfterDiscount > 0 ? item.subtotalAfterDiscount : (item.unitOriginalPrice * qty);
const cur = dynamicSalesMap.get(mpId) || { soldQty: 0, revenue: 0 };
const cur = dynamicSalesMap.get(mpId) || {
soldQty: 0,
revenue: 0,
actualFeeSum: 0,
fallbackFeeSum: 0,
actualCount: 0,
fallbackCount: 0,
};
cur.soldQty += qty;
cur.revenue += rev;
if (isActual) {
// Proportional share of actual order deduction
const share = orderAmount > 0 ? (rev / orderAmount) : 1;
cur.actualFeeSum += actualOrderFee * share;
cur.actualCount += 1;
} else {
// Fallback 30%
cur.fallbackFeeSum += rev * (DEFAULT_FALLBACK_FEE_PERCENT / 100);
cur.fallbackCount += 1;
}
dynamicSalesMap.set(mpId, cur);
}
}
}
// B. Shopee Orders in Range
// B. Shopee Orders
if (channel === "all" || channel === "shopee") {
const spOrders = await prisma.shopeeOrder.findMany({
where: { orderCreatedAt: { not: null } },
select: {
orderId: true,
orderCreatedAt: true,
shop: true,
totalAmount: true,
items: {
select: {
parentSku: true,
@@ -395,6 +439,7 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
quantity: true,
totalPayment: true,
dealPrice: true,
rawData: true,
},
},
},
@@ -402,7 +447,17 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
for (const order of spOrders) {
const orderDate = parseOrderDate(order.orderCreatedAt);
if (!orderDate || orderDate < start || orderDate > end) continue;
if (start && (!orderDate || orderDate < start || orderDate > end)) continue;
// Shopee Order-level actual fee from rawData (first item has order-level fees)
const firstRaw = (order.items[0]?.rawData as any) || {};
const comm = toNum(firstRaw["ค่าคอมมิชชั่น"]);
const service = toNum(firstRaw["ค่าบริการ"]);
const tx = toNum(firstRaw["Transaction Fee"]);
const voucher = toNum(firstRaw["โค้ดส่วนลดชำระโดยผู้ขาย"]);
const orderActualFee = comm + service + tx + voucher;
const isActual = orderActualFee > 0;
const orderTotalRev = order.totalAmount || order.items.reduce((sum, it) => sum + (it.totalPayment > 0 ? it.totalPayment : (it.dealPrice * it.quantity)), 0);
for (const item of order.items) {
const sku = item.skuRef || item.parentSku || "";
@@ -413,15 +468,33 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
const qty = item.quantity || 1;
const rev = item.totalPayment > 0 ? item.totalPayment : (item.dealPrice * qty);
const cur = dynamicSalesMap.get(mpId) || { soldQty: 0, revenue: 0 };
const cur = dynamicSalesMap.get(mpId) || {
soldQty: 0,
revenue: 0,
actualFeeSum: 0,
fallbackFeeSum: 0,
actualCount: 0,
fallbackCount: 0,
};
cur.soldQty += qty;
cur.revenue += rev;
if (isActual) {
const share = orderTotalRev > 0 ? (rev / orderTotalRev) : 1;
cur.actualFeeSum += orderActualFee * share;
cur.actualCount += 1;
} else {
// Fallback 30%
cur.fallbackFeeSum += rev * (DEFAULT_FALLBACK_FEE_PERCENT / 100);
cur.fallbackCount += 1;
}
dynamicSalesMap.set(mpId, cur);
}
}
}
// C. Lazada Orders in Range
// C. Lazada Orders
if (channel === "all" || channel === "lazada") {
const lzOrders = await prisma.lazadaOrder.findMany({
where: { createTime: { not: null } },
@@ -443,7 +516,7 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
for (const order of lzOrders) {
const orderDate = parseOrderDate(order.createTime);
if (!orderDate || orderDate < start || orderDate > end) continue;
if (start && (!orderDate || orderDate < start || orderDate > end)) continue;
for (const item of order.items) {
const sku = item.sellerSku || item.lazadaSku || "";
@@ -454,14 +527,24 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
const qty = 1;
const rev = item.paidPrice > 0 ? item.paidPrice : item.unitPrice;
const cur = dynamicSalesMap.get(mpId) || { soldQty: 0, revenue: 0 };
const cur = dynamicSalesMap.get(mpId) || {
soldQty: 0,
revenue: 0,
actualFeeSum: 0,
fallbackFeeSum: 0,
actualCount: 0,
fallbackCount: 0,
};
cur.soldQty += qty;
cur.revenue += rev;
// Lazada has no settlement import yet -> 30% fallback
cur.fallbackFeeSum += rev * (DEFAULT_FALLBACK_FEE_PERCENT / 100);
cur.fallbackCount += 1;
dynamicSalesMap.set(mpId, cur);
}
}
}
}
// 3. Map Items & Accumulate KPIs
let totalGrossRevenue = 0;
@@ -469,25 +552,58 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
let totalBOMCost = 0;
let totalEstNetProfit = 0;
let totalUnitsSold = 0;
let totalPlatformFee = 0;
let totalActualFeeSum = 0;
let totalFallbackFeeSum = 0;
let totalActualOrdersCount = 0;
let totalFallbackOrdersCount = 0;
const channelStats: Record<string, { soldQty: number; revenue: number; bomCost: number; netProfit: number }> = {
shopee: { soldQty: 0, revenue: 0, bomCost: 0, netProfit: 0 },
lazada: { soldQty: 0, revenue: 0, bomCost: 0, netProfit: 0 },
tiktok: { soldQty: 0, revenue: 0, bomCost: 0, netProfit: 0 },
const channelStats: Record<string, { soldQty: number; revenue: number; platformFee: number; bomCost: number; netProfit: number }> = {
shopee: { soldQty: 0, revenue: 0, platformFee: 0, bomCost: 0, netProfit: 0 },
lazada: { soldQty: 0, revenue: 0, platformFee: 0, bomCost: 0, netProfit: 0 },
tiktok: { soldQty: 0, revenue: 0, platformFee: 0, bomCost: 0, netProfit: 0 },
};
const mappedItems: any[] = [];
for (const item of mpProducts) {
let soldQty = item.totalSoldQty;
let rev = item.totalRevenue;
let soldQty = 0;
let rev = 0;
let platformFee = 0;
let feeSource: "actual" | "hybrid" | "fallback_30pct" = "fallback_30pct";
let actualFeePart = 0;
let fallbackFeePart = 0;
// If dynamic date range active, use filtered order numbers
if (dynamicSalesMap) {
const dyn = dynamicSalesMap.get(item.id);
if (!dyn || dyn.soldQty === 0) continue; // Skip items with no sales in this date range
if (dyn && dyn.soldQty > 0) {
soldQty = dyn.soldQty;
rev = dyn.revenue;
actualFeePart = dyn.actualFeeSum;
fallbackFeePart = dyn.fallbackFeeSum;
platformFee = Math.round((dyn.actualFeeSum + dyn.fallbackFeeSum) * 100) / 100;
if (dyn.actualCount > 0 && dyn.fallbackCount === 0) {
feeSource = "actual";
} else if (dyn.actualCount > 0 && dyn.fallbackCount > 0) {
feeSource = "hybrid";
} else {
feeSource = "fallback_30pct";
}
totalActualOrdersCount += dyn.actualCount;
totalFallbackOrdersCount += dyn.fallbackCount;
} else if (!start) {
// All-time fallback from MarketplaceProduct aggregate if no order details
if (item.totalSoldQty === 0 && item.totalRevenue === 0) continue;
soldQty = item.totalSoldQty;
rev = item.totalRevenue;
platformFee = Math.round(rev * (DEFAULT_FALLBACK_FEE_PERCENT / 100) * 100) / 100;
fallbackFeePart = platformFee;
feeSource = "fallback_30pct";
totalFallbackOrdersCount += 1;
} else {
// Date range filtered and no sales in this period
continue;
}
const v = item.masterVariant!;
@@ -498,13 +614,11 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
const itemBomCost = Math.round(unitBomCost * soldQty * 100) / 100;
const ch = item.channel.toLowerCase();
const feeConfig = CHANNEL_FEES[ch] || { commissionPercent: 7.0, servicePercent: 4.0, paymentPercent: 3.0 };
const totalFeePercent = feeConfig.commissionPercent + feeConfig.servicePercent + feeConfig.paymentPercent;
const estPlatformFee = Math.round(rev * (totalFeePercent / 100) * 100) / 100;
const netRevenue = Math.round((rev - estPlatformFee) * 100) / 100;
const netRevenue = Math.round((rev - platformFee) * 100) / 100;
const netProfit = Math.round((netRevenue - itemBomCost) * 100) / 100;
const netMarginPercent = rev > 0 ? Math.round((netProfit / rev) * 1000) / 10 : 0;
const effectiveFeePercent = rev > 0 ? Math.round((platformFee / rev) * 1000) / 10 : DEFAULT_FALLBACK_FEE_PERCENT;
const avgSellingPrice = soldQty > 0 ? Math.round((rev / soldQty) * 100) / 100 : item.avgPrice;
const directPrice = v.price || avgSellingPrice || 0;
@@ -512,14 +626,18 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
const directMarginPercent = directPrice > 0 ? Math.round((directGrossProfit / directPrice) * 1000) / 10 : 0;
totalGrossRevenue += rev;
totalPlatformFee += platformFee;
totalEstNetRevenue += netRevenue;
totalBOMCost += itemBomCost;
totalEstNetProfit += netProfit;
totalUnitsSold += soldQty;
totalActualFeeSum += actualFeePart;
totalFallbackFeeSum += fallbackFeePart;
if (channelStats[ch]) {
channelStats[ch].soldQty += soldQty;
channelStats[ch].revenue += rev;
channelStats[ch].platformFee += platformFee;
channelStats[ch].bomCost += itemBomCost;
channelStats[ch].netProfit += netProfit;
}
@@ -540,8 +658,9 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
categoryName: v.product?.category?.name || "Uncategorized",
unitBomCost: Math.round(unitBomCost * 100) / 100,
totalBomCost: itemBomCost,
totalFeePercent,
estPlatformFee,
platformFee,
effectiveFeePercent,
feeSource, // "actual" | "hybrid" | "fallback_30pct"
netRevenue,
netProfit,
netMarginPercent,
@@ -563,6 +682,8 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
const overallNetMargin =
totalGrossRevenue > 0 ? Math.round((totalEstNetProfit / totalGrossRevenue) * 1000) / 10 : 0;
const effectiveFeeRate =
totalGrossRevenue > 0 ? Math.round((totalPlatformFee / totalGrossRevenue) * 1000) / 10 : DEFAULT_FALLBACK_FEE_PERCENT;
return {
periodInfo: {
@@ -572,14 +693,25 @@ export const profitabilityRoute = new Elysia({ prefix: "/profitability" })
endDate: dateRange.end ? dateRange.end.toISOString().slice(0, 10) : null,
daysCount: dateRange.daysCount,
},
feePolicy: {
mode: "hybrid_actual_with_30pct_fallback",
fallbackPercent: DEFAULT_FALLBACK_FEE_PERCENT,
description: "Shopee uses actual fees from report rawData. TikTok uses actual net settlement & fees. Any unmapped or non-settled order falls back to 30% platform deduction.",
},
kpis: {
totalMappedProducts: mappedItems.length,
totalUnitsSold,
totalGrossRevenue: Math.round(totalGrossRevenue * 100) / 100,
totalPlatformFee: Math.round(totalPlatformFee * 100) / 100,
totalEstNetRevenue: Math.round(totalEstNetRevenue * 100) / 100,
totalBOMCost: Math.round(totalBOMCost * 100) / 100,
totalEstNetProfit: Math.round(totalEstNetProfit * 100) / 100,
overallNetMargin,
effectiveFeeRate,
actualFeeAmount: Math.round(totalActualFeeSum * 100) / 100,
fallbackFeeAmount: Math.round(totalFallbackFeeSum * 100) / 100,
actualOrdersCount: totalActualOrdersCount,
fallbackOrdersCount: totalFallbackOrdersCount,
channelStats,
},
items: filtered,
@@ -7,7 +7,11 @@ import i18n from '../lib/i18n';
import { useCartStore } from '../store/cartStore';
import { useWishlistStore } from '../store/wishlistStore';
import { useAuthStore } from '../store/authStore';
import { useCookieConsentStore } from '../store/cookieConsentStore';
import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from '../lib/locales';
import CookieBanner from './cookie/CookieBanner';
import CookiePreferencesModal from './cookie/CookiePreferencesModal';
import ScriptManager from './cookie/ScriptManager';
export default function ClientProviders({ children }: { children: ReactNode }) {
useEffect(() => {
@@ -25,13 +29,17 @@ export default function ClientProviders({ children }: { children: ReactNode }) {
void useCartStore.persist.rehydrate()
void useWishlistStore.persist.rehydrate()
void useAuthStore.persist.rehydrate()
void useCookieConsentStore.persist.rehydrate()
}, [])
return (
<>
<ScriptManager />
<ScrollToTop />
{children}
<CartDrawer />
<CookieBanner />
<CookiePreferencesModal />
</>
);
}
+8
View File
@@ -15,6 +15,7 @@ import {
import { useTranslation } from 'react-i18next'
import { resolveLocalized } from '../lib/localization'
import { useLang } from '../hooks/useLang'
import { useCookieConsentStore } from '../store/cookieConsentStore'
interface FooterProps {
categories?: Category[]
@@ -154,6 +155,13 @@ export default function Footer({
</h4>
<div className="site-footer-column-links flex flex-col space-y-2 text-muted-text">
{supportMenu.map((item) => <Link key={item.id} href={item.url} className="ui-footer-link">{translateMenuLabel(item)}</Link>)}
<button
type="button"
onClick={() => useCookieConsentStore.getState().openPreferences()}
className="text-left ui-footer-link hover:underline transition-colors cursor-pointer text-xs"
>
{t('cookie.settings', 'การตั้งค่าคุกกี้')}
</button>
</div>
<div className="pt-4">
<p className="text-[10px] uppercase tracking-widest text-muted-text">
@@ -0,0 +1,78 @@
"use client";
import { useCookieConsentStore } from '../../store/cookieConsentStore';
import { useTranslation } from 'react-i18next';
import { Cookie, Settings2, ShieldCheck } from 'lucide-react';
export default function CookieBanner() {
const { t } = useTranslation();
const { record, isHydrated, acceptAll, rejectAll, openPreferences } = useCookieConsentStore();
// Do not render on server or before rehydration, or if user has already made a choice
if (!isHydrated || record.hasResponded) {
return null;
}
return (
<aside
aria-label={t('cookie.bannerTitle', 'การตั้งค่าคุกกี้และความเป็นส่วนตัว')}
className="fixed bottom-0 inset-x-0 z-50 p-4 sm:p-6 pointer-events-none animate-in fade-in slide-in-from-bottom-6 duration-500"
>
<div className="max-w-5xl mx-auto pointer-events-auto bg-surface-card/95 backdrop-blur-md border border-border-color shadow-2xl rounded-2xl p-5 sm:p-6 text-text-main transition-all">
<div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-5">
{/* Icon & Description */}
<div className="flex items-start gap-3.5 flex-1 pr-0 md:pr-4">
<div className="p-2.5 rounded-xl bg-brand-cool/60 text-brand-primary shrink-0 mt-0.5">
<Cookie className="w-5 h-5" />
</div>
<div className="space-y-1">
<div className="flex items-center gap-2">
<h3 className="font-semibold text-sm sm:text-base text-text-main tracking-wide">
{t('cookie.bannerTitle', 'เราให้ความสำคัญกับความเป็นส่วนตัวของคุณ')}
</h3>
<span className="inline-flex items-center gap-1 text-[11px] font-medium px-2 py-0.5 rounded-full bg-brand-cool/50 text-muted-text">
<ShieldCheck className="w-3 h-3 text-brand-primary" />
PDPA Compliant
</span>
</div>
<p className="text-xs sm:text-sm text-muted-text leading-relaxed">
{t(
'cookie.bannerDesc',
'เราใช้คุกกี้เพื่อเพิ่มประสิทธิภาพ ประสบการณ์ที่ดีในการใช้งานเว็บไซต์ และเพื่อการวิเคราะห์ปรับปรุงบริการ ท่านสามารถเลือกตั้งค่าความยินยอมตามประเภทคุกกี้ได้'
)}
</p>
</div>
</div>
{/* Action Buttons */}
<div className="flex flex-wrap sm:flex-nowrap items-center gap-2.5 w-full md:w-auto shrink-0">
<button
type="button"
onClick={openPreferences}
className="flex-1 sm:flex-none inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-xs sm:text-sm font-medium rounded-lg text-muted-text hover:text-text-main hover:bg-surface-muted transition-colors border border-transparent"
>
<Settings2 className="w-3.5 h-3.5" />
<span>{t('cookie.btnCustomize', 'ตั้งค่าคุกกี้')}</span>
</button>
<button
type="button"
onClick={rejectAll}
className="flex-1 sm:flex-none px-4 py-2 text-xs sm:text-sm font-medium rounded-lg border border-border-color text-text-main hover:bg-surface-muted hover:border-text-main/20 transition-all text-center"
>
{t('cookie.btnRejectAll', 'ปฏิเสธทั้งหมด')}
</button>
<button
type="button"
onClick={acceptAll}
className="w-full sm:w-auto px-5 py-2 text-xs sm:text-sm font-semibold rounded-lg bg-brand-primary text-white hover:bg-brand-primary-hover shadow-sm hover:shadow transition-all text-center tracking-wide"
>
{t('cookie.btnAcceptAll', 'ยอมรับทั้งหมด')}
</button>
</div>
</div>
</div>
</aside>
);
}
@@ -0,0 +1,225 @@
"use client";
import { useState, useEffect } from 'react';
import { useCookieConsentStore, type CookiePreferences } from '../../store/cookieConsentStore';
import { useTranslation } from 'react-i18next';
import { X, ShieldCheck, BarChart3, Target, Lock, Check } from 'lucide-react';
export default function CookiePreferencesModal() {
const { t } = useTranslation();
const {
record,
isPreferencesOpen,
closePreferences,
savePreferences,
acceptAll,
rejectAll,
} = useCookieConsentStore();
// Local state for interactive toggling inside the modal
const [localPrefs, setLocalPrefs] = useState<CookiePreferences>({
necessary: true,
analytics: false,
marketing: false,
});
// Sync local state when modal opens
useEffect(() => {
if (isPreferencesOpen) {
setLocalPrefs({
necessary: true,
analytics: Boolean(record.preferences.analytics),
marketing: Boolean(record.preferences.marketing),
});
}
}, [isPreferencesOpen, record.preferences]);
// Handle ESC key to close
useEffect(() => {
if (!isPreferencesOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') closePreferences();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isPreferencesOpen, closePreferences]);
if (!isPreferencesOpen) return null;
const handleSave = () => {
savePreferences(localPrefs);
};
return (
<div
role="dialog"
aria-modal="true"
aria-labelledby="cookie-modal-title"
className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/50 backdrop-blur-sm animate-in fade-in duration-200"
>
<div
className="w-full max-w-2xl bg-surface-card rounded-2xl shadow-2xl border border-border-color overflow-hidden flex flex-col max-h-[90vh] animate-in zoom-in-95 duration-200"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-border-color bg-surface-nav-rest">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-brand-cool/70 text-brand-primary">
<ShieldCheck className="w-5 h-5" />
</div>
<div>
<h2 id="cookie-modal-title" className="text-base sm:text-lg font-bold text-text-main">
{t('cookie.prefTitle', 'ศูนย์การตั้งค่าความเป็นส่วนตัว (Cookie Preferences)')}
</h2>
<p className="text-xs text-muted-text">
{t('cookie.prefSubtitle', 'จัดการความยินยอมในการจัดเก็บและใช้งานคุกกี้ตาม พ.ร.บ. คุ้มครองข้อมูลส่วนบุคคล (PDPA)')}
</p>
</div>
</div>
<button
type="button"
onClick={closePreferences}
className="p-2 text-muted-text hover:text-text-main rounded-lg hover:bg-surface-muted transition-colors"
aria-label="Close"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Body / Cookie Categories */}
<div className="p-6 space-y-4 overflow-y-auto divide-y divide-border-color/60">
{/* 1. Necessary Cookies */}
<div className="pt-2 first:pt-0">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3 flex-1">
<div className="p-2 rounded-md bg-surface-muted text-muted-text mt-0.5">
<Lock className="w-4 h-4" />
</div>
<div>
<div className="flex items-center gap-2">
<h4 className="text-sm font-semibold text-text-main">
{t('cookie.catNecessaryTitle', 'คุกกี้ที่จำเป็นอย่างยิ่ง (Strictly Necessary)')}
</h4>
<span className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">
{t('cookie.alwaysActive', 'เปิดใช้งานเสมอ')}
</span>
</div>
<p className="text-xs text-muted-text mt-1 leading-relaxed">
{t(
'cookie.catNecessaryDesc',
'คุกกี้เหล่านี้มีความจำเป็นต่อการทำงานพื้นฐานของเว็บไซต์ เช่น การเข้าสู่ระบบ ความปลอดภัย การจดจำสินค้าในตะกร้า และการตั้งค่าภาษา เว็บไซต์ไม่สามารถทำงานได้อย่างถูกต้องหากไม่มีคุกกี้เหล่านี้'
)}
</p>
</div>
</div>
<div className="relative inline-flex items-center cursor-not-allowed opacity-80 shrink-0">
<input
type="checkbox"
checked={true}
disabled
className="sr-only peer"
/>
<div className="w-11 h-6 bg-brand-primary rounded-full peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all"></div>
</div>
</div>
</div>
{/* 2. Analytics Cookies */}
<div className="pt-4">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3 flex-1">
<div className="p-2 rounded-md bg-brand-cool/50 text-brand-primary mt-0.5">
<BarChart3 className="w-4 h-4" />
</div>
<div>
<h4 className="text-sm font-semibold text-text-main">
{t('cookie.catAnalyticsTitle', 'คุกกี้เพื่อการวิเคราะห์และวัดผล (Analytics & Performance)')}
</h4>
<p className="text-xs text-muted-text mt-1 leading-relaxed">
{t(
'cookie.catAnalyticsDesc',
'ช่วยให้เราทราบสถิติการเข้าชม พฤติกรรมหน้าเว็บยอดนิยม และเส้นทางการใช้งานของผู้ใช้ เพื่อนำข้อมูลไปปรับปรุงประสิทธิภาพและบริการ (เช่น Google Analytics 4) ข้อมูลจะถูกจัดเก็บแบบไม่ระบุตัวตนโดยตรง'
)}
</p>
</div>
</div>
<label className="relative inline-flex items-center cursor-pointer shrink-0">
<input
type="checkbox"
checked={localPrefs.analytics}
onChange={(e) =>
setLocalPrefs((prev) => ({ ...prev, analytics: e.target.checked }))
}
className="sr-only peer"
/>
<div className="w-11 h-6 bg-border-color peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-primary"></div>
</label>
</div>
</div>
{/* 3. Marketing Cookies */}
<div className="pt-4">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3 flex-1">
<div className="p-2 rounded-md bg-brand-cool/50 text-brand-primary mt-0.5">
<Target className="w-4 h-4" />
</div>
<div>
<h4 className="text-sm font-semibold text-text-main">
{t('cookie.catMarketingTitle', 'คุกกี้เพื่อการตลาดและโฆษณา (Marketing & Targeting)')}
</h4>
<p className="text-xs text-muted-text mt-1 leading-relaxed">
{t(
'cookie.catMarketingDesc',
'ใช้เพื่อนำเสนอโปรโมชัน โฆษณา และเนื้อหาที่สอดคล้องกับความสนใจของท่านผ่านแพลตฟอร์มพันธมิตร (เช่น Meta Pixel, TikTok Pixel, Google Ads) รวมถึงวัดประสิทธิผลของแคมเปญ'
)}
</p>
</div>
</div>
<label className="relative inline-flex items-center cursor-pointer shrink-0">
<input
type="checkbox"
checked={localPrefs.marketing}
onChange={(e) =>
setLocalPrefs((prev) => ({ ...prev, marketing: e.target.checked }))
}
className="sr-only peer"
/>
<div className="w-11 h-6 bg-border-color peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-primary"></div>
</label>
</div>
</div>
</div>
{/* Footer / Buttons */}
<div className="flex flex-col-reverse sm:flex-row items-center justify-between gap-3 p-4 sm:p-5 border-t border-border-color bg-surface-nav-rest">
<button
type="button"
onClick={rejectAll}
className="w-full sm:w-auto px-4 py-2 text-xs sm:text-sm font-medium rounded-lg text-muted-text hover:text-text-main hover:bg-surface-muted transition-colors text-center"
>
{t('cookie.btnRejectAll', 'ปฏิเสธทั้งหมด')}
</button>
<div className="flex items-center gap-2.5 w-full sm:w-auto">
<button
type="button"
onClick={handleSave}
className="flex-1 sm:flex-none inline-flex items-center justify-center gap-1.5 px-4 py-2 text-xs sm:text-sm font-medium rounded-lg border border-border-color text-text-main hover:bg-surface-muted hover:border-text-main/20 transition-all text-center"
>
<Check className="w-4 h-4 text-brand-primary" />
<span>{t('cookie.btnSavePreferences', 'บันทึกการตั้งค่า')}</span>
</button>
<button
type="button"
onClick={acceptAll}
className="flex-1 sm:flex-none px-5 py-2 text-xs sm:text-sm font-semibold rounded-lg bg-brand-primary text-white hover:bg-brand-primary-hover shadow-sm transition-all text-center"
>
{t('cookie.btnAcceptAll', 'ยอมรับทั้งหมด')}
</button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,170 @@
"use client";
import { useEffect, useRef } from 'react';
import { useCookieConsentStore } from '../../store/cookieConsentStore';
declare global {
interface Window {
dataLayer?: any[];
gtag?: (...args: any[]) => void;
fbq?: any;
_fbq?: any;
ttq?: any;
}
}
export default function ScriptManager() {
const { record, isHydrated } = useCookieConsentStore();
const consentInitializedRef = useRef(false);
const gaInjectedRef = useRef(false);
const metaInjectedRef = useRef(false);
const tiktokInjectedRef = useRef(false);
// 1. Initialize Google Consent Mode v2 Defaults
useEffect(() => {
if (typeof window === 'undefined' || consentInitializedRef.current) return;
consentInitializedRef.current = true;
window.dataLayer = window.dataLayer || [];
if (!window.gtag) {
window.gtag = function () {
window.dataLayer?.push(arguments);
};
}
// Default to 'denied' as required by GDPR/PDPA prior to user choice
window.gtag('consent', 'default', {
analytics_storage: 'denied',
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
});
}, []);
// 2. Sync consent updates whenever state changes
useEffect(() => {
if (!isHydrated || typeof window === 'undefined') return;
const { preferences, hasResponded } = record;
if (window.gtag) {
window.gtag('consent', 'update', {
analytics_storage: hasResponded && preferences.analytics ? 'granted' : 'denied',
ad_storage: hasResponded && preferences.marketing ? 'granted' : 'denied',
ad_user_data: hasResponded && preferences.marketing ? 'granted' : 'denied',
ad_personalization: hasResponded && preferences.marketing ? 'granted' : 'denied',
});
}
// Dispatch custom browser event for any other custom tags/scripts
window.dispatchEvent(
new CustomEvent('homaroma:consent-change', {
detail: {
hasResponded,
preferences,
},
})
);
// 3. Inject GA4 dynamically if enabled and configured
const gaId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
if (gaId && hasResponded && preferences.analytics && !gaInjectedRef.current) {
gaInjectedRef.current = true;
const script = document.createElement('script');
script.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
script.async = true;
document.head.appendChild(script);
window.gtag?.('js', new Date());
window.gtag?.('config', gaId, {
anonymize_ip: true,
});
}
// 4. Inject Meta Pixel dynamically if enabled and configured
const metaPixelId = process.env.NEXT_PUBLIC_META_PIXEL_ID;
if (metaPixelId && hasResponded && preferences.marketing && !metaInjectedRef.current) {
metaInjectedRef.current = true;
(function (f: any, b: any, e: any, v: any, n?: any, t?: any, s?: any) {
if (f.fbq) return;
n = f.fbq = function () {
n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
};
if (!f._fbq) f._fbq = n;
n.push = n;
n.loaded = true;
n.version = '2.0';
n.queue = [];
t = b.createElement(e);
t.async = true;
t.src = v;
s = b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t, s);
})(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
window.fbq('init', metaPixelId);
window.fbq('track', 'PageView');
}
// 5. Inject TikTok Pixel dynamically if enabled and configured
const tiktokPixelId = process.env.NEXT_PUBLIC_TIKTOK_PIXEL_ID;
if (tiktokPixelId && hasResponded && preferences.marketing && !tiktokInjectedRef.current) {
tiktokInjectedRef.current = true;
(function (w: any, d: any, t: any) {
w.TiktokAnalyticsObject = t;
const ttq = (w[t] = w[t] || []);
ttq.methods = [
'page',
'track',
'identify',
'instances',
'debug',
'on',
'off',
'once',
'ready',
'alias',
'group',
'enableCookie',
'disableCookie',
];
ttq.setAndDefer = function (t: any, e: any) {
t[e] = function () {
t.push([e].concat(Array.prototype.slice.call(arguments, 0)));
};
};
for (let i = 0; i < ttq.methods.length; i++) {
ttq.setAndDefer(ttq, ttq.methods[i]);
}
ttq.instance = function (t: any) {
const e = ttq._i[t] || [];
for (let n = 0; n < ttq.methods.length; n++) {
ttq.setAndDefer(e, ttq.methods[n]);
}
return e;
};
ttq.load = function (e: any, n: any) {
const i = 'https://analytics.tiktok.com/i18n/pixel/events.js';
ttq._i = ttq._i || {};
ttq._i[e] = [];
ttq._i[e]._u = i;
ttq._t = ttq._t || {};
ttq._t[e] = +new Date();
ttq._o = ttq._o || {};
ttq._o[e] = n || {};
const o = d.createElement('script');
o.type = 'text/javascript';
o.async = true;
o.src = `${i}?sdkid=${e}&lib=${t}`;
const a = d.getElementsByTagName('script')[0];
a.parentNode.insertBefore(o, a);
};
})(window, document, 'ttq');
window.ttq?.load(tiktokPixelId);
window.ttq?.page();
}
}, [record, isHydrated]);
return null;
}
+7 -7
View File
@@ -11,13 +11,13 @@ export type TranslationSchema = typeof thTranslation
const translations: Record<string, TranslationSchema> = {
th: thTranslation,
en: enTranslation as TranslationSchema,
ja: jaTranslation as TranslationSchema,
zh: zhTranslation as TranslationSchema,
vi: viTranslation as TranslationSchema,
ko: koTranslation as TranslationSchema,
lo: loTranslation as TranslationSchema,
it: itTranslation as TranslationSchema,
en: enTranslation as unknown as TranslationSchema,
ja: jaTranslation as unknown as TranslationSchema,
zh: zhTranslation as unknown as TranslationSchema,
vi: viTranslation as unknown as TranslationSchema,
ko: koTranslation as unknown as TranslationSchema,
lo: loTranslation as unknown as TranslationSchema,
it: itTranslation as unknown as TranslationSchema,
}
export function getServerTranslations(lang = 'th'): TranslationSchema {
@@ -216,6 +216,24 @@
"notFound": "Unable to verify order details",
"networkError": "Connection error. Please try again."
}
},
"cookie": {
"settings": "Cookie Preferences",
"bannerTitle": "We value your privacy",
"bannerDesc": "We use cookies to improve your browsing experience, provide personalized content, and analyze our website traffic in accordance with privacy laws. You can choose to accept all cookies or manage your preferences.",
"btnCustomize": "Preferences",
"btnRejectAll": "Reject Non-Essential",
"btnAcceptAll": "Accept All",
"btnSavePreferences": "Save Preferences",
"prefTitle": "Privacy & Cookie Preferences",
"prefSubtitle": "Manage your consent for cookie storage and data processing under privacy regulations (PDPA & GDPR)",
"alwaysActive": "Always Active",
"catNecessaryTitle": "Strictly Necessary Cookies",
"catNecessaryDesc": "These cookies are essential for the website to function properly, enabling basic functions like navigation, cart checkout, and access to secure areas. The website cannot function properly without these cookies.",
"catAnalyticsTitle": "Analytics & Performance Cookies",
"catAnalyticsDesc": "These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site (e.g., Google Analytics 4). All information is aggregated and anonymous.",
"catMarketingTitle": "Marketing & Targeting Cookies",
"catMarketingDesc": "These cookies may be set through our site by our advertising partners (e.g., Meta Pixel, TikTok Pixel, Google Ads) to build a profile of your interests and show you relevant adverts on other sites."
}
}
@@ -237,6 +237,24 @@
"notFound": "注文情報を確認できませんでした",
"networkError": "接続エラーが発生しました。もう一度お試しください。"
}
},
"cookie": {
"settings": "クッキー設定",
"bannerTitle": "お客様のプライバシーを尊重します",
"bannerDesc": "当ウェブサイトでは、利便性の向上、利用状況の分析、パーソナライズされた広告の提供のためにクッキーを使用しています。同意設定はいつでも変更できます。",
"btnCustomize": "設定",
"btnRejectAll": "必須以外を拒否",
"btnAcceptAll": "すべて同意",
"btnSavePreferences": "設定を保存",
"prefTitle": "プライバシーおよびクッキー設定",
"prefSubtitle": "個人情報保護法(PDPA/GDPR)に基づくクッキーの保存およびデータ利用の同意管理",
"alwaysActive": "常に有効",
"catNecessaryTitle": "必須クッキー (Strictly Necessary)",
"catNecessaryDesc": "ウェブサイトの基本的な機能(ログイン、セキュリティ、カート、言語設定など)に不可欠なクッキーです。このクッキーを無効にすることはできません。",
"catAnalyticsTitle": "分析・パフォーマンスクッキー (Analytics)",
"catAnalyticsDesc": "訪問者数やトラフィックソースを計測し、サイトのパフォーマンスを向上させるためのクッキーです(Google Analyticsなど)。",
"catMarketingTitle": "マーケティング・ターゲティングクッキー (Marketing)",
"catMarketingDesc": "お客様の興味関心に基づいた関連性の高い広告やプロモーションを配信するために使用されます(Meta Pixel、TikTok Pixelなど)。"
}
}
@@ -216,6 +216,24 @@
"notFound": "ไม่สามารถยืนยันข้อมูลคำสั่งซื้อได้",
"networkError": "เกิดข้อผิดพลาดในการเชื่อมต่อ กรุณาลองใหม่อีกครั้ง"
}
},
"cookie": {
"settings": "การตั้งค่าคุกกี้",
"bannerTitle": "เราให้ความสำคัญกับความเป็นส่วนตัวของคุณ",
"bannerDesc": "เราใช้คุกกี้เพื่อเพิ่มประสิทธิภาพ ประสบการณ์ที่ดีในการใช้งานเว็บไซต์ และเพื่อการวิเคราะห์ปรับปรุงบริการ ท่านสามารถเลือกตั้งค่าความยินยอมตามประเภทคุกกี้ได้",
"btnCustomize": "ตั้งค่าคุกกี้",
"btnRejectAll": "ปฏิเสธทั้งหมด",
"btnAcceptAll": "ยอมรับทั้งหมด",
"btnSavePreferences": "บันทึกการตั้งค่า",
"prefTitle": "ศูนย์การตั้งค่าความเป็นส่วนตัว",
"prefSubtitle": "จัดการความยินยอมในการจัดเก็บและใช้งานคุกกี้ตาม พ.ร.บ. คุ้มครองข้อมูลส่วนบุคคล (PDPA)",
"alwaysActive": "เปิดใช้งานเสมอ",
"catNecessaryTitle": "คุกกี้ที่จำเป็นอย่างยิ่ง (Strictly Necessary)",
"catNecessaryDesc": "คุกกี้เหล่านี้มีความจำเป็นต่อการทำงานพื้นฐานของเว็บไซต์ เช่น การเข้าสู่ระบบ ความปลอดภัย การจดจำสินค้าในตะกร้า และการตั้งค่าภาษา เว็บไซต์ไม่สามารถทำงานได้อย่างถูกต้องหากไม่มีคุกกี้เหล่านี้",
"catAnalyticsTitle": "คุกกี้เพื่อการวิเคราะห์และวัดผล (Analytics & Performance)",
"catAnalyticsDesc": "ช่วยให้เราทราบสถิติการเข้าชม พฤติกรรมหน้าเว็บยอดนิยม และเส้นทางการใช้งานของผู้ใช้ เพื่อนำข้อมูลไปปรับปรุงประสิทธิภาพและบริการ (เช่น Google Analytics 4) ข้อมูลจะถูกจัดเก็บแบบไม่ระบุตัวตนโดยตรง",
"catMarketingTitle": "คุกกี้เพื่อการตลาดและโฆษณา (Marketing & Targeting)",
"catMarketingDesc": "ใช้เพื่อนำเสนอโปรโมชัน โฆษณา และเนื้อหาที่สอดคล้องกับความสนใจของท่านผ่านแพลตฟอร์มพันธมิตร (เช่น Meta Pixel, TikTok Pixel, Google Ads) รวมถึงวัดประสิทธิผลของแคมเปญ"
}
}
@@ -237,6 +237,24 @@
"notFound": "无法验证订单信息",
"networkError": "网络连接错误,请稍后重试。"
}
},
"cookie": {
"settings": "Cookie 设置",
"bannerTitle": "我们重视您的隐私",
"bannerDesc": "我们使用 Cookie 来改善您的浏览体验、提供个性化内容以及根据隐私法规分析网站流量。您可以选择接受所有 Cookie 或自定义您的偏好设置。",
"btnCustomize": "偏好设置",
"btnRejectAll": "拒绝非必要",
"btnAcceptAll": "接受全部",
"btnSavePreferences": "保存设置",
"prefTitle": "隐私与 Cookie 偏好中心",
"prefSubtitle": "根据个人数据保护法规 (PDPA/GDPR) 管理 Cookie 存储及数据使用授权",
"alwaysActive": "始终启用",
"catNecessaryTitle": "必要 Cookie (Strictly Necessary)",
"catNecessaryDesc": "这些 Cookie 是网站运行所必需的,用于支持登录、安全性、购物车和语言设置等基本功能。网站无法在缺少此类 Cookie 的情况下正常运行。",
"catAnalyticsTitle": "分析与性能 Cookie (Analytics)",
"catAnalyticsDesc": "帮助我们统计访问量和流量来源,以评估并改善网站性能(例如 Google Analytics 4)。数据为匿名统计。",
"catMarketingTitle": "营销与广告 Cookie (Marketing)",
"catMarketingDesc": "由广告合作伙伴设置(例如 Meta Pixel、TikTok Pixel、Google Ads),用于构建您的兴趣画像并向您推送相关广告。"
}
}
@@ -0,0 +1,124 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const CURRENT_CONSENT_VERSION = '1.0';
export interface CookiePreferences {
necessary: boolean;
analytics: boolean;
marketing: boolean;
}
export interface CookieConsentRecord {
hasResponded: boolean;
version: string;
timestamp: string | null;
preferences: CookiePreferences;
}
interface CookieConsentState {
record: CookieConsentRecord;
isPreferencesOpen: boolean;
isHydrated: boolean;
// Actions
setHydrated: (hydrated: boolean) => void;
openPreferences: () => void;
closePreferences: () => void;
acceptAll: () => void;
rejectAll: () => void;
savePreferences: (preferences: Partial<CookiePreferences>) => void;
resetConsent: () => void;
}
const DEFAULT_RECORD: CookieConsentRecord = {
hasResponded: false,
version: CURRENT_CONSENT_VERSION,
timestamp: null,
preferences: {
necessary: true,
analytics: false,
marketing: false,
},
};
export const useCookieConsentStore = create<CookieConsentState>()(
persist(
(set) => ({
record: DEFAULT_RECORD,
isPreferencesOpen: false,
isHydrated: false,
setHydrated: (hydrated: boolean) => set({ isHydrated: hydrated }),
openPreferences: () => set({ isPreferencesOpen: true }),
closePreferences: () => set({ isPreferencesOpen: false }),
acceptAll: () => {
const now = new Date().toISOString();
set({
record: {
hasResponded: true,
version: CURRENT_CONSENT_VERSION,
timestamp: now,
preferences: {
necessary: true,
analytics: true,
marketing: true,
},
},
isPreferencesOpen: false,
});
},
rejectAll: () => {
const now = new Date().toISOString();
set({
record: {
hasResponded: true,
version: CURRENT_CONSENT_VERSION,
timestamp: now,
preferences: {
necessary: true,
analytics: false,
marketing: false,
},
},
isPreferencesOpen: false,
});
},
savePreferences: (userPrefs: Partial<CookiePreferences>) => {
const now = new Date().toISOString();
set((state) => ({
record: {
hasResponded: true,
version: CURRENT_CONSENT_VERSION,
timestamp: now,
preferences: {
necessary: true,
analytics: Boolean(userPrefs.analytics),
marketing: Boolean(userPrefs.marketing),
},
},
isPreferencesOpen: false,
}));
},
resetConsent: () => {
set({
record: DEFAULT_RECORD,
isPreferencesOpen: false,
});
},
}),
{
name: 'homaroma-cookie-consent',
partialize: (state) => ({ record: state.record }),
skipHydration: true,
onRehydrateStorage: () => (state) => {
state?.setHydrated(true);
},
}
)
);