BOD-24 WIP for document previews for non images. Random cleanup included. #comment Current design for document previews may be bandwidth intensive. Proceeding with design to get v1 completed.

This commit is contained in:
Patrick Fic
2020-03-17 16:50:21 -07:00
parent 5f7284d3a0
commit ec53663a1d
32 changed files with 491 additions and 384 deletions

View File

@@ -0,0 +1,19 @@
import { UploadOutlined } from "@ant-design/icons";
import { Button, Upload } from "antd";
import React from "react";
export default function DocumentsUploadComponent({ handleUpload }) {
return (
<div>
<Upload
multiple={true}
customRequest={handleUpload}
accept="audio/*,video/*,image/*"
>
<Button>
<UploadOutlined /> Click to Upload
</Button>
</Upload>
</div>
);
}

View File

@@ -0,0 +1,143 @@
import { notification } from "antd";
import axios from "axios";
import React from "react";
import { useMutation } from "react-apollo";
import { useTranslation } from "react-i18next";
import Resizer from "react-image-file-resizer";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_NEW_DOCUMENT } from "../../graphql/documents.queries";
import {
selectBodyshop,
selectCurrentUser
} from "../../redux/user/user.selectors";
import { generateCdnThumb } from "../../utils/DocHelpers";
import DocumentsUploadComponent from "./documents-upload.component";
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
bodyshop: selectBodyshop
});
export default connect(
mapStateToProps,
null
)(function DocumentsUploadContainer({
jobId,
invoiceId,
currentUser,
bodyshop,
callbackAfterUpload
}) {
const { t } = useTranslation();
const [insertNewDocument] = useMutation(INSERT_NEW_DOCUMENT);
const handleUpload = ev => {
const { onError, onSuccess, onProgress } = ev;
//If PDF, upload directly.
//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 {
Resizer.imageFileResizer(
ev.file,
3000,
3000,
"PNG",
75,
0,
uri => {
let file = new File([uri], ev.file.name, {});
file.uid = ev.file.uid;
uploadToS3(key, file.type, file, onError, onSuccess, onProgress);
},
"blob"
);
}
};
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();
}
});
})
.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

