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`);
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,
ModalOverlay,
} 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 {
onClose: () => void;
@@ -23,6 +37,14 @@ export default function SheetsModal(props: SheetsModalProps) {
const [file, setFile] = useState<File | null>(null);
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 handleClick = () => {
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 (
<Modal
@@ -71,31 +124,74 @@ export default function SheetsModal(props: SheetsModalProps) {
<ModalHeader>Sheets!</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Input
ref={fileInputRef}
style={{ display: 'none' }}
type='file'
onChange={handleFile}
accept='.json'
data-testid='file-input'
/>
<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>
<Button variant='ontime-filled' padding='0 2em' onClick={handlePullData}>
Pull data
</Button>
</div>
{rundown && (
<>
<PreviewExcel
rundown={rundown ?? []}
project={project ?? projectDataPlaceholder}
userFields={userFields ?? userFieldsPlaceholder}
/>
</>
)}
{!rundown && (
<>
<Input
ref={fileInputRef}
style={{ display: 'none' }}
type='file'
onChange={handleFile}
accept='.json'
data-testid='file-input'
/>
<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>
<ModalFooter>
<Button variant='ontime-ghost-on-light'>Reset</Button>
<Button variant='ontime-filled' padding='0 2em' onClick={handleAuthenticate}>
Authenticate
</Button>
{!rundown && (
<Button variant='ontime-filled' padding='0 2em' onClick={handleAuthenticate}>
Authenticate
</Button>
)}
{rundown && (
<Button variant='ontime-filled' padding='0 2em' onClick={handleFinalise}>
Import
</Button>
)}
</ModalFooter>
</ModalContent>
</Modal>
@@ -397,13 +397,8 @@ export async function previewExcel(req, res) {
* @returns parsed result
*/
export async function previewSheet(req, res) {
if (!req.body.sheetid) {
res.status(400).send({ message: 'missing sheet id' });
return;
}
try {
const options = JSON.parse(req.body.options);
const data = await Sheet.parse(req.body.sheetid, req.body.worksheet, options);
const data = await Sheet.parse(req.body.sheetid, req.body.worksheet);
res.status(200).send(data);
} catch (error) {
res.status(500).send({ message: error.toString() });
@@ -421,13 +416,15 @@ export async function sheetClientFile(req, res) {
}
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);
res.status(200).send('OK');
} catch (error) {
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();
},
];
//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,
validatePatchProjectFile,
validateSettings,
validateSheetPreview,
validateUserFields,
viewValidator,
} from '../controllers/ontimeController.validate.js';
@@ -101,7 +102,5 @@ router.get('/sheet-authstatus', sheetAuthState);
// create route between controller and '/ontime/sheet-authstatus' endpoint
router.get('/sheet-authurl', sheetAuthUrl);
router.get('/sheet-authurl', previewSheet);
// 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 { getAppDataPath } from '../setup.js';
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 { parseProject, parseRundown, parseUserFields } from './parserFunctions.js';
import { ensureDirectory } from './fileManagement.js';
@@ -45,7 +45,7 @@ class sheet {
* @returns {Promise<Partial<ResponseOK>>}
* @throws
*/
public async parse(sheetId: string, worksheet: string, options: ExcelImportOptions) {
public async parse(sheetId: string, worksheet: string, options = defaultExcelImportMap) {
if (!sheet.client) {
if (!(await this.authorized())) {
throw new Error(`Sheet not authorized`);