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
|
import { productMappingSolr } from '@/utils/solrMapping';
import axios from 'axios';
import camelcaseObjectDeep from 'camelcase-object-deep';
export default async function handler(req, res) {
const {
q = '*',
page = 1,
brand = '',
category = '',
priceFrom = 0,
priceTo = 0,
orderBy = '',
operation = 'AND',
fq = '',
limit = 30,
source = '',
} = req.query;
let { stock = '' } = req.query;
// ============================================================
// SITEMAP
// ============================================================
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 parameter = [
// 'q=*:*',
// `rows=${limit}`,
// `start=${offset}`,
// // ❌ EXCLUDE PROMOTION
// 'fq=-(name_s:*promotion* OR display_name_s:*promotion* OR variants_name_t:*promotion*)',
// // ❌ EXCLUDE DUMMY PRODUCT
// 'fq=-(name_s:*dummy* OR display_name_s:*dummy* OR variants_name_t:*dummy* OR default_code_s:A.*)',
// '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('&');
// console.log('[SITEMAP SOLR QUERY]', solrUrl);
const result = await axios(solrUrl, { timeout: 25000 });
// mapping seperti biasa
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) {
console.error('[SITEMAP ERROR]', e);
return res.status(500).json({ error: 'Sitemap query failed' });
}
}
// ============================================================
// SEARCH NORMAL
// ============================================================
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 *]');
}
if (fq && source != 'similar' && typeof fq != 'string') {
fq.push(...filterQueries);
}
const fq_ = filterQueries.join(' AND ');
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}`,
`fq=${encodeURIComponent(fq_)}`,
`mm=${encodeURIComponent(mm)}`,
];
if (priceFrom > 0 || priceTo > 0) {
parameter.push(
`fq=price_tier1_v2_f:[${priceFrom == '' ? '*' : priceFrom} TO ${
priceTo == '' ? '*' : priceTo
}]`
);
}
let { auth } = req.cookies;
if (auth) {
auth = JSON.parse(auth);
if (auth.feature.onlyReadyStock) stock = true;
}
if (brand) {
const brandExpr = brand
.split(',')
.map(
(manufacturer) =>
`manufacture_name:"${encodeURIComponent(manufacturer)}"`
)
.join(' OR ');
parameter.push(`fq={!tag=brand}(${brandExpr})`);
}
if (category) {
const catExpr = category
.split(',')
.map((cat) => `category_name:"${encodeURIComponent(cat)}"`)
.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}`,
];
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 });
}
}
const solrUrl =
process.env.SOLR_HOST + '/solr/product/select?' + parameter.join('&');
const result = await axios(solrUrl);
try {
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 });
}
}
const escapeSolrQuery = (query) => {
if (query == '*') return query;
query = query.replace(/-/g, ' ');
const specialChars = /([\+\!\(\)\{\}\[\]\^"~\*\?:\\\/])/g;
const words = query.split(/\s+/);
const escapedWords = words.map((word) => {
if (specialChars.test(word)) {
return word.replace(specialChars, '\\$1');
}
return word;
});
return escapedWords.join(' ');
};
|