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 () => { const initFecth = async () => {
loading(); loading();
const response = await listDataTracking(showData, page - 1); const response = await listDataTracking(Number(showData), page - 1, search);
const data = response?.data?.data; const data = response?.data?.data;
const newData = data?.content; const newData = data?.content;
setTotalPage(data?.totalPages || 1); setTotalPage(data?.totalPages || 1);
@ -56,23 +56,85 @@ export default function TrackingBeritaCard() {
setContent(response?.data?.data?.content || []); setContent(response?.data?.data?.content || []);
}; };
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value; const value = e.target.value;
setSearch(value); setSearch(value);
if (value.trim() === "") { const response = await listDataTracking(Number(showData), 0, value);
initFecth(); setContent(response?.data?.data?.content || []);
} else {
fecthAll(value);
}
}; };
// const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
// const value = e.target.value;
// setSearch(value);
// if (value.trim() === "") {
// initFecth();
// } else {
// fecthAll(value);
// }
// };
const handleSelect = (id: number) => { const handleSelect = (id: number) => {
setSelectedItems((prev) => setSelectedItems((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id] 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 () => { // const doSave = async () => {
// if (selectedItems.length === 0) { // if (selectedItems.length === 0) {
// toast("Pilih minimal 1 berita untuk disimpan."); // toast("Pilih minimal 1 berita untuk disimpan.");
@ -99,48 +161,63 @@ export default function TrackingBeritaCard() {
// } // }
// }; // };
const doSave = async () => { // const doSave = async () => {
if (selectedItems.length === 0) { // if (selectedItems.length === 0) {
MySwal.fire( // MySwal.fire(
"Peringatan", // "Peringatan",
"Pilih minimal 1 berita untuk disimpan.", // "Pilih minimal 1 berita untuk disimpan.",
"warning" // "warning"
); // );
return; // return;
} // }
try { // try {
loading(); // loading();
const promises = selectedItems.map((id) => // const promises = selectedItems.map((id) =>
mediaTrackingSave({ // mediaTrackingSave({
mediaUploadId: id, // mediaUploadId: id,
duration: 24, // duration: 24,
scrapingPeriod: 3, // scrapingPeriod: 3,
}) // })
); // );
await Promise.all(promises); // await Promise.all(promises);
close(); // close();
await MySwal.fire({ // await MySwal.fire({
icon: "success", // icon: "success",
title: "Berhasil!", // title: "Berhasil!",
text: "Tracking berita berhasil ditambahkan.", // text: "Tracking berita berhasil ditambahkan.",
confirmButtonColor: "#2563eb", // confirmButtonColor: "#2563eb",
}); // });
setSelectedItems([]); // setSelectedItems([]);
initFecth(); // initFecth();
} catch (err: any) { // } catch (err: any) {
close(); // close();
MySwal.fire({ // MySwal.fire({
icon: "error", // icon: "error",
title: "Gagal!", // title: "Gagal!",
text: err?.message || "Terjadi kesalahan saat menyimpan data.", // text: err?.message || "Terjadi kesalahan saat menyimpan data.",
confirmButtonColor: "#dc2626", // 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 ( return (
@ -188,7 +265,7 @@ export default function TrackingBeritaCard() {
<div className="text-sm text-blue-600 font-medium"> <div className="text-sm text-blue-600 font-medium">
{selectedItems.length} Item Terpilih{" "} {selectedItems.length} Item Terpilih{" "}
<span className="text-black"> <span className="text-black">
/ Tracking Berita tersisa {29 - selectedItems.length} / Tracking Berita tersisa {5 - selectedItems.length}
</span> </span>
</div> </div>
<Button className="bg-blue-600 text-white" onClick={doSave}> <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"> <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?.length > 1 &&
content.map((item: any) => ( content.map((item: any) => (
<Card <Card
@ -222,7 +341,7 @@ export default function TrackingBeritaCard() {
</p> </p>
</Card> </Card>
))} ))}
</div> </div> */}
<div className="mt-3"> <div className="mt-3">
{content && content?.length > 0 ? ( {content && content?.length > 0 ? (
<CustomPagination <CustomPagination

View File

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

View File

@ -172,21 +172,89 @@ const TaskTaTable = () => {
); );
} }
const data = res?.data?.data; let contentData = res?.data?.data?.content || [];
const contentData = 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) => { contentData.forEach((item: any, index: number) => {
item.no = (page - 1) * Number(showData) + index + 1; item.no = (page - 1) * Number(showData) + index + 1;
}); });
setDataTable(contentData); setDataTable(contentData);
setTotalData(data?.totalElements); setTotalData(res?.data?.data?.totalElements);
setTotalPage(data?.totalPages); setTotalPage(res?.data?.data?.totalPages);
} catch (error) { } catch (error) {
console.error("Error fetching tasks:", 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() { // async function fetchData() {
// const formattedStartDate = dateFilter // const formattedStartDate = dateFilter
// ? format(new Date(dateFilter), "yyyy-MM-dd") // ? format(new Date(dateFilter), "yyyy-MM-dd")

View File

@ -35,10 +35,19 @@ const TaskTaPage = () => {
<CardTitle> <CardTitle>
<div className="flex flex-col sm:flex-row lg:flex-row lg:items-center"> <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"> <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>
<div className="flex-none"> <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"}> <Link href={"/contributor/task-ta/create"}>
<Button color="primary" className="text-white"> <Button color="primary" className="text-white">
<UploadIcon size={18} className="mr-2" /> <UploadIcon size={18} className="mr-2" />

View File

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

View File

@ -19,6 +19,7 @@ import {
finishTaskTa, finishTaskTa,
getAcceptance, getAcceptance,
getAcceptanceAssignmentStatus, getAcceptanceAssignmentStatus,
getAcceptanceTa,
getAssignmentResponseList, getAssignmentResponseList,
getMediaUpload, getMediaUpload,
getMediaUploadTa, getMediaUploadTa,
@ -173,9 +174,16 @@ interface UploadResult {
creatorGroup: string; creatorGroup: string;
} }
// interface FileUploaded {
// id: number;
// url: string;
// }
interface FileUploaded { interface FileUploaded {
id: number; id: number;
url: string; url: string;
fileName: string;
fileTypeId: number;
} }
export default function FormTaskTaDetail() { export default function FormTaskTaDetail() {
@ -401,6 +409,19 @@ export default function FormTaskTaDetail() {
fetchAcceptanceStatus(); fetchAcceptanceStatus();
}, [id]); }, [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(() => { useEffect(() => {
const fetchExpertsForCompetencies = async () => { const fetchExpertsForCompetencies = async () => {
const allExperts: any[] = []; const allExperts: any[] = [];
@ -502,7 +523,7 @@ export default function FormTaskTaDetail() {
const urls = details.urls.map( const urls = details.urls.map(
(urlObj: any) => urlObj.attachmentUrl || "" (urlObj: any) => urlObj.attachmentUrl || ""
); );
setUrlInputs(urls); // Save the URLs to state setUrlInputs(urls);
} }
if (details?.assignedToLevel) { if (details?.assignedToLevel) {
@ -770,10 +791,10 @@ export default function FormTaskTaDetail() {
const isAccept = true; const isAccept = true;
try { try {
const resSent = await getAcceptance(id, !isAccept); const resSent = await getAcceptanceTa(id, !isAccept);
setSentAcceptance(resSent?.data?.data); setSentAcceptance(resSent?.data?.data || []);
const resAccept = await getAcceptance(id, isAccept); const resAccept = await getAcceptanceTa(id, isAccept);
const acceptanceSort = resAccept?.data?.data?.sort( const acceptanceSort = resAccept?.data?.data?.sort(
(a: AcceptanceData, b: AcceptanceData) => (a: AcceptanceData, b: AcceptanceData) =>
@ -781,7 +802,7 @@ export default function FormTaskTaDetail() {
); );
console.log("Data sort:", acceptanceSort); console.log("Data sort:", acceptanceSort);
setAcceptAcceptance(acceptanceSort); setAcceptAcceptance(acceptanceSort || []);
} catch (error) { } catch (error) {
console.error("Error fetching acceptance data:", error); console.error("Error fetching acceptance data:", error);
} }
@ -960,14 +981,27 @@ export default function FormTaskTaDetail() {
const onReady = (ws: any) => { const onReady = (ws: any) => {
setWavesurfer(ws); setWavesurfer(ws);
setIsPlaying(false);
ws.on("play", () => setIsPlaying(true));
ws.on("pause", () => setIsPlaying(false));
}; };
// const onReady = (ws: any) => {
// setWavesurfer(ws);
// setIsPlaying(false);
// };
const onPlayPause = () => { const onPlayPause = () => {
wavesurfer && wavesurfer.playPause(); 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>) => { const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value); // Perbarui state search setSearch(e.target.value); // Perbarui state search
@ -982,7 +1016,7 @@ export default function FormTaskTaDetail() {
<p className="text-lg font-semibold mb-3"> <p className="text-lg font-semibold mb-3">
{t("detail-task", { defaultValue: "Detail Task" })} {t("detail-task", { defaultValue: "Detail Task" })}
</p> </p>
{/* <div <div
className="flex gap-3" className="flex gap-3"
style={ style={
detail?.createdBy?.id === Number(userId) detail?.createdBy?.id === Number(userId)
@ -999,7 +1033,8 @@ export default function FormTaskTaDetail() {
color="primary" color="primary"
onClick={() => setModalType("terkirim")} onClick={() => setModalType("terkirim")}
> >
{sentAcceptance?.length} {t("sent", { defaultValue: "Sent" })} {sentAcceptance?.length}{" "}
{t("sent", { defaultValue: "Sent" })}
</Button> </Button>
</DialogTrigger> </DialogTrigger>
@ -1009,14 +1044,17 @@ export default function FormTaskTaDetail() {
onClick={() => setModalType("diterima")} onClick={() => setModalType("diterima")}
className="ml-3" className="ml-3"
> >
{acceptAcceptance?.length} {t("accepted", { defaultValue: "Accepted" })} {acceptAcceptance?.length}{" "}
{t("accepted", { defaultValue: "Accepted" })}
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px] overflow-y-auto max-h-[500px]"> <DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px] overflow-y-auto max-h-[500px]">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
{t("assignment-status-details", { defaultValue: "Assignment Status Details" })} {t("assignment-status-details", {
defaultValue: "Assignment Status Details",
})}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
@ -1025,7 +1063,7 @@ export default function FormTaskTaDetail() {
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</div> </div>
</div> */} </div>
</div> </div>
<form> <form>
@ -1255,6 +1293,38 @@ export default function FormTaskTaDetail() {
</Button> </Button>
</div> </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> </div>
<div> <div>
@ -1312,12 +1382,16 @@ export default function FormTaskTaDetail() {
<div> <div>
{selectedText && ( {selectedText && (
<Card className="mt-2"> <Card className="mt-2">
<iframe {/* <iframe
className="w-full h-96 rounded-md" className="w-full h-96 rounded-md"
src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent( src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
selectedText selectedText
)}`} )}`}
title={"Document"} title={"Document"}
/> */}
<iframe
className="w-full h-96"
src={getViewerUrl(selectedText)}
/> />
</Card> </Card>
)} )}
@ -1371,7 +1445,7 @@ export default function FormTaskTaDetail() {
onPause={() => setIsPlaying(false)} onPause={() => setIsPlaying(false)}
/> />
</div> </div>
<Button {/* <Button
size="sm" size="sm"
type="button" type="button"
onClick={onPlayPause} onClick={onPlayPause}
@ -1391,6 +1465,22 @@ export default function FormTaskTaDetail() {
} }
className="h-5 w-5" 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> </Button>
</Card> </Card>
)} )}
@ -1454,6 +1544,24 @@ export default function FormTaskTaDetail() {
)} )}
{isRecording && <p>Recording... {timer} seconds remaining</p>}{" "} {isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
{/* Display remaining time */} {/* 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> </div>
</div> </div>

View File

@ -58,10 +58,8 @@ import { getListCompetencies } from "@/service/management-user/management-user";
const taskSchema = z.object({ const taskSchema = z.object({
// uniqueCode: z.string().min(1, { message: "Judul diperlukan" }), // uniqueCode: z.string().min(1, { message: "Judul diperlukan" }),
title: z.string().min(1, { message: "Judul diperlukan" }), title: z.string().optional(),
naration: z.string().min(2, { naration: z.string().optional(),
message: "Narasi Penugasan harus lebih dari 2 karakter.",
}),
}); });
export type taskDetail = { export type taskDetail = {
@ -585,10 +583,14 @@ export default function FormTaskTaEdit() {
assignedToRole: selectedTarget, assignedToRole: selectedTarget,
assignmentType: taskType, assignmentType: taskType,
assignmentTypeId: type, assignmentTypeId: type,
narration: data.naration, // narration: data.naration,
narration: data.naration ?? detail?.narration ?? "",
expertCompetencies: Array.from(selectedCompetencies).join(","), expertCompetencies: Array.from(selectedCompetencies).join(","),
title: data.title, // title: data.title,
attachmentUrl: links, title: data.title ?? detail?.title ?? "",
attachmentUrl: urlInputs
.map((url: any) => url.attachmentUrl || "")
.filter((url: string) => url.trim() !== ""),
}; };
const response = await createTaskTa(requestData); const response = await createTaskTa(requestData);
@ -802,7 +804,7 @@ export default function FormTaskTaEdit() {
isAudioUploadFinish && isAudioUploadFinish &&
isTextUploadFinish 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 handleLinkChange = (index: number, value: string) => {
const updatedLinks = [...links]; setUrlInputs((prev: any) =>
updatedLinks[index] = value; prev.map((url: any, idx: any) =>
setLinks(updatedLinks); idx === index ? { ...url, attachmentUrl: value } : url
)
);
}; };
const handleAddLink = () => { const handleAddLink = () => {
@ -882,7 +886,9 @@ export default function FormTaskTaEdit() {
)} )}
</div> </div>
<div className="mt-5 space-y-2"> <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"> <div className="flex flex-wrap gap-4">
{userCompetencies?.map((item: any) => ( {userCompetencies?.map((item: any) => (
<div className="flex items-center gap-2" key={item.id}> <div className="flex items-center gap-2" key={item.id}>
@ -897,7 +903,9 @@ export default function FormTaskTaEdit() {
</div> </div>
</div> </div>
<div className="mt-5 space-y-2"> <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"> <div className="flex flex-wrap gap-4">
<Dialog> <Dialog>
<DialogTrigger asChild> <DialogTrigger asChild>
@ -978,7 +986,9 @@ export default function FormTaskTaEdit() {
</div> </div>
<div className="mt-5 space-y-2"> <div className="mt-5 space-y-2">
<Label>{t("description", { defaultValue: "Description" })}</Label> <Label>
{t("description", { defaultValue: "Description" })}
</Label>
<Controller <Controller
control={control} control={control}
name="naration" name="naration"
@ -996,10 +1006,14 @@ export default function FormTaskTaEdit() {
)} )}
</div> </div>
<div className="space-y-2.5 mt-5"> <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-3">
<div className="space-y-2"> <div className="space-y-2">
<Label>{t("audio-visual", { defaultValue: "Audio Visual" })}</Label> <Label>
{t("audio-visual", { defaultValue: "Audio Visual" })}
</Label>
<FileUploader <FileUploader
accept={{ accept={{
"mp4/*": [], "mp4/*": [],
@ -1188,7 +1202,9 @@ export default function FormTaskTaEdit() {
{isRecording && <p>Recording... {timer} seconds remaining</p>}{" "} {isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
{/* Display remaining time */} {/* Display remaining time */}
<div className="mt-4 space-y-2"> <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) => ( {urlInputs.map((url: any, index: any) => (
<div <div
key={url.id} key={url.id}
@ -1205,42 +1221,13 @@ export default function FormTaskTaEdit() {
/> />
</div> </div>
))} ))}
<div className="mt-4 space-y-2"> <button
<Label className="">{t("news-links", { defaultValue: "News Links" })}</Label> type="button"
{links.map((link, index) => ( className="mt-4 bg-green-500 text-white px-4 py-2 rounded"
<div onClick={handleAddLink}
key={index} >
className="flex items-center gap-2 mt-2" {t("add-links", { defaultValue: "Add Links" })}
> </button>
<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"
>
{t("add-links", { defaultValue: "Add Links" })}
</Button>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

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

View File

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

View File

@ -44,9 +44,21 @@ export async function getMediaTrackingResult(data: any) {
return httpGetInterceptor(url); 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( 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); 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) { export async function acceptAssignment(id: any) {
const url = `assignment/acceptance?id=${id}`; const url = `assignment/acceptance?id=${id}`;
return httpPostInterceptor(url, id); return httpPostInterceptor(url, id);