summaryrefslogtreecommitdiff
path: root/src/pages/api/shop/search.js
blob: 1b1b6a9c28162b70f6051a7cc0722dbfe841ba1f (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
import { productMappingSolr } from '@/utils/solrMapping';
import axios from 'axios';
import camelcaseObjectDeep from 'camelcase-object-deep';

// helper untuk escape karakter spesial
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(' ');
};

export default async function handler(req, res) {
  try {
    const {
      q = '*',
      page = 1,
      brand = '',
      category = '',
      priceFrom = 0,
      priceTo = 0,
      orderBy = '',
      operation = 'AND',
      fq = '',
      limit = 30,
      source = '', // <-- penting
    } = req.query;

    console.log('🔍 API /shop/search → source:', source); // debug biar tahu kebaca atau enggak

    // --- 1️⃣ MODE SITEMAP: ambil semua produk tanpa filter ---
    if (source === 'sitemap') {
      const offset = (page - 1) * limit;
      const parameter = ['q=*:*', `rows=${limit}`, `start=${offset}`];

      const solrUrl =
        process.env.SOLR_HOST + '/solr/product/select?' + parameter.join('&');

      console.log('[SOLR QUERY SITEMAP]', solrUrl);

      const result = await axios(solrUrl);

      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);
    }

    // --- 2️⃣ MODE NORMAL (search biasa di website) ---
    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}`;

    // filter default (mode normal)
    const filterQueries = [
      '-publish_b:false',
      'product_rating_f:[8 TO *]',
      'price_tier1_v2_f:[1 TO *]',
    ];
    const fq_ = filterQueries.join(' AND ');

    let keywords = newQ;
    if (checkQ.length >= 3) keywords = formattedQuery;

    let offset = (page - 1) * limit;

    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;
    }

    // parameter query normal
    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=${operation}`,
      `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 || '*'} TO ${priceTo || '*'}]`
      );
    }

    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})`);
    }

    const solrUrl =
      process.env.SOLR_HOST + '/solr/product/select?' + parameter.join('&');

    console.log('[SOLR QUERY NORMAL]', solrUrl);

    const result = await axios(solrUrl);

    result.data.response.products = productMappingSolr(
      result.data.response.docs,
      false
    );
    delete result.data.response.docs;
    result.data = camelcaseObjectDeep(result.data);

    res.status(200).json(result.data);
  } catch (error) {
    console.error('[ERROR /shop/search]', error.message);
    res.status(400).json({ error: error.message });
  }
}