Untitled
unknown
typescript
a year ago
18 kB
6
Indexable
"use client";
import MainLayout from "@/components/HOC/layout/MainLayout";
import React, { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import Image from "next/image";
import axios from "axios";
import { apiEndpoint } from "@/app/api/config";
import Cookies from "js-cookie";
import CheckboxItem from "@/components/Button/CheckBox";
export default function CCTVCertificatePage() {
const [selectedFile, setSelectedFile] = useState<any | null>(null);
const [company, setCompany] = useState<any>(null);
const [businessUnits, setBusinessUnits] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [uploadSuccess, setUploadSuccess] = useState<any | null>(null);
const [uploadedData, setUploadedData] = useState<any>(null);
const [companyDocuments, setCompanyDocuments] = useState<any[]>([]);
const [documentsLicense, setDocumentsLicense] = useState<any[]>([]);
const [business, setBusiness] = useState<any>(null);
const [companies, setCompanies] = useState<any[]>([]);
const [userName, setUserName] = useState<string | null>(null);
const [documentsLicenseNumber, setDocumentsLicenseNumber] = useState<any>();
const [mostRecentLicense, setMostRecentLicense] = useState<any>(null);
const [sampleMonitoringFile, setSampleMonitoringFile] = useState<File | null>(null);
const [attachedFileUrl, setAttachedFileUrl] = useState<string | null>(null);
const handleView = (idDoc: any) => {
router.push(`/business/cctv-certificate/${id}/detail/${idDoc}`);
};
const router = useRouter();
const { id } = useParams();
const [todo, setTodo] = useState<{
device_installed: boolean;
license_acquired: boolean;
sample_recording: boolean;
register_to_police_station: boolean;
}>({
device_installed: false,
license_acquired: false,
sample_recording: false,
register_to_police_station: false
});
useEffect(() => {
const fetchBusinessDetails = async () => {
try {
const userId = Cookies.get("authUserId");
const storedUserName = Cookies.get("authUserName");
if (!userId || !storedUserName) {
router.push("/login");
return;
}
setUserName(storedUserName);
const companiesResponse = await axios.get(
`${apiEndpoint}/api/companies?owner_id=${userId}`
);
const fetchedCompanies = companiesResponse.data.data;
setCompanies(fetchedCompanies);
const businessResponse = await axios.get(
`${apiEndpoint}/api/business_units/${id}`
);
const fetchedBusinesses = businessResponse.data.data;
setBusiness(fetchedBusinesses);
const documentsResponseChamber = await axios.get(
`${apiEndpoint}/api/business_units/${id}/documents?type=cctv_certificate`
);
const fetchedDocumentsChamber = documentsResponseChamber.data.data;
const transformedDocuments = fetchedDocumentsChamber.map(
(doc: any) => ({
...doc,
data:
typeof doc.data === "string" ? JSON.parse(doc.data) : doc.data,
remind_at: null,
expired_at: null,
created_at: "2024-08-26T01:47:09.129Z",
updated_at: "2024-09-02T06:51:21.111Z",
})
);
setDocumentsLicense(transformedDocuments);
if (transformedDocuments.length > 0) {
setMostRecentLicense(transformedDocuments[0]);
if (transformedDocuments[0].data && transformedDocuments[0].data.todo) {
setTodo(transformedDocuments[0].data.todo);
}
}
} catch (error) {
setError("Failed to fetch business details.");
console.error("Error fetching business details:", error);
} finally {
setLoading(false);
}
};
if (id) {
fetchBusinessDetails();
}
}, [id]);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
setSelectedFile(file);
}
};
const handleTodoChange = (key: keyof typeof todo) => {
setTodo(prevTodo => ({
...prevTodo,
[key]: !prevTodo[key]
}));
};
const handleSampleMonitoringFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
setSampleMonitoringFile(file);
}
};
const handleSampleMonitoringUpload = async () => {
if (!sampleMonitoringFile) return;
setUploading(true);
setUploadError(null);
const formData = new FormData();
formData.append('file', sampleMonitoringFile);
try {
const response = await axios.post(
`${apiEndpoint}/api/business_units/${id}/documents/${mostRecentLicense.id}/attach`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
);
setUploadSuccess(true);
setSampleMonitoringFile(null);
if (response.data.attach && response.data.attach.length > 0) {
setAttachedFileUrl(response.data.attach[0].url);
} else {
console.warn('No attached file URL found in the response');
}
} catch (error) {
setUploadError('Failed to upload sample monitoring file.');
console.error('Error uploading sample monitoring file:', error);
} finally {
setUploading(false);
}
};
const handleViewDetail = () => {
router.push(`/business/cctv-certificate/${id}/detail/${documentsLicenseNumber.id}`);
};
const handleUpload = async () => {
router.push(`/business/cctv-certificate/upload/${id}`);
};
const handleRemove = () => {
const fileInput = document.getElementById(
"dropzone-file"
) as HTMLInputElement;
if (fileInput) {
fileInput.value = "";
}
setSelectedFile(null);
setUploadSuccess(false);
setUploadError(null);
};
const getIconForFile = (url: string | null) => {
if (!url) return "/images/Internet.png";
const lowerUrl = url.toLowerCase();
if (lowerUrl.includes(".pdf")) {
return "/images/PdfImage.png";
} else if (lowerUrl.includes(".png"), (".jpg"), (".jpeg")) {
return "/images/Doc.png";
} else {
return "/images/Internet.png";
}
};
if (loading) {
return (
<MainLayout>
<div className="flex justify-center items-center min-h-screen">
<p className="text-blue-500">Loading...</p>
</div>
</MainLayout>
);
}
if (error) {
return (
<MainLayout>
<div className="flex justify-center items-center min-h-screen">
<p className="text-red-500">{error}</p>
</div>
</MainLayout>
);
}
return (
<MainLayout>
<div className="border-solid bg-white p-8 rounded-xl border-2 relative">
<h3 className="text-base text-gray-400 mb-2">Latest update</h3>
<div className="flex">
<Image
className="h-20 w-20 rounded-xl bg-white border-solid border-2"
src="/images/Police.png"
alt="Company Profile"
width={200}
height={200}
/>
<div className="ml-6 mt-4">
{mostRecentLicense ? (
<ul className="space-y-4">
<div className="flex justify-between space-x-8">
<li>
<h2 className="text-gray-400 text-sm">License Number</h2>
<h2 className="text-gray-700 font-bold text-lg">
{mostRecentLicense.data.license_number || "-"}
</h2>
</li>
</div>
</ul>
) : (
<li className="mb-5">
<h2>-</h2>
</li>
)}
</div>
</div>
<h1 className="text-black text-2xl font-bold py-4">
CCTV Certificate
</h1>
<div onClick={handleViewDetail} className="absolute cursor-pointer right-4 top-4 mb-4 flex justify-center items-center w-20 h-8 border-2 border-solid border-gray-400 bg-white rounded-full ">
<h2 className="text-gray-400 text-xs">Detail</h2>
</div>
<div className="flex flex-col items-center w-full ">
<div
className="flex flex-col items-center justify-center w-full h-20 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50"
onClick={handleUpload}
>
<div className="flex space-x-2 text-center items-center justify-center pt-5 pb-6">
{selectedFile ? (
selectedFile ? (
<p className="text-lg font-semibold mt-2 text-gray-500">
{selectedFile.name}
</p>
) : (
<p className="text-lg font-semibold mt-2 text-gray-500">
Unsupported file type
</p>
)
) : (
<>
<Image
className=" min-w-fit"
src="/images/add.png"
alt="Upload"
width={30}
height={30}
/>
<p className="text-xs whitespace-nowrap tracking-wider font-semibold mt-2 text-gray-500">
Add Document
</p>
</>
)}
</div>
<input
id="dropzone-file"
type="file"
className="hidden"
onChange={handleFileChange}
/>
</div>
{selectedFile && !uploadSuccess && (
<>
<div className="flex justify-center p-2 w-full items-center border border-solid border-gray-200 bg-gray-200 mt-6 rounded-xl">
<Image
className=" h-8 w-8 "
src="/images/trash.png"
alt="Add Document"
width={30}
height={30}
/>
<button
onClick={handleRemove}
className="p-2 bg-gray-200 text-xs text-gray-500 -"
disabled={uploading}
>
Remove Document
</button>
</div>
<button
onClick={handleUpload}
className="mt-4 px-4 py-4 w-full bg-blue-500 text-white rounded-xl"
disabled={uploading}
>
{uploading ? "Uploading..." : "Upload File"}
</button>
</>
)}
{uploadSuccess && !selectedFile && <div></div>}
{uploadError && <p className="text-red-500 mt-2">{uploadError}</p>}
{/* Display the uploaded file data */}
</div>
</div>
<div className="mt-5">
<ol className="relative border-gray-500">
{documentsLicense.length > 0 ? (
documentsLicense.map((doc, index) => (
<li key={index} className="mb-5">
<div
onClick={() => handleView(doc.id)}
className="border-2 w-full border-solid cursor-pointer bg-white rounded-xl p-2 flex items-center"
>
<Image
className="h-12 w-12 rounded-xl border-2 border-gray-200 border-solid m-2"
src={getIconForFile(doc.download_url)}
alt="File Icon"
width={100}
height={100}
/>
<div className="flex-grow">
<h3 className="font-semibold ">CCTV Certificate</h3>
<h3 className="text-xs text-gray-400">
Upload: {doc.data.startDate || "Not available"}
</h3>
</div>
<div className="ml-auto">
<Image
className="h-6 w-6"
src="/images/IconDetail.png"
alt="Detail Icon"
width={24}
height={24}
/>
</div>
</div>
</li>
))
) : (
<li className="mb-5">
<p className="text-gray-500">
No CCTV Certificate documents available.
</p>
</li>
)}
</ol>
</div>
{mostRecentLicense && (
<div className="mt-4">
<h3 className="text-lg font-bold mb-2">To Do List:</h3>
<ul>
<CheckboxItem
label="Device Installed"
checked={todo.device_installed}
onChange={() => handleTodoChange('device_installed')}
id="device_installed"
/>
<CheckboxItem
label="License Acquired"
checked={todo.license_acquired}
onChange={() => handleTodoChange('license_acquired')}
id="license_acquired"
/>
<CheckboxItem
label="Sample Recording"
checked={todo.sample_recording}
onChange={() => handleTodoChange('sample_recording')}
id="sample_recording"
/>
<CheckboxItem
label="Register to Police Station"
checked={todo.register_to_police_station}
onChange={() => handleTodoChange('register_to_police_station')}
id="register_to_police_station"
/>
</ul>
</div>
)}
<div className="mt-4">
<h3 className="text-lg font-bold mb-2">Sample Monitoring</h3>
<div className="flex flex-col items-center w-full">
<div
className="flex flex-col items-center justify-center w-full h-20 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50"
onClick={() => document.getElementById('sample-monitoring-file')?.click()}
>
<div className="flex space-x-2 text-center items-center justify-center pt-5 pb-6">
{sampleMonitoringFile ? (
<p className="text-lg font-semibold mt-2 text-gray-500">
{sampleMonitoringFile.name}
</p>
) : (
<>
<Image
className="min-w-fit"
src="/images/add.png"
alt="Upload"
width={30}
height={30}
/>
<p className="text-xs whitespace-nowrap tracking-wider font-semibold mt-2 text-gray-500">
Add Document
</p>
</>
)}
</div>
<input
id="sample-monitoring-file"
type="file"
className="hidden"
onChange={handleSampleMonitoringFileChange}
/>
</div>
{sampleMonitoringFile && (
<>
<div className="flex justify-center p-2 w-full items-center border border-solid border-gray-200 bg-gray-200 mt-6 rounded-xl">
<Image
className="h-8 w-8"
src="/images/trash.png"
alt="Remove Document"
width={30}
height={30}
/>
<button
onClick={() => setSampleMonitoringFile(null)}
className="p-2 bg-gray-200 text-xs text-gray-500"
disabled={uploading}
>
Remove Document
</button>
</div>
<button
onClick={handleSampleMonitoringUpload}
className="mt-4 px-4 py-4 w-full bg-blue-500 text-white rounded-xl"
disabled={uploading}
>
{uploading ? "Uploading..." : "Upload File"}
</button>
</>
)}
{uploadSuccess && !sampleMonitoringFile && (
<p className="text-green-500 mt-2">File uploaded successfully!</p>
)}
{uploadError && <p className="text-red-500 mt-2">{uploadError}</p>}
</div>
</div>
{attachedFileUrl && (
<div className="mt-4">
<h3 className="text-lg font-bold mb-2">Attached Sample Monitoring</h3>
<div className="border-2 w-full border-solid cursor-pointer bg-white rounded-xl p-2 flex items-center">
<Image
className="h-12 w-12 rounded-xl border-2 border-gray-200 border-solid m-2"
src={getIconForFile(attachedFileUrl)}
alt="File Icon"
width={100}
height={100}
/>
<div className="flex-grow">
<h3 className="font-semibold">Sample Monitoring File</h3>
<h3 className="text-xs text-gray-400">
Upload: {new Date().toLocaleDateString()}
</h3>
</div>
<div className="ml-auto">
<a href={attachedFileUrl} target="_blank" rel="noopener noreferrer">
<Image
className="h-6 w-6"
src="/images/IconDetail.png"
alt="View Icon"
width={24}
height={24}
/>
</a>
</div>
</div>
</div>
)}
</MainLayout>
);
}Editor is loading...
Leave a Comment