Files
bodyshop/client/src/components/jobs-documents-gallery/jobs-document-gallery.reassign.component.jsx
2021-03-16 13:15:26 -07:00

121 lines
3.2 KiB
JavaScript

import { Button, Form, Popover, notification } from "antd";
import React, { useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import JobSearchSelect from "../job-search-select/job-search-select.component";
import { useMutation } from "@apollo/client";
import { UPDATE_DOCUMENT } from "../../graphql/documents.queries";
import axios from "axios";
export default function JobsDocumentsGalleryReassign({ galleryImages }) {
const { t } = useTranslation();
const [form] = Form.useForm();
const selectedImages = useMemo(() => {
return [
...galleryImages.images.filter((image) => image.isSelected),
...galleryImages.other.filter((image) => image.isSelected),
];
}, [galleryImages]);
const [visible, setVisible] = useState(false);
const [loading, setLoading] = useState(false);
const [updateDocument] = useMutation(UPDATE_DOCUMENT);
const updateImage = async (i, jobid) => {
//Move the cloudinary image
console.log(i);
//Update it in the database.
const result = await updateDocument({
variables: {
id: i.id,
document: {
key: i.public_id,
jobid: jobid,
},
},
});
if (!!result.errors) {
notification["error"]({
message: t("documents.errors.updating", {
message: JSON.stringify(result.errors),
}),
});
} else {
notification["success"]({
message: t("documents.successes.updated"),
});
}
};
const handleFinish = async ({ jobid }) => {
setLoading(true);
const res = await axios.post("/media/rename", {
documents: selectedImages.map((i) => {
//Need to check if the current key folder is null, or another job.
const currentKeys = i.key.split("/");
currentKeys[1] = jobid;
currentKeys.join("/");
return { id: i.id, from: i.key, to: currentKeys.join("/") };
}),
});
res.data
.filter((d) => d.error)
.forEach((d) => {
notification["error"]({ message: t("documents.errors.updating") });
console.error("Error updating job document", d);
});
const proms = [];
res.data
.filter((d) => !d.error)
.forEach((d) => {
proms.push(updateImage(d, jobid));
});
await Promise.all(proms);
setVisible(false);
setLoading(false);
};
const popContent = (
<div>
<Form onFinish={handleFinish} layout="vertical" form={form}>
<Form.Item
label={t("documents.labels.newjobid")}
style={{ width: "20rem" }}
rules={[
{
required: true,
message: t("general.validation.required"),
},
]}
name={"jobid"}
>
<JobSearchSelect />
</Form.Item>
</Form>
<Button onClick={() => form.submit()}>
{t("general.actions.submit")}
</Button>
</div>
);
return (
<Popover content={popContent} visible={visible}>
<Button
disabled={selectedImages.length < 1}
onClick={() => setVisible(true)}
loading={loading}
>
{t("documents.actions.reassign")}
</Button>
</Popover>
);
}