summaryrefslogtreecommitdiff
path: root/src/pages/api/shop/search.js
blob: 90841e09120205ef7a112596a326c64577543b32 (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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { productMappingSolr } from '@/utils/solrMapping';
import axios from 'axios';
import camelcaseObjectDeep from 'camelcase-object-deep';

const escapeSolrQuery = (query) => {
  if (query == '*') return query;
  query = query.replace(/-/g, ' ');
  const specialChars = /([\+\!\(\)\{\}\[\]\^"~\*\?:\\\/])/g;
  const words = query.split(/\s+/);
  return words.map((word) => specialChars.test(word) ? word.replace(specialChars, '\\$1') : word).join(' ');
};

export default async function handler(req, res) {
  const {
    q = '*',
    page = 1,
    brand = '',
    category = '',
    priceFrom = 0,
    priceTo = 0,
    orderBy = '',
    operation = 'AND',
    fq = '', // bisa berupa string atau array
    limit = 30,
    source = '',
  } = req.query;

  let { stock = '' } = req.query;

  // ============================================================
  // [BARU] 1. LOGIC KHUSUS COMPARE (Wajib ditaruh paling atas)
  // ============================================================
  if (source === 'compare') {
    try {
      let qCompare = q === '*' ? '*:*' : q;
      
      // Sanitasi Query
      if (qCompare !== '*:*') {
        const escaped = escapeSolrQuery(qCompare);
        qCompare = `*${escaped}*`; 
      }

      // Susun Parameter Solr
      const parameter = [
        `q=${encodeURIComponent(qCompare)}`,
        `rows=${limit}`,
        'wt=json',
        'indent=true',
        'defType=edismax',
        
        // Grouping agar varian tidak banjir (per template)
        'group=true',
        'group.field=template_id_i', 
        'group.limit=1',             
        'group.main=true',           
        
        // Field Wajib (Perhatikan: kita butuh product_id_i/default_code_s)
        'fl=id,display_name_s,default_code_s,image_s,price_tier1_v2_f,attribute_set_id_i,attribute_set_name_s,template_id_i,product_id_i',
        
        // Filter Dasar
        'fq=-publish_b:false',
        'fq=price_tier1_v2_f:[1 TO *]'
      ];

      // Logic Locking (Filter Attribute Set ID dari Frontend)
      // Frontend akan mengirim fq="attribute_set_id_i:9"
      if (fq) {
         if (Array.isArray(fq)) {
             fq.forEach(f => parameter.push(`fq=${encodeURIComponent(f)}`));
         } else {
             parameter.push(`fq=${encodeURIComponent(fq)}`);
         }
      }

      // Target Core: VARIANTS (Karena compare butuh data spesifik)
      const solrUrl = process.env.SOLR_HOST + '/solr/variants/select?' + parameter.join('&');

      const result = await axios(solrUrl);

      // Mapping Result
      const mappedProducts = productMappingSolr(
        result.data.response.docs,
        false
      );

      const finalResponse = {
         ...result.data,
         response: {
             ...result.data.response,
             products: mappedProducts
         }
      };
      
      delete finalResponse.response.docs;
      const camelCasedData = camelcaseObjectDeep(finalResponse);

      return res.status(200).json(camelCasedData);

    } catch (e) {
      console.error('[COMPARE SEARCH ERROR]', e.message);
      // Return JSON valid meski kosong, agar frontend tidak error syntax
      return res.status(200).json({ response: { products: [], numFound: 0 } });
    }
  }

  // ============================================================
  // LOGIC KHUSUS UPSELL (Simple & Direct)
  // ============================================================
  if (source === 'upsell') {
    try {
      // Ambil fq dari query (format: product_id_i:(...))
      // Pastikan fq adalah string tunggal
      let fqUpsell = Array.isArray(fq) ? fq.join(' OR ') : fq;
      fqUpsell = decodeURIComponent(fqUpsell);

      const parameter = [
        'q=*:*',
        `rows=${limit}`,
        'wt=json',
        'indent=true',
        'defType=edismax',
        // Filter Query khusus Upsell
        `fq=${encodeURIComponent(fqUpsell)}`,
        // Tetap filter yang publish & ada harga agar produk valid
        `fq=${encodeURIComponent('-publish_b:false')}`, 
        `fq=${encodeURIComponent('price_tier1_v2_f:[1 TO *]')}`
      ];

      // PENTING: SEARCH DI CORE 'VARIANTS'
      const solrUrl = process.env.SOLR_HOST + '/solr/variants/select?' + parameter.join('&');

      const result = await axios(solrUrl);

      // 1. Mapping dasar
      const mappedProducts = productMappingSolr(
        result.data.response.docs,
        false
      );

      // 2. FIX URL LINK: Override ID Varian dengan Template ID
      const rawDocs = result.data.response.docs;
      
      const fixedProducts = mappedProducts.map((p, index) => {
          const raw = rawDocs[index];
          if (raw && raw.template_id_i) {
              return {
                  ...p,
                  id: raw.template_id_i, // Ganti ID Varian jadi ID Template agar link valid
                  variantId: raw.product_id_i 
              };
          }
          return p;
      });

      const finalResponse = {
          ...result.data,
          response: {
              ...result.data.response,
              products: fixedProducts
          }
      };

      delete finalResponse.response.docs;
      const camelCasedData = camelcaseObjectDeep(finalResponse);

      return res.status(200).json(camelCasedData);

    } catch (e) {
      console.error('[UPSELL ERROR]', e.response?.data || e.message);
      return res.status(200).json({ response: { products: [], numFound: 0 } });
    }
  }

  // ============================================================
  // SITEMAP (Biarkan tetap sama)
  // ============================================================
  if (source === 'sitemap') {
    try {
      const offset = (page - 1) * limit;
      const parameter = [
        'q=*:*',
        `rows=${limit}`,
        `start=${offset}`,
        'fl=product_id_i,name_s,default_code_s,image_s,category_name',
        'wt=json',
        'omitHeader=true',
      ];
      const solrUrl = process.env.SOLR_HOST + '/solr/product/select?' + parameter.join('&');
      const result = await axios(solrUrl, { timeout: 25000 });
      result.data.response.products = productMappingSolr(result.data.response.docs, false);
      delete result.data.response.docs;
      result.data = camelcaseObjectDeep(result.data);
      return res.status(200).json(result.data);
    } catch (e) {
      return res.status(500).json({ error: 'Sitemap query failed' });
    }
  }

  // ============================================================
  // SEARCH NORMAL (LOGIKA LAMA)
  // ============================================================

  let paramOrderBy = '';
  switch (orderBy) {
    case 'flashsale-discount-desc': paramOrderBy += 'flashsale_discount_f DESC'; break;
    case 'price-asc': paramOrderBy += 'price_tier1_v2_f ASC'; break;
    case 'price-desc': paramOrderBy += 'price_tier1_v2_f DESC'; break;
    case 'popular': paramOrderBy += 'product_rating_f DESC, search_rank_i DESC,'; break;
    case 'popular-weekly': paramOrderBy += 'search_rank_weekly_i DESC'; break;
    case 'stock': paramOrderBy += 'product_rating_f DESC, stock_total_f DESC'; break;
    case 'flashsale-price-asc': paramOrderBy += 'flashsale_price_f ASC'; break;
    default: paramOrderBy += ''; break;
  }

  let checkQ = q.trim().split(/[\s\+\-\!\(\)\{\}\[\]\^"~\*\?:\\\/]+/);
  let newQ = escapeSolrQuery(q);

  const formattedQuery = `(${newQ.split(' ').map((term) => (term.length < 2 ? term : `${term}*`)).join(' ')})`;
  const mm = checkQ.length > 2 ? (checkQ.length > 5 ? '55%' : '85%') : `${checkQ.length}`;

  const filterQueries = [
    '-publish_b:false',
    'product_rating_f:[8 TO *]',
    'price_tier1_v2_f:[1 TO *]',
  ];

  if (orderBy === 'stock') filterQueries.push('stock_total_f:[1 TO *]');

  // Handle 'fq' parameter from request
  let finalFq = [...filterQueries];
  if (fq) {
      if (Array.isArray(fq)) finalFq.push(...fq);
      else finalFq.push(fq);
  }

  let keywords = newQ;
  if (source === 'similar' || checkQ.length < 3) {
    if (checkQ.length < 2 || checkQ[1].length < 2) keywords = newQ;
    else keywords = newQ + '*';
  } else {
    keywords = formattedQuery;
  }

  let offset = (page - 1) * limit;

  let parameter = [
    'facet.field={!ex=brand}manufacture_name_s',
    'facet.field={!ex=cat}category_name',
    'facet=true',
    'indent=true',
    `facet.query=${escapeSolrQuery(q)}`,
    `q.op=OR`,
    `q=${keywords}`,
    `defType=edismax`,
    'qf=name_s description_clean_t category_name manufacture_name_s variants_code_t variants_name_t category_id_ids default_code_s manufacture_id_i category_id_i',
    `start=${parseInt(offset)}`,
    `rows=${limit}`,
    `sort=${paramOrderBy}`,
    `mm=${encodeURIComponent(mm)}`,
  ];

  // Masukkan semua Filter Query (fq)
  finalFq.forEach(f => {
      parameter.push(`fq=${encodeURIComponent(f)}`);
  });

  if (priceFrom > 0 || priceTo > 0) {
    parameter.push(`fq=price_tier1_v2_f:[${priceFrom || '*'} TO ${priceTo || '*'}]`);
  }

  let { auth } = req.cookies;
  if (auth) {
    auth = JSON.parse(auth);
    if (auth.feature.onlyReadyStock) stock = true;
  }

  if (brand) {
    const brandExpr = brand.split(',').map(m => `manufacture_name:"${encodeURIComponent(m)}"`).join(' OR ');
    parameter.push(`fq={!tag=brand}(${brandExpr})`);
  }

  if (category) {
    const catExpr = category.split(',').map(c => `category_name:"${encodeURIComponent(c)}"`).join(' OR ');
    parameter.push(`fq={!tag=cat}(${catExpr})`);
  }

  if (stock) parameter.push(`fq=stock_total_f:(1 TO *)`);

  // SEARCH NORMAL: DEFAULT KE CORE 'PRODUCT'
  const solrUrl = process.env.SOLR_HOST + '/solr/product/select?' + parameter.join('&');

  try {
    const result = await axios(solrUrl);
    result.data.response.products = productMappingSolr(
      result.data.response.docs,
      auth?.pricelist || false
    );
    result.data.responseHeader.params.start = parseInt(result.data.responseHeader.params.start);
    result.data.responseHeader.params.rows = parseInt(result.data.responseHeader.params.rows);
    delete result.data.response.docs;
    result.data = camelcaseObjectDeep(result.data);
    res.status(200).json(result.data);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
}