Preview Sheet

This commit is contained in:
arc-alex
2023-11-18 20:58:57 +01:00
parent 52a9c85dbc
commit 65efebe180
6 changed files with 150 additions and 37 deletions
+9
View File
@@ -256,3 +256,12 @@ export const getSheetsAuthUrl = async () => {
const res = await axios.get(`${ontimeURL}/sheet-authurl`); const res = await axios.get(`${ontimeURL}/sheet-authurl`);
return res.data; return res.data;
}; };
export const postPreviewSheet = async (sheetId: string, worksheet: string, options?: ExcelImportMap) => {
const response = await axios.post(`${ontimeURL}/sheet-preview`, {
sheetid: sheetId,
worksheet: worksheet,
options: options,
});
return response.data.data;
};
@@ -10,7 +10,21 @@ import {
ModalHeader, ModalHeader,
ModalOverlay, ModalOverlay,
} from '@chakra-ui/react'; } from '@chakra-ui/react';
import { getSheetsAuthStatus, getSheetsAuthUrl, uploadSheetClientFile } from '../../../common/api/ontimeApi'; import { useQueryClient } from '@tanstack/react-query';
import {
getSheetsAuthStatus,
getSheetsAuthUrl,
postPreviewSheet,
uploadSheetClientFile,
patchData,
} from '../../../common/api/ontimeApi';
import { OntimeRundown, ProjectData, UserFields } from 'ontime-types';
import PreviewExcel from '../upload-modal/preview/PreviewExcel';
import { projectDataPlaceholder } from '../../../common/models/ProjectData';
import { userFieldsPlaceholder } from '../../../common/models/UserFields';
import { PROJECT_DATA, RUNDOWN_TABLE, USERFIELDS } from '../../../common/api/apiConstants';
import { maybeAxiosError } from '../../../common/api/apiUtils';
interface SheetsModalProps { interface SheetsModalProps {
onClose: () => void; onClose: () => void;
@@ -23,6 +37,14 @@ export default function SheetsModal(props: SheetsModalProps) {
const [file, setFile] = useState<File | null>(null); const [file, setFile] = useState<File | null>(null);
const [authState, setAuthState] = useState<boolean>(true); const [authState, setAuthState] = useState<boolean>(true);
const [rundown, setRundown] = useState<OntimeRundown | null>(null);
const [userFields, setUserFields] = useState<UserFields | null>(null);
const [project, setProject] = useState<ProjectData | null>(null);
const queryClient = useQueryClient();
const sheetid = useRef<HTMLInputElement>(null);
const worksheet = useRef<HTMLInputElement>(null);
const handleClose = () => onClose(); const handleClose = () => onClose();
const handleClick = () => { const handleClick = () => {
fileInputRef.current?.click(); fileInputRef.current?.click();
@@ -53,7 +75,38 @@ export default function SheetsModal(props: SheetsModalProps) {
} }
}); });
}; };
const handlePullData = () => {}; const handlePullData = () => {
postPreviewSheet(sheetid.current?.value ?? '', worksheet.current?.value ?? '').then((data) => {
setProject(data.project);
setRundown(data.rundown);
setUserFields(data.userFields);
});
};
const handleFinalise = async () => {
// this step is currently only used for excel files, after preview
if (rundown && userFields && project) {
let doClose = false;
try {
await patchData({ rundown, userFields, project });
queryClient.setQueryData(RUNDOWN_TABLE, rundown);
queryClient.setQueryData(USERFIELDS, userFields);
queryClient.setQueryData(PROJECT_DATA, project);
await queryClient.invalidateQueries({
queryKey: [...RUNDOWN_TABLE, ...USERFIELDS, ...PROJECT_DATA],
});
doClose = true;
} catch (error) {
const message = maybeAxiosError(error);
console.log(message);
// setErrors(`Failed applying changes ${message}`);
} finally {
if (doClose) {
handleClose();
}
}
}
};
return ( return (
<Modal <Modal
@@ -71,31 +124,74 @@ export default function SheetsModal(props: SheetsModalProps) {
<ModalHeader>Sheets!</ModalHeader> <ModalHeader>Sheets!</ModalHeader>
<ModalCloseButton /> <ModalCloseButton />
<ModalBody> <ModalBody>
<Input {rundown && (
ref={fileInputRef} <>
style={{ display: 'none' }} <PreviewExcel
type='file' rundown={rundown ?? []}
onChange={handleFile} project={project ?? projectDataPlaceholder}
accept='.json' userFields={userFields ?? userFieldsPlaceholder}
data-testid='file-input' />
/> </>
<div>Need to add some help here</div> )}
<div> {!rundown && (
<Button onClick={handleClick}>Upload Client Secrect</Button> <>
</div> <Input
{authState && <div>You are authenticated</div>} ref={fileInputRef}
{!authState && <div>You are not authenticated</div>} style={{ display: 'none' }}
<div> type='file'
<Button variant='ontime-filled' padding='0 2em' onClick={handlePullData}> onChange={handleFile}
Pull data accept='.json'
</Button> data-testid='file-input'
</div> />
<div>Need to add some help here</div>
<div>
<Button onClick={handleClick}>Upload Client Secrect</Button>
</div>
{authState && <div>You are authenticated</div>}
{!authState && <div>You are not authenticated</div>}
<div>
<label htmlFor='sheetid'>Sheet ID </label>
<Input
type='text'
ref={sheetid}
id='sheetid'
width='440px'
size='sm'
textAlign='right'
variant='ontime-filled-on-light'
/>
<br />
<label htmlFor='worksheet'>Worksheet </label>
<Input
type='text'
ref={worksheet}
id='worksheet'
width='240px'
size='sm'
textAlign='right'
variant='ontime-filled-on-light'
/>
</div>
<div>
<Button variant='ontime-filled' padding='0 2em' onClick={handlePullData}>
Pull data
</Button>
</div>
</>
)}
</ModalBody> </ModalBody>
<ModalFooter> <ModalFooter>
<Button variant='ontime-ghost-on-light'>Reset</Button> <Button variant='ontime-ghost-on-light'>Reset</Button>
<Button variant='ontime-filled' padding='0 2em' onClick={handleAuthenticate}> {!rundown && (
Authenticate <Button variant='ontime-filled' padding='0 2em' onClick={handleAuthenticate}>
</Button> Authenticate
</Button>
)}
{rundown && (
<Button variant='ontime-filled' padding='0 2em' onClick={handleFinalise}>
Import
</Button>
)}
</ModalFooter> </ModalFooter>
</ModalContent> </ModalContent>
</Modal> </Modal>
@@ -397,13 +397,8 @@ export async function previewExcel(req, res) {
* @returns parsed result * @returns parsed result
*/ */
export async function previewSheet(req, res) { export async function previewSheet(req, res) {
if (!req.body.sheetid) {
res.status(400).send({ message: 'missing sheet id' });
return;
}
try { try {
const options = JSON.parse(req.body.options); const data = await Sheet.parse(req.body.sheetid, req.body.worksheet);
const data = await Sheet.parse(req.body.sheetid, req.body.worksheet, options);
res.status(200).send(data); res.status(200).send(data);
} catch (error) { } catch (error) {
res.status(500).send({ message: error.toString() }); res.status(500).send({ message: error.toString() });
@@ -421,13 +416,15 @@ export async function sheetClientFile(req, res) {
} }
try { try {
const client = JSON.parse( fs.readFileSync(req.file.path as string, 'utf-8')); const client = JSON.parse(fs.readFileSync(req.file.path as string, 'utf-8'));
await Sheet.saveClientSecrets(client); await Sheet.saveClientSecrets(client);
res.status(200).send('OK'); res.status(200).send('OK');
} catch (error) { } catch (error) {
res.status(500).send({ message: error.toString() }); res.status(500).send({ message: error.toString() });
} }
fs.unlink(req.file.path, (err) => {if(err) (logger.error(LogOrigin.Server, err.message))}); fs.unlink(req.file.path, (err) => {
if (err) logger.error(LogOrigin.Server, err.message);
});
} }
/** /**
@@ -133,3 +133,15 @@ export const validatePatchProjectFile = [
next(); next();
}, },
]; ];
//TODO: is thise correct
export const validateSheetPreview = [
body('sheetid').isString().optional({ nullable: false }),
body('worksheet').isString().optional({ nullable: false }),
body('options').isObject().optional({ nullable: true }),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
next();
},
];
+2 -3
View File
@@ -31,6 +31,7 @@ import {
validateOscSubscription, validateOscSubscription,
validatePatchProjectFile, validatePatchProjectFile,
validateSettings, validateSettings,
validateSheetPreview,
validateUserFields, validateUserFields,
viewValidator, viewValidator,
} from '../controllers/ontimeController.validate.js'; } from '../controllers/ontimeController.validate.js';
@@ -101,7 +102,5 @@ router.get('/sheet-authstatus', sheetAuthState);
// create route between controller and '/ontime/sheet-authstatus' endpoint // create route between controller and '/ontime/sheet-authstatus' endpoint
router.get('/sheet-authurl', sheetAuthUrl); router.get('/sheet-authurl', sheetAuthUrl);
router.get('/sheet-authurl', previewSheet);
// create route between controller and '/ontime/preview-sheet' endpoint // create route between controller and '/ontime/preview-sheet' endpoint
router.get('/sheet-preview', previewSheet); router.post('/sheet-preview', validateSheetPreview, previewSheet);
+2 -2
View File
@@ -6,7 +6,7 @@ import { URL } from 'url';
import { logger } from '../classes/Logger.js'; import { logger } from '../classes/Logger.js';
import { getAppDataPath } from '../setup.js'; import { getAppDataPath } from '../setup.js';
import { DatabaseModel, LogOrigin } from 'ontime-types'; import { DatabaseModel, LogOrigin } from 'ontime-types';
import { ExcelImportOptions, isExcelImportMap } from 'ontime-utils'; import { ExcelImportOptions, isExcelImportMap, defaultExcelImportMap } from 'ontime-utils';
import { parseExcel } from './parser.js'; import { parseExcel } from './parser.js';
import { parseProject, parseRundown, parseUserFields } from './parserFunctions.js'; import { parseProject, parseRundown, parseUserFields } from './parserFunctions.js';
import { ensureDirectory } from './fileManagement.js'; import { ensureDirectory } from './fileManagement.js';
@@ -45,7 +45,7 @@ class sheet {
* @returns {Promise<Partial<ResponseOK>>} * @returns {Promise<Partial<ResponseOK>>}
* @throws * @throws
*/ */
public async parse(sheetId: string, worksheet: string, options: ExcelImportOptions) { public async parse(sheetId: string, worksheet: string, options = defaultExcelImportMap) {
if (!sheet.client) { if (!sheet.client) {
if (!(await this.authorized())) { if (!(await this.authorized())) {
throw new Error(`Sheet not authorized`); throw new Error(`Sheet not authorized`);