summaryrefslogtreecommitdiff
path: root/src/pages/api/magento-product.ts
blob: f61daf695a411be4474314139ff1242a5dfa8517 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// pages/api/magento-product.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // Kita terima 'skus' (banyak) dan 'main_sku' (utama/pertama)
  const { skus, main_sku } = req.query;

  if (!skus) {
    return res.status(400).json({ error: 'SKUs are required' });
  }

  const token = 'vxrtcjvztv1icgjzsui45de9kmwlz0lf'; 
  const baseUrl = 'https://pimdev.1211.my.id/rest/V1';

  try {
    const skuList = String(skus).split(','); // Contoh: ['221', '222', '223']
    const mainSku = String(main_sku || skuList[0]).trim(); // Fallback ke yang pertama

    // =====================================================================
    // 1. FETCH SEMUA VARIAN SEKALIGUS (Optimasi 'IN' Operator)
    // =====================================================================
    const searchParams = new URLSearchParams({
        'searchCriteria[filter_groups][0][filters][0][field]': 'sku',
        'searchCriteria[filter_groups][0][filters][0][value]': skuList.join(','),
        'searchCriteria[filter_groups][0][filters][0][condition_type]': 'in'
    });

    const productUrl = `${baseUrl}/products?${searchParams.toString()}`;
    
    const productResponse = await fetch(productUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    });

    if (!productResponse.ok) {
        return res.status(200).json({ specsMatrix: [], upsell_ids: [], related_ids: [] });
    }

    const productData = await productResponse.json();
    const items = productData.items || [];

    if (items.length === 0) {
        return res.status(200).json({ specsMatrix: [], upsell_ids: [], related_ids: [] });
    }

    // =====================================================================
    // 2. BUILD SPECS MATRIX
    // Kita butuh daftar semua atribut unik (z_*) dari seluruh varian
    // =====================================================================
    
    // Kumpulkan semua kode atribut unik
    const allAttributeCodes = new Set<string>();
    items.forEach((p: any) => {
        if (p.custom_attributes) {
            p.custom_attributes.forEach((attr: any) => {
                if (attr.attribute_code.startsWith('z')) {
                    allAttributeCodes.add(attr.attribute_code);
                }
            });
        }
    });

    // Fetch Label untuk atribut-atribut tersebut (Sekali jalan)
    const labelsMap: Record<string, string> = {};
    await Promise.all(Array.from(allAttributeCodes).map(async (code) => {
        try {
            const attrUrl = `${baseUrl}/products/attributes/${code}`;
            const res = await fetch(attrUrl, { headers: { 'Authorization': `Bearer ${token}` } });
            if (res.ok) {
                const json = await res.json();
                labelsMap[code] = json.default_frontend_label || code;
            }
        } catch (e) {}
        
        // Fallback label jika gagal
        if (!labelsMap[code]) {
            labelsMap[code] = code.substring(1).replace(/_/g, ' ').trim();
        }
    }));

    // Susun Matrix
    // Struktur: { code, label, values: { [sku]: value } }
    const matrix: any[] = [];
    
    Array.from(allAttributeCodes).forEach((code) => {
        const row: any = {
            code: code,
            label: labelsMap[code],
            values: {} 
        };

        let hasData = false;

        items.forEach((p: any) => {
            const attr = p.custom_attributes.find((a: any) => a.attribute_code === code);
            let rawVal = attr && attr.value !== null ? String(attr.value).trim() : '';
            if (rawVal.length >= 2 && rawVal.startsWith('"') && rawVal.endsWith('"')) {
                rawVal = rawVal.slice(1, -1).trim();
            }
            if (rawVal !== '' && rawVal !== '-') {
                hasData = true;
            } 
            row.values[p.sku] = rawVal; 
        });

        if (hasData) {
            matrix.push(row);
        }
    });

    // Deskripsi produk per varian
    const descriptions:Record<string, string> = {};
    items.forEach((p: any) => {
        const descAttr = p.custom_attributes.find((a: any) => a.attribute_code === 'description' || a.attribute_code === 'short_description');
        descriptions[p.sku] = descAttr ? descAttr.value : '';
    });
    
    const warranties: Record<string, string> = {};
    items.forEach((p: any) => {
        const warAttr = p.custom_attributes.find((a: any) => a.attribute_code === 'z_warranty');
        warranties[p.sku] = warAttr ? warAttr.value : '';
    });

    

    // =====================================================================
    // 3. AMBIL LINKS (UPSELL & RELATED) DARI MAIN VARIANT SAJA
    // =====================================================================
    // Cari data milik varian utama (varian pertama)
    const mainProduct = items.find((p: any) => String(p.sku) === mainSku) || items[0];

    let upsellIds: number[] = [];
    let relatedIds: number[] = [];

    if (mainProduct && mainProduct.product_links) {
        mainProduct.product_links.forEach((link: any) => {
            if (link.link_type === 'upsell') {
                upsellIds.push(Number(link.linked_product_sku));
            } else if (link.link_type === 'related') {
                relatedIds.push(Number(link.linked_product_sku));
            }
        });
    }

    // Response
    res.status(200).json({
        specsMatrix: matrix,
        upsell_ids: upsellIds,
        related_ids: relatedIds,
        descriptions: descriptions,
        warranties: warranties,
    });

  } catch (error) {
    console.error('Proxy Error:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}