u
This commit is contained in:
180
src/tools/search-articles.js
Normal file
180
src/tools/search-articles.js
Normal file
@@ -0,0 +1,180 @@
|
||||
import { defineTool, ToolError } from 'libllmorbiter';
|
||||
import { getStore, getProvider } from '../db/store.js';
|
||||
|
||||
const DEFAULT_LIMIT = 3;
|
||||
const MAX_LIMIT = 20;
|
||||
|
||||
function parseWords(input) {
|
||||
if (typeof input === 'string') {
|
||||
return input.toLowerCase().trim().split(/\s+/).filter(Boolean);
|
||||
}
|
||||
if (Array.isArray(input)) {
|
||||
return input.map((w) => String(w).toLowerCase().trim()).filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the search_articles tool.
|
||||
* Searches articles across name, brand, EAN, SKU, and supplier SKU.
|
||||
* Returns a window of full articles (default 3, max 20), the offset, and the total count.
|
||||
* @param {{ googleAuthId: number, companyId?: number }} ctx
|
||||
*/
|
||||
export function createSearchArticlesTool({ googleAuthId, companyId }) {
|
||||
return defineTool({
|
||||
name: 'search_articles',
|
||||
description:
|
||||
'Text search articles by name, brand, EAN, SKU, or supplier SKU. ' +
|
||||
`Returns window of full articles (default ${DEFAULT_LIMIT}, max ${MAX_LIMIT}), offset, and total count. Ordered alphabetically by name.`,
|
||||
strict: false,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
searchquery: {
|
||||
type: 'string',
|
||||
description: 'Words that must all match across name, brand, EAN, SKU, or supplier SKU (AND logic, order-independent).',
|
||||
},
|
||||
excludewords: {
|
||||
type: 'string',
|
||||
description: 'Words that if all match exclude the article (AND logic, order-independent).',
|
||||
},
|
||||
offset: {
|
||||
type: 'integer',
|
||||
description: 'Pagination offset. Default 0.',
|
||||
},
|
||||
limit: {
|
||||
type: 'integer',
|
||||
description: `Result window size (1–${MAX_LIMIT}). Default ${DEFAULT_LIMIT}.`,
|
||||
},
|
||||
},
|
||||
},
|
||||
invoke: async ({ searchquery = '', excludewords = '', offset = 0, limit = DEFAULT_LIMIT } = {}) => {
|
||||
const store = await getStore();
|
||||
const provider = await getProvider();
|
||||
|
||||
let targetCompanyId = companyId;
|
||||
if (!targetCompanyId) {
|
||||
const gaRes = await provider.query(
|
||||
'SELECT selected_company AS selectedCompanyId FROM google_auth WHERE id = @googleAuthId',
|
||||
{ googleAuthId }
|
||||
);
|
||||
targetCompanyId = gaRes.rows[0]?.selectedCompanyId;
|
||||
}
|
||||
if (!targetCompanyId) {
|
||||
throw new ToolError('No company selected');
|
||||
}
|
||||
|
||||
const coRes = await provider.query(
|
||||
'SELECT default_language_id AS languageId FROM company WHERE id = @companyId',
|
||||
{ companyId: targetCompanyId }
|
||||
);
|
||||
const languageId = coRes.rows[0]?.languageId || 1;
|
||||
|
||||
const [artRes, eanRes, supRes] = await Promise.all([
|
||||
provider.query(
|
||||
`SELECT a.id, a.sku, at.name, b.name AS brandName
|
||||
FROM article a
|
||||
LEFT JOIN articletext at ON at.article_id = a.id AND at.language_id = @languageId
|
||||
LEFT JOIN brand b ON b.id = a.brand_id
|
||||
WHERE a.company_id = @companyId`,
|
||||
{ companyId: targetCompanyId, languageId }
|
||||
),
|
||||
provider.query(
|
||||
`SELECT ae.article_id AS articleId, ae.ean
|
||||
FROM articleean ae
|
||||
INNER JOIN article a ON a.id = ae.article_id
|
||||
WHERE a.company_id = @companyId`,
|
||||
{ companyId: targetCompanyId }
|
||||
),
|
||||
provider.query(
|
||||
`SELECT asup.article_id AS articleId, asup.sku AS supplierSku
|
||||
FROM articlesupplier asup
|
||||
INNER JOIN article a ON a.id = asup.article_id
|
||||
WHERE a.company_id = @companyId`,
|
||||
{ companyId: targetCompanyId }
|
||||
),
|
||||
]);
|
||||
|
||||
const eansMap = new Map();
|
||||
for (const row of eanRes.rows) {
|
||||
if (!row.ean) continue;
|
||||
let list = eansMap.get(row.articleId);
|
||||
if (!list) {
|
||||
list = [];
|
||||
eansMap.set(row.articleId, list);
|
||||
}
|
||||
list.push(String(row.ean));
|
||||
}
|
||||
|
||||
const supplierSkusMap = new Map();
|
||||
for (const row of supRes.rows) {
|
||||
if (!row.supplierSku) continue;
|
||||
let list = supplierSkusMap.get(row.articleId);
|
||||
if (!list) {
|
||||
list = [];
|
||||
supplierSkusMap.set(row.articleId, list);
|
||||
}
|
||||
list.push(String(row.supplierSku));
|
||||
}
|
||||
|
||||
const searchableArticles = artRes.rows.map((row) => {
|
||||
const eans = eansMap.get(row.id) || [];
|
||||
const supplierSkus = supplierSkusMap.get(row.id) || [];
|
||||
const name = row.name || '';
|
||||
const brand = row.brandName || '';
|
||||
const sku = row.sku || '';
|
||||
const searchableText = `${name} ${brand} ${sku} ${eans.join(' ')} ${supplierSkus.join(' ')}`.toLowerCase();
|
||||
return {
|
||||
id: row.id,
|
||||
sku: row.sku,
|
||||
name,
|
||||
searchableText,
|
||||
};
|
||||
});
|
||||
|
||||
const searchWords = parseWords(searchquery);
|
||||
const excludeWords = parseWords(excludewords);
|
||||
|
||||
const filtered = searchableArticles.filter((art) => {
|
||||
if (searchWords.length > 0) {
|
||||
const matchesAll = searchWords.every((word) => art.searchableText.includes(word));
|
||||
if (!matchesAll) return false;
|
||||
}
|
||||
if (excludeWords.length > 0) {
|
||||
const matchesAllExclude = excludeWords.every((word) => art.searchableText.includes(word));
|
||||
if (matchesAllExclude) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
filtered.sort((a, b) => (a.name || '').localeCompare(b.name || '', 'de', { sensitivity: 'base' }));
|
||||
|
||||
const total = filtered.length;
|
||||
const startOffset = Math.max(0, parseInt(offset, 10) || 0);
|
||||
const pageSize = Math.min(Math.max(1, parseInt(limit, 10) || DEFAULT_LIMIT), MAX_LIMIT);
|
||||
const windowSlice = filtered.slice(startOffset, startOffset + pageSize);
|
||||
|
||||
const fullArticles = (
|
||||
await Promise.all(
|
||||
windowSlice.map(async (item) => {
|
||||
try {
|
||||
const { article } = await store.article.getBySku(googleAuthId, item.sku);
|
||||
return article;
|
||||
} catch (err) {
|
||||
console.warn(`[search_articles] could not load full article for sku ${item.sku}:`, err.message);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
)
|
||||
).filter(Boolean);
|
||||
|
||||
return {
|
||||
total,
|
||||
offset: startOffset,
|
||||
limit: pageSize,
|
||||
articles: fullArticles,
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user