u
This commit is contained in:
@@ -243,6 +243,152 @@ export function register(app, basePath = '') {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /brand/{id}/image:
|
||||
* post:
|
||||
* tags: [Brand]
|
||||
* summary: Add or replace brand image
|
||||
* description: |
|
||||
* Uploads an image for the brand (AVIF, WebP, or octet-stream). Converted to AVIF full and thumbnail.
|
||||
* Replaces any existing image for this brand.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Brand id
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* image/avif:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* image/webp:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* application/octet-stream:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Image stored and linked
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* brand:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* fullHash:
|
||||
* type: string
|
||||
* thumbW:
|
||||
* type: integer
|
||||
* thumbH:
|
||||
* type: integer
|
||||
* thumbHash:
|
||||
* type: string
|
||||
* pics:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/BrandPic'
|
||||
* 400:
|
||||
* description: Missing body or invalid image
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Brand not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* delete:
|
||||
* tags: [Brand]
|
||||
* summary: Delete brand image
|
||||
* description: Removes the brand's image. Sets thumbW, thumbH, thumbHash back to null.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Brand id
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Image removed
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* brand:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* thumbW:
|
||||
* type: integer
|
||||
* nullable: true
|
||||
* thumbH:
|
||||
* type: integer
|
||||
* nullable: true
|
||||
* thumbHash:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* pics:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/BrandPic'
|
||||
* 400:
|
||||
* description: No company selected or invalid id
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Brand or image not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
app.post(
|
||||
`${basePath}/brand/:id/image`,
|
||||
express.raw({ type: ['image/avif', 'image/webp', 'application/octet-stream'], limit: AVIF_BODY_LIMIT }),
|
||||
|
||||
@@ -23,6 +23,7 @@ import { createAnalyzeImageTool } from '../tools/analyze-image.js';
|
||||
import { createWebSearchTool } from '../tools/web-search.js';
|
||||
import { createUrlGetTool } from '../tools/url-get.js';
|
||||
import { createPdfReadTool } from '../tools/pdf-read.js';
|
||||
import { createSearchArticlesTool } from '../tools/search-articles.js';
|
||||
import { resolveOpenRouterKey, resolveDefaultModel, RETIRED_MODELS, hasConfiguredOpenRouterKey } from '../tools/llm-key.js';
|
||||
|
||||
const KEEP_ALIVE_MS = 20_000;
|
||||
@@ -123,6 +124,7 @@ async function buildSystemPrompt(vfsRoot, googleAuthId) {
|
||||
'12. reset_vfs: Delete VFS files/artifacts. Preserves SKILL files.',
|
||||
'13. rm: Delete single VFS file (used to delete SKILL files or specific artifacts).',
|
||||
'14. apisuggestionsorissues: Report missing API endpoints, bugs, or issues for triage.',
|
||||
'15. search_articles: Search articles across name, brand, EAN, SKU, and supplier SKU. Returns window of full articles (default 3, max 20), offset, and total count.',
|
||||
'',
|
||||
'VIRTUAL FILESYSTEM:',
|
||||
'- Persistent per-company VFS. Paths are root-relative forward-slash (e.g. "labels/sheet1.png").',
|
||||
@@ -138,15 +140,24 @@ async function buildSystemPrompt(vfsRoot, googleAuthId) {
|
||||
'',
|
||||
'IMAGES:',
|
||||
'- Evaluate images via analyze_image; report model findings.',
|
||||
'- Flow: search_images("query") → analyze_image({ paths: [...], prompt: "…" }) → upload via dashback_request.',
|
||||
'- Flow: search_images("query") → analyze_image({ paths: [...], prompt: "…" }) → upload via fetch in javascript_execute.',
|
||||
'- `image/` is READ-ONLY database storage. Write generated images elsewhere (e.g. "images/…").',
|
||||
'',
|
||||
'OPERATING GUIDELINES:',
|
||||
'- GROSS vs NET PRICES: User prices are almost always GROSS (incl. VAT); API requires NET. Formula: `net = gross / (1 + taxRate / 100)`. Compute in javascript_execute with high precision (4–6 decimals) to prevent rounding error.',
|
||||
'- DISPLAYING GENERATED IMAGES: Inline markdown images supported. Embed written VFS image paths: ``. Other files (PDF, JSON, CSV) do not render inline; provide download links.',
|
||||
'- LABEL TEMPLATES (/labeltemplate): Must use Dashback JSON schema `{ "objects": [ ... ] }`. Do NOT use ZPL.',
|
||||
'- Format output with markdown tables, bullet points, or bold key-value pairs.',
|
||||
...(routesDoc ? ['', 'DASHBACK API ROUTES:', routesDoc] : []),
|
||||
'- Always Format output with markdown and emoji.',
|
||||
...(routesDoc ? [
|
||||
'',
|
||||
'DASHBACK API ROUTES:',
|
||||
'Binary image upload routes (use via fetch() in javascript_execute with image/avif buffer body):',
|
||||
'- POST /article/{sku}/image (Params: sku: str, body: image/avif -> 201 { image: { picId: int, sort: int, full: { w, h, size }, thumb: { w, h }, hash: str, thumbHash: str } })',
|
||||
'- POST /category/{id}/image (Params: id: int, body: image/avif -> 201 { category: { id: int, thumbW: int, thumbH: int, thumbHash: str } })',
|
||||
'- POST /brand/{id}/image (Params: id: int, body: image/avif -> 201 { brand: { id: int, fullHash: str, thumbW: int, thumbH: int, thumbHash: str, pics: [...] } })',
|
||||
'',
|
||||
routesDoc,
|
||||
] : []),
|
||||
].join('\n');
|
||||
|
||||
const sections = [];
|
||||
@@ -632,6 +643,7 @@ export class ConversationManager {
|
||||
createPdfReadTool({ googleAuthId }),
|
||||
createResetVfsTool({ googleAuthId }),
|
||||
createApiSuggestionsOrIssuesTool({ googleAuthId, companyId: this.companyId }),
|
||||
createSearchArticlesTool({ googleAuthId, companyId: this.companyId }),
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
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