From a7650da5e07b1f7f0c70a9cc677dea9c73182eb1 Mon Sep 17 00:00:00 2001 From: karishmas6 Date: Thu, 19 Sep 2024 09:00:56 +0530 Subject: [PATCH] feat: route to write to sheet --- server/src/routes/integration.ts | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/server/src/routes/integration.ts b/server/src/routes/integration.ts index ecb35102..f342624a 100644 --- a/server/src/routes/integration.ts +++ b/server/src/routes/integration.ts @@ -2,6 +2,9 @@ import { Router } from 'express'; import fs from 'fs'; import path from 'path'; import logger from "../logger"; +import { writeDataToSheet } from "../workflow-management/integrations/gsheet" +import { readFile } from "../workflow-management/storage"; + export const router = Router(); @@ -49,3 +52,35 @@ router.post('/upload-credentials', async (req, res) => { return res.status(500).json({ message: 'Failed to save credentials.', error: error.message }); } }); + +router.post('/update-google-sheet/:fileName/:runId', async (req, res) => { + try { + const run = await readFile(`./../storage/runs/${req.params.fileName}_${req.params.runId}.json`); + const parsedRun = JSON.parse(run); + + if (parsedRun.status === 'success' && parsedRun.serializableOutput) { + const data = parsedRun.serializableOutput as { [key: string]: any }[]; + const integrationConfig = await loadIntegrations(); + + if (integrationConfig) { + const { spreadsheetId, sheetName, credentials } = integrationConfig; + + if (spreadsheetId && sheetName && credentials) { + // Convert data to Google Sheets format (headers and rows) + const headers = Object.keys(data[0]); + const rows = data.map((row: { [key: string]: any }) => Object.values(row)); + const outputData = [headers, ...rows]; // Include headers + + await writeDataToSheet(spreadsheetId, sheetName, outputData); + logger.log('info', `Data written to Google Sheet successfully for ${req.params.fileName}_${req.params.runId}`); + return res.send({ success: true, message: 'Data updated in Google Sheet' }); + } + } + return res.status(400).send({ success: false, message: 'Google Sheet integration not configured' }); + } + return res.status(400).send({ success: false, message: 'Run not successful or no data to update' }); + } catch (error) { + logger.log('error', `Failed to write data to Google Sheet for ${req.params.fileName}_${req.params.runId}: ${error.message}`); + return res.status(500).send({ success: false, message: 'Failed to update Google Sheet', error: error.message }); + } + });