diff --git a/src/app/api/products/search-sheets/route.ts b/src/app/api/products/search-sheets/route.ts index 062d7b3..3320da7 100644 --- a/src/app/api/products/search-sheets/route.ts +++ b/src/app/api/products/search-sheets/route.ts @@ -50,9 +50,10 @@ export async function GET(req: NextRequest) { const refLower = ref.toLowerCase() const ugsLower = ugs.toLowerCase() const wordBoundary = new RegExp(`(^|[^a-z0-9])${ugsLower.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`) - const isMatch = ugs && shopifyId && wordBoundary.test(refLower) + // Ne requiert pas shopifyId pour le match UGS — ID peut être absent si produit externe + const isMatch = ugs && wordBoundary.test(refLower) - if (isMatch) { + if (isMatch && shopifyId) { const title = (row[3] ?? '').trim() if (!bestMatch || ugs.length > bestMatch.ugsLength) { bestMatch = { shopifyId, title, ugsLength: ugs.length } diff --git a/src/lib/shopify.ts b/src/lib/shopify.ts index 56d50e5..3e6cc5e 100644 --- a/src/lib/shopify.ts +++ b/src/lib/shopify.ts @@ -27,29 +27,36 @@ export type ShopifyProductResult = export async function searchProductByRef(ref: string): Promise { const { baseUrl, headers } = getConfig() - // Recherche par SKU via l'API variants + // Recherche par SKU via l'API GraphQL (supporte les SKUs avec tirets, contrairement au REST) + const graphqlUrl = `https://${process.env.SHOPIFY_STORE_DOMAIN}/admin/api/${API_VERSION}/graphql.json` const searchBySku = async (sku: string): Promise => { - const res = await fetch( - `${baseUrl}/variants.json?sku=${encodeURIComponent(sku)}&fields=id,sku,product_id&limit=1`, - { headers }, - ) + const query = `{ + productVariants(first: 10, query: "sku:${sku.replace(/"/g, '')}") { + edges { + node { + sku + product { id legacyResourceId title } + } + } + } + }` + const res = await fetch(graphqlUrl, { + method: 'POST', + headers, + body: JSON.stringify({ query }), + }) if (!res.ok) return { found: false } const data = await res.json() - const variants = (data.variants ?? []) as Array<{ id: number; sku: string; product_id: number }> - const match = variants.find(v => v.sku === sku) - if (!match) return { found: false } - - // Récupère le titre du produit - const productRes = await fetch( - `${baseUrl}/products/${match.product_id}.json?fields=id,title`, - { headers }, + const edges = data?.data?.productVariants?.edges ?? [] + // Cherche le match exact (insensible à la casse) parmi les résultats + const match = edges.find((e: { node: { sku: string } }) => + e.node.sku.toLowerCase() === sku.toLowerCase() ) - if (!productRes.ok) return { found: false } - const productData = await productRes.json() + if (!match) return { found: false } return { found: true, - shopifyId: String(match.product_id), - title: productData.product?.title ?? sku, + shopifyId: match.node.product.legacyResourceId, + title: match.node.product.title, } }