BOD-25 BOD-24 Uploading to cloudinary + thumbnail generation

This commit is contained in:
Patrick Fic
2020-04-20 14:14:41 -07:00
parent d3b36776c9
commit 01e6e78c71
33 changed files with 784 additions and 540 deletions

View File

@@ -1,7 +1,7 @@
import { useMutation } from "@apollo/react-hooks";
import { notification } from "antd";
import axios from "axios";
import React, { useRef } from "react";
import { useMutation } from "@apollo/react-hooks";
import { useTranslation } from "react-i18next";
import Resizer from "react-image-file-resizer";
import { connect } from "react-redux";
@@ -11,7 +11,6 @@ import {
selectBodyshop,
selectCurrentUser,
} from "../../redux/user/user.selectors";
import { generateCdnThumb } from "../../utils/DocHelpers";
import DocumentsUploadComponent from "./documents-upload.component";
const mapStateToProps = createStructuredSelector({
@@ -21,6 +20,7 @@ const mapStateToProps = createStructuredSelector({
export function DocumentsUploadContainer({
jobId,
tagsArray,
invoiceId,
currentUser,
bodyshop,
@@ -37,10 +37,7 @@ export function DocumentsUploadContainer({
//If JPEG, resize and upload.
//TODO If this is just an invoice job? Where to put it?
let key = `${bodyshop.id}/${jobId}/${ev.file.name}`;
if (ev.file.type === "application/pdf") {
console.log("It's a PDF.");
uploadToS3(key, ev.file.type, ev.file, onError, onSuccess, onProgress);
} else {
if (ev.file.type.includes("image")) {
Resizer.imageFileResizer(
ev.file,
2500,
@@ -55,6 +52,8 @@ export function DocumentsUploadContainer({
},
"blob"
);
} else {
uploadToS3(key, ev.file.type, ev.file, onError, onSuccess, onProgress);
}
};
@@ -67,18 +66,20 @@ export function DocumentsUploadContainer({
onProgress
) => {
let timestamp = Math.floor(Date.now() / 1000);
console.log("timestamp", timestamp);
//Actually upload to cloudinary
let public_id = fileName;
let tags = `${bodyshop.textid},${
tagsArray ? tagsArray.map((tag) => `{tag},`) : ""
}`;
let eager = "w_200,h_200,c_thumb";
axios
.post("/media/upload", {
eager: "w_200,h_200,c_fill",
public_id: timestamp,
.post("/media/sign", {
eager: eager,
public_id: public_id,
tags: tags,
timestamp: timestamp,
})
.then((response) => {
var signature = response.data;
console.log("signature", signature);
var options = {
headers: { "X-Requested-With": "XMLHttpRequest" },
onUploadProgress: (e) => {
@@ -87,164 +88,76 @@ export function DocumentsUploadContainer({
};
const formData = new FormData();
formData.append("file", file);
formData.append("eager", "w_200,h_200,c_fill");
formData.append("api_key", "473322739956866");
formData.append("public_id", timestamp);
formData.append("eager", eager);
formData.append("api_key", process.env.REACT_APP_CLOUDINARY_API_KEY);
formData.append("public_id", public_id);
formData.append("tags", tags);
formData.append("timestamp", timestamp);
formData.append("signature", signature);
axios
.post(
"https://api.cloudinary.com/v1_1/bodyshop/image/upload",
`${process.env.REACT_APP_CLOUDINARY_ENDPOINT}/upload`,
formData,
options
)
.then((response) => {
console.log("response", response);
// insertNewDocument({
// variables: {
// docInput: [
// {
// jobid: jobId,
// uploaded_by: currentUser.email,
// url,
// thumb_url:
// fileType === "application/pdf"
// ? "application/pdf"
// : generateCdnThumb(fileName),
// key: fileName,
// invoiceid: invoiceId,
// },
// ],
// },
// }).then((r) => {
// onSuccess({
// uid: r.data.insert_documents.returning[0].id,
// url: r.data.insert_documents.returning[0].thumb_url,
// name: r.data.insert_documents.returning[0].name,
// status: "done",
// full_url: r.data.insert_documents.returning[0].url,
// key: r.data.insert_documents.returning[0].key,
// });
// notification["success"]({
// message: t("documents.successes.insert"),
// });
// if (callbackAfterUpload) {
// callbackAfterUpload();
// }
// console.log("ref", UploadRef.current.state.fileList);
// if (onChange) {
// //Used in a form.
// onChange(UploadRef.current.state.fileList);
// }
// });
insertNewDocument({
variables: {
docInput: [
{
jobid: jobId,
uploaded_by: currentUser.email,
url: "c",
thumb_url: "c",
key: fileName,
invoiceid: invoiceId,
type: fileType,
},
],
},
}).then((r) => {
onSuccess({
uid: r.data.insert_documents.returning[0].id,
url: r.data.insert_documents.returning[0].thumb_url,
name: r.data.insert_documents.returning[0].name,
status: "done",
full_url: r.data.insert_documents.returning[0].url,
key: r.data.insert_documents.returning[0].key,
});
notification["success"]({
message: t("documents.successes.insert"),
});
if (callbackAfterUpload) {
callbackAfterUpload();
}
if (onChange) {
//Used in a form.
onChange(UploadRef.current.state.fileList);
}
});
})
.catch((error) => console.log("error", error));
// .catch((error) => {
// onError(error);
// notification["error"]({
// message: t("documents.errors.insert", {
// message: JSON.stringify(error),
// }),
// });
// });
.catch((error) => {
onError(error);
notification["error"]({
message: t("documents.errors.insert", {
message: JSON.stringify(error),
}),
});
});
})
.catch((error) => {
console.log("error", error);
// notification["error"]({
// message: t("documents.errors.getpresignurl", {
// message: JSON.stringify(error),
// }),
// });
notification["error"]({
message: t("documents.errors.getpresignurl", {
message: JSON.stringify(error),
}),
});
});
};
// const uploadToS3 = (
// fileName,
// fileType,
// file,
// onError,
// onSuccess,
// onProgress
// ) => {
// axios
// .post("/sign_s3", {
// fileName,
// fileType,
// })
// .then((response) => {
// var returnData = response.data.data.returnData;
// var signedRequest = returnData.signedRequest;
// var url = returnData.url;
// // setState({ ...state, url: url });
// // Put the fileType in the headers for the upload
// var options = {
// headers: {
// "Content-Type": fileType,
// },
// onUploadProgress: (e) => {
// onProgress({ percent: (e.loaded / e.total) * 100 });
// },
// };
// axios
// .put(signedRequest, file, options)
// .then((response) => {
// insertNewDocument({
// variables: {
// docInput: [
// {
// jobid: jobId,
// uploaded_by: currentUser.email,
// url,
// thumb_url:
// fileType === "application/pdf"
// ? "application/pdf"
// : generateCdnThumb(fileName),
// key: fileName,
// invoiceid: invoiceId,
// },
// ],
// },
// }).then((r) => {
// onSuccess({
// uid: r.data.insert_documents.returning[0].id,
// url: r.data.insert_documents.returning[0].thumb_url,
// name: r.data.insert_documents.returning[0].name,
// status: "done",
// full_url: r.data.insert_documents.returning[0].url,
// key: r.data.insert_documents.returning[0].key,
// });
// notification["success"]({
// message: t("documents.successes.insert"),
// });
// if (callbackAfterUpload) {
// callbackAfterUpload();
// }
// console.log("ref", UploadRef.current.state.fileList);
// if (onChange) {
// //Used in a form.
// onChange(UploadRef.current.state.fileList);
// }
// });
// })
// .catch((error) => {
// onError(error);
// notification["error"]({
// message: t("documents.errors.insert", {
// message: JSON.stringify(error),
// }),
// });
// });
// })
// .catch((error) => {
// notification["error"]({
// message: t("documents.errors.getpresignurl", {
// message: JSON.stringify(error),
// }),
// });
// });
// };
return (
<DocumentsUploadComponent
handleUpload={handleUpload}

View File

@@ -1,52 +1,54 @@
import { useNProgress } from "@tanem/react-nprogress";
//import { useNProgress } from "@tanem/react-nprogress";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectLoading } from "../../redux/application/application.selectors";
const mapStateToProps = createStructuredSelector({
loading: selectLoading
loading: selectLoading,
});
export default connect(mapStateToProps, null)(GlobalLoadingHeader);
function GlobalLoadingHeader({ loading }) {
const { animationDuration, isFinished, progress } = useNProgress({
isAnimating: loading
});
return (
<div
style={{
opacity: isFinished ? 0 : 1,
pointerEvents: "none",
transition: `opacity ${animationDuration}ms linear`
}}>
<div
style={{
background: "#29d",
height: 4,
left: 0,
marginLeft: `${(-1 + progress) * 100}%`,
position: "fixed",
top: 0,
transition: `margin-left ${animationDuration}ms linear`,
width: "100%",
zIndex: 1031
}}>
<div
style={{
boxShadow: "0 0 10px #29d, 0 0 5px #29d",
display: "block",
height: "100%",
opacity: 1,
position: "absolute",
right: 0,
transform: "rotate(3deg) translate(0px, -4px)",
width: 100
}}
/>
</div>
</div>
);
return <span></span>;
// const { animationDuration, isFinished, progress } = useNProgress({
// isAnimating: loading,
// });
// return (
// <div
// style={{
// opacity: isFinished ? 0 : 1,
// pointerEvents: "none",
// transition: `opacity ${animationDuration}ms linear`,
// }}
// >
// <div
// style={{
// background: "#29d",
// height: 4,
// left: 0,
// marginLeft: `${(-1 + progress) * 100}%`,
// position: "fixed",
// top: 0,
// transition: `margin-left ${animationDuration}ms linear`,
// width: "100%",
// zIndex: 1031,
// }}
// >
// <div
// style={{
// boxShadow: "0 0 10px #29d, 0 0 5px #29d",
// display: "block",
// height: "100%",
// opacity: 1,
// position: "absolute",
// right: 0,
// transform: "rotate(3deg) translate(0px, -4px)",
// width: 100,
// }}
// />
// </div>
// </div>
// );
}

View File

@@ -24,6 +24,8 @@ const mapStateToProps = createStructuredSelector({
const mapDispatchToProps = (dispatch) => ({
setInvoiceEnterContext: (context) =>
dispatch(setModalContext({ context: context, modal: "invoiceEnter" })),
setTimeTicketContext: (context) =>
dispatch(setModalContext({ context: context, modal: "timeTicket" })),
});
function Header({
@@ -34,6 +36,7 @@ function Header({
currentUser,
signOutStart,
setInvoiceEnterContext,
setTimeTicketContext,
}) {
const { t } = useTranslation();
//TODO Add
@@ -201,6 +204,17 @@ function Header({
<Menu.Item key="invoices">
<Link to="/manage/invoices">{t("menus.header.invoices")}</Link>
</Menu.Item>
<Menu.Item
key="entertimetickets"
onClick={() => {
setTimeTicketContext({
actions: {},
context: {},
});
}}
>
{t("menus.header.entertimeticket")}
</Menu.Item>
</Menu.SubMenu>
<Menu.SubMenu title={t("menus.header.shop")}>

View File

@@ -13,7 +13,7 @@ export default function JobsDetailLaborContainer({
const { t } = useTranslation();
return (
<div>
<TimeTicketEnterButton actions={{ refetch }} context={{ jobid: jobId }}>
<TimeTicketEnterButton actions={{ refetch }} context={{ jobId: jobId }}>
{t("timetickets.actions.enter")}
</TimeTicketEnterButton>
<LaborAllocationsTableComponent

View File

@@ -0,0 +1,24 @@
import { Button, notification } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import axios from "axios";
export default function JobsDocumentsDownloadButton({ galleryImages }) {
const { t } = useTranslation();
const imagesToDownload = galleryImages.filter((image) => image.isSelected);
const handleDelete = () => {
axios
.post("/media/download", {
ids: imagesToDownload.map((_) => _.key),
})
.then((r) => {
window.open(r.data);
});
};
return (
<Button disabled={imagesToDownload.length < 1} onClick={handleDelete}>
{t("documents.actions.download")}
</Button>
);
}

View File

@@ -1,94 +1,54 @@
import axios from "axios";
import React, { useEffect, useState } from "react";
import Gallery from "react-grid-gallery";
//import { Document, Page, pdfjs } from "react-pdf";
import DocumentsUploadContainer from "../documents-upload/documents-upload.container";
//import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import { Collapse } from "antd";
import { useTranslation } from "react-i18next";
//pdfjs.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.1.266/pdf.worker.min.js`;
import JobsDocumentsDownloadButton from "./jobs-document-gallery.download.component";
import JobsDocumentsDeleteButton from "./jobs-documents-gallery.delete.component";
function JobsDocumentsComponent({ data, jobId, refetch }) {
const [galleryImages, setgalleryImages] = useState([]);
const [pdfDocuments, setPdfDocuments] = useState([]);
useEffect(() => {
setgalleryImages(
data
.filter((item) => item.thumb_url !== "application/pdf")
.reduce((acc, value) => {
acc.push({
src: value.url,
thumbnail: value.thumb_url,
thumbnailHeight: 150,
thumbnailWidth: 150,
isSelected: false,
});
return acc;
}, [])
data.reduce((acc, value) => {
acc.push({
src: value.url,
thumbnail: `${
process.env.REACT_APP_CLOUDINARY_IMAGE_ENDPOINT
}/h_200,w_200,c_thumb/${value.key}${
value.type.includes("pdf") ? ".jpg" : ""
}`,
tags: value.type.includes("pdf") ? [{ value: "PDF" }] : [],
thumbnailHeight: 200,
thumbnailWidth: 200,
isSelected: false,
key: value.key,
id: value.id,
});
return acc;
}, [])
);
}, [data, setgalleryImages]);
useEffect(() => {
setPdfDocuments(
data
.filter((item) => item.thumb_url === "application/pdf")
.reduce((acc, value) => {
acc.push({
src: value.url,
thumbnail: value.thumb_url,
thumbnailHeight: 150,
thumbnailWidth: 150,
isSelected: false,
});
return acc;
}, [])
);
}, [data, setPdfDocuments]);
const { t } = useTranslation();
return (
<div className="clearfix">
<DocumentsUploadContainer jobId={jobId} callbackAfterUpload={refetch} />
<Collapse defaultActiveKey="photos">
<Collapse.Panel key="t" header="t">
<Gallery
images={pdfDocuments}
onSelectImage={(index, image) => {
setPdfDocuments(
pdfDocuments.map((g, idx) =>
index === idx ? { ...g, isSelected: !g.isSelected } : g
)
);
}}
/>
</Collapse.Panel>
<Collapse.Panel key="photos" header={t("documents.labels.photos")}>
<Gallery
images={galleryImages}
onSelectImage={(index, image) => {
setgalleryImages(
galleryImages.map((g, idx) =>
index === idx ? { ...g, isSelected: !g.isSelected } : g
)
);
}}
></Gallery>
</Collapse.Panel>
{
// <Collapse.Panel
// key="documents"
// header={t("documents.labels.documents")}
// >
// {pdfDocuments.map((doc, idx) => (
// <Document key={idx} loading={<LoadingSpinner />} file={doc.src}>
// <Page pageIndex={0} />
// </Document>
// ))}
// </Collapse.Panel>
}
</Collapse>
<JobsDocumentsDownloadButton galleryImages={galleryImages} />
<JobsDocumentsDeleteButton
galleryImages={galleryImages}
deletionCallback={refetch}
/>
<Gallery
images={galleryImages}
onSelectImage={(index, image) => {
setgalleryImages(
galleryImages.map((g, idx) =>
index === idx ? { ...g, isSelected: !g.isSelected } : g
)
);
}}
/>
</div>
);
}

View File

@@ -0,0 +1,72 @@
import { Button, notification } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import axios from "axios";
import { useMutation } from "@apollo/react-hooks";
import { DELETE_DOCUMENT } from "../../graphql/documents.queries";
export default function JobsDocumentsDeleteButton({
galleryImages,
deletionCallback,
}) {
const { t } = useTranslation();
const [deleteDocument] = useMutation(DELETE_DOCUMENT);
const imagesToDelete = galleryImages.filter((image) => image.isSelected);
const handleDelete = () => {
imagesToDelete.forEach((image) => {
let timestamp = Math.floor(Date.now() / 1000);
let public_id = image.key;
axios
.post("/media/sign", {
public_id: public_id,
timestamp: timestamp,
})
.then((response) => {
var signature = response.data;
var options = {
headers: { "X-Requested-With": "XMLHttpRequest" },
};
const formData = new FormData();
formData.append("api_key", process.env.REACT_APP_CLOUDINARY_API_KEY);
formData.append("public_id", public_id);
formData.append("timestamp", timestamp);
formData.append("signature", signature);
axios
.post(
`${process.env.REACT_APP_CLOUDINARY_ENDPOINT}/destroy`,
formData,
options
)
.then((response) => {
deleteDocument({ variables: { id: image.id } })
.then((r) => {
if (deletionCallback) deletionCallback();
})
.catch((error) => {
notification["error"]({
message: t("documents.errors.deleting", {
message: JSON.stringify(error),
}),
});
});
//Delete it from our database.
})
.catch((error) => {
notification["error"]({
message: t("documents.errors.deleting_cloudinary", {
message: JSON.stringify(error),
}),
});
});
});
});
};
return (
<Button disabled={imagesToDelete.length < 1} onClick={handleDelete}>
{t("documents.actions.delete")}
</Button>
);
}

View File

@@ -124,15 +124,6 @@ export default function TimeTicketModalComponent({
<Input disabled />
</Form.Item>
</div>
<button
onClick={() => {
console.log(form.getFieldsValue());
}}
>
Get Them Values
</button>
<LaborAllocationsTable
joblines={lineTicketData.joblines}
timetickets={lineTicketData.timetickets}