88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { FormContext } from './context/form-context';
|
||
import type { Props } from './types';
|
||
import type * as IUS from '@/api/ius/types';
|
||
import { ArrowDownTrayIcon } from '@heroicons/react/24/solid';
|
||
import { Heading, InputFile } from '@repo/ui';
|
||
import Link from 'next/link';
|
||
import { unique } from 'radash';
|
||
import { useContext } from 'react';
|
||
|
||
type DownloadDocumentProps = Pick<FileProps, 'document'>;
|
||
|
||
function DownloadDocument({ document }: DownloadDocumentProps) {
|
||
return document?.href ? (
|
||
<Link
|
||
href={'/api/ius' + document.href}
|
||
target="_blank"
|
||
rel="noopener noreferrer"
|
||
className="text-primary-600 h-10 px-5 py-2.5 text-sm font-medium hover:underline"
|
||
>
|
||
<div className="flex flex-row items-center gap-1">
|
||
<ArrowDownTrayIcon className="h-4 w-4" />
|
||
Скачать
|
||
</div>
|
||
</Link>
|
||
) : (
|
||
false
|
||
);
|
||
}
|
||
|
||
type FileProps = {
|
||
readonly document: Docs[number];
|
||
};
|
||
|
||
function File({ document }: FileProps) {
|
||
const { formFiles, setFormFiles } = useContext(FormContext);
|
||
|
||
const { canUpload, documentTypeId, name } = document;
|
||
|
||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||
if (event.target.files !== null) {
|
||
const file = event.target.files.item(0);
|
||
if (file)
|
||
setFormFiles([
|
||
...formFiles.filter((x) => x.documentTypeId !== documentTypeId),
|
||
{ documentTypeId, file, name },
|
||
]);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<div key={documentTypeId} className="flex flex-col gap-1">
|
||
<label className="mb-2 block text-sm font-normal text-gray-900">{name}:</label>
|
||
<InputFile onChange={handleFileChange} disabled={!canUpload} />
|
||
<DownloadDocument document={document} />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function Files({ documentTypes, documents }: Props) {
|
||
const docs = getDocs({ documentTypes, documents });
|
||
|
||
return (
|
||
<div className="grid gap-4">
|
||
<Heading className="text-sm">Документы</Heading>
|
||
<div className="grid gap-2 md:grid-cols-2">
|
||
{docs.map((document) => (
|
||
<File key={document.documentTypeId} document={document} />
|
||
))}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
type Docs = Array<IUS.Document & { canUpload: boolean }>;
|
||
|
||
function getDocs({ documentTypes, documents }: Pick<Props, 'documentTypes' | 'documents'>): Docs {
|
||
if (!documents.length) {
|
||
return documentTypes.map((x) => ({ ...x, canUpload: true }));
|
||
}
|
||
|
||
return unique(documents, ({ documentTypeId }) => documentTypeId).map((document) => ({
|
||
...document,
|
||
canUpload: documentTypes.some(
|
||
(documentType) => documentType.documentTypeId === document.documentTypeId
|
||
),
|
||
}));
|
||
}
|