From 6c74b0b2421f1790bd993554038911432a4502fb Mon Sep 17 00:00:00 2001 From: David Ascanio Date: Sat, 14 Feb 2026 16:55:33 -0300 Subject: [PATCH 1/2] duplicate-record-validation --- src/pages/api/lib/googleSheets.ts | 50 +++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/pages/api/lib/googleSheets.ts b/src/pages/api/lib/googleSheets.ts index 38ccf98..a5fc84b 100644 --- a/src/pages/api/lib/googleSheets.ts +++ b/src/pages/api/lib/googleSheets.ts @@ -11,17 +11,63 @@ const auth = new google.auth.GoogleAuth({ const sheets = google.sheets({ version: 'v4', auth }); const SPREADSHEET_ID = import.meta.env.GOOGLE_SHEET_ID; +async function emailExists(email: string): Promise { + const formula = `=COUNTIF(G:G,"${email}")`; + + // Escribir fórmula en celda auxiliar + await sheets.spreadsheets.values.update({ + spreadsheetId: SPREADSHEET_ID, + range: 'DATABASE!Z1', // usa una columna libre + valueInputOption: 'USER_ENTERED', + requestBody: { + values: [[formula]], + }, + }); + + // Leer resultado calculado + const result = await sheets.spreadsheets.values.get({ + spreadsheetId: SPREADSHEET_ID, + range: 'DATABASE!Z1', + valueRenderOption: 'UNFORMATTED_VALUE', + }); + + const count = result.data.values?.[0]?.[0] || 0; + + return Number(count) > 0; +} + + export async function appendToSheet(values: any[]) { try { + const email = values[6]; // índice donde está el email en tu array + + if (!email) { + throw new Error('Email requerido'); + } + + const exists = await emailExists(email); + if (exists) { + return { + success: false, + message: 'El email ya existe en la base de datos', + }; + } + await sheets.spreadsheets.values.append({ spreadsheetId: SPREADSHEET_ID, - range: 'DATABASE!A2:H2', + range: 'DATABASE!A:H', valueInputOption: 'RAW', requestBody: { values: [values], }, }); + + return { + success: true, + message: 'Registro guardado correctamente', + }; + } catch (error) { throw error; } -} \ No newline at end of file +} -- 2.39.5 From ce1bf25806db3b6e5a4133cc075811a79bee7247 Mon Sep 17 00:00:00 2001 From: David Ascanio Date: Sat, 14 Feb 2026 17:07:09 -0300 Subject: [PATCH 2/2] A2:H2 --- src/pages/api/lib/googleSheets.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/api/lib/googleSheets.ts b/src/pages/api/lib/googleSheets.ts index a5fc84b..f333aaa 100644 --- a/src/pages/api/lib/googleSheets.ts +++ b/src/pages/api/lib/googleSheets.ts @@ -55,7 +55,7 @@ export async function appendToSheet(values: any[]) { await sheets.spreadsheets.values.append({ spreadsheetId: SPREADSHEET_ID, - range: 'DATABASE!A:H', + range: 'DATABASE!A2:H2', valueInputOption: 'RAW', requestBody: { values: [values], -- 2.39.5