@@ -41,7 +41,7 @@ export default function InvoiceEnterModalComponent({
}
width={"90%"}
visible={visible}
okText={t("general.labels.save")}
okText={t("general.actions.save")}
onOk={() => form.submit()}
okButtonProps={{ htmlType: "submit" }}
onCancel={handleCancel}

View File

@@ -30,7 +30,7 @@ export default function JobLinesUpsertModalComponent({
: t("joblines.labels.new")
}
visible={visible}
okText={t("general.labels.save")}
okText={t("general.actions.save")}
onOk={() => form.submit()}
onCancel={handleCancel}
>

View File

@@ -86,7 +86,7 @@ export default connect(
{t("jobs.actions.convert")}
</Button>,
<Button type="primary" key="submit" htmlType="submit">
{t("general.labels.save")}
{t("general.actions.save")}
</Button>
];

View File

@@ -0,0 +1,104 @@
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`;
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, 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} />
<button
onClick={() => {
axios
.get("/downloadImages", {
images: galleryImages.map(i => i.src)
})
.then(r => console.log("r", r));
}}
>
Dl
</button>
<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>
</div>
);
}
export default JobsDocumentsComponent;

View File

@@ -0,0 +1,18 @@
import React from "react";
import { useQuery } from "react-apollo";
import { GET_DOCUMENTS_BY_JOB } from "../../graphql/documents.queries";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobDocuments from "./jobs-documents-gallery.component";
export default function JobsDocumentsContainer({ jobId }) {
const { loading, error, data, refetch } = useQuery(GET_DOCUMENTS_BY_JOB, {
variables: { jobId: jobId },
fetchPolicy: "network-only"
});
if (loading) return <LoadingSpinner />;
if (error) return <AlertComponent type="error" message={error.message} />;
return <JobDocuments data={data.documents} jobId={jobId} refetch={refetch} />;
}

View File

@@ -1,289 +0,0 @@
import { InboxOutlined } from "@ant-design/icons";
import { Modal, notification, Upload } from "antd";
import axios from "axios";
import React, { useState } from "react";
import { useMutation } from "react-apollo";
import Gallery from "react-grid-gallery";
import { useTranslation } from "react-i18next";
import Resizer from "react-image-file-resizer";
import {
DELETE_DOCUMENT,
INSERT_NEW_DOCUMENT
} from "../../graphql/documents.queries";
import { generateCdnThumb } from "../../utils/DocHelpers";
import "./jobs-documents.styles.scss";
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
function JobsDocumentsComponent({ shopId, jobId, loading, data, currentUser }) {
const { t } = useTranslation();
const [insertNewDocument] = useMutation(INSERT_NEW_DOCUMENT);
const [deleteDocument] = useMutation(DELETE_DOCUMENT);
const [state, setState] = useState({
previewVisible: false,
previewImage: ""
});
const [fileList, setFileList] = useState(
data.reduce((acc, value) => {
acc.push({
uid: value.id,
url: value.thumb_url,
name: value.name,
status: "done",
full_url: value.url,
key: value.key
});
return acc;
}, [])
);
const [galleryImages, setgalleryImages] = useState(
data.reduce((acc, value) => {
acc.push({
src: value.url,
thumbnail: value.thumb_url,
thumbnailHeight: 150,
thumbnailWidth: 150,
isSelected: false
});
return acc;
}, [])
);
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 => {
console.log("response from axios", response);
insertNewDocument({
variables: {
docInput: [
{
jobid: jobId,
uploaded_by: currentUser.email,
url,
thumb_url: generateCdnThumb(fileName),
key: fileName
}
]
}
}).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")
});
});
setState({ ...state, success: true });
})
.catch(error => {
console.log("Error uploading to S3", error);
onError(error);
notification["error"]({
message: t("documents.errors.insert") + JSON.stringify(error)
});
});
})
.catch(error => {
console.log("Outside Error here.", error);
notification["error"]({
message: t("documents.errors.getpresignurl") + JSON.stringify(error)
});
});
};
const handleUpload = ev => {
const { onError, onSuccess, onProgress } = ev;
//If PDF, upload directly.
//If JPEG, resize and upload.
let key = `${shopId}/${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 {
Resizer.imageFileResizer(
ev.file,
3000,
3000,
"JPEG",
75,
0,
uri => {
let file = new File([uri], ev.file.name, {});
file.uid = ev.file.uid;
uploadToS3(key, file.type, file, onError, onSuccess, onProgress);
},
"blob"
);
}
};
const handleCancel = () => setState({ ...state, previewVisible: false });
const handlePreview = async file => {
if (!file.full_url && !file.url) {
file.preview = await getBase64(file.originFileObj);
}
setState({
...state,
previewImage: file.full_url || file.url,
previewVisible: true
});
};
const handleChange = props => {
const { event, fileList, file } = props;
//Required to ensure that the state accurately reflects new data and that images can be deleted in feeded.
if (!event) {
//SPread the new file in where the old one was.
const newFileList = fileList.map(i =>
i.uid === file.uid ? Object.assign({}, i, file.response) : i
);
setFileList(newFileList);
} else {
setFileList(fileList);
}
};
const { previewVisible, previewImage } = state;
const handleRemove = file => {
console.log("file", file);
//Remove the file on S3
axios
.post("/delete_s3", { fileName: file.key })
.then(response => {
//Delete the record in our database.
if (response.status === 200) {
deleteDocument({ variables: { id: file.uid } }).then(r => {
notification["success"]({
message: t("documents.successes.delete")
});
});
} else {
notification["error"]({
message:
1 +
t("documents.errors.deletes3") +
JSON.stringify(response.message)
});
}
})
.catch(error => {
notification["error"]({
message: "2" + t("documents.errors.deletes3") + JSON.stringify(error)
});
});
};
return (
<div className="clearfix">
<button
onClick={() => {
const imageRequest = JSON.stringify({
bucket: process.env.REACT_APP_S3_BUCKET,
key:
"52b7357c-0edd-4c95-85c3-dfdbcdfad9ac/c8ca5761-681a-4bb3-ab76-34c447357be3/Invoice_353284489.pdf",
edits: { format: "jpeg" }
});
const CloudFrontUrl = "https://d18fc493a0fm4o.cloudfront.net";
const url = `${CloudFrontUrl}/${btoa(imageRequest)}`;
console.log("url", url);
}}
>
Test PDF
</button>
<Upload.Dragger
customRequest={handleUpload}
accept=".pdf,.jpg,.jpeg"
listType="picture-card"
fileList={fileList}
multiple={true}
onPreview={handlePreview}
onRemove={handleRemove}
onChange={handleChange}
>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">
Click or drag file to this area to upload
</p>
<p className="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading
company data or other band files
</p>
</Upload.Dragger>
<Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
<img alt="example" style={{ width: "100%" }} src={previewImage} />
</Modal>
<button
onClick={() => {
axios
.get("/downloadImages", {
images: galleryImages.map(i => i.src)
})
.then(r => console.log("r", r));
}}
>
Dl
</button>
<Gallery
images={galleryImages}
onSelectImage={(index, image) => {
console.log("index, image", index, image);
setgalleryImages(
galleryImages.map((g, idx) =>
index === idx ? { ...g, isSelected: !g.isSelected } : g
)
);
}}
></Gallery>
</div>
);
}
export default JobsDocumentsComponent;

View File

@@ -1,48 +0,0 @@
import React from "react";
import { useQuery } from "react-apollo";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_SHOP_ID } from "../../graphql/bodyshop.queries";
import { GET_DOCUMENTS_BY_JOB } from "../../graphql/documents.queries";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobDocuments from "./jobs-documents.component";
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser
});
export default connect(
mapStateToProps,
null
)(function JobsDocumentsContainer({ jobId, currentUser }) {
const { loading, error, data } = useQuery(GET_DOCUMENTS_BY_JOB, {
variables: { jobId: jobId },
fetchPolicy: "network-only"
});
const shopData = useQuery(QUERY_SHOP_ID, {
fetchPolicy: "network-only"
});
if (loading || shopData.loading) return <LoadingSpinner />;
if (error || shopData.error)
return (
<AlertComponent
type="error"
message={error.message || shopData.error.message}
/>
);
return (
<JobDocuments
data={data.documents}
jobId={jobId}
currentUser={currentUser}
shopId={
shopData.data.bodyshops[0].id ? shopData.data.bodyshops[0].id : "error"
}
/>
);
});

View File

@@ -16,7 +16,7 @@ export default function NoteUpsertModalComponent({
<Modal
title={noteState.id ? t("notes.actions.edit") : t("notes.actions.new")}
visible={visible}
okText={t("general.labels.save")}
okText={t("general.actions.save")}
onOk={() => {
noteState.id ? updateExistingNote() : insertNewNote();
}}

View File

@@ -16,7 +16,7 @@ export default function OwnerDetailFormComponent({ form }) {
<ResetForm resetFields={resetFields} />
) : null}
<Button type="primary" key="submit" htmlType="submit">
{t("general.labels.save")}
{t("general.actions.save")}
</Button>
<Row>
<Col span={8}>

View File

@@ -7,7 +7,7 @@ export default function VehicleDetailFormComponent() {
return (
<div>
<Button type="primary" key="submit" htmlType="submit">
{t("general.labels.save")}
{t("general.actions.save")}
</Button>
<Row>
<Col span={8}>