2023-05-06 16:08:21 +10:00
|
|
|
import { ChangeEvent } from "react";
|
2023-01-25 10:50:58 +01:00
|
|
|
import router from "next/router";
|
|
|
|
|
import { NEXT_PUBLIC_WEBAPP_URL } from "../lib/constants";
|
2023-04-04 22:02:32 +00:00
|
|
|
import toast from "react-hot-toast";
|
2023-01-25 10:50:58 +01:00
|
|
|
|
2023-04-21 21:51:20 +10:00
|
|
|
export const uploadDocument = async (event: ChangeEvent) => {
|
|
|
|
|
if (event.target instanceof HTMLInputElement && event.target?.files && event.target.files[0]) {
|
2023-01-25 10:50:58 +01:00
|
|
|
const body = new FormData();
|
|
|
|
|
const document = event.target.files[0];
|
2023-03-27 12:58:17 +02:00
|
|
|
const fileName: string = event.target.files[0].name;
|
|
|
|
|
|
|
|
|
|
if (!fileName.endsWith(".pdf")) {
|
|
|
|
|
toast.error("Non-PDF documents are not supported yet.");
|
|
|
|
|
return;
|
|
|
|
|
}
|
2023-04-21 21:51:20 +10:00
|
|
|
|
2023-01-25 10:50:58 +01:00
|
|
|
body.append("document", document || "");
|
2023-04-21 21:51:20 +10:00
|
|
|
|
2023-05-06 16:08:21 +10:00
|
|
|
await toast.promise(
|
|
|
|
|
fetch("/api/documents", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
body,
|
|
|
|
|
}).then((response: Response) => {
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error("Could not upload document");
|
2023-01-25 10:50:58 +01:00
|
|
|
}
|
2023-05-06 16:08:21 +10:00
|
|
|
|
2023-01-25 10:50:58 +01:00
|
|
|
response.json().then((createdDocumentIdFromBody) => {
|
2023-04-04 22:10:30 +00:00
|
|
|
router.push(
|
|
|
|
|
`${NEXT_PUBLIC_WEBAPP_URL}/documents/${createdDocumentIdFromBody}/recipients`
|
|
|
|
|
);
|
2023-01-25 10:50:58 +01:00
|
|
|
});
|
2023-05-06 16:08:21 +10:00
|
|
|
}),
|
|
|
|
|
{
|
|
|
|
|
loading: "Uploading document...",
|
|
|
|
|
success: `${fileName} uploaded successfully.`,
|
|
|
|
|
error: "Could not upload document :/",
|
|
|
|
|
}
|
|
|
|
|
).catch((_err) => {
|
|
|
|
|
// Do nothing
|
|
|
|
|
});
|
2023-01-25 10:50:58 +01:00
|
|
|
}
|
|
|
|
|
};
|