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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
|
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 = '',
group = 'true',
} = req.query;
let { stock = '' } = req.query;
// ============================================================
// [PERBAIKAN] 1. LOGIC KHUSUS COMPARE (PAKAI URLSearchParams)
// ============================================================
if (source === 'compare') {
try {
let qCompare = q === '*' ? '*:*' : q;
if (qCompare !== '*:*') {
qCompare = escapeSolrQuery(qCompare);
qCompare = qCompare
.split(/\s+/)
.map((term) => {
if (term && !term.includes('*')) {
return term + '*';
}
return term;
})
.join(' ');
}
// [SOLUSI] Gunakan URLSearchParams untuk menyusun URL dengan aman
const params = new URLSearchParams();
params.append('q', qCompare);
params.append('rows', limit);
params.append('wt', 'json');
params.append('indent', 'true');
// Gunakan eDisMax parser (Otak Cerdas)
params.append('defType', 'edismax');
// Set Prioritas Pencarian (Boost ^)
// 1. default_code_s^20 : SKU persis (Prioritas Tertinggi)
// 2. search_keywords_t^10 : Field baru (Case insensitive)
// 3. display_name_s^1 : Cadangan
params.append(
'qf',
'default_code_s^20 search_keywords_t^10 display_name_s^1',
);
const compareWords = qCompare.split(/\s+/).filter((w) => w.length > 0);
let compareMm = '100%';
if (compareWords.length >= 3) {
compareMm = '75%';
}
params.append('mm', compareMm);
if (group === 'false') {
params.append('group', 'false');
} else {
params.append('group', 'true');
params.append('group.field', 'template_id_i');
params.append('group.limit', '1');
params.append('group.main', 'true');
}
// Field List (fl)
params.append(
'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 Query (fq) Dasar
params.append('fq', '-publish_b:false');
params.append('fq', 'price_tier1_v2_f:[1 TO *]');
// Logic Locking (Filter Attribute Set ID dari Frontend)
if (fq) {
if (Array.isArray(fq)) {
fq.forEach((f) => params.append('fq', f));
} else {
params.append('fq', fq);
}
}
// Target Core: VARIANTS
// HAPUS parameter manual dari string URL, gunakan params object
const solrUrl = process.env.SOLR_HOST + '/solr/variants/select';
// Axios akan otomatis handle encoding % dan & dengan benar
const result = await axios.get(solrUrl, { params: params });
// 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);
if (e.response && e.response.data) {
// Log detail error dari Solr
console.error(
'[SOLR DETAILS]:',
JSON.stringify(e.response.data, null, 2),
);
}
return res.status(200).json({ response: { products: [], numFound: 0 } });
}
}
// ============================================================
// LOGIC KHUSUS UPSELL (KODE LAMA ANDA)
// ============================================================
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 (KODE LAMA ANDA)
// ============================================================
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 (KODE LAMA ANDA)
// ============================================================
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 *)`);
if (typeof fq === 'string') parameter.push(`fq=${encodeURIComponent(fq)}`);
if (Array.isArray(fq))
parameter = parameter.concat(
fq.map((val) => `fq=${encodeURIComponent(val)}`),
);
// Searchkey
if (req.query.from === 'searchkey') {
const ids = req.query.ids ? req.query.ids.split(',').filter(Boolean) : [];
const q = ids.map((id) => `product_id_i:${id}`).join(' OR ');
const strictQuery = [
`q=${encodeURIComponent(q)}`,
`fq=-publish_b:false AND price_tier1_v2_f:[1 TO *] AND product_rating_f:[8 TO *]`,
// `qf=variants_code_t variants_name_t`,
`rows=${limit}`,
`start=${offset}`,
`sort=${paramOrderBy}`,
];
const solrUrl =
process.env.SOLR_HOST + '/solr/product/select?' + strictQuery.join('&');
console.log('[SEARCHKEY FINAL QUERY]', solrUrl);
const result = await axios(solrUrl);
try {
result.data.response.products = productMappingSolr(
result.data.response.docs,
auth?.pricelist || false,
);
delete result.data.response.docs;
result.data = camelcaseObjectDeep(result.data);
return res.status(200).json(result.data);
} catch (e) {
return res.status(400).json({ error: e.message });
}
}
// 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 });
}
}
|