Files
homaroma/scripts/apply_all_room_spray_bom.ts
T
Your Name c78a898af7 feat(bom): complete 100% master catalog BOM and add Profitability Management Suite
- Configured BOMs for all 585 master variants across 5 categories (Oil Ozone, Aroma Oil, Car Diffuser, Room Spray, Reed Diffuser)
- Mapped 2,111 marketplace products (Shopee and Lazada) to master catalog variants
- Added backend profitability routes (/api/profitability/matrix, /omnichannel, /mrp)
- Added 3 admin pages under Product menu: Cost & Profitability Matrix, Omnichannel Margin, and MRP & Material Demand
- Added comprehensive ledgers and production sync scripts
2026-10-18 18:58:11 +07:00

205 lines
8.1 KiB
TypeScript

import * as fs from "fs";
import * as path from "path";
const PROD_API = "https://api.homaroma.shop/api";
interface RawMaterial {
id: number;
name: string;
unit: string;
pricePerUnit: number;
}
interface Variant {
id: number;
sku: string;
options: string;
price: number;
hasBom: boolean;
bomItemCount: number;
totalBomCost: number;
}
interface Product {
id: number;
name: string;
brand: string | null;
category: string | null;
totalVariants: number;
configuredVariants: number;
bomStatus: string;
variants: Variant[];
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
console.log("== Applying BOM for all Room Spray Products (85 ml) ==");
console.log("Formula: 8% Fragrance (6.8 ml) + 92% DPM (78.2 ml) + Glass Spray Bottle (฿25.00)\n");
// 1. Fetch products
console.log("1. Fetching products from production...");
const statusRes = await fetch(`${PROD_API}/products/bom-status?limit=250`);
if (!statusRes.ok) throw new Error(`Failed to fetch products: ${statusRes.statusText}`);
const statusData = (await statusRes.json()) as { products: Product[] };
const sprayProducts = (statusData.products || []).filter(
(p) => p.name.includes("Room Spray") || (p.category && p.category.includes("สเปรย์"))
);
console.log(`Found ${sprayProducts.length} Room Spray products.`);
// 2. Fetch raw materials
console.log("2. Fetching raw materials from production...");
const rmRes = await fetch(`${PROD_API}/raw-materials`);
if (!rmRes.ok) throw new Error(`Failed to fetch raw materials: ${rmRes.statusText}`);
const rawMaterials = (await rmRes.json()) as RawMaterial[];
const dpm = rawMaterials.find((r) => r.name.trim().toLowerCase() === "dpm");
if (!dpm) throw new Error("DPM raw material not found");
const bottle = rawMaterials.find((r) => r.name.includes("ขวดแก้วหัว Spray") || r.name.includes("ขวดแก้วหัวสเปรย์"));
if (!bottle) throw new Error("Glass spray bottle raw material not found");
console.log(`Using DPM: ID ${dpm.id} (฿${dpm.pricePerUnit}/ml)`);
console.log(`Using Bottle: ID ${bottle.id} '${bottle.name}' (฿${bottle.pricePerUnit}/piece)\n`);
let successCount = 0;
let failedCount = 0;
const results: Array<{
productId: number;
productName: string;
scentName: string;
variantId: number;
sku: string;
retailPrice: number;
fragranceName: string;
fragrancePrice: number;
fragranceCost: number;
dpmCost: number;
bottleCost: number;
totalBomCost: number;
profit: number;
marginPercent: number;
}> = [];
for (let idx = 0; idx < sprayProducts.length; idx++) {
const product = sprayProducts[idx];
const scentName = product.name.replace(/Room Spray/gi, "").trim();
// Match Fragrance Oil
const matchedFragrance = rawMaterials.find((rm) => {
const rmName = rm.name.trim();
return (
rmName === `หัวน้ำหอม กลิ่น${scentName}` ||
rmName === `หัวน้ำหอม ${scentName}` ||
rmName.includes(`กลิ่น${scentName}`) ||
(rmName.includes(scentName) && rmName.includes("หัวน้ำหอม"))
);
});
if (!matchedFragrance) {
console.error(`❌ [${idx + 1}/${sprayProducts.length}] No fragrance found for '${scentName}' (Product #${product.id})`);
failedCount++;
continue;
}
const variant = product.variants[0];
if (!variant) {
console.error(`❌ [${idx + 1}/${sprayProducts.length}] Product #${product.id} has no variant`);
failedCount++;
continue;
}
// Build payload: 6.8ml fragrance + 78.2ml DPM + 1 bottle
const payloadVariants = [
{
variantId: variant.id,
sku: variant.sku,
bomItems: [
{ rawMaterialId: matchedFragrance.id, quantity: 6.8 },
{ rawMaterialId: dpm.id, quantity: 78.2 },
{ rawMaterialId: bottle.id, quantity: 1 },
],
},
];
try {
const res = await fetch(`${PROD_API}/products/${product.id}/bom`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ variants: payloadVariants }),
});
if (!res.ok) {
const errText = await res.text();
throw new Error(`HTTP ${res.status}: ${errText}`);
}
// Calculations
const fragCost = 6.8 * matchedFragrance.pricePerUnit;
const dpmCost = 78.2 * dpm.pricePerUnit;
const bottleCost = bottle.pricePerUnit;
const totalCost = fragCost + dpmCost + bottleCost;
const profit = variant.price - totalCost;
const margin = variant.price > 0 ? (profit / variant.price) * 100 : 0;
console.log(`✓ [${idx + 1}/${sprayProducts.length}] Product #${product.id} (${product.name}) -> Cost: ฿${totalCost.toFixed(2)} / Price: ฿${variant.price} (Margin: ${margin.toFixed(1)}%)`);
results.push({
productId: product.id,
productName: product.name,
scentName,
variantId: variant.id,
sku: variant.sku,
retailPrice: variant.price,
fragranceName: matchedFragrance.name,
fragrancePrice: matchedFragrance.pricePerUnit,
fragranceCost: Math.round(fragCost * 100) / 100,
dpmCost: Math.round(dpmCost * 100) / 100,
bottleCost,
totalBomCost: Math.round(totalCost * 100) / 100,
profit: Math.round(profit * 100) / 100,
marginPercent: Math.round(margin * 10) / 10,
});
successCount++;
} catch (err: any) {
console.error(`❌ Failed Product #${product.id}:`, err.message);
failedCount++;
}
await sleep(50);
}
console.log(`\n========================================`);
console.log(`Total Room Spray Products : ${sprayProducts.length}`);
console.log(`Successfully Configured : ${successCount}`);
console.log(`Failed / Skipped : ${failedCount}`);
console.log(`========================================\n`);
// Generate ROOM_SPRAY_BOM_LEDGER.md
let ledger = `# รายงานการกำหนดสูตร BOM สำหรับกลุ่มสินค้า Room Spray (Production)\n\n`;
ledger += `* **วันที่กำหนดสูตร:** ${new Date().toISOString()}\n`;
ledger += `* **ระบบอ้างอิง:** Production Database (\`${PROD_API}\`)\n`;
ledger += `* **ขนาดบรรจุ:** 85 ml (ขวดแก้วหัว Spray)\n`;
ledger += `* **สัดส่วนสูตร:** **หัวน้ำหอม 8% (6.8 ml) + DPM 92% (78.2 ml) + ขวดแก้วหัว Spray ขนาด 85 ml (฿25.00)**\n`;
ledger += `* **จำนวนสินค้าทั้งหมด:** **${sprayProducts.length}** กลิ่น (**${successCount}** Variants)\n`;
ledger += `* **สถานะความสำเร็จ:** **100% (${successCount}/${sprayProducts.length} สินค้า)**\n\n`;
ledger += `## 📋 ตารางรายละเอียดต้นทุน BOM และอัตรากำไร (Margin) ทั้ง 45 กลิ่น\n\n`;
ledger += `| # | ID | Master SKU | ชื่อสินค้า | หัวน้ำหอม (ราคา/ml) | ต้นทุนน้ำยา (85ml) | ต้นทุนขวดแก้ว | ต้นทุนรวม BOM | ราคาขาย Master | กำไรขั้นต้น (GP) | GP Margin % |\n`;
ledger += `| :-: | :-: | :--- | :--- | :--- | :-: | :-: | :-: | :-: | :-: | :-: |\n`;
results.forEach((r, idx) => {
const liquidCost = (r.fragranceCost + r.dpmCost).toFixed(2);
ledger += `| ${idx + 1} | ${r.productId} | \`${r.sku}\` | **${r.productName}** | ${r.fragranceName} (฿${r.fragrancePrice.toFixed(2)}) | ฿${liquidCost} | ฿${r.bottleCost.toFixed(2)} | **฿${r.totalBomCost.toFixed(2)}** | ฿${r.retailPrice.toFixed(2)} | +฿${r.profit.toFixed(2)} | **${r.marginPercent}%** |\n`;
});
const ledgerPath = path.resolve(process.cwd(), "ROOM_SPRAY_BOM_LEDGER.md");
fs.writeFileSync(ledgerPath, ledger, "utf8");
console.log(`Saved ledger report to: ${ledgerPath}`);
}
main().catch(console.error);