fix: adjust the dev code to be the same as prod

This commit is contained in:
Sabda Yagra 2025-12-09 12:01:13 +07:00
parent 76b7b4b86e
commit f1ecebfb0f
11 changed files with 884 additions and 341 deletions

View File

@ -40,7 +40,7 @@ export default function TrackingBeritaCard() {
const initFecth = async () => {
loading();
const response = await listDataTracking(showData, page - 1);
const response = await listDataTracking(Number(showData), page - 1, search);
const data = response?.data?.data;
const newData = data?.content;
setTotalPage(data?.totalPages || 1);
@ -56,23 +56,85 @@ export default function TrackingBeritaCard() {
setContent(response?.data?.data?.content || []);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const handleInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setSearch(value);
if (value.trim() === "") {
initFecth();
} else {
fecthAll(value);
}
const response = await listDataTracking(Number(showData), 0, value);
setContent(response?.data?.data?.content || []);
};
// const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
// const value = e.target.value;
// setSearch(value);
// if (value.trim() === "") {
// initFecth();
// } else {
// fecthAll(value);
// }
// };
const handleSelect = (id: number) => {
setSelectedItems((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
);
};
const doSave = async () => {
if (selectedItems.length === 0) {
MySwal.fire(
"Peringatan",
"Pilih minimal 1 berita untuk disimpan.",
"warning"
);
return;
}
try {
loading();
const promises = selectedItems.map(async (id) => {
const res = await mediaTrackingSave({
mediaUploadId: id,
duration: 24,
scrapingPeriod: 3,
});
// cek pesan API
if (!res?.data?.success) {
throw new Error(
res?.data?.message ||
"Limit media tracking per hari sudah tercapai. Maksimal 5 tracking per hari."
);
}
return res;
});
await Promise.all(promises);
close();
await MySwal.fire({
icon: "success",
title: "Berhasil!",
text: "Tracking berita berhasil ditambahkan.",
confirmButtonColor: "#2563eb",
});
setSelectedItems([]);
initFecth();
} catch (err: any) {
close();
MySwal.fire({
icon: "error",
title: "Gagal!",
text: err?.message || "Terjadi kesalahan saat menyimpan data.",
confirmButtonColor: "#dc2626",
});
}
};
// const doSave = async () => {
// if (selectedItems.length === 0) {
// toast("Pilih minimal 1 berita untuk disimpan.");
@ -99,48 +161,63 @@ export default function TrackingBeritaCard() {
// }
// };
const doSave = async () => {
if (selectedItems.length === 0) {
MySwal.fire(
"Peringatan",
"Pilih minimal 1 berita untuk disimpan.",
"warning"
);
return;
}
// const doSave = async () => {
// if (selectedItems.length === 0) {
// MySwal.fire(
// "Peringatan",
// "Pilih minimal 1 berita untuk disimpan.",
// "warning"
// );
// return;
// }
try {
loading();
// try {
// loading();
const promises = selectedItems.map((id) =>
mediaTrackingSave({
mediaUploadId: id,
duration: 24,
scrapingPeriod: 3,
})
);
await Promise.all(promises);
// const promises = selectedItems.map((id) =>
// mediaTrackingSave({
// mediaUploadId: id,
// duration: 24,
// scrapingPeriod: 3,
// })
// );
// await Promise.all(promises);
close();
// close();
await MySwal.fire({
icon: "success",
title: "Berhasil!",
text: "Tracking berita berhasil ditambahkan.",
confirmButtonColor: "#2563eb",
});
// await MySwal.fire({
// icon: "success",
// title: "Berhasil!",
// text: "Tracking berita berhasil ditambahkan.",
// confirmButtonColor: "#2563eb",
// });
setSelectedItems([]);
initFecth();
} catch (err: any) {
close();
MySwal.fire({
icon: "error",
title: "Gagal!",
text: err?.message || "Terjadi kesalahan saat menyimpan data.",
confirmButtonColor: "#dc2626",
});
}
// setSelectedItems([]);
// initFecth();
// } catch (err: any) {
// close();
// MySwal.fire({
// icon: "error",
// title: "Gagal!",
// text: err?.message || "Terjadi kesalahan saat menyimpan data.",
// confirmButtonColor: "#dc2626",
// });
// }
// };
const slugify = (text: string) => {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-$)+/g, "");
};
const goToDetail = (item: any) => {
const type = item.type || "image";
const slug = slugify(item.title || "");
const url = `/in/${type}/detail/${item.id}-${slug}`;
window.location.href = url;
};
return (
@ -188,7 +265,7 @@ export default function TrackingBeritaCard() {
<div className="text-sm text-blue-600 font-medium">
{selectedItems.length} Item Terpilih{" "}
<span className="text-black">
/ Tracking Berita tersisa {29 - selectedItems.length}
/ Tracking Berita tersisa {5 - selectedItems.length}
</span>
</div>
<Button className="bg-blue-600 text-white" onClick={doSave}>
@ -198,6 +275,48 @@ export default function TrackingBeritaCard() {
)}
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{content?.length > 0 &&
content.map((item: any) => (
<Card
key={item.id}
className="relative overflow-hidden shadow-sm border rounded-lg"
>
{/* KLIK GAMBAR = CHECKLIST */}
<div
className="cursor-pointer"
onClick={() => handleSelect(item.id)}
>
<img
src={item.thumbnailLink}
alt={item.title}
className="w-full h-[300px] object-cover"
/>
{/* CHECKBOX */}
<div className="absolute top-2 left-2">
<div className="w-5 h-5 border-2 border-white bg-white rounded-sm flex items-center justify-center">
{selectedItems.includes(item.id) && (
<div className="w-3 h-3 bg-blue-600 rounded-sm" />
)}
</div>
</div>
</div>
{/* KLIK JUDUL = DETAIL */}
<p
className="p-2 text-sm font-medium hover:underline cursor-pointer"
onClick={(e) => {
e.stopPropagation();
goToDetail(item);
}}
>
{item.title}
</p>
</Card>
))}
</div>
{/* <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{content?.length > 1 &&
content.map((item: any) => (
<Card
@ -222,7 +341,7 @@ export default function TrackingBeritaCard() {
</p>
</Card>
))}
</div>
</div> */}
<div className="mt-3">
{content && content?.length > 0 ? (
<CustomPagination

View File

@ -206,7 +206,7 @@ const useTableColumns = (activeTab: "ta" | "daily" | "special") => {
</DropdownMenuItem>
</Link>
)}
{(roleId == 11 || roleId == 12 || roleId == 19) && (
{(roleId == 12 || roleId == 19) && (
<Link
href={`/contributor/task-ta/upload-task/${row.original.id}`}
>

View File

@ -172,21 +172,89 @@ const TaskTaTable = () => {
);
}
const data = res?.data?.data;
const contentData = data?.content || [];
let contentData = res?.data?.data?.content || [];
// ⛔ Jika upload belum selesai → sembunyikan task baru
const isUploadingTA =
localStorage.getItem("TA_UPLOAD_IN_PROGRESS") === "true";
if (isUploadingTA) {
const now = new Date();
// Filter task yg dibuat < 5 menit terakhir (belum selesai upload)
contentData = contentData.filter((item: any) => {
const created = new Date(item.createdAt);
const diff = now.getTime() - created.getTime();
return diff > 5 * 60 * 1000; // lebih dari 5 menit
});
}
contentData.forEach((item: any, index: number) => {
item.no = (page - 1) * Number(showData) + index + 1;
});
setDataTable(contentData);
setTotalData(data?.totalElements);
setTotalPage(data?.totalPages);
setTotalData(res?.data?.data?.totalElements);
setTotalPage(res?.data?.data?.totalPages);
} catch (error) {
console.error("Error fetching tasks:", error);
}
}
// async function fetchData() {
// const formattedStartDate = dateFilter
// ? format(new Date(dateFilter), "yyyy-MM-dd")
// : "";
// try {
// let res;
// if (activeTab === "ta") {
// res = await listTaskTa(
// page - 1,
// search,
// showData,
// filterByCode,
// formattedStartDate,
// "atensi-khusus",
// statusFilter
// );
// } else if (activeTab === "daily") {
// res = await listTaskTa(
// page - 1,
// search,
// showData,
// filterByCode,
// formattedStartDate,
// "tugas-harian",
// statusFilter
// );
// } else if (activeTab === "special") {
// res = await listTask(
// page - 1,
// search,
// showData,
// filterByCode,
// formattedStartDate,
// "atensi-khusus",
// statusFilter
// );
// }
// const data = res?.data?.data;
// const contentData = data?.content || [];
// contentData.forEach((item: any, index: number) => {
// item.no = (page - 1) * Number(showData) + index + 1;
// });
// setDataTable(contentData);
// setTotalData(data?.totalElements);
// setTotalPage(data?.totalPages);
// } catch (error) {
// console.error("Error fetching tasks:", error);
// }
// }
// async function fetchData() {
// const formattedStartDate = dateFilter
// ? format(new Date(dateFilter), "yyyy-MM-dd")

View File

@ -35,10 +35,19 @@ const TaskTaPage = () => {
<CardTitle>
<div className="flex flex-col sm:flex-row lg:flex-row lg:items-center">
<div className="flex-1 text-xl font-medium text-default-900">
{t("tabel", { defaultValue: "Tabel" })} {t("task-ta", { defaultValue: "Task Ta" })}
{t("tabel", { defaultValue: "Tabel" })}{" "}
{t("task-ta", { defaultValue: "Task Ta" })}
</div>
<div className="flex-none">
{roleId !== 12 && (
{/* {roleId !== 12 && (
<Link href={"/contributor/task-ta/create"}>
<Button color="primary" className="text-white">
<UploadIcon size={18} className="mr-2" />
{t("create-task", { defaultValue: "Create Task" })}
</Button>
</Link>
)} */}
{roleId !== 12 && roleId !== 19 && (
<Link href={"/contributor/task-ta/create"}>
<Button color="primary" className="text-white">
<UploadIcon size={18} className="mr-2" />

View File

@ -1372,6 +1372,7 @@ export default function FormConvertSPIT() {
);
}
// {spit with new layout file placements}
// "use client";
// import React, { ChangeEvent, useEffect, useRef, useState } from "react";

View File

@ -19,6 +19,7 @@ import {
finishTaskTa,
getAcceptance,
getAcceptanceAssignmentStatus,
getAcceptanceTa,
getAssignmentResponseList,
getMediaUpload,
getMediaUploadTa,
@ -173,9 +174,16 @@ interface UploadResult {
creatorGroup: string;
}
// interface FileUploaded {
// id: number;
// url: string;
// }
interface FileUploaded {
id: number;
url: string;
fileName: string;
fileTypeId: number;
}
export default function FormTaskTaDetail() {
@ -401,6 +409,19 @@ export default function FormTaskTaDetail() {
fetchAcceptanceStatus();
}, [id]);
const getViewerUrl = (url: string) => {
const ext = url.split(".").pop()?.toLowerCase();
if (ext === "pdf") {
return url; // langsung tampilkan PDF
}
// doc / docx → pakai Google Viewer, lebih compatible
return `https://docs.google.com/viewer?url=${encodeURIComponent(
url
)}&embedded=true`;
};
useEffect(() => {
const fetchExpertsForCompetencies = async () => {
const allExperts: any[] = [];
@ -502,7 +523,7 @@ export default function FormTaskTaDetail() {
const urls = details.urls.map(
(urlObj: any) => urlObj.attachmentUrl || ""
);
setUrlInputs(urls); // Save the URLs to state
setUrlInputs(urls);
}
if (details?.assignedToLevel) {
@ -770,10 +791,10 @@ export default function FormTaskTaDetail() {
const isAccept = true;
try {
const resSent = await getAcceptance(id, !isAccept);
setSentAcceptance(resSent?.data?.data);
const resSent = await getAcceptanceTa(id, !isAccept);
setSentAcceptance(resSent?.data?.data || []);
const resAccept = await getAcceptance(id, isAccept);
const resAccept = await getAcceptanceTa(id, isAccept);
const acceptanceSort = resAccept?.data?.data?.sort(
(a: AcceptanceData, b: AcceptanceData) =>
@ -781,7 +802,7 @@ export default function FormTaskTaDetail() {
);
console.log("Data sort:", acceptanceSort);
setAcceptAcceptance(acceptanceSort);
setAcceptAcceptance(acceptanceSort || []);
} catch (error) {
console.error("Error fetching acceptance data:", error);
}
@ -960,14 +981,27 @@ export default function FormTaskTaDetail() {
const onReady = (ws: any) => {
setWavesurfer(ws);
setIsPlaying(false);
ws.on("play", () => setIsPlaying(true));
ws.on("pause", () => setIsPlaying(false));
};
// const onReady = (ws: any) => {
// setWavesurfer(ws);
// setIsPlaying(false);
// };
const onPlayPause = () => {
wavesurfer && wavesurfer.playPause();
};
const handleRemoveFile = (id: number) => {};
// const handleRemoveFile = (id: number) => {};
const handleRemoveFile = (file: FileUploaded) => {
console.log(file);
// contoh kalau kamu mau hapus dari state:
setVideoUploadedFiles((prev) => prev.filter((f) => f.id !== file.id));
};
const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value); // Perbarui state search
@ -982,7 +1016,7 @@ export default function FormTaskTaDetail() {
<p className="text-lg font-semibold mb-3">
{t("detail-task", { defaultValue: "Detail Task" })}
</p>
{/* <div
<div
className="flex gap-3"
style={
detail?.createdBy?.id === Number(userId)
@ -999,7 +1033,8 @@ export default function FormTaskTaDetail() {
color="primary"
onClick={() => setModalType("terkirim")}
>
{sentAcceptance?.length} {t("sent", { defaultValue: "Sent" })}
{sentAcceptance?.length}{" "}
{t("sent", { defaultValue: "Sent" })}
</Button>
</DialogTrigger>
@ -1009,14 +1044,17 @@ export default function FormTaskTaDetail() {
onClick={() => setModalType("diterima")}
className="ml-3"
>
{acceptAcceptance?.length} {t("accepted", { defaultValue: "Accepted" })}
{acceptAcceptance?.length}{" "}
{t("accepted", { defaultValue: "Accepted" })}
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px] overflow-y-auto max-h-[500px]">
<DialogHeader>
<DialogTitle>
{t("assignment-status-details", { defaultValue: "Assignment Status Details" })}
{t("assignment-status-details", {
defaultValue: "Assignment Status Details",
})}
</DialogTitle>
</DialogHeader>
@ -1025,7 +1063,7 @@ export default function FormTaskTaDetail() {
</DialogContent>
</Dialog>
</div>
</div> */}
</div>
</div>
<form>
@ -1255,6 +1293,38 @@ export default function FormTaskTaDetail() {
</Button>
</div>
))}
{/* {videoUploadedFiles?.map((file, index) => (
<div
key={index}
className="flex justify-between border px-3.5 py-3 my-6 rounded-md"
>
<div
className="flex gap-3 items-center cursor-pointer"
onClick={() =>
setSelectedVideo(
`https://mediahub.polri.go.id/api/v2/assignment-expert/file/viewer?id=${file.id}`
)
}
>
<VideoIcon />
<div>
<div className="text-sm text-card-foreground">
{file.fileName}
</div>
</div>
</div>
<Button
size="icon"
color="destructive"
variant="outline"
className="border-none rounded-full"
onClick={() => handleRemoveFile(file)}
>
<Icon icon="tabler:x" className="h-5 w-5" />
</Button>
</div>
))} */}
</div>
</div>
<div>
@ -1312,12 +1382,16 @@ export default function FormTaskTaDetail() {
<div>
{selectedText && (
<Card className="mt-2">
<iframe
{/* <iframe
className="w-full h-96 rounded-md"
src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
selectedText
)}`}
title={"Document"}
/> */}
<iframe
className="w-full h-96"
src={getViewerUrl(selectedText)}
/>
</Card>
)}
@ -1371,7 +1445,7 @@ export default function FormTaskTaDetail() {
onPause={() => setIsPlaying(false)}
/>
</div>
<Button
{/* <Button
size="sm"
type="button"
onClick={onPlayPause}
@ -1391,6 +1465,22 @@ export default function FormTaskTaDetail() {
}
className="h-5 w-5"
/>
</Button> */}
<Button
size="sm"
type="button"
onClick={onPlayPause}
className="flex items-center gap-2 bg-primary text-white p-2 rounded"
>
{isPlaying ? "Pause" : "Play"}
<Icon
icon={
isPlaying
? "carbon:pause-outline"
: "famicons:play-sharp"
}
className="h-5 w-5"
/>
</Button>
</Card>
)}
@ -1454,6 +1544,24 @@ export default function FormTaskTaDetail() {
)}
{isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
{/* Display remaining time */}
<div className="mt-4">
<Label>Link Url</Label>
{urlInputs.map((url: any, index: any) => (
<Link
key={index}
href={url}
target="_blank"
className="flex items-center gap-2 mt-2"
>
<input
type="url"
className="border rounded p-2 w-full cursor-pointer"
value={url}
placeholder={`Masukkan link berita ${index + 1}`}
/>
</Link>
))}
</div>
</div>
</div>
</div>

View File

@ -58,10 +58,8 @@ import { getListCompetencies } from "@/service/management-user/management-user";
const taskSchema = z.object({
// uniqueCode: z.string().min(1, { message: "Judul diperlukan" }),
title: z.string().min(1, { message: "Judul diperlukan" }),
naration: z.string().min(2, {
message: "Narasi Penugasan harus lebih dari 2 karakter.",
}),
title: z.string().optional(),
naration: z.string().optional(),
});
export type taskDetail = {
@ -585,10 +583,14 @@ export default function FormTaskTaEdit() {
assignedToRole: selectedTarget,
assignmentType: taskType,
assignmentTypeId: type,
narration: data.naration,
// narration: data.naration,
narration: data.naration ?? detail?.narration ?? "",
expertCompetencies: Array.from(selectedCompetencies).join(","),
title: data.title,
attachmentUrl: links,
// title: data.title,
title: data.title ?? detail?.title ?? "",
attachmentUrl: urlInputs
.map((url: any) => url.attachmentUrl || "")
.filter((url: string) => url.trim() !== ""),
};
const response = await createTaskTa(requestData);
@ -802,7 +804,7 @@ export default function FormTaskTaEdit() {
isAudioUploadFinish &&
isTextUploadFinish
) {
successSubmit("/in/contributor/task");
successSubmit("/in/contributor/task-ta");
}
}
@ -841,9 +843,11 @@ export default function FormTaskTaEdit() {
};
const handleLinkChange = (index: number, value: string) => {
const updatedLinks = [...links];
updatedLinks[index] = value;
setLinks(updatedLinks);
setUrlInputs((prev: any) =>
prev.map((url: any, idx: any) =>
idx === index ? { ...url, attachmentUrl: value } : url
)
);
};
const handleAddLink = () => {
@ -882,7 +886,9 @@ export default function FormTaskTaEdit() {
)}
</div>
<div className="mt-5 space-y-2">
<Label>{t("areas-expertise", { defaultValue: "Areas Expertise" })}</Label>
<Label>
{t("areas-expertise", { defaultValue: "Areas Expertise" })}
</Label>
<div className="flex flex-wrap gap-4">
{userCompetencies?.map((item: any) => (
<div className="flex items-center gap-2" key={item.id}>
@ -897,7 +903,9 @@ export default function FormTaskTaEdit() {
</div>
</div>
<div className="mt-5 space-y-2">
<Label>{t("choose-expert", { defaultValue: "Choose Expert" })}</Label>
<Label>
{t("choose-expert", { defaultValue: "Choose Expert" })}
</Label>
<div className="flex flex-wrap gap-4">
<Dialog>
<DialogTrigger asChild>
@ -978,7 +986,9 @@ export default function FormTaskTaEdit() {
</div>
<div className="mt-5 space-y-2">
<Label>{t("description", { defaultValue: "Description" })}</Label>
<Label>
{t("description", { defaultValue: "Description" })}
</Label>
<Controller
control={control}
name="naration"
@ -996,10 +1006,14 @@ export default function FormTaskTaEdit() {
)}
</div>
<div className="space-y-2.5 mt-5">
<Label htmlFor="attachments">{t("attachment", { defaultValue: "Attachment" })}</Label>
<Label htmlFor="attachments">
{t("attachment", { defaultValue: "Attachment" })}
</Label>
<div className="space-y-3">
<div className="space-y-2">
<Label>{t("audio-visual", { defaultValue: "Audio Visual" })}</Label>
<Label>
{t("audio-visual", { defaultValue: "Audio Visual" })}
</Label>
<FileUploader
accept={{
"mp4/*": [],
@ -1188,7 +1202,9 @@ export default function FormTaskTaEdit() {
{isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
{/* Display remaining time */}
<div className="mt-4 space-y-2">
<h2 className="text-lg font-bold">{t("news-links", { defaultValue: "News Links" })}</h2>
<h2 className="text-lg font-bold">
{t("news-links", { defaultValue: "News Links" })}
</h2>
{urlInputs.map((url: any, index: any) => (
<div
key={url.id}
@ -1205,42 +1221,13 @@ export default function FormTaskTaEdit() {
/>
</div>
))}
<div className="mt-4 space-y-2">
<Label className="">{t("news-links", { defaultValue: "News Links" })}</Label>
{links.map((link, index) => (
<div
key={index}
className="flex items-center gap-2 mt-2"
>
<Input
type="url"
className="border rounded p-2 w-full"
placeholder={`Masukkan link berita ${index + 1}`}
value={link}
onChange={(e) =>
handleLinkChange(index, e.target.value)
}
/>
{links.length > 1 && (
<button
type="button"
className="bg-red-500 text-white px-3 py-1 rounded"
onClick={() => handleRemoveRow(index)}
>
<Trash2 className="h-4 w-4" />
</button>
)}
</div>
))}
<Button
type="button"
className="mt-2 bg-blue-500 text-white px-4 py-2 rounded"
onClick={handleAddRow}
size="sm"
className="mt-4 bg-green-500 text-white px-4 py-2 rounded"
onClick={handleAddLink}
>
{t("add-links", { defaultValue: "Add Links" })}
</Button>
</div>
</button>
</div>
</div>
</div>

View File

@ -260,67 +260,147 @@ export default function FormTaskTa() {
});
};
const save = async (data: TaskSchema) => {
const requestData: {
id?: number;
title: string;
assignedToUsers: any;
assignmentTypeId: string;
narration: string;
assignmentType: string;
expertCompetencies: string;
// const save = async (data: TaskSchema) => {
// const cleanedLinks = links
// .map((link) => link.trim())
// .filter((link) => link !== "" && link.startsWith("http"));
// const requestData: {
// id?: number;
// title: string;
// assignedToUsers: any;
// assignmentTypeId: string;
// narration: string;
// assignmentType: string;
// expertCompetencies: string;
// attachmentUrl: string[];
} = {
// } = {
// ...data,
// assignedToUsers: handleExpertChange(),
// assignmentType: taskType,
// assignmentTypeId: type,
// narration: data.narration,
// expertCompetencies: Array.from(selectedCompetencies).join(","),
// title: data.title,
// attachmentUrl: cleanedLinks,
// };
// const response = await createTaskTa(requestData);
// localStorage.setItem("TA_UPLOAD_IN_PROGRESS", "true");
// console.log("Form Data Submitted:", requestData);
// console.log("response", response);
// const id = response?.data?.data.id;
// loading();
// if (imageFiles?.length == 0) {
// setIsImageUploadFinish(true);
// }
// const allUploads: Promise<any>[] = [];
// imageFiles.forEach((item, index) => {
// allUploads.push(uploadResumableFile(index, String(id), item, "1", "0"));
// });
// videoFiles.forEach((item, index) => {
// allUploads.push(uploadResumableFile(index, String(id), item, "2", "0"));
// });
// textFiles.forEach((item, index) => {
// allUploads.push(uploadResumableFile(index, String(id), item, "3", "0"));
// });
// audioFiles.forEach((item, index) => {
// allUploads.push(uploadResumableFile(index, String(id), item, "4", "0"));
// });
// // ⬅ WAJIB
// await Promise.all(allUploads);
// localStorage.removeItem("TA_UPLOAD_IN_PROGRESS");
// // imageFiles?.map(async (item: any, index: number) => {
// // await uploadResumableFile(index, String(id), item, "1", "0");
// // });
// // if (videoFiles?.length == 0) {
// // setIsVideoUploadFinish(true);
// // }
// // videoFiles?.map(async (item: any, index: number) => {
// // await uploadResumableFile(index, String(id), item, "2", "0");
// // });
// // if (textFiles?.length == 0) {
// // setIsTextUploadFinish(true);
// // }
// // textFiles?.map(async (item: any, index: number) => {
// // await uploadResumableFile(index, String(id), item, "3", "0");
// // });
// // if (audioFiles?.length == 0) {
// // setIsAudioUploadFinish(true);
// // }
// // audioFiles.map(async (item: FileWithPreview, index: number) => {
// // await uploadResumableFile(
// // index,
// // String(id),
// // item, // Use .file to access the actual File object
// // "4",
// // "0" // Optional: Replace with actual duration if available
// // );
// // });
// };
const save = async (data: TaskSchema) => {
const cleanedLinks = links
.map((link) => link.trim())
.filter((link) => link.startsWith("http"));
const requestData = {
...data,
assignedToUsers: handleExpertChange(),
assignmentType: taskType,
assignmentTypeId: type,
narration: data.narration,
expertCompetencies: Array.from(selectedCompetencies).join(","),
title: data.title,
// attachmentUrl: links,
attachmentUrl: cleanedLinks,
};
const response = await createTaskTa(requestData);
const id = String(response?.data?.data.id);
console.log("Form Data Submitted:", requestData);
console.log("response", response);
// Set block table TA
localStorage.setItem("TA_UPLOAD_IN_PROGRESS", "true");
const id = response?.data?.data.id;
loading();
if (imageFiles?.length == 0) {
setIsImageUploadFinish(true);
}
imageFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "1", "0");
});
loading(); // SHOW SWAL LOADING
if (videoFiles?.length == 0) {
setIsVideoUploadFinish(true);
}
videoFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "2", "0");
});
// Kumpulkan semua upload
const allUploads: Promise<any>[] = [];
if (textFiles?.length == 0) {
setIsTextUploadFinish(true);
}
textFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "3", "0");
});
if (audioFiles?.length == 0) {
setIsAudioUploadFinish(true);
}
audioFiles.map(async (item: FileWithPreview, index: number) => {
await uploadResumableFile(
index,
String(id),
item, // Use .file to access the actual File object
"4",
"0" // Optional: Replace with actual duration if available
imageFiles.forEach((item, idx) =>
allUploads.push(uploadResumableFile(idx, id, item, "1", "0"))
);
});
videoFiles.forEach((item, idx) =>
allUploads.push(uploadResumableFile(idx, id, item, "2", "0"))
);
textFiles.forEach((item, idx) =>
allUploads.push(uploadResumableFile(idx, id, item, "3", "0"))
);
audioFiles.forEach((item, idx) =>
allUploads.push(uploadResumableFile(idx, id, item, "4", "0"))
);
// Tunggu upload selesai
await Promise.all(allUploads);
// Hapus flag
localStorage.removeItem("TA_UPLOAD_IN_PROGRESS");
// Close loading + redirect
successSubmit("/in/contributor/task-ta");
};
const onSubmit = (data: TaskSchema) => {
@ -393,75 +473,117 @@ export default function FormTaskTa() {
setAudioFiles((prev) => prev.filter((_, idx) => idx !== index));
};
async function uploadResumableFile(
// async function uploadResumableFile(
// idx: number,
// id: string,
// file: any,
// fileTypeId: string,
// duration: string
// ) {
// console.log("Tus Upload : ", idx, id, file, fileTypeId, duration);
// const resCsrf = await getCsrfToken();
// const csrfToken = resCsrf?.data?.token;
// console.log("CSRF TOKEN : ", csrfToken);
// const headers = {
// "X-XSRF-TOKEN": csrfToken,
// };
// const upload = new Upload(file, {
// endpoint: `${process.env.NEXT_PUBLIC_API}/assignment-expert/file/upload`,
// headers: headers,
// retryDelays: [0, 3000, 6000, 12_000, 24_000],
// chunkSize: 20_000,
// metadata: {
// assignmentId: id,
// filename: file.name,
// contentType: file.type,
// fileTypeId: fileTypeId,
// duration,
// },
// onBeforeRequest: function (req) {
// var xhr = req.getUnderlyingObject();
// xhr.withCredentials = true;
// },
// onError: async (e: any) => {
// console.log("Error upload :", e);
// error(e);
// },
// onChunkComplete: (
// chunkSize: any,
// bytesAccepted: any,
// bytesTotal: any
// ) => {
// // const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100);
// // progressInfo[idx].percentage = uploadPersen;
// // counterUpdateProgress++;
// // console.log(counterUpdateProgress);
// // setProgressList(progressInfo);
// // setCounterProgress(counterUpdateProgress);
// },
// onSuccess: async () => {
// // uploadPersen = 100;
// // progressInfo[idx].percentage = 100;
// // counterUpdateProgress++;
// // setCounterProgress(counterUpdateProgress);
// successTodo();
// if (fileTypeId == "1") {
// setIsImageUploadFinish(true);
// } else if (fileTypeId == "2") {
// setIsVideoUploadFinish(true);
// }
// if (fileTypeId == "3") {
// setIsTextUploadFinish(true);
// }
// if (fileTypeId == "4") {
// setIsAudioUploadFinish(true);
// }
// },
// });
// upload.start();
// }
function uploadResumableFile(
idx: number,
id: string,
file: any,
fileTypeId: string,
duration: string
) {
console.log("Tus Upload : ", idx, id, file, fileTypeId, duration);
return new Promise(async (resolve, reject) => {
const resCsrf = await getCsrfToken();
const csrfToken = resCsrf?.data?.token;
console.log("CSRF TOKEN : ", csrfToken);
const headers = {
"X-XSRF-TOKEN": csrfToken,
};
const upload = new Upload(file, {
endpoint: `${process.env.NEXT_PUBLIC_API}/assignment-expert/file/upload`,
headers: headers,
retryDelays: [0, 3000, 6000, 12_000, 24_000],
chunkSize: 20_000,
headers: { "X-XSRF-TOKEN": csrfToken },
retryDelays: [0, 3000, 6000, 12000],
chunkSize: 20000,
metadata: {
assignmentId: id,
filename: file.name,
contentType: file.type,
fileTypeId: fileTypeId,
fileTypeId,
duration,
},
onBeforeRequest: function (req) {
var xhr = req.getUnderlyingObject();
xhr.withCredentials = true;
onBeforeRequest(req) {
req.getUnderlyingObject().withCredentials = true;
},
onError: async (e: any) => {
console.log("Error upload :", e);
error(e);
onError(err) {
console.error("Upload error:", err);
reject(err);
},
onChunkComplete: (
chunkSize: any,
bytesAccepted: any,
bytesTotal: any
) => {
// const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100);
// progressInfo[idx].percentage = uploadPersen;
// counterUpdateProgress++;
// console.log(counterUpdateProgress);
// setProgressList(progressInfo);
// setCounterProgress(counterUpdateProgress);
},
onSuccess: async () => {
// uploadPersen = 100;
// progressInfo[idx].percentage = 100;
// counterUpdateProgress++;
// setCounterProgress(counterUpdateProgress);
successTodo();
if (fileTypeId == "1") {
setIsImageUploadFinish(true);
} else if (fileTypeId == "2") {
setIsVideoUploadFinish(true);
}
if (fileTypeId == "3") {
setIsTextUploadFinish(true);
}
if (fileTypeId == "4") {
setIsAudioUploadFinish(true);
}
onSuccess() {
console.log("Upload selesai:", file.name);
resolve(true);
},
});
upload.start();
});
}
useEffect(() => {

View File

@ -296,17 +296,109 @@ export default function FormTaskTaNew() {
initState();
}, [id, refresh]);
// const save = async (data: ImageSchema) => {
// loading();
// const finalTags = tags.join(", ");
// const finalTitle = data.title || detail?.title || "";
// const finalDescription = articleBody || data.description;
// if (!finalDescription.trim()) {
// MySwal.fire("Error", "Deskripsi tidak boleh kosong.", "error");
// return;
// }
// let requestData: {
// assignmentExpertId: any;
// title: string;
// description: string;
// htmlDescription: string;
// fileTypeId: string;
// categoryId: any;
// subCategoryId: any;
// uploadedBy: string;
// statusId: string;
// publishedFor: string;
// creatorName: string;
// tags: string;
// isYoutube: boolean;
// isInternationalMedia: boolean;
// attachFromScheduleId?: number; // ✅ Tambahkan properti ini
// } = {
// ...data,
// assignmentExpertId: detail?.id || null,
// title: finalTitle,
// description: finalDescription,
// htmlDescription: finalDescription,
// fileTypeId: fileTypeId,
// categoryId: "235",
// subCategoryId: "171",
// uploadedBy: "2b7c8d83-d298-4b19-9f74-b07924506b58",
// statusId: "1",
// publishedFor: "7",
// creatorName: "Penugasan-Ta",
// tags: "penugasan-Ta",
// isYoutube: false,
// isInternationalMedia: false,
// };
// let id = Cookies.get("idCreate");
// if (scheduleId !== undefined) {
// requestData.attachFromScheduleId = Number(scheduleId); // ✅ Tambahkan nilai ini
// }
// if (id == undefined) {
// const response = await createMedia(requestData);
// console.log("Form Data Submitted:", requestData);
// Cookies.set("idCreate", response?.data?.data, { expires: 1 });
// id = response?.data?.data;
// // Upload Thumbnail
// loading();
// if (imageFiles?.length == 0) {
// setIsImageUploadFinish(true);
// }
// imageFiles?.map(async (item: any, index: number) => {
// await uploadResumableFile(index, String(id), item, "1", "0");
// });
// if (videoFiles?.length == 0) {
// setIsVideoUploadFinish(true);
// }
// videoFiles?.map(async (item: any, index: number) => {
// await uploadResumableFile(index, String(id), item, "2", "0");
// });
// if (textFiles?.length == 0) {
// setIsTextUploadFinish(true);
// }
// textFiles?.map(async (item: any, index: number) => {
// await uploadResumableFile(index, String(id), item, "3", "0");
// });
// if (audioFiles?.length == 0) {
// setIsAudioUploadFinish(true);
// }
// audioFiles.map(async (item: FileWithPreview, index: number) => {
// await uploadResumableFile(
// index,
// String(id),
// item, // Use .file to access the actual File object
// "4",
// "0" // Optional: Replace with actual duration if available
// );
// });
// }
// };
const save = async (data: ImageSchema) => {
loading();
const finalTags = tags.join(", ");
const finalTitle = data.title || detail?.title || "";
const finalDescription = articleBody || data.description;
if (!finalDescription.trim()) {
MySwal.fire("Error", "Deskripsi tidak boleh kosong.", "error");
return;
}
let requestData: {
assignmentExpertId: any;
title: string;
@ -322,74 +414,53 @@ export default function FormTaskTaNew() {
tags: string;
isYoutube: boolean;
isInternationalMedia: boolean;
attachFromScheduleId?: number; // ✅ Tambahkan properti ini
attachFromScheduleId?: number;
} = {
...data,
assignmentExpertId: detail?.id || null,
title: finalTitle,
description: finalDescription,
htmlDescription: finalDescription,
fileTypeId: fileTypeId,
categoryId: "235",
subCategoryId: selectedCategory,
categoryId: "171",
subCategoryId: "171",
uploadedBy: "2b7c8d83-d298-4b19-9f74-b07924506b58",
statusId: "1",
publishedFor: publishedFor.join(","),
publishedFor: "7",
creatorName: "Penugasan-Ta",
tags: "penugasan-Ta",
isYoutube: false,
isInternationalMedia: false,
};
let id = Cookies.get("idCreate");
if (scheduleId !== undefined) {
requestData.attachFromScheduleId = Number(scheduleId); // ✅ Tambahkan nilai ini
requestData.attachFromScheduleId = Number(scheduleId);
}
if (id == undefined) {
// SELALU create baru
const response = await createMedia(requestData);
console.log("Form Data Submitted:", requestData);
const id = String(response?.data?.data);
Cookies.set("idCreate", response?.data?.data, { expires: 1 });
id = response?.data?.data;
const allUploads: Promise<any>[] = [];
// Upload Thumbnail
loading();
if (imageFiles?.length == 0) {
setIsImageUploadFinish(true);
}
imageFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "1", "0");
});
if (videoFiles?.length == 0) {
setIsVideoUploadFinish(true);
}
videoFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "2", "0");
});
if (textFiles?.length == 0) {
setIsTextUploadFinish(true);
}
textFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "3", "0");
});
if (audioFiles?.length == 0) {
setIsAudioUploadFinish(true);
}
audioFiles.map(async (item: FileWithPreview, index: number) => {
await uploadResumableFile(
index,
String(id),
item, // Use .file to access the actual File object
"4",
"0" // Optional: Replace with actual duration if available
imageFiles.forEach((file, idx) =>
allUploads.push(uploadResumableFile(idx, id, file, "1", "0"))
);
});
}
videoFiles.forEach((file, idx) =>
allUploads.push(uploadResumableFile(idx, id, file, "2", "0"))
);
textFiles.forEach((file, idx) =>
allUploads.push(uploadResumableFile(idx, id, file, "3", "0"))
);
audioFiles.forEach((file, idx) =>
allUploads.push(uploadResumableFile(idx, id, file, "4", "0"))
);
await Promise.all(allUploads);
successSubmit("/in/contributor/task-ta");
};
const onSubmit = (data: ImageSchema) => {
@ -408,76 +479,117 @@ export default function FormTaskTaNew() {
});
};
async function uploadResumableFile(
// async function uploadResumableFile(
// idx: number,
// id: string,
// file: any,
// fileTypeId: string,
// duration: string
// ) {
// console.log(idx, id, file, fileTypeId, duration);
// const resCsrf = await getCsrfToken();
// const csrfToken = resCsrf?.data?.token;
// const headers = {
// "X-XSRF-TOKEN": csrfToken,
// };
// const upload = new Upload(file, {
// endpoint: `${process.env.NEXT_PUBLIC_API}/media/file/upload`,
// headers: headers,
// retryDelays: [0, 3000, 6000, 12_000, 24_000],
// chunkSize: 20_000,
// metadata: {
// mediaid: id,
// filename: file.name,
// contentType: file.type,
// fileTypeId: fileTypeId,
// duration,
// isWatermark: "true",
// },
// onBeforeRequest: function (req) {
// var xhr = req.getUnderlyingObject();
// xhr.withCredentials = true;
// },
// onError: async (e: any) => {
// console.log("Error upload :", e);
// error(e);
// },
// onChunkComplete: (
// chunkSize: any,
// bytesAccepted: any,
// bytesTotal: any
// ) => {
// // const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100);
// // progressInfo[idx].percentage = uploadPersen;
// // counterUpdateProgress++;
// // console.log(counterUpdateProgress);
// // setProgressList(progressInfo);
// // setCounterProgress(counterUpdateProgress);
// },
// onSuccess: async () => {
// // uploadPersen = 100;
// // progressInfo[idx].percentage = 100;
// // counterUpdateProgress++;
// // setCounterProgress(counterUpdateProgress);
// successTodo();
// if (fileTypeId == "1") {
// setIsImageUploadFinish(true);
// } else if (fileTypeId == "2") {
// setIsVideoUploadFinish(true);
// }
// if (fileTypeId == "3") {
// setIsTextUploadFinish(true);
// }
// if (fileTypeId == "4") {
// setIsAudioUploadFinish(true);
// }
// },
// });
// upload.start();
// }
function uploadResumableFile(
idx: number,
id: string,
file: any,
fileTypeId: string,
duration: string
) {
console.log(idx, id, file, fileTypeId, duration);
return new Promise(async (resolve, reject) => {
const resCsrf = await getCsrfToken();
const csrfToken = resCsrf?.data?.token;
console.log("CSRF TOKEN : ", csrfToken);
const headers = {
"X-XSRF-TOKEN": csrfToken,
};
const upload = new Upload(file, {
endpoint: `${process.env.NEXT_PUBLIC_API}/media/file/upload`,
headers: headers,
headers: { "X-XSRF-TOKEN": csrfToken },
retryDelays: [0, 3000, 6000, 12_000, 24_000],
chunkSize: 20_000,
metadata: {
mediaid: id,
filename: file.name,
contentType: file.type,
fileTypeId: fileTypeId,
fileTypeId,
duration,
isWatermark: "true",
},
onBeforeRequest: function (req) {
var xhr = req.getUnderlyingObject();
xhr.withCredentials = true;
req.getUnderlyingObject().withCredentials = true;
},
onError: async (e: any) => {
console.log("Error upload :", e);
error(e);
onError: (e) => {
console.log("Error upload:", e);
reject(e);
},
onChunkComplete: (
chunkSize: any,
bytesAccepted: any,
bytesTotal: any
) => {
// const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100);
// progressInfo[idx].percentage = uploadPersen;
// counterUpdateProgress++;
// console.log(counterUpdateProgress);
// setProgressList(progressInfo);
// setCounterProgress(counterUpdateProgress);
},
onSuccess: async () => {
// uploadPersen = 100;
// progressInfo[idx].percentage = 100;
// counterUpdateProgress++;
// setCounterProgress(counterUpdateProgress);
successTodo();
if (fileTypeId == "1") {
setIsImageUploadFinish(true);
} else if (fileTypeId == "2") {
setIsVideoUploadFinish(true);
}
if (fileTypeId == "3") {
setIsTextUploadFinish(true);
}
if (fileTypeId == "4") {
setIsAudioUploadFinish(true);
}
onSuccess: () => {
resolve(true);
},
});
upload.start();
});
}
useEffect(() => {

View File

@ -44,9 +44,21 @@ export async function getMediaTrackingResult(data: any) {
return httpGetInterceptor(url);
}
export async function listDataTracking(size: any, page: any) {
// export async function listDataTracking(size: any, page: any) {
// return await httpGetInterceptor(
// `media/public/list?enablePage=1&sort=desc&size=${size}&page=${page}`
// );
// }
export async function listDataTracking(
size: number,
page: number,
keyword = "",
categoryFilter = "",
statusFilter = ""
) {
return await httpGetInterceptor(
`media/public/list?enablePage=1&sort=desc&size=${size}&page=${page}`
`media/list?isForAdmin=true&title=${keyword}&enablePage=1&sortBy=createdAt&sort=desc&size=${size}&page=${page}&categoryId=${categoryFilter}&statusId=${statusFilter}`
);
}

View File

@ -127,6 +127,11 @@ export async function getAcceptance(id: any, isAccept: any) {
return httpGetInterceptor(url);
}
export async function getAcceptanceTa(id: any, isAccept: any) {
const url = `assignment-expert/acceptance?id=${id}&isAccept=${isAccept}`;
return httpGetInterceptor(url);
}
export async function acceptAssignment(id: any) {
const url = `assignment/acceptance?id=${id}`;
return httpPostInterceptor(url, id);