diff --git a/src/app/api/products/search-sheets/route.ts b/src/app/api/products/search-sheets/route.ts index d54ae21..8b7916d 100644 --- a/src/app/api/products/search-sheets/route.ts +++ b/src/app/api/products/search-sheets/route.ts @@ -32,6 +32,10 @@ export async function GET(req: NextRequest) { s => s.properties.title, ) + // Collecte tous les matches et retourne le plus spécifique (UGS la plus longue) + // pour éviter que "26618" matche avant "26618-D" dans le nom de fichier + let bestMatch: { shopifyId: string; title: string; ugsLength: number } | null = null + for (const tab of tabs) { const range = encodeURIComponent(`${tab}!A2:D`) const res = await fetch( @@ -53,13 +57,15 @@ export async function GET(req: NextRequest) { const wordBoundary = new RegExp(`(^|[^a-z0-9])${ugsLower.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`) const isMatch = ugs && shopifyId && wordBoundary.test(refLower) - if (isMatch) { - const title = (row[3] ?? '').trim() // col D = Nom - return NextResponse.json({ found: true, shopifyId, title }) + if (isMatch && (!bestMatch || ugs.length > bestMatch.ugsLength)) { + bestMatch = { shopifyId, title: (row[3] ?? '').trim(), ugsLength: ugs.length } } } } + if (bestMatch) { + return NextResponse.json({ found: true, shopifyId: bestMatch.shopifyId, title: bestMatch.title }) + } return NextResponse.json({ found: false }) } catch (err) { const message = err instanceof Error ? err.message : 'Erreur'