import backgroundImage from "@Assets/images/background_refonte.svg"; import CoffreIcon from "@Assets/logo_small_blue.svg"; import Auth from "@Front/Api/Auth/IdNot"; import Loader from "@Front/Components/DesignSystem/Loader"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import HelpBox from "@Front/Components/Elements/HelpBox"; import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage"; import Module from "@Front/Config/Module"; import UserStore from "@Front/Stores/UserStore"; import Image from "next/image"; import { useRouter } from "next/router"; import React, { useEffect, useState } from "react"; import classes from "./classes.module.scss"; // Importer les composants de UI pour les barres de progression import { LinearProgress, Box, Typography as MuiTypography } from "@mui/material"; import AuthModal from "src/sdk/AuthModal"; import MessageBus from "src/sdk/MessageBus"; import Iframe from "src/sdk/Iframe"; import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService"; import ImportData, { ProgressInfo } from "src/common/Api/LeCoffreApi/sdk/ImportData"; import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService"; import OfficeService from "src/common/Api/LeCoffreApi/sdk/OfficeService"; import OfficeRoleService from "src/common/Api/LeCoffreApi/sdk/OfficeRoleService"; import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService"; import { DEFAULT_STORAGE_URLS, DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants"; export default function LoginCallBack() { const router = useRouter(); const [idNotUser, setIdNotUser] = useState(null); const [isAuthModalOpen, setIsAuthModalOpen] = useState(false); const [isConnected, setIsConnected] = useState(false); // États pour les barres de progression const [showProgress, setShowProgress] = useState(false); const [progressInfo, setProgressInfo] = useState({ globalProgress: 0, currentStep: '', stepProgress: 0, description: '' }); const getOffice = async (idNotUser: any) => { return await new Promise((resolve: (office: any) => void) => { OfficeService.getOffices().then((processes: any[]) => { const officeFound: any = processes.length > 0 ? processes.find((office: any) => office.processData.idNot === idNotUser.office.idNot) : null; if (officeFound) { resolve(officeFound); } else { // Some info must be here or have some value, just to be sure if (!idNotUser.office.office_status || idNotUser.office.office_status !== 'ACTIVATED') { console.error(`[LoginCallback] office_status is not ACTIVATED for idNot ${idNotUser.office.idNot}`); return; } // I guess if we don't have crpcen that's also a big problem if (!idNotUser.office.crpcen) { console.error(`[LoginCallback] crpcen is not set for idNot ${idNotUser.office.idNot}`); return; } // We create office const officeData: any = { idNot: idNotUser.office.idNot, name: idNotUser.office.name, crpcen: idNotUser.office.crpcen, address: { create: { address: idNotUser.office.address.address, zip_code: idNotUser.office.address.zip_code, city: idNotUser.office.address.city } }, office_status: idNotUser.office.office_status // must be ACTIVATED though }; Auth.getInstance().getIdNotUserForOffice(idNotUser.office.idNot).then((users: any) => { console.log('users : ', users); const activeUsers = users.result.filter((user: any) => user.activite === 'En exercice'); let officeCollaborators: any[] = []; for (const user of activeUsers) { CollaboratorService.getCollaboratorByUid(user.uid).then((collaborator: any) => { console.log('collaborator : ', collaborator); officeCollaborators.push(collaborator); }); } OfficeService.createOffice(officeData, officeCollaborators, DEFAULT_VALIDATOR_ID, [...DEFAULT_STORAGE_URLS]).then((process: any) => { if (process) { const office: any = process.processData; resolve(office); } }); }); } return; }); }); }; const getCollaborator = async (idNotUser: any) => { return await new Promise(async (resolve: (role: any) => void) => { const processFound: any | null = await CollaboratorService.getCollaboratorBy({ idNot: idNotUser.idNot }); if (processFound) { console.log('Found a collaborator for idNot', idNotUser.idNot); // TODO: check if the collaborator is in the office process const office: any = await getOffice(idNotUser); // Take the role of the collaborator MessageBus.getInstance().getRolesForProcess(processFound.processId).then((roles: any) => { console.log('roles : ', roles); // We should find one pairing id in the role 'owner' const owners = roles['owner'].members; if (owners.length !== 1) { console.error('[LoginCallback] owner should have 1 member'); return; } const ownerPairingId = owners[0]; // Now we can check if the owner pairing id is in the office roles MessageBus.getInstance().getRolesForProcess(office.processId).then((officeRoles: any) => { const officeOwners = officeRoles['owner'].members; if (!officeOwners.includes(ownerPairingId)) { // We add the newly created collaborator to the office roles OfficeService.addCollaborators(office, officeRoles, [ownerPairingId]).then((process: any) => { resolve(processFound); }); } else { // Nothing to do resolve(processFound); } }); }); } else { console.log('No collaborator found for idNot', idNotUser.idNot); const office: any = await getOffice(idNotUser); const role: any = (await RoleService.getRoles()) .map((process: any) => process.processData) .find((role: any) => role.name === idNotUser.role.name); const officeRole: any = (await OfficeRoleService.getOfficeRoles()) .map((process: any) => process.processData) .filter((officeRole: any) => officeRole.office.uid === office.processData.uid) .find((officeRole: any) => officeRole.name === idNotUser.office_role.name); if (!office || !role || !officeRole) { LoaderService.getInstance().hide(); setShowProgress(true); await ImportData.import(office, DEFAULT_VALIDATOR_ID, (info: ProgressInfo) => { setProgressInfo(info); }); setShowProgress(false); LoaderService.getInstance().show(); } const collaboratorData: any = { idNot: idNotUser.idNot, contact: idNotUser.contact, office: { uid: office.uid }, role: { uid: role.uid }, office_role: { uid: officeRole.uid } }; CollaboratorService.createCollaborator(collaboratorData, DEFAULT_VALIDATOR_ID).then((newCollaborator: any) => { if (newCollaborator) { // Now that we created the collaborator, we must check that it's in the office roles (probably not) MessageBus.getInstance().getRolesForProcess(newCollaborator.processId).then((roles: any) => { console.log('roles : ', roles); // We should have our own pairing id in roles['owner'] const owner = roles['owner'].members; if (owner.length !== 1) { console.error('[LoginCallback] owner should have 1 member'); return; } const ownerPairingId = owner[0]; if (ownerPairingId !== newCollaborator.processData.uid) { console.error('[LoginCallback] owner pairing id is not the same as the collaborator uid'); return; } // is ownerPairingId in roles for the office process? MessageBus.getInstance().getRolesForProcess(office.processId).then((officeRoles: any) => { const officeOwners = officeRoles['owner'].members; if (!officeOwners.includes(ownerPairingId)) { // We add the newly created collaborator to the office roles OfficeService.addCollaborators(office, officeRoles, [ownerPairingId]).then((process: any) => { resolve(newCollaborator); }); } else { // Nothing to do resolve(newCollaborator); } }); }); } }); } }); }; useEffect(() => { async function getUser() { UserStore.instance.disconnect(); // TODO: review // HACK: If start with http://local.lecoffreio.4nkweb:3000/authorized-client // Replace with http://localhost:3000/authorized-client if (window.location.href.startsWith('http://local.lecoffreio.4nkweb:3000/authorized-client')) { window.location.href = window.location.href.replace('http://local.lecoffreio.4nkweb:3000/authorized-client', 'http://localhost:3000/authorized-client'); return; } const code = router.query["code"]; if (code) { try { // Nettoyer l'URL pour ne garder que la racine const rootUrl = window.location.origin; if (window.location.href !== rootUrl) { window.history.replaceState({}, document.title, rootUrl); } const user: any = await Auth.getInstance().getIdNotUser(code as string); setIdNotUser(user.idNotUser); setIsAuthModalOpen(true); console.log('[LoginCallback] idNotUser', idNotUser); /* const token: any = null; if (!token) return router.push(Module.getInstance().get().modules.pages.Login.props.path); await UserStore.instance.connect(token.accessToken, token.refreshToken); const jwt = JwtService.getInstance().decodeJwt(); if (!jwt) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1"); if (jwt.rules && !jwt.rules.includes("GET folders")) { return router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path); } setIsAuthModalOpen(true); //return router.push(Module.getInstance().get().modules.pages.Folder.props.path); */ return; } catch (e: any) { if (e.http_status === 401 && e.message === "Email not found") { return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=3"); } if (e.http_status === 409) { return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=4"); } return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1"); } } /* const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken"); if (!refreshToken) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1"); const isTokenRefreshed = await JwtService.getInstance().refreshToken(refreshToken); const jwt = JwtService.getInstance().decodeJwt(); if (!jwt) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1"); if (!jwt.rules.includes("GET folders")) { return router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path); } if (isTokenRefreshed) { //setIsAuthModalOpen(true); //return router.push(Module.getInstance().get().modules.pages.Folder.props.path); return; } */ return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=2"); } getUser(); }, [router]); return (
coffre Connexion à votre espace professionnel
{!showProgress ? ( ) : ( Importation des données {/* Progression globale */} Progression globale: {Math.round(progressInfo.globalProgress)}% {progressInfo.currentStep} {/* Progression par étape */} Progression de l'étape: {Math.round(progressInfo.stepProgress)}% {progressInfo.description || ''} )}
{isAuthModalOpen && { setIsAuthModalOpen(false); setIsConnected(true); setTimeout(() => { LoaderService.getInstance().show(); MessageBus.getInstance().initMessageListener(); MessageBus.getInstance().isReady().then(async () => { const collaborator: any = await getCollaborator(idNotUser); if (!UserStore.instance.connect(collaborator)) { console.error('[LoginCallback] collaborator not connected'); router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1"); return; } MessageBus.getInstance().destroyMessageListener(); LoaderService.getInstance().hide(); /* if (jwt.rules && !jwt.rules.includes("GET folders")) { router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path); } */ window.location.href = Module.getInstance().get().modules.pages.Folder.props.path; }); }, 100); }} />} {isConnected &&