update
This commit is contained in:
parent
b623304e9d
commit
475987bcd3
|
|
@ -10,83 +10,170 @@ import {
|
|||
DialogFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
import {
|
||||
getGaleryFileData,
|
||||
updateGalery,
|
||||
updateUploadGaleryFile,
|
||||
deleteGaleryFile,
|
||||
} from "@/service/galery";
|
||||
import { error, success } from "@/config/swal";
|
||||
import withReactContent from "sweetalert2-react-content";
|
||||
import Swal from "sweetalert2";
|
||||
|
||||
export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
|
||||
const [title, setTitle] = useState(data.title || "");
|
||||
const [description, setDescription] = useState(data.desc || "");
|
||||
const [title, setTitle] = useState("");
|
||||
const MySwal = withReactContent(Swal);
|
||||
const [description, setDescription] = useState("");
|
||||
const [oldFiles, setOldFiles] = useState<any[]>([]);
|
||||
const [newFiles, setNewFiles] = useState<File[]>([]);
|
||||
const [newFilePreviews, setNewFilePreviews] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetchOldFiles = async () => {
|
||||
const fetchOldFiles = async (galleryId: any) => {
|
||||
try {
|
||||
const res = await getGaleryFileData(data.id);
|
||||
const res = await getGaleryFileData(galleryId);
|
||||
const allImages = res?.data?.data ?? [];
|
||||
|
||||
const filteredImages = allImages.filter(
|
||||
(img: any) => img.gallery_id === data.id
|
||||
const filtered = allImages.filter(
|
||||
(img: any) => img.gallery_id === galleryId
|
||||
);
|
||||
|
||||
setOldFiles(filteredImages);
|
||||
setOldFiles(filtered);
|
||||
} catch (e) {
|
||||
console.error("Error fetch files:", e);
|
||||
console.error("Error fetching files:", e);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open && data?.id) {
|
||||
fetchOldFiles();
|
||||
setTitle(data.title || "");
|
||||
setDescription(data.description || "");
|
||||
setTitle(data.title ?? "");
|
||||
|
||||
setDescription(data.description ?? data.desc ?? "");
|
||||
fetchOldFiles(data.id);
|
||||
|
||||
setNewFiles([]);
|
||||
setNewFilePreviews([]);
|
||||
} else if (!open) {
|
||||
}
|
||||
}, [open, data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!newFiles || newFiles.length === 0) {
|
||||
setNewFilePreviews([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const urls = newFiles.map((f) => URL.createObjectURL(f));
|
||||
setNewFilePreviews(urls);
|
||||
|
||||
return () => {
|
||||
urls.forEach((u) => URL.revokeObjectURL(u));
|
||||
};
|
||||
}, [newFiles]);
|
||||
|
||||
const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const uploaded = Array.from(e.target.files || []) as File[];
|
||||
if (uploaded.length === 0) return;
|
||||
setNewFiles((prev) => [...prev, ...uploaded]);
|
||||
};
|
||||
|
||||
const removeOldFile = (id: number) => {
|
||||
setOldFiles((prev) => prev.filter((f) => f.id !== id));
|
||||
async function doDelete(id: any) {
|
||||
const resDelete = await deleteGaleryFile(id);
|
||||
if (resDelete?.error) {
|
||||
error(resDelete.message);
|
||||
return false;
|
||||
}
|
||||
success("Berhasil Hapus");
|
||||
return;
|
||||
}
|
||||
|
||||
const removeOldFile = (id: any) => {
|
||||
MySwal.fire({
|
||||
title: "Hapus Data",
|
||||
icon: "warning",
|
||||
showCancelButton: true,
|
||||
cancelButtonColor: "#3085d6",
|
||||
confirmButtonColor: "#d33",
|
||||
confirmButtonText: "Hapus",
|
||||
}).then((result) => {
|
||||
if (result.isConfirmed) {
|
||||
doDelete(id);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const removeNewFile = (index: number) => {
|
||||
setNewFiles((prev) => prev.filter((_, i) => i !== index));
|
||||
setNewFilePreviews((prev) => prev.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
if (!data?.id) {
|
||||
alert("Gallery ID tidak tersedia.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const formMain = new FormData();
|
||||
formMain.append("title", title);
|
||||
formMain.append("description", description);
|
||||
|
||||
formMain.append("old_files", JSON.stringify(oldFiles.map((f) => f.id)));
|
||||
|
||||
await updateGalery(data.id, formMain);
|
||||
const updateRes = await updateGalery(data.id, formMain);
|
||||
console.log("updateGalery response:", updateRes);
|
||||
|
||||
if (updateRes?.error) {
|
||||
alert(updateRes.message || "Gagal update galeri");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const galleryId = data.id;
|
||||
const failedUploads: any[] = [];
|
||||
|
||||
for (const file of newFiles) {
|
||||
const formFile = new FormData();
|
||||
formFile.append("gallery_id", String(data.id));
|
||||
formFile.append("title", title);
|
||||
formFile.append("file", file);
|
||||
try {
|
||||
const formFile = new FormData();
|
||||
formFile.append("gallery_id", String(galleryId));
|
||||
formFile.append("title", title);
|
||||
formFile.append("is_active", "true");
|
||||
formFile.append("file", file);
|
||||
|
||||
await updateUploadGaleryFile(data.id, formFile);
|
||||
const uploadRes = await updateUploadGaleryFile(data.id, formFile);
|
||||
|
||||
console.log("uploadRes:", uploadRes);
|
||||
|
||||
if (uploadRes?.error) {
|
||||
failedUploads.push({
|
||||
name: file.name,
|
||||
error: uploadRes.message,
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
failedUploads.push({ name: file.name, error: err });
|
||||
}
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (failedUploads.length > 0) {
|
||||
let msg = failedUploads.map((f) => `${f.name}: ${f.error}`).join("\n");
|
||||
alert("Ada file gagal diupload:\n" + msg);
|
||||
return;
|
||||
}
|
||||
|
||||
onClose();
|
||||
if (onUpdated) onUpdated();
|
||||
} catch (err) {
|
||||
onUpdated && onUpdated();
|
||||
} catch (err: any) {
|
||||
setLoading(false);
|
||||
console.error("Error update gallery:", err);
|
||||
alert("Gagal menyimpan perubahan galeri");
|
||||
console.error("Update error:", err);
|
||||
|
||||
if (err?.response?.data) {
|
||||
alert("Server error: " + JSON.stringify(err.response.data));
|
||||
} else {
|
||||
alert("Gagal menyimpan galeri");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -97,8 +184,7 @@ export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
|
|||
<DialogTitle>Edit Galeri</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* FORM */}
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4 px-4 pb-4">
|
||||
{/* TITLE */}
|
||||
<div>
|
||||
<label className="font-medium text-sm">Judul Galeri *</label>
|
||||
|
|
@ -139,14 +225,13 @@ export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
|
|||
</div>
|
||||
</label>
|
||||
|
||||
{/* OLD FILES */}
|
||||
{oldFiles.length > 0 && (
|
||||
<div className="flex gap-3 mt-3 flex-wrap">
|
||||
{oldFiles.map((f) => (
|
||||
<div key={f.id} className="relative w-20 h-20">
|
||||
<Image
|
||||
src={f.image_url}
|
||||
alt={f.title}
|
||||
alt={f.title || "image"}
|
||||
fill
|
||||
className="object-cover rounded-lg"
|
||||
/>
|
||||
|
|
@ -161,16 +246,17 @@ export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{/* NEW FILES */}
|
||||
{newFiles.length > 0 && (
|
||||
{newFilePreviews.length > 0 && (
|
||||
<div className="flex gap-3 mt-3 flex-wrap">
|
||||
{newFiles.map((file, idx) => (
|
||||
<div key={idx} className="relative w-20 h-20">
|
||||
<Image
|
||||
src={URL.createObjectURL(file)}
|
||||
alt={file.name}
|
||||
fill
|
||||
className="object-cover rounded-lg"
|
||||
{newFilePreviews.map((src, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="relative w-20 h-20 overflow-hidden rounded-lg border"
|
||||
>
|
||||
<img
|
||||
src={src}
|
||||
alt={`new-${idx}`}
|
||||
className="object-cover w-full h-full"
|
||||
/>
|
||||
<button
|
||||
onClick={() => removeNewFile(idx)}
|
||||
|
|
@ -185,8 +271,7 @@ export function DialogUpdateGaleri({ open, onClose, data, onUpdated }: any) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* FOOTER */}
|
||||
<DialogFooter className="mt-6 flex gap-2">
|
||||
<DialogFooter className="mt-6 flex gap-2 px-4 pb-4">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-6 py-2 rounded-lg bg-gray-200 text-gray-700"
|
||||
|
|
|
|||
|
|
@ -63,3 +63,10 @@ export async function deleteGalery(id: string) {
|
|||
};
|
||||
return await httpDeleteInterceptor(`galleries/${id}`, headers);
|
||||
}
|
||||
|
||||
export async function deleteGaleryFile(id: any) {
|
||||
const headers = {
|
||||
"content-type": "application/json",
|
||||
};
|
||||
return await httpDeleteInterceptor(`gallery-files/${id}`, headers);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue