summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/lib/category/components/Breadcrumb.jsx44
-rw-r--r--src/pages/api/shop/search.js230
-rw-r--r--src/pages/api/shop/searchkey.js43
-rw-r--r--src/pages/searchkey/[slug].jsx96
-rw-r--r--src/pages/sitemap/searchkey.xml.js37
-rw-r--r--src/pages/sitemap/searchkey/[page].js42
6 files changed, 413 insertions, 79 deletions
diff --git a/src/lib/category/components/Breadcrumb.jsx b/src/lib/category/components/Breadcrumb.jsx
index 8579bb14..fa2846e4 100644
--- a/src/lib/category/components/Breadcrumb.jsx
+++ b/src/lib/category/components/Breadcrumb.jsx
@@ -15,13 +15,14 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
const breadcrumbs = useQuery(
['category-breadcrumbs', categoryId],
async () =>
- await odooApi('GET', `/api/v1/category/${categoryId}/category-breadcrumb`)
+ await odooApi(
+ 'GET',
+ `/api/v1/category/${categoryId}/category-breadcrumb`,
+ ),
);
const { isDesktop, isMobile } = useDevice();
-
const items = breadcrumbs.data ?? [];
- const lastIdx = items.length - 1;
/* =========================
DESKTOP
@@ -58,29 +59,40 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
{/* Categories */}
{items.map((category, index) => {
- const isLast = index === lastIdx;
+ const isLastCategory = index === items.length - 1;
+ const isClickable = currentLabel || !isLastCategory;
+
return (
- <BreadcrumbItem key={index} isCurrentPage={isLast}>
- {isLast ? (
- <BreadcrumbLink className='block whitespace-normal break-words md:whitespace-nowrap'>
- {category.name}
- </BreadcrumbLink>
- ) : (
+ <BreadcrumbItem key={index} isCurrentPage={!isClickable}>
+ {isClickable ? (
<BreadcrumbLink
as={Link}
href={createSlug(
'/shop/category/',
category.name,
- category.id
+ category.id,
)}
className='!text-danger-500'
>
{category.name}
</BreadcrumbLink>
+ ) : (
+ <BreadcrumbLink className='block whitespace-normal break-words md:whitespace-nowrap'>
+ {category.name}
+ </BreadcrumbLink>
)}
</BreadcrumbItem>
);
})}
+
+ {/* Searchkey / Current Page */}
+ {currentLabel && (
+ <BreadcrumbItem isCurrentPage>
+ <BreadcrumbLink className='block whitespace-normal break-words md:whitespace-nowrap'>
+ {currentLabel}
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ )}
</ChakraBreadcrumb>
</Skeleton>
{shortDesc && (
@@ -119,6 +131,8 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
.join(' / ')
: '';
+ const finalLabel = currentLabel || lastCat?.name;
+
return (
<div className='container mx-auto py-2 mt-2'>
<Skeleton isLoaded={!breadcrumbs.isLoading} className='w-full'>
@@ -152,6 +166,7 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
</BreadcrumbLink>
</BreadcrumbItem>
+ {/* Jika ada kategori sebelum secondLast, tampilkan '..' (link ke beforeSecond) */}
{beforeSecond && (
<BreadcrumbItem>
<BreadcrumbLink
@@ -159,7 +174,7 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
href={createSlug(
'/shop/category/',
beforeSecond.name,
- beforeSecond.id
+ beforeSecond.id,
)}
title={hiddenText}
className='!text-danger-500'
@@ -176,7 +191,7 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
href={createSlug(
'/shop/category/',
secondLast.name,
- secondLast.id
+ secondLast.id,
)}
className='!text-danger-500'
>
@@ -185,6 +200,7 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
</BreadcrumbItem>
)}
+ {/* lastCat (current) dengan truncate & lebar dibatasi */}
{lastCat && (
<BreadcrumbItem isCurrentPage>
<span
@@ -192,7 +208,7 @@ const Breadcrumb = ({ categoryId, shortDesc }) => {
style={{ maxWidth: '60vw' }}
title={lastCat.name}
>
- {lastCat.name}
+ {finalLabel}
</span>
</BreadcrumbItem>
)}
diff --git a/src/pages/api/shop/search.js b/src/pages/api/shop/search.js
index 89d75cd0..1f636f28 100644
--- a/src/pages/api/shop/search.js
+++ b/src/pages/api/shop/search.js
@@ -7,7 +7,11 @@ const escapeSolrQuery = (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(' ');
+ return words
+ .map((word) =>
+ specialChars.test(word) ? word.replace(specialChars, '\\$1') : word,
+ )
+ .join(' ');
};
export default async function handler(req, res) {
@@ -23,7 +27,7 @@ export default async function handler(req, res) {
fq = '', // bisa berupa string atau array
limit = 30,
source = '',
- group = 'true',
+ group = 'true',
} = req.query;
let { stock = '' } = req.query;
@@ -37,12 +41,15 @@ export default async function handler(req, res) {
if (qCompare !== '*:*') {
qCompare = escapeSolrQuery(qCompare);
- qCompare = qCompare.split(/\s+/).map(term => {
- if (term && !term.includes('*')) {
- return term + '*';
- }
- return term;
- }).join(' ');
+ qCompare = qCompare
+ .split(/\s+/)
+ .map((term) => {
+ if (term && !term.includes('*')) {
+ return term + '*';
+ }
+ return term;
+ })
+ .join(' ');
}
// [SOLUSI] Gunakan URLSearchParams untuk menyusun URL dengan aman
@@ -52,17 +59,20 @@ export default async function handler(req, res) {
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);
+ 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%';
@@ -79,7 +89,10 @@ export default async function handler(req, res) {
}
// 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');
+ 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');
@@ -88,7 +101,7 @@ export default async function handler(req, res) {
// Logic Locking (Filter Attribute Set ID dari Frontend)
if (fq) {
if (Array.isArray(fq)) {
- fq.forEach(f => params.append('fq', f));
+ fq.forEach((f) => params.append('fq', f));
} else {
params.append('fq', fq);
}
@@ -97,34 +110,36 @@ export default async function handler(req, res) {
// 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
+ false,
);
const finalResponse = {
...result.data,
response: {
...result.data.response,
- products: mappedProducts
- }
+ 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));
+ console.error(
+ '[SOLR DETAILS]:',
+ JSON.stringify(e.response.data, null, 2),
+ );
}
return res.status(200).json({ response: { products: [], numFound: 0 } });
}
@@ -149,49 +164,49 @@ export default async function handler(req, res) {
// 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 *]')}`
+ `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 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
+ 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 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
- }
+ ...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 } });
@@ -212,9 +227,13 @@ export default async function handler(req, res) {
'wt=json',
'omitHeader=true',
];
- const solrUrl = process.env.SOLR_HOST + '/solr/product/select?' + parameter.join('&');
+ 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);
+ 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);
@@ -229,21 +248,45 @@ export default async function handler(req, res) {
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;
+ 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 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',
@@ -256,8 +299,8 @@ export default async function handler(req, res) {
// Handle 'fq' parameter from request
let finalFq = [...filterQueries];
if (fq) {
- if (Array.isArray(fq)) finalFq.push(...fq);
- else finalFq.push(fq);
+ if (Array.isArray(fq)) finalFq.push(...fq);
+ else finalFq.push(fq);
}
let keywords = newQ;
@@ -287,12 +330,14 @@ export default async function handler(req, res) {
];
// Masukkan semua Filter Query (fq)
- finalFq.forEach(f => {
- parameter.push(`fq=${encodeURIComponent(f)}`);
+ finalFq.forEach((f) => {
+ parameter.push(`fq=${encodeURIComponent(f)}`);
});
if (priceFrom > 0 || priceTo > 0) {
- parameter.push(`fq=price_tier1_v2_f:[${priceFrom || '*'} TO ${priceTo || '*'}]`);
+ parameter.push(
+ `fq=price_tier1_v2_f:[${priceFrom || '*'} TO ${priceTo || '*'}]`,
+ );
}
let { auth } = req.cookies;
@@ -302,32 +347,87 @@ export default async function handler(req, res) {
}
if (brand) {
- const brandExpr = brand.split(',').map(m => `manufacture_name:"${encodeURIComponent(m)}"`).join(' OR ');
+ 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 ');
+ 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('&');
+ 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
+ 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,
);
- 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 });
}
-} \ No newline at end of file
+}
diff --git a/src/pages/api/shop/searchkey.js b/src/pages/api/shop/searchkey.js
new file mode 100644
index 00000000..f5546a36
--- /dev/null
+++ b/src/pages/api/shop/searchkey.js
@@ -0,0 +1,43 @@
+import axios from 'axios';
+
+export default async function handler(req, res) {
+ const { url = '', page = 1, limit = 30, all } = req.query;
+
+ let q = '*:*';
+
+ // ✅ kalau BUKAN sitemap
+ if (!all) {
+ const cleanUrl = url.trim();
+ if (!cleanUrl) {
+ return res.status(400).json({ error: 'Missing url param' });
+ }
+ q = `keywords_s:"${cleanUrl}"`;
+ }
+
+ const offset = (page - 1) * limit;
+
+ const params = [
+ `q.op=AND`,
+ `q=${q}`,
+ `indent=true`,
+ `rows=${limit}`,
+ `start=${offset}`,
+ ];
+
+ try {
+ const result = await axios.post(
+ `${process.env.SOLR_HOST}/solr/searchkey/select`,
+ params.join('&'),
+ {
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ }
+ );
+
+ res.status(200).json(result.data);
+ } catch (error) {
+ console.error(error?.response?.data || error);
+ res.status(500).json({ error: 'Internal Server Error' });
+ }
+}
diff --git a/src/pages/searchkey/[slug].jsx b/src/pages/searchkey/[slug].jsx
new file mode 100644
index 00000000..b0fc9ab8
--- /dev/null
+++ b/src/pages/searchkey/[slug].jsx
@@ -0,0 +1,96 @@
+import axios from 'axios';
+import { useRouter } from 'next/router';
+import { useEffect, useState } from 'react';
+import Seo from '@/core/components/Seo';
+import dynamic from 'next/dynamic';
+import { capitalizeEachWord } from '../../utils/capializeFIrstWord';
+
+// ✅ Breadcrumb = default export
+import Breadcrumb from '@/lib/category/components/Breadcrumb';
+
+const BasicLayout = dynamic(() =>
+ import('@/core/components/layouts/BasicLayout')
+);
+const ProductSearch = dynamic(() =>
+ import('@/lib/product/components/ProductSearch')
+);
+
+export default function KeywordPage() {
+ const route = useRouter();
+
+ const [result, setResult] = useState(null);
+ const [query, setQuery] = useState(null);
+ const [categoryId, setCategoryId] = useState(null);
+
+ const slugRaw = route.query.slug || null;
+ const readableSlug = slugRaw
+ ? decodeURIComponent(slugRaw)
+ .replace(/-/g, ' ')
+ .replace(/\b\w/g, (c) => c.toUpperCase())
+ : '';
+
+ // 🔹 Fetch searchkey dari Solr
+ const getSearchKeyData = async (slug) => {
+ try {
+ const res = await axios(
+ `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/searchkey?url=${slug}&from=searchkey`
+ );
+
+ setResult(res?.data?.response?.docs?.[0] || null);
+ } catch (e) {
+ console.error('Fetching searchkey failed:', e);
+ }
+ };
+
+ // 🔹 Trigger fetch saat slug siap
+ useEffect(() => {
+ if (!route.isReady || !slugRaw) return;
+ getSearchKeyData(slugRaw);
+ }, [route.isReady, slugRaw]);
+
+ // 🔹 Ambil product_ids + categoryId dari Solr
+ useEffect(() => {
+ if (!result) return;
+
+ // product search
+ const ids = result.product_ids_is || [];
+ setQuery({
+ ids: ids.join(','),
+ from: 'searchkey',
+ });
+
+ // breadcrumb category
+ const catId =
+ result.category_id_i ||
+ result.public_categ_id_i ||
+ (result.category_ids_is && result.category_ids_is[0]);
+
+ if (catId) {
+ setCategoryId(catId);
+ }
+ }, [result]);
+
+ return (
+ <BasicLayout>
+ <Seo
+ title={`Beli ${readableSlug} Original & Harga Terjangkau - indoteknik.com`}
+ description={`Beli ${readableSlug} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar.`}
+ additionalMetaTags={[
+ {
+ property: 'keywords',
+ content: `Beli ${readableSlug}, harga ${readableSlug}, ${readableSlug} murah`,
+ },
+ ]}
+ canonical={`${process.env.NEXT_PUBLIC_SELF_HOST}${route.asPath}`}
+ />
+
+ {/* ✅ Breadcrumb (auto fetch via component) */}
+ {categoryId && (
+ <Breadcrumb categoryId={categoryId} currentLabel={readableSlug} />
+ )}
+
+ {/* ✅ Product result */}
+ {query && <ProductSearch query={query} prefixUrl={route.asPath} />}
+ </BasicLayout>
+ );
+}
diff --git a/src/pages/sitemap/searchkey.xml.js b/src/pages/sitemap/searchkey.xml.js
new file mode 100644
index 00000000..e4ca2434
--- /dev/null
+++ b/src/pages/sitemap/searchkey.xml.js
@@ -0,0 +1,37 @@
+import productSearchApi from '@/lib/product/api/productSearchApi';
+import { create } from 'xmlbuilder';
+import _ from 'lodash-contrib';
+import axios from 'axios';
+
+export async function getServerSideProps({ res }) {
+ const baseUrl = process.env.SELF_HOST + '/sitemap/searchkey';
+ const limit = 1000;
+ const keywords = await axios(
+ `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/searchkey?limit=${limit}&all=1`
+ );
+ // console.log(keywords);
+ const pageCount = Math.ceil(keywords.data.response.numFound / limit);
+ const pages = Array.from({ length: pageCount }, (_, i) => i + 1);
+ const sitemapIndex = create('sitemapindex', { encoding: 'UTF-8' }).att(
+ 'xmlns',
+ 'http://www.sitemaps.org/schemas/sitemap/0.9'
+ );
+
+ const date = new Date();
+ // const date = '2025-10-30';
+ pages.forEach((page) => {
+ const sitemap = sitemapIndex.ele('sitemap');
+ sitemap.ele('loc', `${baseUrl}/${page}.xml`);
+ sitemap.ele('lastmod', date.toISOString().slice(0, 10));
+ });
+
+ res.setHeader('Content-Type', 'text/xml');
+ res.write(sitemapIndex.end());
+ res.end();
+
+ return { props: {} };
+}
+
+export default function SitemapProducts() {
+ return null;
+}
diff --git a/src/pages/sitemap/searchkey/[page].js b/src/pages/sitemap/searchkey/[page].js
new file mode 100644
index 00000000..cee53f5e
--- /dev/null
+++ b/src/pages/sitemap/searchkey/[page].js
@@ -0,0 +1,42 @@
+import productSearchApi from '@/lib/product/api/productSearchApi';
+import { create } from 'xmlbuilder';
+import _ from 'lodash-contrib';
+import { createSlug } from '@/core/utils/slug';
+import axios from 'axios';
+
+export async function getServerSideProps({ query, res }) {
+ // const baseUrl = process.env.SELF_HOST + '/shop/product/';
+ const { page } = query;
+ const limit = 500;
+ const keywords = await axios(
+ `${
+ process.env.NEXT_PUBLIC_SELF_HOST
+ }/api/shop/searchkey?limit=${limit}&page=${page.replace('.xml', '')}&all=1`
+ );
+
+ const sitemap = create('urlset', { encoding: 'utf-8' }).att(
+ 'xmlns',
+ 'http://www.sitemaps.org/schemas/sitemap/0.9'
+ );
+
+ const date = new Date();
+ // const date = '2025-10-30';
+ keywords.data.response.docs.forEach((product) => {
+ const url = sitemap.ele('url');
+ const loc = product.url_s;
+ url.ele('loc', loc);
+ url.ele('lastmod', date.toISOString().slice(0, 10));
+ url.ele('changefreq', 'daily');
+ url.ele('priority', '0.8');
+ });
+
+ res.setHeader('Content-Type', 'text/xml');
+ res.write(sitemap.end());
+ res.end();
+
+ return { props: {} };
+}
+
+export default function SitemapProducts() {
+ return null;
+}