mams_frontend/src/features/gridActions/ReconciliationUpload.tsx

140 lines
6.1 KiB
TypeScript

import { useMemo, useRef, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import { useAuth } from '../../auth/AuthContext';
import { rpc, ApiError, type Envelope } from '../../api/client';
import { uploadAttachment } from '../../api/attachments';
import { useLabel, useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
import { DateField } from '../../components/DateField';
import { resolveFields } from '../forms/fields';
import type { Option } from '../../api/entity';
/**
* Legacy "Upload file" popup of the reconciliation screens: one file, uploaded first to the server's temporary folder,
* then handed to RECONCILIATION_UPLOAD_FILE. The point-of-sale reconciliation also asks for the date and industrial estate.
*/
export function ReconciliationUpload({ entity, onClose, onDone }: { entity: 'RECONCILIATION' | 'RECONCILIATION_POS'; onClose: () => void; onDone: () => void }) {
const { config } = useAuth();
const t = useT();
const lab = useLabel();
const ui = useUi();
const notify = useNotify();
const pos = entity === 'RECONCILIATION_POS';
const input = useRef<HTMLInputElement>(null);
const [file, setFile] = useState<File | null>(null);
const [date, setDate] = useState('');
const [location, setLocation] = useState('');
const [touched, setTouched] = useState(false);
const [fileError, setFileError] = useState('');
const fields = useMemo(
() => (config && pos ? resolveFields(config, entity, 'CREATE', undefined, ['RECONCILE_DATE', 'LOCATION_IDS']) : []),
[config, entity, pos],
);
// the point-of-sale form has no estate field of its own in the role's metadata: use the estate list the other screens carry
const locOptions = useMemo(
() => (config?.ROLE_FIELD_STATUS_AUTHORITY_VIEW as unknown as { FIELD_NAME: string; DDL_VALUES?: Option[] }[] | undefined)?.find((r) => r.FIELD_NAME === 'LOCATION_IDS' && r.DDL_VALUES?.length)?.DDL_VALUES ?? [],
[config],
);
const dateField = fields.find((f) => f.name === 'RECONCILE_DATE');
const upload = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const serverFile = await uploadAttachment(file!);
const sent = [{ file: serverFile, name: file!.name }];
const args = pos
? { RECONCILIATION_POSEXCEL: { RECONCILIATION_POSEXCEL: sent, RECONCILE_DATE: date.replace(/\D/g, ''), LOCATION_IDS: location } }
: { reconciliationExcel: { reconciliationExcel: sent } };
const r = await rpc<Envelope>(entity, 'RECONCILIATION_UPLOAD_FILE', args, { post: true });
// a rejected file can come back with an empty MESSAGE: fall through to the code, then to a plain "wrong file" text
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE || r.MESSAGECODE || (typeof r.DATA === 'string' ? r.DATA : '') || 'WRONG_FILE_UPLOADED'), r.CODE, r.DATA);
return r;
},
onSuccess: (r) => {
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
onDone();
},
onError: (e) => notify.warning('WRONG_FILE_UPLOADED', failText(e as Error)),
});
// never an empty alert: an unknown / blank message reads as "wrong file"
const failText = (e: Error) => {
const m = (e.message ?? '').trim();
const shown = m ? t(m) : '';
return shown && !/^[A-Z0-9_.]+$/.test(shown) ? shown : ui('wrongFileType');
};
const missing =!file || (pos && (!date || !location));
return (
<Dialog open onClose={onClose} fullWidth maxWidth="xs">
<DialogTitle>{t('UPLOAD_GENERAL_FILE')}</DialogTitle>
<DialogContent>
<Stack spacing={1.5} sx={{ pt: 0.5 }}>
{pos && (
<>
<DateField
label={lab(dateField?.caption ?? 'RECONCILE_DATE')}
value={date}
onChange={setDate}
error={touched && !date}
fullWidth
/>
<TextField
select
label={lab('INDUSTRIAL_ESTATE')}
value={location}
onChange={(e) => setLocation(e.target.value)}
error={touched && !location}
fullWidth
>
{locOptions.map((o) => (
<MenuItem key={String(o.CODE)} value={String(o.CODE)}>{o.NAME || t(o.CAPTION_CODE ?? String(o.CODE))}</MenuItem>
))}
</TextField>
</>
)}
<input ref={input} type="file" hidden accept=".csv,.xls,.xlsx" onChange={(e) => {
const f = e.target.files?.[0] ?? null;
e.target.value = '';
if (f && !/\.(csv|xls|xlsx)$/i.test(f.name)) {
setFile(null);
setFileError(ui('wrongFileType'));
notify.warning('WRONG_FILE_TYPE_ONLY_CSV_XLS', ui('wrongFileType'));
return;
}
setFileError('');
setFile(f);
}} />
<Box
onClick={() => input.current?.click()}
sx={{ border: 2, borderStyle: 'dashed', borderColor: touched && !file ? 'error.main' : 'divider', borderRadius: 2, p: 3, textAlign: 'center', cursor: 'pointer' }}
>
<UploadFileIcon color="primary" />
<Typography sx={{
fontSize: 14
}}>{file ? file.name : t('MUST_UPLOAD_FILE')}</Typography>
</Box>
{fileError && <Alert severity="error">{fileError}</Alert>}
{upload.error && <Alert severity="error">{failText(upload.error as Error)}</Alert>}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('CLOSE')}</Button>
<Button
variant="contained"
disabled={upload.isPending}
onClick={() => {
setTouched(true);
if (!missing) upload.mutate();
}}
>
{t('UPLOAD_GENERAL_FILE')}
</Button>
</DialogActions>
</Dialog>
);
}