chore: google integration auth notif

This commit is contained in:
RohitR311
2024-11-13 00:06:32 +05:30
parent 7197bbffe6
commit c033ff5255

View File

@@ -1,12 +1,20 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from "react";
import { GenericModal } from "../atoms/GenericModal"; import { GenericModal } from "../atoms/GenericModal";
import { MenuItem, Typography, CircularProgress, Alert, AlertTitle, Chip } from "@mui/material"; import {
MenuItem,
Typography,
CircularProgress,
Alert,
AlertTitle,
Chip,
} from "@mui/material";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import axios from 'axios'; import axios from "axios";
import { useGlobalInfoStore } from '../../context/globalInfo'; import { useGlobalInfoStore } from "../../context/globalInfo";
import { getStoredRecording } from '../../api/storage'; import { getStoredRecording } from "../../api/storage";
import { apiUrl } from '../../apiConfig.js'; import { apiUrl } from "../../apiConfig.js";
import Cookies from 'js-cookie';
interface IntegrationProps { interface IntegrationProps {
isOpen: boolean; isOpen: boolean;
handleStart: (data: IntegrationSettings) => void; handleStart: (data: IntegrationSettings) => void;
@@ -18,14 +26,20 @@ export interface IntegrationSettings {
data: string; data: string;
} }
export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: IntegrationProps) => { export const IntegrationSettingsModal = ({
isOpen,
handleStart,
handleClose,
}: IntegrationProps) => {
const [settings, setSettings] = useState<IntegrationSettings>({ const [settings, setSettings] = useState<IntegrationSettings>({
spreadsheetId: '', spreadsheetId: "",
spreadsheetName: '', spreadsheetName: "",
data: '', data: "",
}); });
const [spreadsheets, setSpreadsheets] = useState<{ id: string, name: string }[]>([]); const [spreadsheets, setSpreadsheets] = useState<
{ id: string; name: string }[]
>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -41,26 +55,43 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
const response = await axios.get(`${apiUrl}/auth/google/callback`); const response = await axios.get(`${apiUrl}/auth/google/callback`);
const { google_sheet_email, files } = response.data; const { google_sheet_email, files } = response.data;
} catch (error) { } catch (error) {
setError('Error authenticating with Google'); setError("Error authenticating with Google");
} }
}; };
const fetchSpreadsheetFiles = async () => { const fetchSpreadsheetFiles = async () => {
try { try {
const response = await axios.get(`${apiUrl}/auth/gsheets/files?robotId=${recordingId}`, { const response = await axios.get(
`${apiUrl}/auth/gsheets/files?robotId=${recordingId}`,
{
withCredentials: true, withCredentials: true,
}); }
);
setSpreadsheets(response.data); setSpreadsheets(response.data);
} catch (error: any) { } catch (error: any) {
console.error('Error fetching spreadsheet files:', error.response?.data?.message || error.message); console.error(
notify('error', `Error fetching spreadsheet files: ${error.response?.data?.message || error.message}`); "Error fetching spreadsheet files:",
error.response?.data?.message || error.message
);
notify(
"error",
`Error fetching spreadsheet files: ${
error.response?.data?.message || error.message
}`
);
} }
}; };
const handleSpreadsheetSelect = (e: React.ChangeEvent<HTMLInputElement>) => { const handleSpreadsheetSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedSheet = spreadsheets.find(sheet => sheet.id === e.target.value); const selectedSheet = spreadsheets.find(
(sheet) => sheet.id === e.target.value
);
if (selectedSheet) { if (selectedSheet) {
setSettings({ ...settings, spreadsheetId: selectedSheet.id, spreadsheetName: selectedSheet.name }); setSettings({
...settings,
spreadsheetId: selectedSheet.id,
spreadsheetName: selectedSheet.name,
});
} }
}; };
@@ -68,12 +99,19 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
try { try {
const response = await axios.post( const response = await axios.post(
`${apiUrl}/auth/gsheets/update`, `${apiUrl}/auth/gsheets/update`,
{ spreadsheetId: settings.spreadsheetId, spreadsheetName: settings.spreadsheetName, robotId: recordingId }, {
spreadsheetId: settings.spreadsheetId,
spreadsheetName: settings.spreadsheetName,
robotId: recordingId,
},
{ withCredentials: true } { withCredentials: true }
); );
console.log('Google Sheet ID updated:', response.data); console.log("Google Sheet ID updated:", response.data);
} catch (error: any) { } catch (error: any) {
console.error('Error updating Google Sheet ID:', error.response?.data?.message || error.message); console.error(
"Error updating Google Sheet ID:",
error.response?.data?.message || error.message
);
} }
}; };
@@ -87,16 +125,30 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
setRecording(null); setRecording(null);
setSpreadsheets([]); setSpreadsheets([]);
setSettings({ spreadsheetId: '', spreadsheetName: '', data: '' }); setSettings({ spreadsheetId: "", spreadsheetName: "", data: "" });
} catch (error: any) { } catch (error: any) {
console.error('Error removing Google Sheets integration:', error.response?.data?.message || error.message); console.error(
"Error removing Google Sheets integration:",
error.response?.data?.message || error.message
);
} }
}; };
useEffect(() => { useEffect(() => {
// Check if there is a success message in cookies
const status = Cookies.get("robot_auth_status");
const message = Cookies.get("robot_auth_message");
if (status === "success" && message) {
notify("success", message);
// Clear the cookies after reading
Cookies.remove("robot_auth_status");
Cookies.remove("robot_auth_message");
}
// Check if we're on the callback URL // Check if we're on the callback URL
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code'); const code = urlParams.get("code");
if (code) { if (code) {
handleOAuthCallback(); handleOAuthCallback();
} }
@@ -114,22 +166,44 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
return ( return (
<GenericModal isOpen={isOpen} onClose={handleClose} modalStyle={modalStyle}> <GenericModal isOpen={isOpen} onClose={handleClose} modalStyle={modalStyle}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', marginLeft: '65px' }}> <div
<Typography variant="h6" >Integrate with Google Sheet <Chip label="beta" color="primary" variant="outlined" /></Typography> style={{
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
marginLeft: "65px",
}}
>
<Typography variant="h6">
Integrate with Google Sheet{" "}
<Chip label="beta" color="primary" variant="outlined" />
</Typography>
{recording && recording.google_sheet_id ? ( {recording && recording.google_sheet_id ? (
<> <>
<Alert severity="info"> <Alert severity="info">
<AlertTitle>Google Sheet Integrated Successfully.</AlertTitle> <AlertTitle>Google Sheet Integrated Successfully.</AlertTitle>
Every time this robot creates a successful run, its captured data is appended to your {recording.google_sheet_name} Google Sheet. You can check the data updates <a href={`https://docs.google.com/spreadsheets/d/${recording.google_sheet_id}`} target="_blank" rel="noreferrer">here</a>. Every time this robot creates a successful run, its captured data
is appended to your {recording.google_sheet_name} Google Sheet.
You can check the data updates{" "}
<a
href={`https://docs.google.com/spreadsheets/d/${recording.google_sheet_id}`}
target="_blank"
rel="noreferrer"
>
here
</a>
.
<br /> <br />
<strong>Note:</strong> The data extracted before integrating with Google Sheets will not be synced in the Google Sheet. Only the data extracted after the integration will be synced. <strong>Note:</strong> The data extracted before integrating with
Google Sheets will not be synced in the Google Sheet. Only the
data extracted after the integration will be synced.
</Alert> </Alert>
<Button <Button
variant="outlined" variant="outlined"
color="error" color="error"
onClick={removeIntegration} onClick={removeIntegration}
style={{ marginTop: '15px' }} style={{ marginTop: "15px" }}
> >
Remove Integration Remove Integration
</Button> </Button>
@@ -138,7 +212,11 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
<> <>
{!recording?.google_sheet_email ? ( {!recording?.google_sheet_email ? (
<> <>
<p>If you enable this option, every time this robot runs a task successfully, its captured data will be appended to your Google Sheet.</p> <p>
If you enable this option, every time this robot runs a task
successfully, its captured data will be appended to your
Google Sheet.
</p>
<Button <Button
variant="contained" variant="contained"
color="primary" color="primary"
@@ -150,18 +228,18 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
) : ( ) : (
<> <>
{recording.google_sheet_email && ( {recording.google_sheet_email && (
<Typography sx={{ margin: '20px 0px 30px 0px' }}> <Typography sx={{ margin: "20px 0px 30px 0px" }}>
Authenticated as: {recording.google_sheet_email} Authenticated as: {recording.google_sheet_email}
</Typography> </Typography>
)} )}
{loading ? ( {loading ? (
<CircularProgress sx={{ marginBottom: '15px' }} /> <CircularProgress sx={{ marginBottom: "15px" }} />
) : error ? ( ) : error ? (
<Typography color="error">{error}</Typography> <Typography color="error">{error}</Typography>
) : spreadsheets.length === 0 ? ( ) : spreadsheets.length === 0 ? (
<> <>
<div style={{ display: 'flex', gap: '10px' }}> <div style={{ display: "flex", gap: "10px" }}>
<Button <Button
variant="outlined" variant="outlined"
color="primary" color="primary"
@@ -181,7 +259,7 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
) : ( ) : (
<> <>
<TextField <TextField
sx={{ marginBottom: '15px' }} sx={{ marginBottom: "15px" }}
select select
label="Select Google Sheet" label="Select Google Sheet"
required required
@@ -189,7 +267,7 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
onChange={handleSpreadsheetSelect} onChange={handleSpreadsheetSelect}
fullWidth fullWidth
> >
{spreadsheets.map(sheet => ( {spreadsheets.map((sheet) => (
<MenuItem key={sheet.id} value={sheet.id}> <MenuItem key={sheet.id} value={sheet.id}>
{sheet.name} {sheet.name}
</MenuItem> </MenuItem>
@@ -197,8 +275,14 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
</TextField> </TextField>
{settings.spreadsheetId && ( {settings.spreadsheetId && (
<Typography sx={{ marginBottom: '10px' }}> <Typography sx={{ marginBottom: "10px" }}>
Selected Sheet: {spreadsheets.find(s => s.id === settings.spreadsheetId)?.name} (ID: {settings.spreadsheetId}) Selected Sheet:{" "}
{
spreadsheets.find(
(s) => s.id === settings.spreadsheetId
)?.name
}{" "}
(ID: {settings.spreadsheetId})
</Typography> </Typography>
)} )}
@@ -209,7 +293,7 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
updateGoogleSheetId(); updateGoogleSheetId();
handleStart(settings); handleStart(settings);
}} }}
style={{ marginTop: '10px' }} style={{ marginTop: "10px" }}
disabled={!settings.spreadsheetId || loading} disabled={!settings.spreadsheetId || loading}
> >
Submit Submit
@@ -226,13 +310,13 @@ export const IntegrationSettingsModal = ({ isOpen, handleStart, handleClose }: I
}; };
export const modalStyle = { export const modalStyle = {
top: '40%', top: "40%",
left: '50%', left: "50%",
transform: 'translate(-50%, -50%)', transform: "translate(-50%, -50%)",
width: '50%', width: "50%",
backgroundColor: 'background.paper', backgroundColor: "background.paper",
p: 4, p: 4,
height: 'fit-content', height: "fit-content",
display: 'block', display: "block",
padding: '20px', padding: "20px",
}; };