fix: recherche produit via Google Sheets (UGS col C → Shopify ID col A) + fallback Shopify
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
|
||||
/**
|
||||
* Cherche un produit dans Google Sheets par sa référence (UGS, col C).
|
||||
* Retourne le Shopify ID (col A) et le titre (col D) si trouvé.
|
||||
* Parcourt tous les onglets.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session) return NextResponse.json({ found: false }, { status: 401 })
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
const ref = searchParams.get('ref')?.trim()
|
||||
if (!ref) return NextResponse.json({ found: false }, { status: 400 })
|
||||
|
||||
const apiKey = process.env.GOOGLE_API_KEY
|
||||
const sheetId = process.env.GOOGLE_SHEETS_ID
|
||||
if (!apiKey || !sheetId) {
|
||||
return NextResponse.json({ found: false, error: 'GOOGLE_API_KEY et GOOGLE_SHEETS_ID requis' }, { status: 500 })
|
||||
}
|
||||
|
||||
try {
|
||||
// Récupère la liste des onglets
|
||||
const metaRes = await fetch(
|
||||
`https://sheets.googleapis.com/v4/spreadsheets/${sheetId}?key=${apiKey}&fields=sheets.properties.title`,
|
||||
)
|
||||
if (!metaRes.ok) throw new Error(`Sheets metadata error: ${metaRes.status}`)
|
||||
const meta = await metaRes.json()
|
||||
const tabs: string[] = (meta.sheets as Array<{ properties: { title: string } }>).map(
|
||||
s => s.properties.title,
|
||||
)
|
||||
|
||||
for (const tab of tabs) {
|
||||
const range = encodeURIComponent(`${tab}!A2:D`)
|
||||
const res = await fetch(
|
||||
`https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${range}?key=${apiKey}`,
|
||||
)
|
||||
if (!res.ok) continue
|
||||
const data = await res.json()
|
||||
const rows = (data.values ?? []) as string[][]
|
||||
|
||||
for (const row of rows) {
|
||||
const shopifyId = (row[0] ?? '').trim() // col A = ID Shopify
|
||||
// col C = UGS (index 2 car on commence à A)
|
||||
const ugs = (row[2] ?? '').trim()
|
||||
|
||||
if (ugs.toLowerCase() === ref.toLowerCase() && shopifyId) {
|
||||
const title = (row[3] ?? '').trim() // col D = Nom
|
||||
return NextResponse.json({ found: true, shopifyId, title })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ found: false })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur'
|
||||
return NextResponse.json({ found: false, error: message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user