// pages/api/magento-product.ts import type { NextApiRequest, NextApiResponse } from 'next'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { sku } = req.query; if (!sku) { return res.status(400).json({ error: 'SKU is required' }); } // Token Magento const token = 'vxrtcjvztv1icgjzsui45de9kmwlz0lf'; const baseUrl = 'https://pimdev.1211.my.id/rest/V1/products'; try { // 1. Pastikan SKU menjadi string dan hapus spasi kiri/kanan const cleanSku = String(sku).trim(); // 2. Encode SKU const encodedSku = encodeURIComponent(cleanSku); // 3. Bentuk URL Final const finalUrl = `${baseUrl}/${encodedSku}`; // --- DEBUGGING LOG --- console.log('Fetching URL:', finalUrl); // Request ke Product Endpoint const response = await fetch(finalUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, }); if (!response.ok) { console.error(`Magento Error: ${response.status} ${response.statusText}`); return res.status(response.status).json({ error: 'Failed to fetch from Magento', magentoStatus: response.status, checkedUrl: finalUrl }); } const data = await response.json(); // ===================================================================== // TAMBAHAN 1: FETCH LABEL ATRIBUT (z_*) // ===================================================================== let specsWithLabels: any[] = []; // Cek apakah ada custom_attributes if (data.custom_attributes) { // Filter atribut yang kodenya dimulai dengan 'z' // FIX: Menghapus filter 'Pakai link' agar MSDS tetap muncul const zAttributes = data.custom_attributes.filter((attr: any) => attr.attribute_code.startsWith('z') ); // Fetch detail label untuk setiap atribut secara paralel specsWithLabels = await Promise.all( zAttributes.map(async (attr: any) => { try { // Endpoint untuk ambil detail atribut (Label) const attrUrl = `https://pimdev.1211.my.id/rest/V1/products/attributes/${attr.attribute_code}`; const attrRes = await fetch(attrUrl, { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', } }); if (attrRes.ok) { const attrData = await attrRes.json(); return { code: attr.attribute_code, // FIX: Kirim code agar bisa dideteksi frontend (z_doc_) label: attrData.default_frontend_label || attr.attribute_code, value: attr.value }; } } catch (err) { console.error(`Failed to fetch label for ${attr.attribute_code}`); } // Fallback: Format manual const fallbackLabel = attr.attribute_code .substring(1).replace(/_/g, ' ').trim(); return { code: attr.attribute_code, // FIX: Kirim code di fallback juga label: fallbackLabel, value: attr.value }; }) ); } // ===================================================================== // TAMBAHAN 2: AMBIL UP-SELLS (product_links) // ===================================================================== let upsellIds: number[] = []; if (data.product_links && Array.isArray(data.product_links)) { upsellIds = data.product_links // Filter hanya link type 'upsell' .filter((link: any) => link.link_type === 'upsell') // Ambil SKU (yang isinya ID Odoo) dan ubah ke number .map((link: any) => Number(link.linked_product_sku)); } // ===================================================================== // RESPONSE GABUNGAN // ===================================================================== const responseData = { ...data, specs: specsWithLabels, // Data Spesifikasi (z_*) upsell_ids: upsellIds // Data Upsell ID (product_links) }; res.status(200).json(responseData); } catch (error) { console.error('Proxy Server Error:', error); res.status(500).json({ error: 'Internal Server Error' }); } }