mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-22 07:29:08 +00:00
refactor: improve sheet flow management
This commit is contained in:
committed by
Carlos Valente
parent
f53cb687bf
commit
f739ba122b
@@ -11,6 +11,7 @@ export const CUSTOM_VIEWS = ['customViews'];
|
|||||||
export const PROJECT_DATA = ['project'];
|
export const PROJECT_DATA = ['project'];
|
||||||
export const PROJECT_LIST = ['projectList'];
|
export const PROJECT_LIST = ['projectList'];
|
||||||
export const PROJECT_RUNDOWNS = ['projectRundowns'];
|
export const PROJECT_RUNDOWNS = ['projectRundowns'];
|
||||||
|
export const RUNDOWN = ['rundown'];
|
||||||
export const CURRENT_RUNDOWN_QUERY_KEY = ['rundown', 'current'];
|
export const CURRENT_RUNDOWN_QUERY_KEY = ['rundown', 'current'];
|
||||||
export const getRundownQueryKey = (rundownId: string) => ['rundown', rundownId];
|
export const getRundownQueryKey = (rundownId: string) => ['rundown', rundownId];
|
||||||
export const RUNTIME = ['runtimeStore'];
|
export const RUNTIME = ['runtimeStore'];
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export interface AutocompleteInputProps extends Omit<InputProps, 'value' | 'defa
|
|||||||
emptyLabel?: string;
|
emptyLabel?: string;
|
||||||
trailingElement?: (option: string) => ReactNode;
|
trailingElement?: (option: string) => ReactNode;
|
||||||
inputRef?: Ref<HTMLInputElement>;
|
inputRef?: Ref<HTMLInputElement>;
|
||||||
|
openOnFocus?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function AutocompleteInput({
|
export default function AutocompleteInput({
|
||||||
@@ -27,6 +28,7 @@ export default function AutocompleteInput({
|
|||||||
inputRef,
|
inputRef,
|
||||||
onValueChange,
|
onValueChange,
|
||||||
options,
|
options,
|
||||||
|
openOnFocus = false,
|
||||||
trailingElement,
|
trailingElement,
|
||||||
value,
|
value,
|
||||||
variant = 'subtle',
|
variant = 'subtle',
|
||||||
@@ -34,6 +36,7 @@ export default function AutocompleteInput({
|
|||||||
}: AutocompleteInputProps) {
|
}: AutocompleteInputProps) {
|
||||||
const internalInputRef = useRef<HTMLInputElement | null>(null);
|
const internalInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
const { onFocus, ...restInputProps } = inputProps;
|
||||||
|
|
||||||
const handleInputRef = (node: HTMLInputElement | null) => {
|
const handleInputRef = (node: HTMLInputElement | null) => {
|
||||||
internalInputRef.current = node;
|
internalInputRef.current = node;
|
||||||
@@ -81,6 +84,12 @@ export default function AutocompleteInput({
|
|||||||
>
|
>
|
||||||
<BaseAutocomplete.Input
|
<BaseAutocomplete.Input
|
||||||
ref={handleInputRef}
|
ref={handleInputRef}
|
||||||
|
onFocus={(event) => {
|
||||||
|
onFocus?.(event);
|
||||||
|
if (openOnFocus) {
|
||||||
|
setOpen(true);
|
||||||
|
}
|
||||||
|
}}
|
||||||
className={cx([
|
className={cx([
|
||||||
inputStyles.input,
|
inputStyles.input,
|
||||||
inputStyles[variant],
|
inputStyles[variant],
|
||||||
@@ -88,7 +97,7 @@ export default function AutocompleteInput({
|
|||||||
fluid && inputStyles.fluid,
|
fluid && inputStyles.fluid,
|
||||||
className,
|
className,
|
||||||
])}
|
])}
|
||||||
{...inputProps}
|
{...restInputProps}
|
||||||
/>
|
/>
|
||||||
<BaseAutocomplete.Portal>
|
<BaseAutocomplete.Portal>
|
||||||
<BaseAutocomplete.Positioner side='bottom' align='start' className={styles.positioner}>
|
<BaseAutocomplete.Positioner side='bottom' align='start' className={styles.positioner}>
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
import Info from '../../../../../common/components/info/Info';
|
|
||||||
import ExternalLink from '../../../../../common/components/link/external-link/ExternalLink';
|
|
||||||
|
|
||||||
const googleSheetDocsUrl = 'https://docs.getontime.no/features/import-spreadsheet-gsheet/';
|
|
||||||
|
|
||||||
export default function GSheetInfo() {
|
|
||||||
return (
|
|
||||||
<Info>
|
|
||||||
Ontime can import data from spreadsheets by: <br />- importing the spreadsheet file in Ontime <br />-
|
|
||||||
synchronising your project with a Google Sheet
|
|
||||||
<br />
|
|
||||||
<br />
|
|
||||||
To synchronise with a Google Sheet, you will need to allow Ontime to authenticate with your Google account.
|
|
||||||
<ExternalLink href={googleSheetDocsUrl}>See the docs</ExternalLink>
|
|
||||||
</Info>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+216
-84
@@ -1,59 +1,138 @@
|
|||||||
import type { SpreadsheetWorksheetOptions } from 'ontime-types';
|
import type { AuthenticationStatus, SpreadsheetWorksheetOptions } from 'ontime-types';
|
||||||
import { ChangeEvent, useEffect, useState } from 'react';
|
import { ChangeEvent, useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { IoCheckmark, IoShieldCheckmarkOutline } from 'react-icons/io5';
|
import { IoCheckmark, IoCloudDownloadOutline, IoShieldCheckmarkOutline } from 'react-icons/io5';
|
||||||
|
|
||||||
import { getWorksheetOptions } from '../../../../../common/api/sheets';
|
import {
|
||||||
|
getWorksheetOptions,
|
||||||
|
requestConnection,
|
||||||
|
revokeAuthentication,
|
||||||
|
verifyAuthenticationStatus,
|
||||||
|
} from '../../../../../common/api/sheets';
|
||||||
import { maybeAxiosError } from '../../../../../common/api/utils';
|
import { maybeAxiosError } from '../../../../../common/api/utils';
|
||||||
import Button from '../../../../../common/components/buttons/Button';
|
import Button from '../../../../../common/components/buttons/Button';
|
||||||
import CopyTag from '../../../../../common/components/copy-tag/CopyTag';
|
import CopyTag from '../../../../../common/components/copy-tag/CopyTag';
|
||||||
import Input from '../../../../../common/components/input/input/Input';
|
import Input from '../../../../../common/components/input/input/Input';
|
||||||
|
import Tag from '../../../../../common/components/tag/Tag';
|
||||||
import { openLink } from '../../../../../common/utils/linkUtils';
|
import { openLink } from '../../../../../common/utils/linkUtils';
|
||||||
import * as Panel from '../../../panel-utils/PanelUtils';
|
import * as Panel from '../../../panel-utils/PanelUtils';
|
||||||
import useGoogleSheet from './useGoogleSheet';
|
|
||||||
import { useSheetStore } from './useSheetStore';
|
import style from './SourcesPanel.module.scss';
|
||||||
|
|
||||||
interface GSheetSetupProps {
|
interface GSheetSetupProps {
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
onWorksheetOptionsLoaded?: (options: SpreadsheetWorksheetOptions) => void;
|
onSheetLoaded: (sheetId: string, options: SpreadsheetWorksheetOptions) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function GSheetSetup(props: GSheetSetupProps) {
|
export default function GSheetSetup(props: GSheetSetupProps) {
|
||||||
const { onCancel, onWorksheetOptionsLoaded } = props;
|
const { onCancel, onSheetLoaded } = props;
|
||||||
|
|
||||||
const { revoke, connect, verifyAuth } = useGoogleSheet();
|
|
||||||
const [file, setFile] = useState<File | null>(null);
|
const [file, setFile] = useState<File | null>(null);
|
||||||
|
const [sheetId, setSheetId] = useState('');
|
||||||
|
const [authenticationStatus, setAuthenticationStatus] = useState<AuthenticationStatus>('not_authenticated');
|
||||||
const [authKey, setAuthKey] = useState<string | null>(null);
|
const [authKey, setAuthKey] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState<'' | 'cancel' | 'connect' | 'authenticate'>('');
|
const [loading, setLoading] = useState<'' | 'cancel' | 'connect' | 'authenticate' | 'load-sheet'>('');
|
||||||
const [authLink, setAuthLink] = useState('');
|
const [authLink, setAuthLink] = useState('');
|
||||||
|
const [authError, setAuthError] = useState('');
|
||||||
|
const [worksheetError, setWorksheetError] = useState('');
|
||||||
|
const pollTimeoutRef = useRef<number | null>(null);
|
||||||
|
const authFallbackTimeoutRef = useRef<number | null>(null);
|
||||||
|
const focusListenerRef = useRef<(() => void) | null>(null);
|
||||||
|
|
||||||
const sheetId = useSheetStore((state) => state.sheetId);
|
const clearPollTimeout = useCallback(() => {
|
||||||
const setSheetId = useSheetStore((state) => state.setSheetId);
|
if (pollTimeoutRef.current !== null) {
|
||||||
const setWorksheets = useSheetStore((state) => state.setWorksheets);
|
window.clearTimeout(pollTimeoutRef.current);
|
||||||
const patchStepData = useSheetStore((state) => state.patchStepData);
|
pollTimeoutRef.current = null;
|
||||||
const authenticationStatus = useSheetStore((state) => state.authenticationStatus);
|
|
||||||
const setAuthenticationStatus = useSheetStore((state) => state.setAuthenticationStatus);
|
|
||||||
const authenticationError = useSheetStore((state) => state.stepData.authenticate.error);
|
|
||||||
|
|
||||||
/** Check if we are authenticated */
|
|
||||||
const getAuthStatus = async () => {
|
|
||||||
const result = await verifyAuth();
|
|
||||||
if (result) {
|
|
||||||
setAuthenticationStatus(result.authenticated);
|
|
||||||
}
|
}
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
|
const clearAuthFallbackTimeout = useCallback(() => {
|
||||||
|
if (authFallbackTimeoutRef.current !== null) {
|
||||||
|
window.clearTimeout(authFallbackTimeoutRef.current);
|
||||||
|
authFallbackTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const clearFocusListener = useCallback(() => {
|
||||||
|
if (focusListenerRef.current !== null) {
|
||||||
|
window.removeEventListener('focus', focusListenerRef.current);
|
||||||
|
focusListenerRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const loadWorksheetOptions = useCallback(
|
||||||
|
async (nextSheetId: string) => {
|
||||||
|
const worksheetOptions = await getWorksheetOptions(nextSheetId);
|
||||||
|
onSheetLoaded(nextSheetId, worksheetOptions);
|
||||||
|
setWorksheetError('');
|
||||||
|
},
|
||||||
|
[onSheetLoaded],
|
||||||
|
);
|
||||||
|
|
||||||
|
const pollUntilAuthenticated = useCallback(
|
||||||
|
async (attempts: number = 0) => {
|
||||||
|
clearPollTimeout();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await verifyAuthenticationStatus();
|
||||||
|
setAuthenticationStatus(result.authenticated);
|
||||||
|
setSheetId(result.sheetId);
|
||||||
|
|
||||||
|
if (result.authenticated === 'pending') {
|
||||||
|
if (attempts < 10) {
|
||||||
|
pollTimeoutRef.current = window.setTimeout(() => {
|
||||||
|
pollUntilAuthenticated(attempts + 1);
|
||||||
|
}, 2000);
|
||||||
|
} else {
|
||||||
|
setLoading('');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.authenticated === 'authenticated') {
|
||||||
|
try {
|
||||||
|
await loadWorksheetOptions(result.sheetId);
|
||||||
|
} catch (error) {
|
||||||
|
setWorksheetError(maybeAxiosError(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading('');
|
||||||
|
} catch (error) {
|
||||||
|
setAuthError(maybeAxiosError(error));
|
||||||
|
setLoading('');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[clearPollTimeout, loadWorksheetOptions],
|
||||||
|
);
|
||||||
|
|
||||||
/** check if the current session has been authenticated */
|
/** check if the current session has been authenticated */
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
patchStepData({ authenticate: { available: false, error: '' } });
|
setAuthError('');
|
||||||
untilAuthenticated();
|
pollUntilAuthenticated();
|
||||||
}, []);
|
|
||||||
|
return () => {
|
||||||
|
clearFocusListener();
|
||||||
|
clearPollTimeout();
|
||||||
|
clearAuthFallbackTimeout();
|
||||||
|
};
|
||||||
|
}, [clearAuthFallbackTimeout, clearFocusListener, clearPollTimeout, pollUntilAuthenticated]);
|
||||||
|
|
||||||
// user cancels the flow
|
// user cancels the flow
|
||||||
const handleRevoke = async () => {
|
const handleRevoke = async () => {
|
||||||
setLoading('cancel');
|
setLoading('cancel');
|
||||||
await revoke();
|
try {
|
||||||
await getAuthStatus();
|
const result = await revokeAuthentication();
|
||||||
setLoading('');
|
setAuthenticationStatus(result.authenticated);
|
||||||
|
setSheetId('');
|
||||||
|
setAuthKey(null);
|
||||||
|
setAuthLink('');
|
||||||
|
setAuthError('');
|
||||||
|
setWorksheetError('');
|
||||||
|
} catch (error) {
|
||||||
|
setAuthError(maybeAxiosError(error));
|
||||||
|
} finally {
|
||||||
|
setLoading('');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCancelFlow = () => {
|
const handleCancelFlow = () => {
|
||||||
@@ -76,68 +155,81 @@ export default function GSheetSetup(props: GSheetSetupProps) {
|
|||||||
const handleConnect = async () => {
|
const handleConnect = async () => {
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
if (!sheetId) return;
|
if (!sheetId) return;
|
||||||
patchStepData({ worksheet: { available: false, error: '' } });
|
|
||||||
|
|
||||||
setLoading('connect');
|
setLoading('connect');
|
||||||
const result = await connect(file, sheetId);
|
setAuthError('');
|
||||||
if (result) {
|
setWorksheetError('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await requestConnection(file, sheetId);
|
||||||
setAuthLink(result.verification_url);
|
setAuthLink(result.verification_url);
|
||||||
setAuthKey(result.user_code);
|
setAuthKey(result.user_code);
|
||||||
|
} catch (error) {
|
||||||
|
setAuthError(maybeAxiosError(error));
|
||||||
|
} finally {
|
||||||
|
setLoading('');
|
||||||
}
|
}
|
||||||
setLoading('');
|
|
||||||
};
|
|
||||||
|
|
||||||
const untilAuthenticated = async (attempts: number = 0) => {
|
|
||||||
const result = await verifyAuth();
|
|
||||||
if (result?.authenticated) {
|
|
||||||
setAuthenticationStatus(result.authenticated);
|
|
||||||
if (result.authenticated !== 'pending') {
|
|
||||||
if (result.authenticated == 'authenticated') {
|
|
||||||
try {
|
|
||||||
const worksheetOptions = await getWorksheetOptions(result.sheetId);
|
|
||||||
setWorksheets(worksheetOptions.worksheets);
|
|
||||||
onWorksheetOptionsLoaded?.(worksheetOptions);
|
|
||||||
} catch (error) {
|
|
||||||
const message = maybeAxiosError(error);
|
|
||||||
patchStepData({ worksheet: { available: false, error: message } });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setLoading('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (attempts <= 10) {
|
|
||||||
setTimeout(() => untilAuthenticated(attempts + 1), 2000);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setLoading('');
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Open google auth
|
* Open google auth
|
||||||
*/
|
*/
|
||||||
const handleAuthenticate = async () => {
|
const handleAuthenticate = () => {
|
||||||
setLoading('authenticate');
|
setLoading('authenticate');
|
||||||
|
setAuthError('');
|
||||||
|
clearFocusListener();
|
||||||
|
clearPollTimeout();
|
||||||
|
clearAuthFallbackTimeout();
|
||||||
|
|
||||||
// open link and schedule a check for when the user focuses again
|
// open link and schedule a check for when the user focuses again
|
||||||
openLink(authLink);
|
openLink(authLink);
|
||||||
window.addEventListener(
|
authFallbackTimeoutRef.current = window.setTimeout(() => {
|
||||||
'focus',
|
if (document.hasFocus()) {
|
||||||
async () => {
|
setLoading('');
|
||||||
untilAuthenticated();
|
}
|
||||||
},
|
}, 1500);
|
||||||
{ once: true },
|
|
||||||
);
|
function authFocusHandler() {
|
||||||
|
clearAuthFallbackTimeout();
|
||||||
|
clearFocusListener();
|
||||||
|
pollUntilAuthenticated();
|
||||||
|
}
|
||||||
|
|
||||||
|
focusListenerRef.current = authFocusHandler;
|
||||||
|
window.addEventListener('focus', authFocusHandler, { once: true });
|
||||||
};
|
};
|
||||||
|
|
||||||
const canConnect = file && sheetId;
|
const handleLoadSheet = async () => {
|
||||||
|
if (!sheetId) return;
|
||||||
|
|
||||||
|
setLoading('load-sheet');
|
||||||
|
setWorksheetError('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await loadWorksheetOptions(sheetId);
|
||||||
|
} catch (error) {
|
||||||
|
setWorksheetError(maybeAxiosError(error));
|
||||||
|
} finally {
|
||||||
|
setLoading('');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const canConnect = Boolean(file) && Boolean(sheetId);
|
||||||
|
const canLoadSheet = Boolean(sheetId);
|
||||||
const canAuthenticate = Boolean(authKey) && Boolean(authLink);
|
const canAuthenticate = Boolean(authKey) && Boolean(authLink);
|
||||||
const isLoading = Boolean(loading);
|
const isLoading = Boolean(loading);
|
||||||
const isAuthenticated = authenticationStatus === 'authenticated';
|
const isAuthenticated = authenticationStatus === 'authenticated';
|
||||||
const isAuthenticating = authenticationStatus === 'pending';
|
const isAuthenticating = authenticationStatus === 'pending';
|
||||||
|
const statusLabel = isAuthenticated ? 'Connected' : isAuthenticating ? 'Waiting for confirmation' : 'Not connected';
|
||||||
|
const statusClass = isAuthenticated ? style.statusReady : isAuthenticating ? style.statusPending : style.statusIdle;
|
||||||
|
const statusVariant = isAuthenticated ? 'default' : 'warning';
|
||||||
|
const setupMessage = isAuthenticated
|
||||||
|
? 'Load a spreadsheet by its Google Sheet ID.'
|
||||||
|
: canAuthenticate
|
||||||
|
? 'Finish the device verification in your browser, then return here.'
|
||||||
|
: 'Upload your client secret and enter the sheet ID you want to access.';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Panel.Section>
|
<Panel.Section className={style.setupShell}>
|
||||||
<Panel.Title>
|
<Panel.Title>
|
||||||
Sync with Google Sheet (experimental)
|
Sync with Google Sheet (experimental)
|
||||||
{isAuthenticated ? (
|
{isAuthenticated ? (
|
||||||
@@ -148,24 +240,62 @@ export default function GSheetSetup(props: GSheetSetupProps) {
|
|||||||
<Button onClick={handleCancelFlow}>Go Back</Button>
|
<Button onClick={handleCancelFlow}>Go Back</Button>
|
||||||
)}
|
)}
|
||||||
</Panel.Title>
|
</Panel.Title>
|
||||||
<Panel.ListGroup>
|
<div className={style.setupIntro}>
|
||||||
<Panel.Description>Upload Client Secret provided by Google</Panel.Description>
|
<div className={style.setupIntroText}>
|
||||||
<Panel.Error>{authenticationError}</Panel.Error>
|
<p className={style.setupLead}>{statusLabel}</p>
|
||||||
<Input fluid type='file' onChange={handleClientSecret} accept='.json' disabled={isLoading || canAuthenticate} />
|
<p className={style.setupBody}>{setupMessage}</p>
|
||||||
</Panel.ListGroup>
|
</div>
|
||||||
<Panel.ListGroup>
|
<Tag className={statusClass} variant={statusVariant}>
|
||||||
|
{statusLabel}
|
||||||
|
</Tag>
|
||||||
|
</div>
|
||||||
|
{!isAuthenticated && (
|
||||||
|
<Panel.ListGroup className={style.setupBlock}>
|
||||||
|
<Panel.Description>Upload Client Secret provided by Google</Panel.Description>
|
||||||
|
<Panel.Error>{authError}</Panel.Error>
|
||||||
|
<Input
|
||||||
|
fluid
|
||||||
|
type='file'
|
||||||
|
onChange={handleClientSecret}
|
||||||
|
accept='.json'
|
||||||
|
disabled={isLoading || canAuthenticate}
|
||||||
|
/>
|
||||||
|
<div className={style.setupHint}>Use the OAuth client JSON downloaded from your Google Cloud project.</div>
|
||||||
|
</Panel.ListGroup>
|
||||||
|
)}
|
||||||
|
{isAuthenticated && authError && (
|
||||||
|
<Panel.ListGroup className={style.setupBlock}>
|
||||||
|
<Panel.Error>{authError}</Panel.Error>
|
||||||
|
</Panel.ListGroup>
|
||||||
|
)}
|
||||||
|
<Panel.ListGroup className={style.setupBlock}>
|
||||||
<Panel.Description>Enter ID of sheet to synchronise</Panel.Description>
|
<Panel.Description>Enter ID of sheet to synchronise</Panel.Description>
|
||||||
<Panel.Error>{undefined}</Panel.Error>
|
<Panel.Error>{worksheetError}</Panel.Error>
|
||||||
<Input
|
<Input
|
||||||
fluid
|
fluid
|
||||||
|
value={sheetId}
|
||||||
placeholder='Sheet ID'
|
placeholder='Sheet ID'
|
||||||
onChange={(event) => setSheetId(event.target.value)}
|
onChange={(event) => {
|
||||||
|
setWorksheetError('');
|
||||||
|
setSheetId(event.target.value);
|
||||||
|
}}
|
||||||
disabled={isLoading || canAuthenticate}
|
disabled={isLoading || canAuthenticate}
|
||||||
/>
|
/>
|
||||||
</Panel.ListGroup>
|
</Panel.ListGroup>
|
||||||
{!canAuthenticate ? (
|
{isAuthenticated ? (
|
||||||
<Panel.ListGroup>
|
<Panel.ListGroup className={style.setupBlock}>
|
||||||
<Panel.InlineElements>
|
<Panel.Description>Load the current spreadsheet configuration</Panel.Description>
|
||||||
|
<Panel.InlineElements wrap='wrap' className={style.setupActions}>
|
||||||
|
<Button onClick={handleLoadSheet} disabled={!canLoadSheet || isLoading} loading={loading === 'load-sheet'}>
|
||||||
|
<IoCloudDownloadOutline />
|
||||||
|
Load sheet
|
||||||
|
</Button>
|
||||||
|
</Panel.InlineElements>
|
||||||
|
</Panel.ListGroup>
|
||||||
|
) : !canAuthenticate ? (
|
||||||
|
<Panel.ListGroup className={style.setupBlock}>
|
||||||
|
<Panel.Description>Generate a Google device code</Panel.Description>
|
||||||
|
<Panel.InlineElements wrap='wrap' className={style.setupActions}>
|
||||||
<Button onClick={handleConnect} disabled={!canConnect || isLoading} loading={loading === 'connect'}>
|
<Button onClick={handleConnect} disabled={!canConnect || isLoading} loading={loading === 'connect'}>
|
||||||
<IoCheckmark />
|
<IoCheckmark />
|
||||||
Connect
|
Connect
|
||||||
@@ -173,8 +303,9 @@ export default function GSheetSetup(props: GSheetSetupProps) {
|
|||||||
</Panel.InlineElements>
|
</Panel.InlineElements>
|
||||||
</Panel.ListGroup>
|
</Panel.ListGroup>
|
||||||
) : (
|
) : (
|
||||||
<Panel.ListGroup>
|
<Panel.ListGroup className={style.setupBlock}>
|
||||||
<Panel.InlineElements>
|
<Panel.Description>Authenticate this Ontime session with Google</Panel.Description>
|
||||||
|
<Panel.InlineElements wrap='wrap' className={style.setupActions}>
|
||||||
{isAuthenticating && <span>Authenticating...</span>}
|
{isAuthenticating && <span>Authenticating...</span>}
|
||||||
<CopyTag copyValue={authKey ?? ''} disabled={!canAuthenticate}>
|
<CopyTag copyValue={authKey ?? ''} disabled={!canAuthenticate}>
|
||||||
{authKey ? authKey : 'Upload files to generate Auth Key'}
|
{authKey ? authKey : 'Upload files to generate Auth Key'}
|
||||||
@@ -184,6 +315,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
|
|||||||
Authenticate
|
Authenticate
|
||||||
</Button>
|
</Button>
|
||||||
</Panel.InlineElements>
|
</Panel.InlineElements>
|
||||||
|
<div className={style.setupHint}>Open the browser prompt, complete the code flow, then come back here.</div>
|
||||||
</Panel.ListGroup>
|
</Panel.ListGroup>
|
||||||
)}
|
)}
|
||||||
</Panel.Section>
|
</Panel.Section>
|
||||||
|
|||||||
+133
-26
@@ -1,36 +1,143 @@
|
|||||||
.uploadSection,
|
.introStack {
|
||||||
.finishSection {
|
|
||||||
margin-top: 1rem;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
padding: 3rem 1rem;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
background-color: $gray-1350;
|
|
||||||
border: 1px solid $white-10;
|
|
||||||
border-radius: $component-border-radius-md;
|
|
||||||
}
|
|
||||||
|
|
||||||
.uploadSection {
|
|
||||||
flex-direction: row;
|
|
||||||
gap: 2rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.finishSection {
|
|
||||||
font-size: 1.5rem;
|
|
||||||
text-align: center;
|
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
.error {
|
.setupLead,
|
||||||
color: $red-500;
|
.finishTitle {
|
||||||
}
|
margin: 0;
|
||||||
.success {
|
color: $ui-white;
|
||||||
color: $green-500;
|
font-size: 1rem;
|
||||||
}
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setupBody,
|
||||||
|
.finishDescription,
|
||||||
|
.sourceDescription {
|
||||||
|
margin: 0;
|
||||||
|
color: $gray-400;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceGrid,
|
||||||
|
.finishSection {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceGrid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceCard,
|
||||||
|
.finishSection,
|
||||||
|
.setupBlock {
|
||||||
|
border: 1px solid $white-10;
|
||||||
|
border-radius: $component-border-radius-md;
|
||||||
|
background: $gray-1350;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceCard {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
min-height: 14rem;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceHeader,
|
||||||
|
.setupIntroText {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceTitle {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1rem;
|
||||||
|
color: $ui-white;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sourceMeta,
|
||||||
|
.setupHint {
|
||||||
|
color: $gray-500;
|
||||||
|
font-size: calc(1rem - 2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.finishSection {
|
||||||
|
display: flex;
|
||||||
|
padding: 2rem 1rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
text-align: center;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.finishBadge {
|
||||||
|
padding: 0.35rem 0.7rem;
|
||||||
|
font-size: calc(1rem - 3px);
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
border-radius: 2px;
|
||||||
|
color: $blue-300;
|
||||||
|
background-color: rgb(87 153 255 / 12%);
|
||||||
|
border: 1px solid rgb(87 153 255 / 22%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.setupShell {
|
||||||
|
margin-top: 1rem;
|
||||||
|
border-top: 1px solid $white-10;
|
||||||
|
padding-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setupIntro {
|
||||||
|
padding: 0 2rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setupBlock {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 2rem;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setupActions {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statusIdle {
|
||||||
|
color: $gray-400;
|
||||||
|
background-color: $white-3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statusPending {
|
||||||
|
color: $orange-400;
|
||||||
|
background-color: rgb(255 162 0 / 10%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.statusReady {
|
||||||
|
color: $green-400;
|
||||||
|
background-color: rgb(57 198 120 / 10%);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: $medium-screen) {
|
@media (max-width: $medium-screen) {
|
||||||
.uploadSection {
|
.sourceGrid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setupIntro {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.setupBlock {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+122
-97
@@ -1,4 +1,8 @@
|
|||||||
import type { SpreadsheetPreviewResponse, SpreadsheetWorksheetMetadata } from 'ontime-types';
|
import type {
|
||||||
|
SpreadsheetPreviewResponse,
|
||||||
|
SpreadsheetWorksheetMetadata,
|
||||||
|
SpreadsheetWorksheetOptions,
|
||||||
|
} from 'ontime-types';
|
||||||
import { getErrorMessage, ImportMap } from 'ontime-utils';
|
import { getErrorMessage, ImportMap } from 'ontime-utils';
|
||||||
import { ChangeEvent, useCallback, useRef, useState } from 'react';
|
import { ChangeEvent, useCallback, useRef, useState } from 'react';
|
||||||
import { IoCloudOutline, IoDownloadOutline } from 'react-icons/io5';
|
import { IoCloudOutline, IoDownloadOutline } from 'react-icons/io5';
|
||||||
@@ -10,40 +14,45 @@ import {
|
|||||||
} from '../../../../../common/api/excel';
|
} from '../../../../../common/api/excel';
|
||||||
import {
|
import {
|
||||||
getWorksheetMetadata as getGoogleWorksheetMetadata,
|
getWorksheetMetadata as getGoogleWorksheetMetadata,
|
||||||
getWorksheetOptions,
|
|
||||||
previewRundown as previewGoogleSheet,
|
previewRundown as previewGoogleSheet,
|
||||||
uploadRundown,
|
uploadRundown,
|
||||||
} from '../../../../../common/api/sheets';
|
} from '../../../../../common/api/sheets';
|
||||||
import { maybeAxiosError } from '../../../../../common/api/utils';
|
|
||||||
import Button from '../../../../../common/components/buttons/Button';
|
import Button from '../../../../../common/components/buttons/Button';
|
||||||
import * as Editor from '../../../../../common/components/editor-utils/EditorUtils';
|
import Info from '../../../../../common/components/info/Info';
|
||||||
|
import ExternalLink from '../../../../../common/components/link/external-link/ExternalLink';
|
||||||
import Modal from '../../../../../common/components/modal/Modal';
|
import Modal from '../../../../../common/components/modal/Modal';
|
||||||
import useRundown from '../../../../../common/hooks-query/useRundown';
|
import useRundown from '../../../../../common/hooks-query/useRundown';
|
||||||
import { validateExcelImport } from '../../../../../common/utils/uploadUtils';
|
import { validateExcelImport } from '../../../../../common/utils/uploadUtils';
|
||||||
import * as Panel from '../../../panel-utils/PanelUtils';
|
import * as Panel from '../../../panel-utils/PanelUtils';
|
||||||
import GSheetInfo from './GSheetInfo';
|
|
||||||
import GSheetSetup from './GSheetSetup';
|
import GSheetSetup from './GSheetSetup';
|
||||||
import SheetImportEditor from './sheet-import/SheetImportEditor';
|
import SheetImportEditor from './sheet-import/SheetImportEditor';
|
||||||
import useGoogleSheet from './useGoogleSheet';
|
import useSpreadsheetImport from './useSpreadsheetImport';
|
||||||
import { useSheetStore } from './useSheetStore';
|
|
||||||
|
|
||||||
import style from './SourcesPanel.module.scss';
|
import style from './SourcesPanel.module.scss';
|
||||||
|
|
||||||
|
const googleSheetDocsUrl = 'https://docs.getontime.no/features/import-spreadsheet-gsheet/';
|
||||||
|
|
||||||
|
type ActiveSource =
|
||||||
|
| {
|
||||||
|
kind: 'excel';
|
||||||
|
worksheetNames: string[];
|
||||||
|
initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
kind: 'gsheet';
|
||||||
|
sheetId: string;
|
||||||
|
worksheetNames: string[];
|
||||||
|
initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null;
|
||||||
|
};
|
||||||
|
|
||||||
export default function SourcesPanel() {
|
export default function SourcesPanel() {
|
||||||
const [importFlow, setImportFlow] = useState<'none' | 'excel' | 'gsheet' | 'finished'>('none');
|
const [importFlow, setImportFlow] = useState<'none' | 'excel' | 'gsheet' | 'finished'>('none');
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [hasFile, setHasFile] = useState<'none' | 'loading' | 'done'>('none');
|
const [hasFile, setHasFile] = useState<'none' | 'loading' | 'done'>('none');
|
||||||
const [initialWorksheetMetadata, setInitialWorksheetMetadata] = useState<SpreadsheetWorksheetMetadata | null>(null);
|
const [activeSource, setActiveSource] = useState<ActiveSource | null>(null);
|
||||||
|
|
||||||
const { data: currentRundown } = useRundown();
|
const { data: currentRundown } = useRundown();
|
||||||
const { importRundown, verifyAuth } = useGoogleSheet();
|
const { importRundown } = useSpreadsheetImport();
|
||||||
|
|
||||||
const setWorksheets = useSheetStore((state) => state.setWorksheets);
|
|
||||||
const worksheetNames = useSheetStore((state) => state.worksheetNames);
|
|
||||||
const authenticationStatus = useSheetStore((state) => state.authenticationStatus);
|
|
||||||
const setAuthenticationStatus = useSheetStore((state) => state.setAuthenticationStatus);
|
|
||||||
const setSheetId = useSheetStore((state) => state.setSheetId);
|
|
||||||
const sheetId = useSheetStore((state) => state.sheetId);
|
|
||||||
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
@@ -51,7 +60,7 @@ export default function SourcesPanel() {
|
|||||||
const fileToUpload = event.target.files?.[0];
|
const fileToUpload = event.target.files?.[0];
|
||||||
|
|
||||||
if (!fileToUpload) {
|
if (!fileToUpload) {
|
||||||
setWorksheets(null);
|
setActiveSource(null);
|
||||||
setHasFile('none');
|
setHasFile('none');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -60,15 +69,17 @@ export default function SourcesPanel() {
|
|||||||
setError('');
|
setError('');
|
||||||
validateExcelImport(fileToUpload);
|
validateExcelImport(fileToUpload);
|
||||||
const worksheetOptions = await uploadExcel(fileToUpload);
|
const worksheetOptions = await uploadExcel(fileToUpload);
|
||||||
setWorksheets(worksheetOptions.worksheets);
|
setActiveSource({
|
||||||
setInitialWorksheetMetadata(worksheetOptions.metadata);
|
kind: 'excel',
|
||||||
|
worksheetNames: worksheetOptions.worksheets,
|
||||||
|
initialWorksheetMetadata: worksheetOptions.metadata,
|
||||||
|
});
|
||||||
setImportFlow('excel');
|
setImportFlow('excel');
|
||||||
setHasFile('done');
|
setHasFile('done');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = getErrorMessage(error);
|
const errorMessage = getErrorMessage(error);
|
||||||
setError(`Error uploading file: ${errorMessage}`);
|
setError(`Error uploading file: ${errorMessage}`);
|
||||||
setWorksheets(null);
|
setActiveSource(null);
|
||||||
setInitialWorksheetMetadata(null);
|
|
||||||
setHasFile('none');
|
setHasFile('none');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -78,34 +89,15 @@ export default function SourcesPanel() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const resetFlow = () => {
|
const resetFlow = () => {
|
||||||
// we purposely omit clearing the authentication status
|
|
||||||
setImportFlow('none');
|
setImportFlow('none');
|
||||||
setHasFile('none');
|
setHasFile('none');
|
||||||
setWorksheets(null);
|
setActiveSource(null);
|
||||||
setError('');
|
setError('');
|
||||||
setSheetId(null);
|
|
||||||
setInitialWorksheetMetadata(null);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const openGSheetFlow = async () => {
|
const openGSheetFlow = () => {
|
||||||
setError('');
|
setError('');
|
||||||
setInitialWorksheetMetadata(null);
|
setActiveSource(null);
|
||||||
const result = await verifyAuth();
|
|
||||||
if (result) {
|
|
||||||
setAuthenticationStatus(result.authenticated);
|
|
||||||
setSheetId(result.sheetId);
|
|
||||||
if (result.authenticated === 'authenticated' && result.sheetId) {
|
|
||||||
try {
|
|
||||||
const worksheetOptions = await getWorksheetOptions(result.sheetId);
|
|
||||||
setWorksheets(worksheetOptions.worksheets);
|
|
||||||
setInitialWorksheetMetadata(worksheetOptions.metadata);
|
|
||||||
} catch (error) {
|
|
||||||
const message = maybeAxiosError(error);
|
|
||||||
setError(`Error getting worksheets: ${message}`);
|
|
||||||
setInitialWorksheetMetadata(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setImportFlow('gsheet');
|
setImportFlow('gsheet');
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -120,7 +112,7 @@ export default function SourcesPanel() {
|
|||||||
const handleFinished = () => {
|
const handleFinished = () => {
|
||||||
setImportFlow('finished');
|
setImportFlow('finished');
|
||||||
setHasFile('none');
|
setHasFile('none');
|
||||||
setWorksheets(null);
|
setActiveSource(null);
|
||||||
setError('');
|
setError('');
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -143,35 +135,62 @@ export default function SourcesPanel() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const loadWorksheetMetadata = useCallback(
|
const loadWorksheetMetadata = useCallback(
|
||||||
(worksheet: string) =>
|
(worksheet: string) => {
|
||||||
importFlow === 'excel'
|
if (!activeSource) {
|
||||||
|
throw new Error('No spreadsheet source loaded');
|
||||||
|
}
|
||||||
|
|
||||||
|
return activeSource.kind === 'excel'
|
||||||
? getExcelWorksheetMetadata(worksheet)
|
? getExcelWorksheetMetadata(worksheet)
|
||||||
: getGoogleWorksheetMetadata(sheetId as string, worksheet),
|
: getGoogleWorksheetMetadata(activeSource.sheetId, worksheet);
|
||||||
[importFlow, sheetId],
|
},
|
||||||
|
[activeSource],
|
||||||
);
|
);
|
||||||
|
|
||||||
const previewImport = useCallback(
|
const previewImport = useCallback(
|
||||||
(importMap: ImportMap): Promise<SpreadsheetPreviewResponse> =>
|
(importMap: ImportMap): Promise<SpreadsheetPreviewResponse> => {
|
||||||
importFlow === 'excel' ? importExcelPreview(importMap) : previewGoogleSheet(sheetId as string, importMap),
|
if (!activeSource) {
|
||||||
[importFlow, sheetId],
|
throw new Error('No spreadsheet source loaded');
|
||||||
|
}
|
||||||
|
|
||||||
|
return activeSource.kind === 'excel'
|
||||||
|
? importExcelPreview(importMap)
|
||||||
|
: previewGoogleSheet(activeSource.sheetId, importMap);
|
||||||
|
},
|
||||||
|
[activeSource],
|
||||||
);
|
);
|
||||||
|
|
||||||
const exportToGoogleSheet = useCallback(
|
const exportToGoogleSheet = useCallback(
|
||||||
(importMap: ImportMap): Promise<void> => uploadRundown(sheetId as string, importMap),
|
(importMap: ImportMap): Promise<void> => {
|
||||||
[sheetId],
|
if (!activeSource || activeSource.kind !== 'gsheet') {
|
||||||
|
throw new Error('Google Sheet source not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
return uploadRundown(activeSource.sheetId, importMap);
|
||||||
|
},
|
||||||
|
[activeSource],
|
||||||
);
|
);
|
||||||
|
|
||||||
const isExcelFlow = importFlow === 'excel';
|
const handleSheetLoaded = useCallback((sheetId: string, worksheetOptions: SpreadsheetWorksheetOptions) => {
|
||||||
|
setActiveSource({
|
||||||
|
kind: 'gsheet',
|
||||||
|
sheetId,
|
||||||
|
worksheetNames: worksheetOptions.worksheets,
|
||||||
|
initialWorksheetMetadata: worksheetOptions.metadata,
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const isGSheetFlow = importFlow === 'gsheet';
|
const isGSheetFlow = importFlow === 'gsheet';
|
||||||
const isAuthenticated = authenticationStatus === 'authenticated';
|
|
||||||
const showInput = importFlow === 'none';
|
const showInput = importFlow === 'none';
|
||||||
const showCompleted = importFlow === 'finished';
|
const showCompleted = importFlow === 'finished';
|
||||||
const showAuth = isGSheetFlow && (!isAuthenticated || !worksheetNames?.length);
|
const showAuth = isGSheetFlow && activeSource === null;
|
||||||
const showImportWorkspace =
|
const showImportWorkspace = activeSource !== null;
|
||||||
(isExcelFlow && hasFile === 'done' && Boolean(worksheetNames?.length)) ||
|
const importModalTitle = activeSource?.kind === 'excel' ? 'Import spreadsheet' : 'Synchronise with Google Sheet';
|
||||||
(isGSheetFlow && isAuthenticated && Boolean(sheetId) && Boolean(worksheetNames?.length));
|
const sourceKey = (() => {
|
||||||
const importModalTitle = isExcelFlow ? 'Import spreadsheet' : 'Synchronise with Google Sheet';
|
if (!activeSource) return null;
|
||||||
const sourceKey = isExcelFlow ? 'excel' : sheetId ? `gsheet:${sheetId}` : null;
|
if (activeSource.kind === 'excel') return 'excel';
|
||||||
|
return `gsheet:${activeSource.sheetId}`;
|
||||||
|
})();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Panel.Section>
|
<Panel.Section>
|
||||||
@@ -179,8 +198,17 @@ export default function SourcesPanel() {
|
|||||||
<Panel.SubHeader>Synchronise your rundown with an external source</Panel.SubHeader>
|
<Panel.SubHeader>Synchronise your rundown with an external source</Panel.SubHeader>
|
||||||
{error && <Panel.Error>{error}</Panel.Error>}
|
{error && <Panel.Error>{error}</Panel.Error>}
|
||||||
{showInput && (
|
{showInput && (
|
||||||
<>
|
<div className={style.introStack}>
|
||||||
<GSheetInfo />
|
<Info>
|
||||||
|
<Info.Title>Choose between a quick file import or a live Google Sheet connection.</Info.Title>
|
||||||
|
<Info.Body>
|
||||||
|
Google Sheets sync needs a client secret and a one-time device authentication before you can load a
|
||||||
|
sheet by ID.
|
||||||
|
</Info.Body>
|
||||||
|
<Info.Footer>
|
||||||
|
<ExternalLink href={googleSheetDocsUrl}>Read setup guide</ExternalLink>
|
||||||
|
</Info.Footer>
|
||||||
|
</Info>
|
||||||
<input
|
<input
|
||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
style={{ display: 'none' }}
|
style={{ display: 'none' }}
|
||||||
@@ -189,50 +217,47 @@ export default function SourcesPanel() {
|
|||||||
accept='.xlsx'
|
accept='.xlsx'
|
||||||
data-testid='file-input'
|
data-testid='file-input'
|
||||||
/>
|
/>
|
||||||
<div className={style.uploadSection}>
|
<div className={style.sourceGrid}>
|
||||||
<div>
|
<section className={style.sourceCard}>
|
||||||
<Button variant='primary' onClick={handleUpload} loading={hasFile === 'loading'}>
|
<div className={style.sourceHeader}>
|
||||||
|
<h4 className={style.sourceTitle}>Import spreadsheet</h4>
|
||||||
|
</div>
|
||||||
|
<p className={style.sourceDescription}>
|
||||||
|
Bring in a one-off spreadsheet, review the mapping, and apply the data to the current rundown.
|
||||||
|
</p>
|
||||||
|
<div className={style.sourceMeta}>Accepts `.xlsx` files</div>
|
||||||
|
<Button variant='primary' size='large' fluid onClick={handleUpload} loading={hasFile === 'loading'}>
|
||||||
<IoDownloadOutline />
|
<IoDownloadOutline />
|
||||||
Import from spreadsheet
|
Import from spreadsheet
|
||||||
</Button>
|
</Button>
|
||||||
<Panel.Description>Accepts .xlsx files</Panel.Description>
|
</section>
|
||||||
</div>
|
<section className={style.sourceCard}>
|
||||||
<Editor.Separator orientation='vertical' />
|
<div className={style.sourceHeader}>
|
||||||
<div>
|
<h4 className={style.sourceTitle}>Synchronise with Google</h4>
|
||||||
<Button variant='primary' onClick={openGSheetFlow} disabled={hasFile !== 'none'}>
|
</div>
|
||||||
|
<p className={style.sourceDescription}>
|
||||||
|
Connect a Google account once, then load any sheet by ID and keep the import flow inside Ontime.
|
||||||
|
</p>
|
||||||
|
<div className={style.sourceMeta}>Requires Google OAuth client credentials</div>
|
||||||
|
<Button variant='primary' size='large' fluid onClick={openGSheetFlow} disabled={hasFile !== 'none'}>
|
||||||
<IoCloudOutline />
|
<IoCloudOutline />
|
||||||
Synchronise with Google
|
Synchronise with Google
|
||||||
</Button>
|
</Button>
|
||||||
<Panel.Description>Start authentication process</Panel.Description>
|
</section>
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</div>
|
||||||
)}
|
)}
|
||||||
{showCompleted && (
|
{showCompleted && (
|
||||||
<div className={style.finishSection}>
|
<div className={style.finishSection}>
|
||||||
{error ? (
|
<span className={style.finishBadge}>Import complete</span>
|
||||||
<span key='finish__error' className={style.error}>
|
<div className={style.finishTitle}>Spreadsheet data applied.</div>
|
||||||
Import failed
|
<div className={style.finishDescription}>You can close this flow or start another import.</div>
|
||||||
</span>
|
<Button variant='subtle-white' onClick={resetFlow}>
|
||||||
) : (
|
Reset flow
|
||||||
<span key='finish__success' className={style.success}>
|
|
||||||
Import successful
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<Button variant='primary' onClick={resetFlow}>
|
|
||||||
Return
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{showAuth && (
|
{showAuth && <GSheetSetup onCancel={cancelGSheetFlow} onSheetLoaded={handleSheetLoaded} />}
|
||||||
<GSheetSetup
|
|
||||||
onCancel={cancelGSheetFlow}
|
|
||||||
onWorksheetOptionsLoaded={(worksheetOptions) => {
|
|
||||||
setWorksheets(worksheetOptions.worksheets);
|
|
||||||
setInitialWorksheetMetadata(worksheetOptions.metadata);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={showImportWorkspace}
|
isOpen={showImportWorkspace}
|
||||||
title={importModalTitle}
|
title={importModalTitle}
|
||||||
@@ -243,13 +268,13 @@ export default function SourcesPanel() {
|
|||||||
bodyElements={
|
bodyElements={
|
||||||
<SheetImportEditor
|
<SheetImportEditor
|
||||||
sourceKey={sourceKey ?? 'spreadsheet'}
|
sourceKey={sourceKey ?? 'spreadsheet'}
|
||||||
worksheetNames={worksheetNames ?? []}
|
worksheetNames={activeSource?.worksheetNames ?? []}
|
||||||
initialMetadata={initialWorksheetMetadata}
|
initialMetadata={activeSource?.initialWorksheetMetadata ?? null}
|
||||||
loadMetadata={loadWorksheetMetadata}
|
loadMetadata={loadWorksheetMetadata}
|
||||||
previewImport={previewImport}
|
previewImport={previewImport}
|
||||||
onApply={handleApplyImport}
|
onApply={handleApplyImport}
|
||||||
onCancel={cancelImportFlow}
|
onCancel={cancelImportFlow}
|
||||||
onExport={isGSheetFlow && sheetId ? exportToGoogleSheet : undefined}
|
onExport={activeSource?.kind === 'gsheet' ? exportToGoogleSheet : undefined}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
+1
@@ -51,6 +51,7 @@ export default function MappingFieldRow({
|
|||||||
className={cx([style.columnInput, warning && style.columnInputWarn])}
|
className={cx([style.columnInput, warning && style.columnInputWarn])}
|
||||||
maxLength={50}
|
maxLength={50}
|
||||||
options={options}
|
options={options}
|
||||||
|
openOnFocus
|
||||||
trailingElement={(option) => (assigned.has(option) ? <IoCheckmark /> : null)}
|
trailingElement={(option) => (assigned.has(option) ? <IoCheckmark /> : null)}
|
||||||
placeholder='Spreadsheet column'
|
placeholder='Spreadsheet column'
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
|
|||||||
+2
-2
@@ -49,14 +49,14 @@ describe('deriveHeaderOptionsState()', () => {
|
|||||||
const values = makeValues({});
|
const values = makeValues({});
|
||||||
const { sampleHeaders } = deriveHeaderOptionsState(values, ['Title', 'Title', '', ' ', 'Cue']);
|
const { sampleHeaders } = deriveHeaderOptionsState(values, ['Title', 'Title', '', ' ', 'Cue']);
|
||||||
|
|
||||||
expect(sampleHeaders).toEqual(['title', 'cue']);
|
expect(sampleHeaders).toEqual(['Title', 'Cue']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deduplicates headers case-insensitively', () => {
|
it('deduplicates headers case-insensitively', () => {
|
||||||
const values = makeValues({});
|
const values = makeValues({});
|
||||||
const { sampleHeaders } = deriveHeaderOptionsState(values, ['Title', 'TITLE', 'title', 'Artist']);
|
const { sampleHeaders } = deriveHeaderOptionsState(values, ['Title', 'TITLE', 'title', 'Artist']);
|
||||||
|
|
||||||
expect(sampleHeaders).toEqual(['title', 'artist']);
|
expect(sampleHeaders).toEqual(['Title', 'Artist']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('matches headers case-insensitively', () => {
|
it('matches headers case-insensitively', () => {
|
||||||
|
|||||||
+4
-7
@@ -1,6 +1,7 @@
|
|||||||
import type { ImportMap } from 'ontime-utils';
|
import type { ImportMap } from 'ontime-utils';
|
||||||
|
|
||||||
import { makeStageKey } from '../../../../../../common/utils/localStorage';
|
import { makeStageKey } from '../../../../../../common/utils/localStorage';
|
||||||
|
import { normaliseColumnName } from './spreadsheetImportUtils';
|
||||||
|
|
||||||
export type MappingWarning = {
|
export type MappingWarning = {
|
||||||
kind: 'duplicate' | 'missing' | 'invalid-name' | 'name-collision';
|
kind: 'duplicate' | 'missing' | 'invalid-name' | 'name-collision';
|
||||||
@@ -149,10 +150,6 @@ export function getPersistedImportState(sourceKey: string): ImportFormValues {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function normaliseColumn(value: string | undefined): string {
|
|
||||||
return value?.trim().toLowerCase() ?? '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates import mappings and generates warnings for duplicate or missing spreadsheet columns.
|
* Validates import mappings and generates warnings for duplicate or missing spreadsheet columns.
|
||||||
*/
|
*/
|
||||||
@@ -161,7 +158,7 @@ export function getImportWarnings(
|
|||||||
detectedSpreadsheetColumns: string[],
|
detectedSpreadsheetColumns: string[],
|
||||||
existingCustomFieldLabels: string[] = [],
|
existingCustomFieldLabels: string[] = [],
|
||||||
): Record<string, MappingWarning | undefined> {
|
): Record<string, MappingWarning | undefined> {
|
||||||
const normalisedHeaders = new Set(detectedSpreadsheetColumns.map(normaliseColumn).filter(Boolean));
|
const normalisedHeaders = new Set(detectedSpreadsheetColumns.map(normaliseColumnName).filter(Boolean));
|
||||||
const builtInLabels = new Set(builtInFieldDefs.map((def) => def.label.toLowerCase()));
|
const builtInLabels = new Set(builtInFieldDefs.map((def) => def.label.toLowerCase()));
|
||||||
const existingLabels = new Set(existingCustomFieldLabels.map((label) => label.trim().toLowerCase()).filter(Boolean));
|
const existingLabels = new Set(existingCustomFieldLabels.map((label) => label.trim().toLowerCase()).filter(Boolean));
|
||||||
const seenColumns = new Set<string>();
|
const seenColumns = new Set<string>();
|
||||||
@@ -173,7 +170,7 @@ export function getImportWarnings(
|
|||||||
const field = values.builtIn[i];
|
const field = values.builtIn[i];
|
||||||
if (!field.enabled) continue;
|
if (!field.enabled) continue;
|
||||||
|
|
||||||
const normalised = normaliseColumn(field.header);
|
const normalised = normaliseColumnName(field.header);
|
||||||
if (!normalised) continue;
|
if (!normalised) continue;
|
||||||
|
|
||||||
const key = `builtIn.${i}.header`;
|
const key = `builtIn.${i}.header`;
|
||||||
@@ -189,7 +186,7 @@ export function getImportWarnings(
|
|||||||
|
|
||||||
// 2. check custom fields
|
// 2. check custom fields
|
||||||
values.custom.forEach(({ importName }, index) => {
|
values.custom.forEach(({ importName }, index) => {
|
||||||
const normalised = normaliseColumn(importName);
|
const normalised = normaliseColumnName(importName);
|
||||||
if (!normalised) return;
|
if (!normalised) return;
|
||||||
|
|
||||||
const key = `custom.${index}.importName`;
|
const key = `custom.${index}.importName`;
|
||||||
|
|||||||
+3
-3
@@ -1,13 +1,13 @@
|
|||||||
import type { CustomField, CustomFieldKey } from 'ontime-types';
|
import type { CustomField, CustomFieldKey, SpreadsheetPreviewResponse } from 'ontime-types';
|
||||||
import { isOntimeEvent, isOntimeGroup, isOntimeMilestone } from 'ontime-types';
|
import { isOntimeEvent, isOntimeGroup, isOntimeMilestone } from 'ontime-types';
|
||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
import { type PreviewState, getCellValue } from './previewTableUtils';
|
import { getCellValue } from './previewTableUtils';
|
||||||
|
|
||||||
import style from './PreviewTable.module.scss';
|
import style from './PreviewTable.module.scss';
|
||||||
|
|
||||||
interface PreviewTableProps {
|
interface PreviewTableProps {
|
||||||
preview: PreviewState | null;
|
preview: SpreadsheetPreviewResponse | null;
|
||||||
columnLabels: string[];
|
columnLabels: string[];
|
||||||
isLoadingMetadata: boolean;
|
isLoadingMetadata: boolean;
|
||||||
worksheetHeaders: string[];
|
worksheetHeaders: string[];
|
||||||
|
|||||||
+1
-7
@@ -1,16 +1,10 @@
|
|||||||
import type { CustomField, CustomFieldKey, CustomFields, OntimeEntry, Rundown, RundownSummary } from 'ontime-types';
|
import type { CustomField, CustomFieldKey, OntimeEntry } from 'ontime-types';
|
||||||
import { isOntimeEvent, isOntimeMilestone } from 'ontime-types';
|
import { isOntimeEvent, isOntimeMilestone } from 'ontime-types';
|
||||||
import type { ImportMap } from 'ontime-utils';
|
import type { ImportMap } from 'ontime-utils';
|
||||||
import { millisToString } from 'ontime-utils';
|
import { millisToString } from 'ontime-utils';
|
||||||
|
|
||||||
import { builtInFieldDefs } from '../importMapUtils';
|
import { builtInFieldDefs } from '../importMapUtils';
|
||||||
|
|
||||||
export type PreviewState = {
|
|
||||||
rundown: Rundown;
|
|
||||||
customFields: CustomFields;
|
|
||||||
summary: RundownSummary;
|
|
||||||
};
|
|
||||||
|
|
||||||
type BuiltInImportKey = keyof Omit<ImportMap, 'worksheet' | 'custom'>;
|
type BuiltInImportKey = keyof Omit<ImportMap, 'worksheet' | 'custom'>;
|
||||||
|
|
||||||
const importKeyByLabel = new Map<string, BuiltInImportKey>(builtInFieldDefs.map((def) => [def.label, def.importKey]));
|
const importKeyByLabel = new Map<string, BuiltInImportKey>(builtInFieldDefs.map((def) => [def.label, def.importKey]));
|
||||||
|
|||||||
+17
-6
@@ -1,7 +1,7 @@
|
|||||||
import type { ImportFormValues } from './importMapUtils';
|
import type { ImportFormValues } from './importMapUtils';
|
||||||
|
|
||||||
export function normaliseHeaderName(value: string): string {
|
export function normaliseColumnName(value: string | undefined): string {
|
||||||
return value.trim().toLowerCase();
|
return value?.trim().toLowerCase() ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,26 +11,37 @@ export function normaliseHeaderName(value: string): string {
|
|||||||
* offer in the UI and the subset already assigned to any field.
|
* offer in the UI and the subset already assigned to any field.
|
||||||
*/
|
*/
|
||||||
export function deriveHeaderOptionsState(values: ImportFormValues, headers: string[]) {
|
export function deriveHeaderOptionsState(values: ImportFormValues, headers: string[]) {
|
||||||
const sampleHeaders = [...new Set(headers.map(normaliseHeaderName).filter(Boolean))];
|
const seenHeaders = new Set<string>();
|
||||||
|
const sampleHeaders: string[] = [];
|
||||||
|
|
||||||
|
for (const header of headers) {
|
||||||
|
const normalized = normaliseColumnName(header);
|
||||||
|
if (!normalized || seenHeaders.has(normalized)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
seenHeaders.add(normalized);
|
||||||
|
sampleHeaders.push(header.trim());
|
||||||
|
}
|
||||||
|
|
||||||
const assignedColumns = new Set<string>();
|
const assignedColumns = new Set<string>();
|
||||||
|
|
||||||
for (const field of values.builtIn) {
|
for (const field of values.builtIn) {
|
||||||
if (!field.enabled) continue;
|
if (!field.enabled) continue;
|
||||||
const normalized = normaliseHeaderName(field.header);
|
const normalized = normaliseColumnName(field.header);
|
||||||
if (normalized) {
|
if (normalized) {
|
||||||
assignedColumns.add(normalized);
|
assignedColumns.add(normalized);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const { importName } of values.custom) {
|
for (const { importName } of values.custom) {
|
||||||
const normalized = normaliseHeaderName(importName);
|
const normalized = normaliseColumnName(importName);
|
||||||
if (normalized) {
|
if (normalized) {
|
||||||
assignedColumns.add(normalized);
|
assignedColumns.add(normalized);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const assignedHeaders = new Set(sampleHeaders.filter((header) => assignedColumns.has(normaliseHeaderName(header))));
|
const assignedHeaders = new Set(sampleHeaders.filter((header) => assignedColumns.has(normaliseColumnName(header))));
|
||||||
|
|
||||||
return { sampleHeaders, assignedHeaders };
|
return { sampleHeaders, assignedHeaders };
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-16
@@ -16,14 +16,13 @@ import {
|
|||||||
getResolvedCustomFields,
|
getResolvedCustomFields,
|
||||||
persistImportState,
|
persistImportState,
|
||||||
} from './importMapUtils';
|
} from './importMapUtils';
|
||||||
import type { PreviewState } from './preview/previewTableUtils';
|
|
||||||
import { deriveHeaderOptionsState } from './spreadsheetImportUtils';
|
import { deriveHeaderOptionsState } from './spreadsheetImportUtils';
|
||||||
|
|
||||||
type ImportAction =
|
type ImportAction =
|
||||||
| { type: 'startPreview' }
|
| { type: 'startPreview' }
|
||||||
| { type: 'startApply' }
|
| { type: 'startApply' }
|
||||||
| { type: 'startExport' }
|
| { type: 'startExport' }
|
||||||
| { type: 'previewSuccess'; preview: PreviewState }
|
| { type: 'previewSuccess'; preview: SpreadsheetPreviewResponse }
|
||||||
| { type: 'applySuccess' }
|
| { type: 'applySuccess' }
|
||||||
| { type: 'exportSuccess' }
|
| { type: 'exportSuccess' }
|
||||||
| { type: 'clearPreview'; error?: string }
|
| { type: 'clearPreview'; error?: string }
|
||||||
@@ -33,7 +32,7 @@ type ImportAction =
|
|||||||
type ImportState = {
|
type ImportState = {
|
||||||
loading: '' | 'preview' | 'apply' | 'export';
|
loading: '' | 'preview' | 'apply' | 'export';
|
||||||
error: string;
|
error: string;
|
||||||
preview: PreviewState | null;
|
preview: SpreadsheetPreviewResponse | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const initialImportState: ImportState = {
|
const initialImportState: ImportState = {
|
||||||
@@ -106,7 +105,7 @@ interface UseSheetImportFormProps {
|
|||||||
initialMetadata: SpreadsheetWorksheetMetadata | null;
|
initialMetadata: SpreadsheetWorksheetMetadata | null;
|
||||||
loadMetadata: (worksheet: string) => Promise<SpreadsheetWorksheetMetadata>;
|
loadMetadata: (worksheet: string) => Promise<SpreadsheetWorksheetMetadata>;
|
||||||
previewImport: (importMap: ReturnType<typeof convertToImportMap>) => Promise<SpreadsheetPreviewResponse>;
|
previewImport: (importMap: ReturnType<typeof convertToImportMap>) => Promise<SpreadsheetPreviewResponse>;
|
||||||
onApply: (preview: PreviewState) => Promise<void>;
|
onApply: (preview: SpreadsheetPreviewResponse) => Promise<void>;
|
||||||
onExport?: (importMap: ReturnType<typeof convertToImportMap>) => Promise<void>;
|
onExport?: (importMap: ReturnType<typeof convertToImportMap>) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,6 +127,7 @@ export function useSheetImportForm({
|
|||||||
const {
|
const {
|
||||||
control,
|
control,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
|
getValues,
|
||||||
reset,
|
reset,
|
||||||
setValue,
|
setValue,
|
||||||
watch,
|
watch,
|
||||||
@@ -163,10 +163,7 @@ export function useSheetImportForm({
|
|||||||
const metadataError = worksheetMetadataQuery.error ? maybeAxiosError(worksheetMetadataQuery.error) : '';
|
const metadataError = worksheetMetadataQuery.error ? maybeAxiosError(worksheetMetadataQuery.error) : '';
|
||||||
|
|
||||||
// --- Derived state ---
|
// --- Derived state ---
|
||||||
const { sampleHeaders, assignedHeaders } = useMemo(
|
const { sampleHeaders, assignedHeaders } = deriveHeaderOptionsState(values, headers);
|
||||||
() => deriveHeaderOptionsState(values, headers),
|
|
||||||
[values, headers],
|
|
||||||
);
|
|
||||||
const columnLabels = buildColumnLabels(values);
|
const columnLabels = buildColumnLabels(values);
|
||||||
|
|
||||||
const [state, dispatch] = useReducer(importReducer, initialImportState);
|
const [state, dispatch] = useReducer(importReducer, initialImportState);
|
||||||
@@ -176,12 +173,13 @@ export function useSheetImportForm({
|
|||||||
);
|
);
|
||||||
const warnings = getImportWarnings(values, headers, existingCustomFieldLabels);
|
const warnings = getImportWarnings(values, headers, existingCustomFieldLabels);
|
||||||
const warningCount = Object.values(warnings).filter(Boolean).length;
|
const warningCount = Object.values(warnings).filter(Boolean).length;
|
||||||
|
const previewRef = useRef<SpreadsheetPreviewResponse | null>(null);
|
||||||
|
|
||||||
// Rehydrate the form from persisted/default state whenever the source context changes.
|
// Rehydrate the form from persisted/default state whenever the source context changes.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
reset(initialFormValues);
|
reset(initialFormValues);
|
||||||
dispatch({ type: 'reset' });
|
dispatch({ type: 'reset' });
|
||||||
}, [initialMetadata, initialFormValues, reset, sourceKey]);
|
}, [initialFormValues, reset]);
|
||||||
|
|
||||||
// Keep the worksheet selection valid if the available worksheets change underneath the form.
|
// Keep the worksheet selection valid if the available worksheets change underneath the form.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -190,15 +188,19 @@ export function useSheetImportForm({
|
|||||||
setValue('worksheet', worksheetNames[0], { shouldDirty: true, shouldValidate: true });
|
setValue('worksheet', worksheetNames[0], { shouldDirty: true, shouldValidate: true });
|
||||||
}, [setValue, values.worksheet, worksheetNames]);
|
}, [setValue, values.worksheet, worksheetNames]);
|
||||||
|
|
||||||
// Clear preview on any form change.
|
useEffect(() => {
|
||||||
|
previewRef.current = state.preview;
|
||||||
|
}, [state.preview]);
|
||||||
|
|
||||||
|
// Clear preview on any form change without re-subscribing on preview updates.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const sub = watch(() => {
|
const sub = watch(() => {
|
||||||
if (state.preview) {
|
if (!previewRef.current) return;
|
||||||
dispatch({ type: 'clearPreview' });
|
previewRef.current = null;
|
||||||
}
|
dispatch({ type: 'clearPreview' });
|
||||||
});
|
});
|
||||||
return () => sub.unsubscribe();
|
return () => sub.unsubscribe();
|
||||||
}, [watch, state.preview]);
|
}, [watch]);
|
||||||
|
|
||||||
// Race condition guard for async preview requests.
|
// Race condition guard for async preview requests.
|
||||||
const requestIdRef = useRef(0);
|
const requestIdRef = useRef(0);
|
||||||
@@ -229,12 +231,12 @@ export function useSheetImportForm({
|
|||||||
try {
|
try {
|
||||||
dispatch({ type: 'startApply' });
|
dispatch({ type: 'startApply' });
|
||||||
await onApply(state.preview);
|
await onApply(state.preview);
|
||||||
persistImportState(sourceKey, values);
|
persistImportState(sourceKey, getValues());
|
||||||
dispatch({ type: 'applySuccess' });
|
dispatch({ type: 'applySuccess' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
dispatch({ type: 'failure', error: maybeAxiosError(error) });
|
dispatch({ type: 'failure', error: maybeAxiosError(error) });
|
||||||
}
|
}
|
||||||
}, [onApply, sourceKey, state.preview, values]);
|
}, [getValues, onApply, sourceKey, state.preview]);
|
||||||
|
|
||||||
const handleExport = useCallback(
|
const handleExport = useCallback(
|
||||||
async (formValues: ImportFormValues) => {
|
async (formValues: ImportFormValues) => {
|
||||||
|
|||||||
-72
@@ -1,72 +0,0 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { AuthenticationStatus, CustomFields, ProjectRundowns, ProjectRundownsList } from 'ontime-types';
|
|
||||||
import { ImportMap } from 'ontime-utils';
|
|
||||||
|
|
||||||
import {
|
|
||||||
CURRENT_RUNDOWN_QUERY_KEY,
|
|
||||||
CUSTOM_FIELDS,
|
|
||||||
PROJECT_RUNDOWNS,
|
|
||||||
getRundownQueryKey,
|
|
||||||
} from '../../../../../common/api/constants';
|
|
||||||
import { patchData } from '../../../../../common/api/db';
|
|
||||||
import { requestConnection, revokeAuthentication, verifyAuthenticationStatus } from '../../../../../common/api/sheets';
|
|
||||||
import { maybeAxiosError } from '../../../../../common/api/utils';
|
|
||||||
import { useSheetStore } from './useSheetStore';
|
|
||||||
|
|
||||||
export default function useGoogleSheet() {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const patchStepData = useSheetStore((state) => state.patchStepData);
|
|
||||||
|
|
||||||
/** whether the current session has been authenticated */
|
|
||||||
const verifyAuth = async (): Promise<{ authenticated: AuthenticationStatus; sheetId: string } | void> => {
|
|
||||||
try {
|
|
||||||
return await verifyAuthenticationStatus();
|
|
||||||
} catch (error) {
|
|
||||||
patchStepData({ authenticate: { available: false, error: maybeAxiosError(error) } });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** requests connection to a google sheet */
|
|
||||||
const connect = async (
|
|
||||||
file: File,
|
|
||||||
sheetId: string,
|
|
||||||
): Promise<{ verification_url: string; user_code: string } | void> => {
|
|
||||||
try {
|
|
||||||
return await requestConnection(file, sheetId);
|
|
||||||
} catch (error) {
|
|
||||||
patchStepData({ authenticate: { available: false, error: maybeAxiosError(error) } });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** requests the revoking of an existing authenticated session */
|
|
||||||
const revoke = async (): Promise<{ authenticated: AuthenticationStatus } | void> => {
|
|
||||||
try {
|
|
||||||
return await revokeAuthentication();
|
|
||||||
} catch (error) {
|
|
||||||
patchStepData({ authenticate: { available: false, error: maybeAxiosError(error) } });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** applies rundown and customFields to current project */
|
|
||||||
const importRundown = async (rundowns: ProjectRundowns, customFields: CustomFields) => {
|
|
||||||
try {
|
|
||||||
await patchData({ rundowns, customFields });
|
|
||||||
// we are unable to optimistically set the rundown since we need
|
|
||||||
// it to be normalised
|
|
||||||
const loadedRundownId = queryClient.getQueryData<ProjectRundownsList>(PROJECT_RUNDOWNS)?.loaded;
|
|
||||||
const rundownQueryKey = loadedRundownId ? getRundownQueryKey(loadedRundownId) : CURRENT_RUNDOWN_QUERY_KEY;
|
|
||||||
await queryClient.invalidateQueries({ queryKey: rundownQueryKey });
|
|
||||||
await queryClient.invalidateQueries({ queryKey: CUSTOM_FIELDS });
|
|
||||||
} catch (error) {
|
|
||||||
patchStepData({ pullPush: { available: true, error: maybeAxiosError(error) } });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
connect,
|
|
||||||
revoke,
|
|
||||||
verifyAuth,
|
|
||||||
importRundown,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
-48
@@ -1,48 +0,0 @@
|
|||||||
import { AuthenticationStatus } from 'ontime-types';
|
|
||||||
import { create } from 'zustand';
|
|
||||||
|
|
||||||
type SheetStore = {
|
|
||||||
stepData: typeof initialStepData;
|
|
||||||
patchStepData: (patch: Partial<typeof initialStepData>) => void;
|
|
||||||
setWorksheets: (worksheetNames: string[] | null) => void;
|
|
||||||
worksheetNames: string[] | null;
|
|
||||||
|
|
||||||
//gSheet
|
|
||||||
sheetId: string | null;
|
|
||||||
setSheetId: (sheetId: string | null) => void;
|
|
||||||
authenticationStatus: AuthenticationStatus;
|
|
||||||
setAuthenticationStatus: (status: AuthenticationStatus) => void;
|
|
||||||
|
|
||||||
reset: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const initialStepData = {
|
|
||||||
authenticate: { available: false, error: '' },
|
|
||||||
sheetId: { available: false, error: '' },
|
|
||||||
worksheet: { available: false, error: '' },
|
|
||||||
pullPush: { available: false, error: '' },
|
|
||||||
};
|
|
||||||
|
|
||||||
const initialState = {
|
|
||||||
stepData: initialStepData,
|
|
||||||
worksheetNames: null,
|
|
||||||
sheetId: null,
|
|
||||||
authenticationStatus: 'not_authenticated' as AuthenticationStatus,
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useSheetStore = create<SheetStore>((set, get) => ({
|
|
||||||
...initialState,
|
|
||||||
|
|
||||||
patchStepData: (patch: Partial<typeof initialStepData>) => {
|
|
||||||
const stepData = get().stepData;
|
|
||||||
set({ stepData: { ...stepData, ...patch } });
|
|
||||||
},
|
|
||||||
|
|
||||||
setWorksheets: (worksheetNames: string[] | null) => set({ worksheetNames }),
|
|
||||||
|
|
||||||
setSheetId: (sheetId: string | null) => set({ sheetId }),
|
|
||||||
|
|
||||||
setAuthenticationStatus: (status: AuthenticationStatus) => set({ authenticationStatus: status }),
|
|
||||||
|
|
||||||
reset: () => set(initialState),
|
|
||||||
}));
|
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { CustomFields, ProjectRundowns } from 'ontime-types';
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
|
||||||
|
import { CUSTOM_FIELDS, RUNDOWN } from '../../../../../common/api/constants';
|
||||||
|
import { patchData } from '../../../../../common/api/db';
|
||||||
|
|
||||||
|
export default function useSpreadsheetImport() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
/** applies rundown and customFields to current project */
|
||||||
|
const importRundown = useCallback(
|
||||||
|
async (rundowns: ProjectRundowns, customFields: CustomFields) => {
|
||||||
|
await patchData({ rundowns, customFields });
|
||||||
|
// we are unable to optimistically set the rundown since we need
|
||||||
|
// it to be normalised
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: RUNDOWN,
|
||||||
|
});
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: CUSTOM_FIELDS,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[queryClient],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
importRundown,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -215,7 +215,7 @@ function verifyConnection(
|
|||||||
|
|
||||||
export function hasAuth(): { authenticated: AuthenticationStatus; sheetId: string } {
|
export function hasAuth(): { authenticated: AuthenticationStatus; sheetId: string } {
|
||||||
if (!currentSheetId) {
|
if (!currentSheetId) {
|
||||||
throw new Error('No sheet ID');
|
return { authenticated: 'not_authenticated', sheetId: '' };
|
||||||
}
|
}
|
||||||
if (cleanupTimeout) {
|
if (cleanupTimeout) {
|
||||||
return { authenticated: 'pending', sheetId: currentSheetId };
|
return { authenticated: 'pending', sheetId: currentSheetId };
|
||||||
|
|||||||
@@ -32,8 +32,9 @@ test('imports spreadsheet and applies imported rundown to editor', async ({ page
|
|||||||
// apply import
|
// apply import
|
||||||
await page.getByRole('button', { name: 'Preview import' }).click();
|
await page.getByRole('button', { name: 'Preview import' }).click();
|
||||||
await page.getByRole('button', { name: 'Apply import' }).click();
|
await page.getByRole('button', { name: 'Apply import' }).click();
|
||||||
await expect(page.getByText('Import successful')).toBeVisible();
|
await expect(page.getByText('Import complete')).toBeVisible();
|
||||||
await page.getByRole('button', { name: 'Return' }).click();
|
await expect(page.getByText('Spreadsheet data applied.')).toBeVisible();
|
||||||
|
await page.getByRole('button', { name: 'Reset flow' }).click();
|
||||||
|
|
||||||
// verify the data in the rundown
|
// verify the data in the rundown
|
||||||
await page.getByRole('button', { name: 'Close settings' }).scrollIntoViewIfNeeded();
|
await page.getByRole('button', { name: 'Close settings' }).scrollIntoViewIfNeeded();
|
||||||
|
|||||||
Reference in New Issue
Block a user