-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathDocumentDetails.js
484 lines (440 loc) · 22.5 KB
/
DocumentDetails.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
////////////////////////////////////////////////////////////
/*
* Addition of feature of fetching Latitude and Longitude from uploaded photo
- i have added a function (extractGeoLocation) to extract latitude and longitude from an uploaded image file.
- It takes the file object as input and returns a promise.
- Within the promise, EXIF.get() is called with the file object to extract EXIF data.
- Latitude and longitude are then retrieved from the EXIF data and converted to decimal format using the convertToDecimal function.
- If latitude and longitude are found, the promise is resolved with an object containing latitude and longitude.
Otherwise, if not found still it resolve the promise with latitude and longitude as NULL value.
- The convertToDecimal function converts GPS coordinates from degrees, minutes, and seconds format to decimal format.
- The getData function is modified to include the geolocation extraction logic.
- When files are uploaded (e?.length > 0), the function extractGeoLocation extracts geolocation if any
- If geolocation extraction is successful, it logs the latitude and longitude to the console.
- After extracting geolocation, the function continues with the existing logic to handle the uploaded files.
*/
import React, { useEffect, useMemo, useState } from "react";
import {
CardLabel,
Dropdown,
UploadFile,
Toast,
Loader,
FormStep,
MultiUploadWrapper,
CitizenInfoLabel,
SubmitBar,
SearchIcon
} from "@upyog/digit-ui-react-components";
import Timeline from "../components/Timeline";
import DocumentsPreview from "../../../templates/ApplicationDetails/components/DocumentsPreview";
import { stringReplaceAll } from "../utils";
import cloneDeep from "lodash/cloneDeep";
import EXIF from 'exif-js';
const DocumentDetails = ({ t, config, onSelect, userType, formData, setError: setFormError, clearErrors: clearFormErrors, formState, onSubmit }) => {
const stateId = Digit.ULBService.getStateId();
const tenantId = "pg.citya";
const [documents, setDocuments] = useState(formData?.documents?.documents || []);
const [error, setError] = useState(null);
const [enableSubmit, setEnableSubmit] = useState(true)
const [checkRequiredFields, setCheckRequiredFields] = useState(false);
const checkingFlow = formData?.uiFlow?.flow;
const [isNextButtonDisabled, setIsNextButtonDisabled] = useState(false);
const beforeUploadDocuments = cloneDeep(formData?.PrevStateDocuments || []);
const {data: bpaTaxDocuments, isLoading} = Digit.Hooks.obps.useBPATaxDocuments(stateId, formData, beforeUploadDocuments || []);
const handleSaveAsDraft = () => {
// Clone formData to avoid directly modifying the original object
let updatedFormData = { ...formData };
// Nest the documentStep (i.e., documents array) inside formData.documents
updatedFormData.documents = { ...formData.documents, documents };
// Construct the BPA object using only the required fields
let BPA = {
id: updatedFormData.id,
applicationNo: updatedFormData.applicationNo,
approvalNo: updatedFormData.approvalNo,
accountId: updatedFormData.accountId,
edcrNumber: updatedFormData.edcrNumber,
riskType: updatedFormData.riskType,
businessService: updatedFormData.businessService,
landId: updatedFormData.landId,
tenantId: updatedFormData.tenantId,
approvalDate: updatedFormData.approvalDate,
applicationDate: updatedFormData.applicationDate,
status: updatedFormData.status,
documents: updatedFormData.documents.documents, // Include only necessary document details
landInfo: {
...updatedFormData.landInfo,
address: {
...updatedFormData.landInfo?.address,
city: updatedFormData.landInfo?.address?.city?.code, // Ensure city is a string
},
owners: updatedFormData.landInfo?.owners.map(owner => ({
...owner,
gender: owner.gender?.code // Ensure gender is a string
})),
unit: updatedFormData.landInfo?.unit.map(unit => ({
id: unit.id,
floorNo: unit.floorNo,
unitType: unit.unitType,
blockIndex: unit.blockIndex,
usageCategory: unit.usageCategory,
occupancyType: unit.occupancyType // Only necessary fields
})),
},
assignee: updatedFormData.assignee || [], // Assuming this can be an empty array
workflow: {
action: "SAVE_AS_DRAFT", // Always set action as SAVE_AS_DRAFT
assignes: null,
comments: null,
varificationDocuments: null
},
auditDetails: updatedFormData.auditDetails,
additionalDetails: updatedFormData.additionalDetails,
applicationType: "BUILDING_PLAN_SCRUTINY",
serviceType: "NEW_CONSTRUCTION",
occupancyType: "A"
};
// Call the update service to save as draft
Digit.OBPSService.update({ BPA }, tenantId)
.then(response => {
console.log("Draft saved successfully", response);
})
.catch(error => {
console.error("Error saving draft", error);
});
};
const handleSubmit = () => {
let document = formData.documents;
let documentStep;
let RealignedDocument = [];
bpaTaxDocuments && bpaTaxDocuments.map((ob) => {
documents && documents.filter(x => ob.code === stringReplaceAll(x?.additionalDetails.category,"_",".")).map((doc) => {
RealignedDocument.push(doc);
})
})
documentStep = { ...document, documents: RealignedDocument };
onSelect(config.key, documentStep);
};
const onSkip = () => onSelect();
function onAdd() { }
useEffect(() => {
const allRequiredDocumentsCode = bpaTaxDocuments.filter( e => e.required).map(e => e.code)
const reqDocumentEntered = allRequiredDocumentsCode.filter(reqCode => documents.reduce((acc,doc) => {
if (reqCode == `${doc?.documentType?.split('.')?.[0]}.${doc?.documentType?.split('.')?.[1]}`) {
return true
}
else{
return acc
}
}, false))
if ((reqDocumentEntered.length == allRequiredDocumentsCode.length ) && documents.length > 0) {
setEnableSubmit(false);
}else {
setEnableSubmit(true);
}
}, [documents, checkRequiredFields])
return (
<div>
<Timeline currentStep={checkingFlow === "OCBPA" ? 3 : 3} flow= {checkingFlow === "OCBPA" ? "OCBPA" : ""}/>
{!isLoading ?
<FormStep
t={t}
config={config}
onSelect={handleSubmit}
onSkip={onSkip}
// isDisabled={window.location.href.includes("editApplication")||window.location.href.includes("sendbacktocitizen")?false:enableSubmit}
isDisabled={(window.location.href.includes("editApplication") || window.location.href.includes("sendbacktocitizen") ? false : enableSubmit) || isNextButtonDisabled}
onAdd={onAdd}
>
{/* {bpaTaxDocuments?.map((document, index) => { */}
{bpaTaxDocuments?.filter(document => document.code !== "ARCHITECT.UNDERTAKING" && document.code !== "CITIZEN.UNDERTAKING").map((document, index) => {
return (
<div style={{ background: "#FAFAFA", border: "1px solid #D6D5D4", padding: "8px", borderRadius: "4px", maxWidth:"600px", minWidth: "280px", marginBottom:"15px", paddingTop:"15px" }}>
<SelectDocument
key={index}
document={document}
t={t}
error={error}
setError={setError}
setDocuments={setDocuments}
documents={documents}
setCheckRequiredFields={setCheckRequiredFields}
formData={formData}
beforeUploadDocuments={beforeUploadDocuments || []}
isNextButtonDisabled={isNextButtonDisabled}
setIsNextButtonDisabled={setIsNextButtonDisabled}
/>
</div>
);
})}
{error && <Toast label={error} onClose={() => setError(null)} error />}
{/*Adding Save As Draft Button */}
{/* <SubmitBar
label={t("BPA_SAVE_AS_DRAFT")}
onSubmit={handleSaveAsDraft}
disabled={enableSubmit}
/> */}
<br></br>
</FormStep>: <Loader />}
{(window.location.href.includes("/bpa/building_plan_scrutiny/new_construction") || window.location.href.includes("/ocbpa/building_oc_plan_scrutiny/new_construction")) && formData?.applicationNo ? <CitizenInfoLabel info={t("CS_FILE_APPLICATION_INFO_LABEL")} text={`${t("BPA_APPLICATION_NUMBER_LABEL")} ${formData?.applicationNo} ${t("BPA_DOCS_INFORMATION")}`} className={"info-banner-wrap-citizen-override"} /> : ""}
</div>
);
}
const SelectDocument = React.memo(function MyComponent({
t,
document: doc,
setDocuments,
error,
setError,
documents,
setCheckRequiredFields,
formData,
beforeUploadDocuments,
setIsNextButtonDisabled // Add this line
}) {
const filteredDocument = documents?.filter((item) => item?.documentType?.includes(doc?.code))[0] || beforeUploadDocuments?.filter((item) => item?.documentType?.includes(doc?.code))[0];
const tenantId = Digit.ULBService.getStateId(); //Digit.ULBService.getCurrentTenantId();
const [selectedDocument, setSelectedDocument] = useState(
filteredDocument
? { ...filteredDocument, active: true, code: filteredDocument?.documentType, i18nKey: filteredDocument?.documentType }
: doc?.dropdownData?.length > 0
? doc?.dropdownData[0]
: {}
);
const [file, setFile] = useState(null);
const [uploadedFile, setUploadedFile] = useState(() => documents?.filter((item) => item?.documentType?.includes(doc?.code)).map( e => ({fileStoreId: e?.fileStoreId, fileName: e?.fileName || ""}) ) || null);
const [newArray, setnewArray ] = useState([]);
const [uploadedfileArray, setuploadedfileArray] = useState([]);
const [fileArray, setfileArray] = useState([] || formData?.documents?.documents.filter((ob) => ob.documentType === selectedDocument.code) );
const [latitude, setLatitude] = useState(null);
const [longitude, setLongitude] = useState(null);
function extractGeoLocation(file) {
return new Promise((resolve) => {
EXIF.getData(file, function() {
const lat = EXIF.getTag(this, 'GPSLatitude');
const lon = EXIF.getTag(this, 'GPSLongitude');
if (lat && lon) {
// Convert GPS coordinates to decimal format
const latDecimal = convertToDecimal(lat);
const lonDecimal = convertToDecimal(lon);
resolve({ latitude: latDecimal, longitude: lonDecimal });
} else {
resolve({ latitude: null, longitude: null });
if (doc?.code === "SITEPHOTOGRAPH.ONE")
{
{alert("Please Upload a Photo with Location Details")}
}
else{null}
}
});
});
}
function convertToDecimal(coordinate) {
const degrees = coordinate[0];
const minutes = coordinate[1];
const seconds = coordinate[2];
return degrees + minutes / 60 + seconds / 3600;
}
const handleSelectDocument = (value) => {
if(filteredDocument?.documentType){
filteredDocument.documentType=value?.code;
let currDocs=documents?.filter((item) => item?.documentType?.includes(doc?.code));
currDocs.map(doc=>doc.documentType=value?.code);
let newDoc=[ ...documents?.filter((item) => !item?.documentType?.includes(doc?.code)),...currDocs]
setDocuments(newDoc);
}
setSelectedDocument(value);
};
function selectfile(e, key) {
e && setFile(e.file);
e && setfileArray([...fileArray,e.file]);
}
function getData(e) {
let key = selectedDocument.code;
let data, newArr;
if (e?.length > 0) {
// Extract geo location from the first file
extractGeoLocation(e[0][1].file)
.then(location => {
console.log('Latitude:', location.latitude);
console.log('Longitude:', location.longitude);
setLatitude(location.latitude);
setLongitude(location.longitude);
{if (doc?.code === "SITEPHOTOGRAPH.ONE"){
if(location.latitude !==null && location.longitude !==null){
sessionStorage.setItem("Latitude",location.latitude)
sessionStorage.setItem("Longitude",location.longitude)
}
else{
sessionStorage.removeItem("Latitude");
sessionStorage.removeItem("Longitude");
}
}}
// Continue with your existing codezz
data = Object.fromEntries(e);
newArr = Object.values(data);
newArr = formData?.documents?.documents?.filter((ob) => ob.documentType === selectedDocument.code);
setnewArray(newArr);
// const filteredDocumentsByFileStoreId = documents?.filter((item) => item?.fileStoreId !== uploadedFile.fileStoreId) || []
let newfiles = [];
e?.map((doc, index) => {
newfiles.push({
documentType: selectedDocument?.code,
fileName: doc?.[0] || "",
additionalDetails:{category:selectedDocument?.code.split(".").slice(0,2).join('_'),
latitude: location.latitude,
longitude: location.longitude,
},
fileStoreId: doc?.[1]?.fileStoreId?.fileStoreId,
documentUid: doc?.[1].fileStoreId?.fileStoreId,
fileName: doc?.[0] || "",
id: documents ? documents.find(x => x.documentType === selectedDocument?.code)?.id : undefined,
})
})
const __documents = [
...documents.filter(e => e.documentType !== key),
...newfiles,
]
setDocuments(__documents);
newArr?.map((ob) => {
if (!ob?.file) {
ob.file = {}
}
ob.file.documentType = key;
selectfile(ob, key);
});
})
.catch(error => {
console.error('Error extracting geo location:', error);
// Handle error if needed
});
// Rest of your code...
} else if (e?.length == 0) {
const __documents = [
...documents.filter(e => e.documentType !== key),
]
setDocuments(__documents);
}
}
function setcodeafterupload(){
if (selectedDocument?.code) {
setDocuments((prev) => {
//const filteredDocumentsByDocumentType = prev?.filter((item) => item?.documentType !== selectedDocument?.code);
if (uploadedFile === null || uploadedFile?.fileStoreId === undefined || uploadedFile?.fileStoreId === null) {
return prev;
}
const filteredDocumentsByFileStoreId = prev?.filter((item) => item?.fileStoreId !== uploadedFile.fileStoreId);
let newfiles = [];
uploadedfileArray && uploadedfileArray.map((doc, index) => {
newfiles.push({
documentType: selectedDocument?.code,
fileStoreId: doc.fileStoreId,
fileName: fileArray[index]?.name || "",
additionalDetails:{category:selectedDocument?.code.split(".").slice(0,2).join('_'),
latitude: latitude,
longitude: longitude,
},
documentUid: doc.fileStoreId,
fileName: fileArray[index]?.name || "",
id:documents? documents.find(x => x.documentType === selectedDocument?.code)?.id:undefined,
})
})
return [
...filteredDocumentsByFileStoreId,
...newfiles,
];
});
setuploadedfileArray([]);
}
}
useEffect(() => {
uploadedfileArray.length>0 && setcodeafterupload();
if (selectedDocument?.code) {
setDocuments((prev) => {
//const filteredDocumentsByDocumentType = prev?.filter((item) => item?.documentType !== selectedDocument?.code);
if (uploadedFile === null|| uploadedFile?.fileStoreId === undefined || uploadedFile?.fileStoreId === null) {
if (prev?.length > 0) {
prev?.forEach(data => {
const normalDocumentType = `${data?.documentType?.split('.')[0]}.${data?.documentType?.split('.')[1]}`;
const selectedDocumentType = `${selectedDocument?.code?.split('.')[0]}.${selectedDocument?.code?.split('.')[1]}`;
if (normalDocumentType == selectedDocumentType) {
if (data?.documentType) data.documentType = selectedDocument?.code;
if (data?.file?.documentType) data.file.documentType = selectedDocument?.code;
}
});
}
return prev;
}
const filteredDocumentsByFileStoreId = prev?.filter((item) => item?.fileStoreId !== uploadedFile.fileStoreId);
return [
...filteredDocumentsByFileStoreId,
{
documentType: selectedDocument?.code,
fileStoreId: uploadedFile.fileStoreId,
documentUid: uploadedFile.fileStoreId,
fileName: file?.name ||uploadedFile.fileName || "document",
id:documents? documents.find(x => x.documentType === selectedDocument?.code)?.id:undefined,
},
];
});
}
}, [uploadedFile, selectedDocument]);
useEffect(() => {
if(!selectedDocument.code && uploadedFile!== null)
setuploadedfileArray([...uploadedfileArray,uploadedFile])
},[uploadedFile]);
const allowedFileTypes = /(.*?)(jpg|jpeg|png|image|pdf)$/i;
const uploadedFilesPreFill = useMemo(()=>{
let selectedUplDocs=[];
formData?.documents?.documents?.filter((ob) => ob.documentType === selectedDocument.code).forEach(e =>
selectedUplDocs.push([e.fileName, {file: {name: e.fileName, type: e.documentType}, fileStoreId: {fileStoreId: e.fileStoreId, tenantId}}])
)
return selectedUplDocs;
},[formData])
return (
<div /* style={{ marginBottom: "24px" }} */>
<CardLabel>{doc?.required ? `${t(doc?.code)} *` : `${t(doc?.code)}`}</CardLabel>
<Dropdown
t={t}
isMandatory={false}
option={Digit.Utils.locale.sortDropdownNames(doc?.dropdownData,'i18nKey',t)}
selected={selectedDocument}
optionKey="i18nKey"
select={handleSelectDocument}
/>
<MultiUploadWrapper
module="BPA"
tenantId={tenantId}
getFormState={getData}
setuploadedstate={uploadedFilesPreFill}
t={t}
extraStyleName={"OBPS"}
allowedFileTypesRegex={allowedFileTypes}
allowedMaxSizeInMB={10}
acceptFiles= "image/*, .pdf, .png, .jpeg, .jpg"
/>
{doc?.uploadedDocuments?.length && <DocumentsPreview isSendBackFlow={true} documents={doc?.uploadedDocuments} />}
{doc?.code === "SITEPHOTOGRAPH.ONE" && (
sessionStorage.getItem("Latitude") && sessionStorage.getItem("Longitude") ? (
<div>
<p>Latitude: {sessionStorage.getItem("Latitude")}</p>
<p>Longitude: {sessionStorage.getItem("Longitude")}</p>
<div
style={{ position: "relative", zIndex: "100", right: "-500px", marginTop: "-24px", marginRight: "20px", cursor: "pointer" }}
onClick={() => window.open(`http://maps.google.com/maps?q=${sessionStorage.getItem("Latitude")},${sessionStorage.getItem("Longitude")}`, '_blank')}
>
<SearchIcon />
</div>
{setIsNextButtonDisabled(false)} {/* Enable the "Next" button */}
</div>
) : (
<div>
<p style={{ color: 'red' }}>Please upload a Photo with Location details.</p>
{setIsNextButtonDisabled(true)} {/* Disable the "Next" button */}
</div>
)
)}
</div>
);
});
export default DocumentDetails;