integration modal changed

This commit is contained in:
AmitChauhan63390
2025-01-27 21:29:11 +05:30
parent e89d64d04f
commit ae700764b9
2 changed files with 353 additions and 372 deletions

View File

@@ -672,8 +672,17 @@ router.get("/airtable/callback", async (req, res) => {
if (err) console.error('Session cleanup error:', err); if (err) console.error('Session cleanup error:', err);
}); });
res.cookie("airtable_auth_status", "success", {
httpOnly: false,
maxAge: 60000,
}); // 1-minute expiration
res.cookie("airtable_auth_message", "Robot successfully authenticated", {
httpOnly: false,
maxAge: 60000,
});
res.redirect( res.redirect(
`${process.env.PUBLIC_URL}/robots/${state}/integrate?success=true` `${process.env.PUBLIC_URL}/robots/${state}/integrate || http://localhost:5173/robots/${state}/integrate`
); );
} catch (error: any) { } catch (error: any) {

View File

@@ -6,10 +6,9 @@ import {
CircularProgress, CircularProgress,
Alert, Alert,
AlertTitle, AlertTitle,
Chip, Button,
TextField,
} from "@mui/material"; } from "@mui/material";
import Button from "@mui/material/Button";
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";
@@ -52,9 +51,6 @@ export const IntegrationSettingsModal = ({
handleClose, handleClose,
}: IntegrationProps) => { }: IntegrationProps) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [selectedIntegrationType, setSelectedIntegrationType] = useState<
"googleSheets" | "airtable" | null
>(null);
const [settings, setSettings] = useState<IntegrationSettings>({ const [settings, setSettings] = useState<IntegrationSettings>({
spreadsheetId: "", spreadsheetId: "",
spreadsheetName: "", spreadsheetName: "",
@@ -64,114 +60,61 @@ export const IntegrationSettingsModal = ({
integrationType: "googleSheets", integrationType: "googleSheets",
}); });
const [airtableTables, setAirtableTables] = useState<{ id: string; name: string }[]>([]); const [spreadsheets, setSpreadsheets] = useState<{ id: string; name: string }[]>([]);
const [spreadsheets, setSpreadsheets] = useState< const [airtableBases, setAirtableBases] = useState<{ id: string; name: string }[]>([]);
{ id: string; name: string }[]
>([]);
const [airtableBases, setAirtableBases] = 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);
const { recordingId, notify } = useGlobalInfoStore(); const { recordingId, notify } = useGlobalInfoStore();
const [recording, setRecording] = useState<any>(null); const [recording, setRecording] = useState<any>(null);
const [airtableAuthStatus, setAirtableAuthStatus] = useState<boolean | null>(null);
// Authenticate with Google Sheets
const authenticateWithGoogle = () => { const authenticateWithGoogle = () => {
window.location.href = `${apiUrl}/auth/google?robotId=${recordingId}`; window.location.href = `${apiUrl}/auth/google?robotId=${recordingId}`;
}; };
// Authenticate with Airtable
const authenticateWithAirtable = () => { const authenticateWithAirtable = () => {
window.location.href = `${apiUrl}/auth/airtable?robotId=${recordingId}`; window.location.href = `${apiUrl}/auth/airtable?robotId=${recordingId}`;
}; };
const handleIntegrationType = (type: "googleSheets" | "airtable") => { // Fetch Google Sheets files
setSelectedIntegrationType(type);
setSettings({
...settings,
integrationType: type,
});
};
const fetchAirtableTables = async (baseId: string) => {
try {
const response = await axios.get(
`${apiUrl}/auth/airtable/tables?baseId=${baseId}&robotId=${recordingId}`,
{
withCredentials: true,
}
);
setAirtableTables(response.data);
} catch (error: any) {
console.error(
"Error fetching Airtable tables:",
error.response?.data?.message || error.message
);
notify(
"error",
t("integration_settings.errors.fetch_error", {
message: error.response?.data?.message || error.message,
})
);
}
};
const fetchSpreadsheetFiles = async () => { const fetchSpreadsheetFiles = async () => {
try { try {
const response = await axios.get( const response = await axios.get(
`${apiUrl}/auth/gsheets/files?robotId=${recordingId}`, `${apiUrl}/auth/gsheets/files?robotId=${recordingId}`,
{ { withCredentials: true }
withCredentials: true,
}
); );
setSpreadsheets(response.data); setSpreadsheets(response.data);
} catch (error: any) { } catch (error: any) {
console.error( console.error("Error fetching spreadsheet files:", error);
"Error fetching spreadsheet files:", notify("error", t("integration_settings.errors.fetch_error", {
error.response?.data?.message || error.message message: error.response?.data?.message || error.message,
); }));
notify(
"error",
t("integration_settings.errors.fetch_error", {
message: error.response?.data?.message || error.message,
})
);
} }
}; };
console.log("recordingId", recordingId); // Fetch Airtable bases
const fetchAirtableBases = async () => { const fetchAirtableBases = async () => {
try { try {
const response = await axios.get( const response = await axios.get(
`${apiUrl}/auth/airtable/bases?robotId=${recordingId}`, `${apiUrl}/auth/airtable/bases?robotId=${recordingId}`,
{ { withCredentials: true }
withCredentials: true,
}
); );
setAirtableBases(response.data); setAirtableBases(response.data);
console.log("Airtable bases:", response.data);
} catch (error: any) { } catch (error: any) {
console.error( console.error("Error fetching Airtable bases:", error);
"Error fetching Airtable bases:", notify("error", t("integration_settings.errors.fetch_error", {
error.response?.data?.message || error.message message: error.response?.data?.message || error.message,
); }));
notify(
"error",
t("integration_settings.errors.fetch_error", {
message: error.response?.data?.message || error.message,
})
);
} }
}; };
// Handle Google Sheets selection
const handleSpreadsheetSelect = (e: React.ChangeEvent<HTMLInputElement>) => { const handleSpreadsheetSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedSheet = spreadsheets.find( const selectedSheet = spreadsheets.find((sheet) => sheet.id === e.target.value);
(sheet) => sheet.id === e.target.value
);
if (selectedSheet) { if (selectedSheet) {
setSettings({ setSettings({
...settings, ...settings,
@@ -181,10 +124,9 @@ export const IntegrationSettingsModal = ({
} }
}; };
// Handle Airtable base selection
const handleAirtableBaseSelect = (e: React.ChangeEvent<HTMLInputElement>) => { const handleAirtableBaseSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedBase = airtableBases.find( const selectedBase = airtableBases.find((base) => base.id === e.target.value);
(base) => base.id === e.target.value
);
if (selectedBase) { if (selectedBase) {
setSettings({ setSettings({
...settings, ...settings,
@@ -194,9 +136,10 @@ export const IntegrationSettingsModal = ({
} }
}; };
// Update Google Sheets integration
const updateGoogleSheetId = async () => { const updateGoogleSheetId = async () => {
try { try {
const response = await axios.post( await axios.post(
`${apiUrl}/auth/gsheets/update`, `${apiUrl}/auth/gsheets/update`,
{ {
spreadsheetId: settings.spreadsheetId, spreadsheetId: settings.spreadsheetId,
@@ -205,19 +148,19 @@ export const IntegrationSettingsModal = ({
}, },
{ withCredentials: true } { withCredentials: true }
); );
notify(`success`, t("integration_settings.notifications.sheet_selected")); notify("success", t("integration_settings.notifications.sheet_selected"));
console.log("Google Sheet ID updated:", response.data);
} catch (error: any) { } catch (error: any) {
console.error( console.error("Error updating Google Sheet ID:", error);
"Error updating Google Sheet ID:", notify("error", t("integration_settings.errors.update_error", {
error.response?.data?.message || error.message message: error.response?.data?.message || error.message,
); }));
} }
}; };
const updateAirtableBaseId = async () => { // Update Airtable integration
const updateAirtableBase = async () => {
try { try {
const response = await axios.post( await axios.post(
`${apiUrl}/auth/airtable/update`, `${apiUrl}/auth/airtable/update`,
{ {
baseId: settings.airtableBaseId, baseId: settings.airtableBaseId,
@@ -226,332 +169,361 @@ export const IntegrationSettingsModal = ({
}, },
{ withCredentials: true } { withCredentials: true }
); );
notify(`success`, t("integration_settings.notifications.base_selected")); notify("success", t("integration_settings.notifications.base_selected"));
console.log("Airtable Base ID updated:", response.data);
} catch (error: any) { } catch (error: any) {
console.error( console.error("Error updating Airtable base:", error);
"Error updating Airtable Base ID:", notify("error", t("integration_settings.errors.update_error", {
error.response?.data?.message || error.message message: error.response?.data?.message || error.message,
); }));
} }
}; };
const removeIntegration = async () => { // Remove Google Sheets integration
const removeGoogleSheetsIntegration = async () => {
try { try {
const endpoint =
selectedIntegrationType === "googleSheets"
? "/auth/gsheets/remove"
: "/auth/airtable/remove";
await axios.post( await axios.post(
`${apiUrl}${endpoint}`, `${apiUrl}/auth/gsheets/remove`,
{ robotId: recordingId }, { robotId: recordingId },
{ withCredentials: true } { withCredentials: true }
); );
setRecording(null);
setSpreadsheets([]); setSpreadsheets([]);
setAirtableBases([]); setSettings({ ...settings, spreadsheetId: "", spreadsheetName: "" });
setSelectedIntegrationType(null); notify("success", t("integration_settings.notifications.integration_removed"));
setSettings({
spreadsheetId: "",
spreadsheetName: "",
airtableBaseId: "",
airtableBaseName: "",
data: "",
integrationType: "googleSheets",
});
} catch (error: any) { } catch (error: any) {
console.error( console.error("Error removing Google Sheets integration:", error);
"Error removing integration:", notify("error", t("integration_settings.errors.remove_error", {
error.response?.data?.message || error.message message: error.response?.data?.message || error.message,
); }));
} }
}; };
// Remove Airtable integration
const removeAirtableIntegration = async () => {
try {
await axios.post(
`${apiUrl}/auth/airtable/remove`,
{ robotId: recordingId },
{ withCredentials: true }
);
setAirtableBases([]);
setSettings({ ...settings, airtableBaseId: "", airtableBaseName: "" });
notify("success", t("integration_settings.notifications.integration_removed"));
} catch (error: any) {
console.error("Error removing Airtable integration:", error);
notify("error", t("integration_settings.errors.remove_error", {
message: error.response?.data?.message || error.message,
}));
}
};
// Handle OAuth callback for Airtable
const handleAirtableOAuthCallback = async () => {
try {
const response = await axios.get(`${apiUrl}/auth/airtable/callback`);
if (response.data.success) {
setAirtableAuthStatus(true);
fetchAirtableBases(); // Fetch bases after successful authentication
}
} catch (error) {
setError("Error authenticating with Airtable");
}
};
// Fetch recording info on component mount
useEffect(() => { useEffect(() => {
const status = getCookie("robot_auth_status");
const message = getCookie("robot_auth_message");
if (status === "success" && message) {
notify("success", message);
removeCookie("robot_auth_status");
removeCookie("robot_auth_message");
}
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
if (code) {
// Determine which authentication callback to handle
// You'll need to implement similar callback logic for Airtable
}
const fetchRecordingInfo = async () => { const fetchRecordingInfo = async () => {
if (!recordingId) return; if (!recordingId) return;
const recording = await getStoredRecording(recordingId); const recording = await getStoredRecording(recordingId);
if (recording) { if (recording) {
setRecording(recording); setRecording(recording);
// Determine integration type based on existing integration
if (recording.google_sheet_id) { if (recording.google_sheet_id) {
setSelectedIntegrationType("googleSheets"); setSettings({ ...settings, integrationType: "googleSheets" });
} else if (recording.airtable_base_id) { } else if (recording.airtable_base_id) {
setSelectedIntegrationType("airtable"); setSettings({ ...settings, integrationType: "airtable" });
} }
} }
}; };
fetchRecordingInfo(); fetchRecordingInfo();
}, [recordingId]); }, [recordingId]);
// Initial integration type selection // Handle Airtable authentication status
if (!selectedIntegrationType) { useEffect(() => {
return ( const status = getCookie("airtable_auth_status");
<GenericModal const message = getCookie("airtable_auth_message");
isOpen={isOpen}
onClose={handleClose} if (status === "success" && message) {
modalStyle={modalStyle} notify("success", message);
> removeCookie("airtable_auth_status");
<div removeCookie("airtable_auth_message");
style={{ setAirtableAuthStatus(true);
display: "flex", fetchAirtableBases(); // Fetch bases after successful authentication
flexDirection: "column", }
alignItems: "center",
padding: "20px", const urlParams = new URLSearchParams(window.location.search);
}} const code = urlParams.get("code");
> if (code) {
<Typography variant="h6" sx={{ marginBottom: "20px" }}> handleAirtableOAuthCallback();
{t("integration_settings.title_select_integration")} }
</Typography> }, [recordingId]);
<div style={{ display: "flex", gap: "20px" }}>
<Button console.log(recording)
variant="contained"
color="primary"
onClick={() => handleIntegrationType("googleSheets")} const [selectedIntegrationType, setSelectedIntegrationType] = useState<
> "googleSheets" | "airtable" | null
Google Sheets >(null);
</Button>
<Button // Add this UI at the top of the modal return statement
variant="contained" if (!selectedIntegrationType) {
color="secondary" return (
onClick={() => handleIntegrationType("airtable")} <GenericModal
> isOpen={isOpen}
Airtable onClose={handleClose}
</Button> modalStyle={modalStyle}
</div> >
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
padding: "20px"
}}>
<Typography variant="h6" sx={{ marginBottom: "20px" }}>
{t("integration_settings.title_select_integration")}
</Typography>
<div style={{ display: "flex", gap: "20px" }}>
{/* Google Sheets Button */}
<Button
variant="contained"
color="primary"
onClick={() => {
setSelectedIntegrationType("googleSheets");
setSettings({ ...settings, integrationType: "googleSheets" });
}}
>
Google Sheets
</Button>
{/* Airtable Button */}
<Button
variant="contained"
color="secondary"
onClick={() => {
setSelectedIntegrationType("airtable");
setSettings({ ...settings, integrationType: "airtable" });
}}
>
Airtable
</Button>
</div> </div>
</GenericModal> </div>
); </GenericModal>
} );
}
return ( return (
<GenericModal isOpen={isOpen} onClose={handleClose} modalStyle={modalStyle}> <GenericModal isOpen={isOpen} onClose={handleClose} modalStyle={modalStyle}>
<div <div style={{
style={{ display: "flex",
display: "flex", flexDirection: "column",
flexDirection: "column", alignItems: "flex-start",
alignItems: "flex-start", marginLeft: "65px",
marginLeft: "65px", }}>
}}
>
<Typography variant="h6"> <Typography variant="h6">
{selectedIntegrationType === "googleSheets" {t("integration_settings.title")}
? t("integration_settings.title_google")
: t("integration_settings.title_airtable")}
</Typography> </Typography>
{recording && {/* Google Sheets Integration */}
(recording.google_sheet_id || recording.airtable_base_id ? ( {settings.integrationType === "googleSheets" && (
<>
<Alert
severity="info"
sx={{ marginTop: "10px", border: "1px solid #ff00c3" }}
>
<AlertTitle>
{t("integration_settings.alerts.success.title")}
</AlertTitle>
{selectedIntegrationType === "googleSheets" ? (
<>
{t("integration_settings.alerts.success.content", {
sheetName: recording.google_sheet_name,
})}
<a
href={`https://docs.google.com/spreadsheets/d/${recording.google_sheet_id}`}
target="_blank"
rel="noreferrer"
>
{t("integration_settings.alerts.success.here")}
</a>
</>
) : (
<>
{t("integration_settings.alerts.success.content", {
sheetName: recording.airtable_base_name,
})}
<a
href={`https://airtable.com/${recording.airtable_base_id}`}
target="_blank"
rel="noreferrer"
>
{t("integration_settings.alerts.success.here")}
</a>
</>
)}
<br />
<strong>
{t("integration_settings.alerts.success.note")}
</strong>{" "}
{t("integration_settings.alerts.success.sync_limitation")}
</Alert>
<Button
variant="outlined"
color="error"
onClick={removeIntegration}
style={{ marginTop: "15px" }}
>
{t("integration_settings.buttons.remove_integration")}
</Button>
</>
) : null)}
{!recording?.[
selectedIntegrationType === "googleSheets"
? "google_sheet_email"
: "airtable_email"
] ? (
<> <>
<p>{t("integration_settings.descriptions.sync_info")}</p> {recording?.google_sheet_id ? (
<Button
variant="contained"
color="primary"
onClick={
selectedIntegrationType === "googleSheets"
? authenticateWithGoogle
: authenticateWithAirtable
}
>
{t("integration_settings.buttons.authenticate")}
</Button>
</>
) : (
<>
{recording[
selectedIntegrationType === "googleSheets"
? "google_sheet_email"
: "airtable_email"
] && (
<Typography sx={{ margin: "20px 0px 30px 0px" }}>
{t("integration_settings.descriptions.authenticated_as", {
email:
recording[
selectedIntegrationType === "googleSheets"
? "google_sheet_email"
: "airtable_email"
],
})}
</Typography>
)}
{loading ? (
<CircularProgress sx={{ marginBottom: "15px" }} />
) : error ? (
<Typography color="error">{error}</Typography>
) : (selectedIntegrationType === "googleSheets"
? spreadsheets
: airtableBases
).length === 0 ? (
<> <>
<div style={{ display: "flex", gap: "10px" }}> <Alert severity="info" sx={{ marginTop: "10px", border: "1px solid #ff00c3" }}>
<Button <AlertTitle>{t("integration_settings.alerts.success.title")}</AlertTitle>
variant="outlined" {t("integration_settings.alerts.success.content", {
color="primary" sheetName: recording.google_sheet_name,
onClick={ })}
selectedIntegrationType === "googleSheets" <a
? fetchSpreadsheetFiles href={`https://docs.google.com/spreadsheets/d/${recording.google_sheet_id}`}
: fetchAirtableBases target="_blank"
} rel="noreferrer"
> >
{t("integration_settings.buttons.fetch_sheets")} {t("integration_settings.alerts.success.here")}
</Button> </a>
<Button </Alert>
variant="outlined" <Button
color="error" variant="outlined"
onClick={removeIntegration} color="error"
> onClick={removeGoogleSheetsIntegration}
{t("integration_settings.buttons.remove_integration")} style={{ marginTop: "15px" }}
</Button> >
</div> {t("integration_settings.buttons.remove_integration")}
</Button>
</> </>
) : ( ) : (
<> <>
<TextField {!recording?.google_sheet_email ? (
sx={{ marginBottom: "15px" }} <>
select <p>{t("integration_settings.descriptions.sync_info")}</p>
label={t("integration_settings.fields.select_sheet")} <Button
required variant="contained"
value={ color="primary"
selectedIntegrationType === "googleSheets" onClick={authenticateWithGoogle}
? settings.spreadsheetId >
: settings.airtableBaseId {t("integration_settings.buttons.authenticate")}
} </Button>
onChange={ </>
selectedIntegrationType === "googleSheets" ) : (
? handleSpreadsheetSelect <>
: handleAirtableBaseSelect <Typography sx={{ margin: "20px 0px 30px 0px" }}>
} {t("integration_settings.descriptions.authenticated_as", {
fullWidth email: recording.google_sheet_email,
> })}
{(selectedIntegrationType === "googleSheets" </Typography>
? spreadsheets {loading ? (
: airtableBases <CircularProgress sx={{ marginBottom: "15px" }} />
).map((item) => ( ) : error ? (
<MenuItem key={item.id} value={item.id}> <Typography color="error">{error}</Typography>
{item.name} ) : spreadsheets.length === 0 ? (
</MenuItem> <Button
))} variant="outlined"
</TextField> color="primary"
onClick={fetchSpreadsheetFiles}
{(selectedIntegrationType === "googleSheets" >
? settings.spreadsheetId {t("integration_settings.buttons.fetch_sheets")}
: settings.airtableBaseId) && ( </Button>
<Typography sx={{ marginBottom: "10px" }}> ) : (
{t("integration_settings.fields.selected_sheet", { <>
name: <TextField
selectedIntegrationType === "googleSheets" sx={{ marginBottom: "15px" }}
? spreadsheets.find( select
(s) => s.id === settings.spreadsheetId label={t("integration_settings.fields.select_sheet")}
)?.name required
: airtableBases.find( value={settings.spreadsheetId}
(b) => b.id === settings.airtableBaseId onChange={handleSpreadsheetSelect}
)?.name, fullWidth
id: >
selectedIntegrationType === "googleSheets" {spreadsheets.map((sheet) => (
? settings.spreadsheetId <MenuItem key={sheet.id} value={sheet.id}>
: settings.airtableBaseId, {sheet.name}
})} </MenuItem>
</Typography> ))}
</TextField>
<Button
variant="contained"
color="primary"
onClick={() => {
updateGoogleSheetId();
handleStart(settings);
}}
style={{ marginTop: "10px" }}
disabled={!settings.spreadsheetId || loading}
>
{t("integration_settings.buttons.submit")}
</Button>
</>
)}
</>
)} )}
</>
)}
</>
)}
{/* Airtable Integration */}
{settings.integrationType === "airtable" && (
<>
{recording?.airtable_base_id ? (
<>
<Alert severity="info" sx={{ marginTop: "10px", border: "1px solid #00c3ff" }}>
<AlertTitle>{t("integration_settings.alerts.airtable_success.title")}</AlertTitle>
{t("integration_settings.alerts.airtable_success.content", {
baseName: recording.airtable_base_name,
})}
<a
href={`https://airtable.com/${recording.airtable_base_id}`}
target="_blank"
rel="noreferrer"
>
{t("integration_settings.alerts.airtable_success.here")}
</a>
</Alert>
<Button <Button
variant="contained" variant="outlined"
color="primary" color="error"
onClick={() => { onClick={removeAirtableIntegration}
if (selectedIntegrationType === "googleSheets") { style={{ marginTop: "15px" }}
updateGoogleSheetId();
} else {
updateAirtableBaseId();
}
handleStart(settings);
}}
style={{ marginTop: "10px" }}
disabled={
!(selectedIntegrationType === "googleSheets"
? settings.spreadsheetId
: settings.airtableBaseId) || loading
}
> >
{t("integration_settings.buttons.submit")} {t("integration_settings.buttons.remove_integration")}
</Button> </Button>
</> </>
) : (
<>
{!recording?.airtable_access_token ? (
<>
<p>{t("integration_settings.descriptions.airtable_sync_info")}</p>
<Button
variant="contained"
color="secondary"
onClick={authenticateWithAirtable}
>
{t("integration_settings.buttons.authenticate_airtable")}
</Button>
</>
) : (
<>
<Typography sx={{ margin: "20px 0px 30px 0px" }}>
{t("integration_settings.descriptions.authenticated_as", {
email: "hghghg",
})}
</Typography>
{loading ? (
<CircularProgress sx={{ marginBottom: "15px" }} />
) : error ? (
<Typography color="error">{error}</Typography>
) : airtableBases.length === 0 ? (
<Button
variant="outlined"
color="secondary"
onClick={fetchAirtableBases}
>
{t("integration_settings.buttons.fetch_airtable_bases")}
</Button>
) : (
<>
<TextField
sx={{ marginBottom: "15px" }}
select
label={t("integration_settings.fields.select_airtable_base")}
required
value={settings.airtableBaseId}
onChange={handleAirtableBaseSelect}
fullWidth
>
{airtableBases.map((base) => (
<MenuItem key={base.id} value={base.id}>
{base.name}
</MenuItem>
))}
</TextField>
<Button
variant="contained"
color="secondary"
onClick={() => {
updateAirtableBase();
handleStart(settings);
}}
style={{ marginTop: "10px" }}
disabled={!settings.airtableBaseId || loading}
>
{t("integration_settings.buttons.submit_airtable")}
</Button>
</>
)}
</>
)}
</>
)} )}
</> </>
)} )}