fix: all article detail, update and delete

This commit is contained in:
Sabda Yagra 2025-10-11 20:04:06 +07:00
parent 5cb651b7ae
commit ecb878fc7a
10 changed files with 1287 additions and 2288 deletions

View File

@ -186,7 +186,7 @@ const TableAudio = () => {
totalPage: Number(showData),
title: search || undefined,
categoryId: categoryFilter ? Number(categoryFilter) : undefined,
typeId: 2, // video content type
typeId: 4,
statusId:
statusFilter?.length > 0 ? Number(statusFilter[0]) : undefined,
startDate: formattedStartDate || undefined,

View File

@ -185,7 +185,7 @@ const TableTeks = () => {
totalPage: Number(showData),
title: search || undefined,
categoryId: categoryFilter ? Number(categoryFilter) : undefined,
typeId: 2, // video content type
typeId: 3,
statusId:
statusFilter?.length > 0 ? Number(statusFilter[0]) : undefined,
startDate: formattedStartDate || undefined,

View File

@ -50,6 +50,7 @@ import dynamic from "next/dynamic";
import SuggestionModal from "@/components/modal/suggestions-modal";
import { formatDateToIndonesian } from "@/utils/globals";
import ApprovalHistoryModal from "@/components/modal/approval-history-modal";
import { listArticleCategories } from "@/service/content";
const videoSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
@ -63,7 +64,7 @@ const ViewEditor = dynamic(() => import("@/components/editor/view-editor"), {
type Category = {
id: string;
name: string;
title: string;
};
type FileType = {
@ -153,6 +154,7 @@ export default function FormVideoDetail() {
const [isUserMabesApprover, setIsUserMabesApprover] = useState(false);
const [refresh, setRefresh] = useState(false);
const [detailVideos, setDetailVideos] = useState<string[]>([]);
const [selectedCategory, setSelectedCategory] = useState<string>("");
const {
control,
@ -179,8 +181,8 @@ export default function FormVideoDetail() {
useEffect(() => {
async function fetchCategories() {
const categoryRes = await listEnableCategory("2"); // video type
setCategories(categoryRes?.data || []);
const categoryRes = await listArticleCategories(1, 100);
setCategories(categoryRes?.data.data || []);
}
fetchCategories();
}, []);
@ -191,11 +193,10 @@ export default function FormVideoDetail() {
try {
const response = await getArticleDetail(Number(id));
const details = response?.data?.data;
setSelectedCategory(String(details.categories[0].id));
const mappedDetail: Detail = {
...details,
categoryName:
details?.categories?.[0]?.title || details?.categoryName,
categoryId: details?.categories?.[0]?.id,
htmlDescription: details?.htmlDescription,
statusName: getStatusName(details?.statusId),
uploadedById: details?.createdById,
@ -311,39 +312,17 @@ export default function FormVideoDetail() {
<div className="py-3 w-full space-y-2">
<Label>Category</Label>
<Select
value={selectedCategory}
onValueChange={setSelectedCategory}
disabled
value={String(detail?.categoryId || detail?.category?.id)}
// onValueChange={(id) => {
// console.log("Selected Category:", id);
// setSelectedTarget(id);
// }}
>
<SelectTrigger>
<SelectValue placeholder="Pilih" />
<SelectValue placeholder="Pilih kategori" />
</SelectTrigger>
<SelectContent>
{/* Show the category from details if it doesn't exist in categories list */}
{detail &&
!categories?.find(
(cat) =>
String(cat.id) ===
String(detail.categoryId || detail?.category?.id)
) && (
<SelectItem
key={String(detail.categoryId || detail?.category?.id)}
value={String(
detail.categoryId || detail?.category?.id
)}
>
{detail.categoryName || detail?.category?.name}
</SelectItem>
)}
{categories?.map((category) => (
<SelectItem
key={String(category.id)}
value={String(category.id)}
>
{category.name}
{categories?.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.title}
</SelectItem>
))}
</SelectContent>

File diff suppressed because it is too large Load Diff

View File

@ -25,6 +25,7 @@ import { Switch } from "@/components/ui/switch";
import Cookies from "js-cookie";
import {
createMedia,
getArticleDetail,
getTagsBySubCategoryId,
listEnableCategory,
rejectFiles,
@ -64,6 +65,7 @@ import { formatDateToIndonesian } from "@/utils/globals";
import ApprovalHistoryModal from "@/components/modal/approval-history-modal";
import { useDropzone } from "react-dropzone";
import AudioPlayer from "@/components/audio-player";
import { listArticleCategories } from "@/service/content";
const imageSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
@ -76,7 +78,7 @@ const imageSchema = z.object({
type Category = {
id: string;
name: string;
title: string;
};
type FileType = {
@ -230,28 +232,8 @@ export default function FormAudioDetail() {
}, []);
const getCategories = async () => {
try {
const category = await listEnableCategory(fileTypeId);
const resCategory: Category[] = category?.data.data.content;
setCategories(resCategory);
console.log("data category", resCategory);
if (scheduleId && scheduleType === "3") {
const findCategory = resCategory.find((o) =>
o.name.toLowerCase().includes("pers rilis")
);
if (findCategory) {
// setValue("categoryId", findCategory.id);
setSelectedCategory(findCategory.id);
const response = await getTagsBySubCategoryId(findCategory.id);
setTags(response?.data?.data);
}
}
} catch (error) {
console.error("Failed to fetch categories:", error);
}
const categoryRes = await listArticleCategories(1, 100);
setCategories(categoryRes?.data.data || []);
};
const setupPlacementCheck = (length: number) => {
@ -265,11 +247,12 @@ export default function FormAudioDetail() {
useEffect(() => {
async function initState() {
if (id) {
const response = await detailMedia(id);
const response = await getArticleDetail(Number(id));
const details = response?.data?.data;
console.log("detail", details);
setFiles(details?.files);
console.log("ISI FILES:", details?.files);
setSelectedCategory(String(details.categories[0].id));
setDetail(details);
setMain({
@ -495,36 +478,17 @@ export default function FormAudioDetail() {
<div className="py-3 w-full space-y-2">
<Label>Category</Label>
<Select
value={selectedCategory}
onValueChange={setSelectedCategory}
disabled
value={String(detail?.category?.id)}
// onValueChange={(id) => {
// console.log("Selected Category:", id);
// setSelectedTarget(id);
// }}
>
<SelectTrigger>
<SelectValue placeholder="Pilih" />
<SelectValue placeholder="Pilih kategori" />
</SelectTrigger>
<SelectContent>
{/* Show the category from details if it doesn't exist in categories list */}
{detail &&
!categories.find(
(cat) =>
String(cat.id) === String(detail.category.id)
) && (
<SelectItem
key={String(detail.category.id)}
value={String(detail.category.id)}
>
{detail.category.name}
</SelectItem>
)}
{categories.map((category) => (
<SelectItem
key={String(category.id)}
value={String(category.id)}
>
{category.name}
{categories?.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.title}
</SelectItem>
))}
</SelectContent>

View File

@ -32,8 +32,10 @@ import Cookies from "js-cookie";
import {
createMedia,
deleteFile,
getArticleDetail,
getTagsBySubCategoryId,
listEnableCategory,
updateArticle,
uploadThumbnail,
} from "@/service/content/content";
import { detailMedia } from "@/service/curated-content/curated-content";
@ -47,6 +49,7 @@ import { getCsrfToken } from "@/service/auth";
import { Upload } from "tus-js-client";
import dynamic from "next/dynamic";
import { htmlToString } from "@/utils/globals";
import { listArticleCategories, uploadArticleFiles } from "@/service/content";
const audioSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
@ -54,12 +57,36 @@ const audioSchema = z.object({
.string()
.min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }),
creatorName: z.string().min(1, { message: "Creator diperlukan" }),
// tags: z.string().min(1, { message: "Judul diperlukan" }),
files: z
.array(z.any())
.optional()
.refine(
(files) =>
!files ||
files.every(
(file: File) =>
[
"audio/mpeg",
"audio/wav",
"audio/x-wav",
"audio/mp4",
"audio/aac",
].includes(file.type) && file.size <= 20 * 1024 * 1024
),
{
message:
"Hanya file audio (.mp3, .wav, .m4a, .aac) dengan ukuran maksimal 20MB yang diperbolehkan.",
}
),
publishedFor: z
.array(z.string())
.min(1, { message: "Minimal 1 target publish harus dipilih." }),
});
type Category = {
id: string;
name: string;
title: string;
};
type Detail = {
@ -97,19 +124,16 @@ const CustomEditor = dynamic(
export default function FormAudioUpdate() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const { id } = useParams() as { id: string };
console.log(id);
const editor = useRef(null);
type AudioSchema = z.infer<typeof audioSchema>;
let progressInfo: any = [];
let counterUpdateProgress = 0;
const [progressList, setProgressList] = useState<any>([]);
let uploadPersen = 0;
const [isStartUpload, setIsStartUpload] = useState(false);
const [counterProgress, setCounterProgress] = useState(0);
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const taskId = Cookies.get("taskId");
const scheduleId = Cookies.get("scheduleId");
@ -117,7 +141,7 @@ export default function FormAudioUpdate() {
const [categories, setCategories] = useState<Category[]>([]);
const [selectedCategory, setSelectedCategory] = useState<any>();
const [tags, setTags] = useState<any[]>([]);
const [detail, setDetail] = useState<Detail>();
const [detail, setDetail] = useState<any>(null);
const [refresh, setRefresh] = useState(false);
const [selectedPublishers, setSelectedPublishers] = useState<number[]>([]);
const [detailThumb, setDetailThumb] = useState<any>([]);
@ -131,10 +155,8 @@ export default function FormAudioUpdate() {
const options: Option[] = [
{ id: "all", name: "SEMUA" },
{ id: "5", name: "UMUM" },
{ id: "6", name: "JOURNALIS" },
{ id: "7", name: "POLRI" },
{ id: "8", name: "KSP" },
{ id: "4", name: "UMUM" },
{ id: "5", name: "JOURNALIS" },
];
const [unitSelection, setUnitSelection] = useState({
@ -163,6 +185,7 @@ export default function FormAudioUpdate() {
formState: { errors },
} = useForm<AudioSchema>({
resolver: zodResolver(audioSchema),
defaultValues: { publishedFor: [] },
});
const handleImageChange = (event: ChangeEvent<HTMLInputElement>) => {
@ -186,28 +209,8 @@ export default function FormAudioUpdate() {
}, []);
const getCategories = async () => {
try {
const category = await listEnableCategory(fileTypeId);
const resCategory: Category[] = category?.data.data.content;
setCategories(resCategory);
console.log("data category", resCategory);
if (scheduleId && scheduleType === "3") {
const findCategory = resCategory.find((o) =>
o.name.toLowerCase().includes("pers rilis")
);
if (findCategory) {
// setValue("categoryId", findCategory.id);
setSelectedCategory(findCategory.id); // Set the selected category
const response = await getTagsBySubCategoryId(findCategory.id);
setTags(response?.data?.data);
}
}
} catch (error) {
console.error("Failed to fetch categories:", error);
}
const categoryRes = await listArticleCategories(1, 100);
setCategories(categoryRes?.data.data || []);
};
const handleAddTag = (e: React.KeyboardEvent<HTMLInputElement>) => {
@ -215,7 +218,7 @@ export default function FormAudioUpdate() {
e.preventDefault();
const newTag = e.currentTarget.value.trim();
if (!tags.includes(newTag)) {
setTags((prevTags) => [...prevTags, newTag]); // Tambahkan tag baru
setTags((prevTags) => [...prevTags, newTag]);
if (inputRef.current) {
inputRef.current.value = ""; // Kosongkan input
}
@ -236,23 +239,16 @@ export default function FormAudioUpdate() {
useEffect(() => {
async function initState() {
if (id) {
const response = await detailMedia(id);
const response = await getArticleDetail(Number(id));
const details = response?.data?.data;
setDetail(details);
setSelectedTarget(String(details.category.id));
// Set form values immediately and then again after a delay to ensure editor is ready
setSelectedCategory(String(details.categories[0].id));
setValue("title", details.title);
setValue("description", details.htmlDescription);
setValue("creatorName", details.creatorName);
// Set again after delay to ensure editor has loaded
setTimeout(() => {
setValue("title", details.title);
setValue("description", details.htmlDescription);
setValue("creatorName", details.creatorName);
}, 500);
setValue("creatorName", details.createdByName ?? "");
setTags(details.tags?.split(",").map((t: string) => t.trim()) || []);
setPublishedFor(details.publishedFor?.split(",") || []);
if (details?.files) {
setPrefFiles(details.files);
@ -339,53 +335,76 @@ export default function FormAudioUpdate() {
const save = async (data: AudioSchema) => {
const finalTags = tags.join(", ");
const requestData = {
...data,
id: detail?.id,
title: data.title,
// const requestData = {
// ...data,
// id: detail?.id,
// title: data.title,
// description: htmlToString(data.description),
// htmlDescription: data.description,
// fileTypeId,
// categoryId: selectedTarget,
// subCategoryId: selectedTarget,
// uploadedBy: "2b7c8d83-d298-4b19-9f74-b07924506b58",
// statusId: "1",
// publishedFor: publishedFor.join(","),
// creatorName: data.creatorName,
// tags: finalTags,
// isYoutube: false,
// isInternationalMedia: false,
// };
const payload = {
aiArticleId: detail?.aiArticleId ?? "",
categoryIds: selectedCategory ?? "",
createdById: detail?.createdById ?? "",
description: htmlToString(data.description),
htmlDescription: data.description,
fileTypeId,
categoryId: selectedTarget,
subCategoryId: selectedTarget,
uploadedBy: "2b7c8d83-d298-4b19-9f74-b07924506b58",
statusId: "1",
publishedFor: publishedFor.join(","),
creatorName: data.creatorName,
tags: finalTags,
isYoutube: false,
isInternationalMedia: false,
isDraft: false,
isPublish: true,
slug: detail?.slug ?? data.title.toLowerCase().replace(/\s+/g, "-"),
statusId: detail?.statusId ?? 1,
tags: tags.join(","),
title: data.title,
typeId: detail?.typeId ?? 4,
};
const response = await createMedia(requestData);
console.log("Form Data Submitted:", requestData);
if (response?.error) {
error(response?.message);
return false;
const res = await updateArticle(Number(id), payload);
if (res?.error) {
error(res.message || "Gagal memperbarui data");
return;
}
const formMedia = new FormData();
const thumbnail = files[0];
formMedia.append("file", thumbnail);
const responseThumbnail = await uploadThumbnail(id, formMedia);
if (responseThumbnail?.error == true) {
error(responseThumbnail?.message);
return false;
if (files.length > 0) {
const formData = new FormData();
// Add all files to FormData
files.forEach((file, index) => {
formData.append("files", file);
});
const uploadResponse = await uploadArticleFiles(id, formData);
}
const progressInfoArr = [];
for (const item of files) {
progressInfoArr.push({ percentage: 0, fileName: item.name });
}
progressInfo = progressInfoArr;
setIsStartUpload(true);
setProgressList(progressInfoArr);
// const formMedia = new FormData();
// const thumbnail = files[0];
// formMedia.append("file", thumbnail);
// const responseThumbnail = await uploadThumbnail(id, formMedia);
// if (responseThumbnail?.error == true) {
// error(responseThumbnail?.message);
// return false;
// }
// const progressInfoArr = [];
// for (const item of files) {
// progressInfoArr.push({ percentage: 0, fileName: item.name });
// }
// progressInfo = progressInfoArr;
// setIsStartUpload(true);
// setProgressList(progressInfoArr);
close();
// showProgress();
files.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "0");
});
// files.map(async (item: any, index: number) => {
// await uploadResumableFile(index, String(id), item, "0");
// });
MySwal.fire({
title: "Sukses",
@ -411,7 +430,6 @@ export default function FormAudioUpdate() {
const resCsrf = await getCsrfToken();
const csrfToken = resCsrf?.data?.token;
console.log("CSRF TOKEN : ", csrfToken);
const headers = {
"X-XSRF-TOKEN": csrfToken,
};
@ -690,36 +708,16 @@ export default function FormAudioUpdate() {
<div className="py-3 w-full space-y-2">
<Label>Category</Label>
<Select
value={selectedTarget}
onValueChange={(id) => {
console.log("Selected Category:", id);
setSelectedTarget(id);
}}
value={selectedCategory}
onValueChange={setSelectedCategory}
>
<SelectTrigger>
<SelectValue placeholder="Pilih" />
<SelectValue placeholder="Pilih kategori" />
</SelectTrigger>
<SelectContent>
{/* Show the category from details if it doesn't exist in categories list */}
{detail &&
!categories.find(
(cat) =>
String(cat.id) === String(detail.category.id)
) && (
<SelectItem
key={String(detail.category.id)}
value={String(detail.category.id)}
>
{detail.category.name}
</SelectItem>
)}
{categories.map((category) => (
<SelectItem
key={String(category.id)}
value={String(category.id)}
>
{" "}
{category.name}
{categories?.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.title}
</SelectItem>
))}
</SelectContent>
@ -954,15 +952,9 @@ export default function FormAudioUpdate() {
<Controller
control={control}
name="creatorName"
render={({ field }) => (
<Input
type="text"
value={field?.value}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
render={({ field }) => <Input {...field} />}
/>
{errors.creatorName?.message && (
<p className="text-red-400 text-sm">
{errors.creatorName.message}
@ -1006,23 +998,77 @@ export default function FormAudioUpdate() {
</div>
</div>
<div className="px-3 py-3">
<div className="flex flex-col gap-6 space-y-2">
<div className="mt-4 space-y-2">
<Label>Publish Target</Label>
{options.map((option: Option) => (
<div key={option.id} className="flex gap-2 items-center">
<Checkbox
id={option.id}
checked={
option.id === "all"
? publishedFor.length ===
options.filter((opt) => opt.id !== "all").length
: publishedFor.includes(option.id)
}
onCheckedChange={() => handleCheckboxChange(option.id)}
/>
<Label htmlFor={option.id}>{option.name}</Label>
</div>
))}
<Controller
control={control}
name="publishedFor"
render={({ field }) => (
<div className="py-3">
<div className="flex flex-col gap-3 space-y-2">
{options.map((option) => {
const isAllChecked =
field.value.length ===
options.filter((opt: any) => opt.id !== "all")
.length;
const isChecked =
option.id === "all"
? isAllChecked
: field.value.includes(option.id);
const handleChange = () => {
let updated: string[] = [];
if (option.id === "all") {
updated = isAllChecked
? []
: options
.filter((opt: any) => opt.id !== "all")
.map((opt: any) => opt.id);
} else {
updated = isChecked
? field.value.filter(
(val) => val !== option.id
)
: [...field.value, option.id];
if (isAllChecked && option.id !== "all") {
updated = updated.filter(
(val) => val !== "all"
);
}
}
field.onChange(updated);
setPublishedFor(updated);
};
return (
<div
key={option.id}
className="flex gap-2 items-center"
>
<Checkbox
id={option.id}
checked={isChecked}
onCheckedChange={handleChange}
className="border"
/>
<Label htmlFor={option.id}>{option.name}</Label>
</div>
);
})}
{errors.publishedFor && (
<p className="text-red-500 text-sm">
{errors.publishedFor.message}
</p>
)}
</div>
</div>
)}
/>
</div>
</div>
{/* <div className="px-3 py-3 flex flex-row items-center text-blue-500 gap-2 text-sm">

View File

@ -25,6 +25,7 @@ import { Switch } from "@/components/ui/switch";
import Cookies from "js-cookie";
import {
createMedia,
getArticleDetail,
getTagsBySubCategoryId,
listEnableCategory,
rejectFiles,
@ -63,6 +64,7 @@ import { formatDateToIndonesian } from "@/utils/globals";
import ApprovalHistoryModal from "@/components/modal/approval-history-modal";
import FileTextPreview from "../file-preview-text";
import FileTextThumbnail from "../file-text-thumbnail";
import { listArticleCategories } from "@/service/content";
const imageSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
@ -75,7 +77,7 @@ const imageSchema = z.object({
type Category = {
id: string;
name: string;
title: string;
};
type FileType = {
@ -199,24 +201,8 @@ export default function FormTeksDetail() {
const getCategories = async () => {
try {
const category = await listEnableCategory(fileTypeId);
const resCategory: Category[] = category?.data?.data?.content;
setCategories(resCategory);
console.log("data category", resCategory);
if (scheduleId && scheduleType === "3") {
const findCategory = resCategory.find((o) =>
o.name.toLowerCase().includes("pers rilis")
);
if (findCategory) {
// setValue("categoryId", findCategory.id);
setSelectedCategory(findCategory.id); // Set the selected category
const response = await getTagsBySubCategoryId(findCategory.id);
setTags(response?.data?.data);
}
}
const categoryRes = await listArticleCategories(1, 100);
setCategories(categoryRes?.data.data || []);
} catch (error) {
console.error("Failed to fetch categories:", error);
}
@ -233,9 +219,11 @@ export default function FormTeksDetail() {
useEffect(() => {
async function initState() {
if (id) {
const response = await detailMedia(id);
const response = await getArticleDetail(Number(id));
const details = response?.data?.data;
console.log("detail", details);
setSelectedCategory(String(details.categories[0].id));
setFiles(details?.files);
setDetail(details);
setMain({
@ -441,36 +429,17 @@ export default function FormTeksDetail() {
<div className="py-3 w-full space-y-2">
<Label>Category</Label>
<Select
value={selectedCategory}
onValueChange={setSelectedCategory}
disabled
value={String(detail?.category?.id)}
// onValueChange={(id) => {
// console.log("Selected Category:", id);
// setSelectedTarget(id);
// }}
>
<SelectTrigger>
<SelectValue placeholder="Pilih" />
<SelectValue placeholder="Pilih kategori" />
</SelectTrigger>
<SelectContent>
{/* Show the category from details if it doesn't exist in categories list */}
{detail &&
!categories.find(
(cat) =>
String(cat.id) === String(detail.category.id)
) && (
<SelectItem
key={String(detail.category.id)}
value={String(detail.category.id)}
>
{detail.category.name}
</SelectItem>
)}
{categories.map((category) => (
<SelectItem
key={String(category.id)}
value={String(category.id)}
>
{category.name}
{categories?.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.title}
</SelectItem>
))}
</SelectContent>

View File

@ -31,8 +31,10 @@ import { Switch } from "@/components/ui/switch";
import Cookies from "js-cookie";
import {
createMedia,
getArticleDetail,
getTagsBySubCategoryId,
listEnableCategory,
updateArticle,
uploadThumbnail,
} from "@/service/content/content";
import { detailMedia } from "@/service/curated-content/curated-content";
@ -47,6 +49,7 @@ import { getCsrfToken } from "@/service/auth";
import dynamic from "next/dynamic";
import { htmlToString } from "@/utils/globals";
import Link from "next/link";
import { listArticleCategories, uploadArticleFiles } from "@/service/content";
const teksSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
@ -54,12 +57,35 @@ const teksSchema = z.object({
.string()
.min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }),
creatorName: z.string().min(1, { message: "Creator diperlukan" }),
// tags: z.string().min(1, { message: "Judul diperlukan" }),
files: z
.array(z.any())
.optional()
.refine(
(files) =>
!files ||
files.every(
(file: File) =>
[
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"text/plain",
].includes(file.type) && file.size <= 10 * 1024 * 1024
),
{
message:
"Hanya file .pdf, .doc, .docx, atau .txt dengan ukuran maksimal 10MB yang diperbolehkan.",
}
),
publishedFor: z
.array(z.string())
.min(1, { message: "Minimal 1 target publish harus dipilih." }),
});
type Category = {
id: string;
name: string;
title: string;
};
type Detail = {
@ -106,14 +132,12 @@ export default function FormTeksUpdate() {
console.log(id);
const editor = useRef(null);
type TeksSchema = z.infer<typeof teksSchema>;
let progressInfo: any = [];
let counterUpdateProgress = 0;
const [progressList, setProgressList] = useState<any>([]);
let uploadPersen = 0;
const [isStartUpload, setIsStartUpload] = useState(false);
const [counterProgress, setCounterProgress] = useState(0);
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const taskId = Cookies.get("taskId");
const scheduleId = Cookies.get("scheduleId");
@ -121,10 +145,9 @@ export default function FormTeksUpdate() {
const [categories, setCategories] = useState<Category[]>([]);
const [selectedCategory, setSelectedCategory] = useState<any>();
const [tags, setTags] = useState<any[]>([]);
const [detail, setDetail] = useState<Detail>();
const [detail, setDetail] = useState<any>(null);
const [refresh, setRefresh] = useState(false);
const [selectedPublishers, setSelectedPublishers] = useState<number[]>([]);
const [files, setFiles] = useState<FileWithPreview[]>([]);
const [selectedOptions, setSelectedOptions] = useState<{
[fileId: number]: string[];
@ -155,10 +178,8 @@ export default function FormTeksUpdate() {
const options: Option[] = [
{ id: "all", label: "SEMUA" },
{ id: "5", label: "UMUM" },
{ id: "6", label: "JOURNALIS" },
{ id: "7", label: "POLRI" },
{ id: "8", label: "KSP" },
{ id: "4", label: "UMUM" },
{ id: "5", label: "JOURNALIS" },
];
const {
@ -168,37 +189,9 @@ export default function FormTeksUpdate() {
formState: { errors },
} = useForm<TeksSchema>({
resolver: zodResolver(teksSchema),
defaultValues: { publishedFor: [] },
});
// const handleKeyDown = (e: any) => {
// const newTag = e.target.value.trim(); // Ambil nilai input
// if (e.key === "Enter" && newTag) {
// e.preventDefault(); // Hentikan submit form
// if (!tags.includes(newTag)) {
// setTags((prevTags) => [...prevTags, newTag]); // Tambah tag baru
// setValue("tags", ""); // Kosongkan input
// }
// }
// };
const handleImageChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
const files = Array.from(event.target.files);
setSelectedFiles((prevImages: any) => [...prevImages, ...files]);
console.log("DATAFILE::", selectedFiles);
}
};
const handleRemoveImage = (index: number) => {
setSelectedFiles((prevImages) => prevImages.filter((_, i) => i !== index));
};
// const handleCheckboxChange = (id: number) => {
// setSelectedPublishers((prev) =>
// prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
// );
// };
useEffect(() => {
async function initState() {
getCategories();
@ -208,50 +201,24 @@ export default function FormTeksUpdate() {
}, []);
const getCategories = async () => {
try {
const category = await listEnableCategory(fileTypeId);
const resCategory: Category[] = category?.data?.data?.content;
setCategories(resCategory);
console.log("data category", resCategory);
if (scheduleId && scheduleType === "3") {
const findCategory = resCategory.find((o) =>
o.name.toLowerCase().includes("pers rilis")
);
if (findCategory) {
// setValue("categoryId", findCategory.id);
setSelectedCategory(findCategory.id); // Set the selected category
const response = await getTagsBySubCategoryId(findCategory.id);
setTags(response?.data?.data);
}
}
} catch (error) {
console.error("Failed to fetch categories:", error);
}
const categoryRes = await listArticleCategories(1, 100);
setCategories(categoryRes?.data.data || []);
};
useEffect(() => {
async function initState() {
if (id) {
const response = await detailMedia(id);
const response = await getArticleDetail(Number(id));
const details = response?.data?.data;
setDetail(details);
setSelectedTarget(String(details.category.id));
// Set form values immediately and then again after a delay to ensure editor is ready
setSelectedCategory(String(details.categories[0].id));
console.log("CATEGORIIII", details.categories[0].id);
setValue("title", details.title);
setValue("description", details.htmlDescription);
setValue("creatorName", details.creatorName);
// Set again after delay to ensure editor has loaded
setTimeout(() => {
setValue("title", details.title);
setValue("description", details.htmlDescription);
setValue("creatorName", details.creatorName);
}, 500);
setValue("creatorName", details.createdByName ?? "");
setTags(details.tags?.split(",").map((t: string) => t.trim()) || []);
setPublishedFor(details.publishedFor?.split(",") || []);
if (details?.files) {
setFiles(details.files);
@ -332,58 +299,77 @@ export default function FormTeksUpdate() {
const save = async (data: TeksSchema) => {
loading();
const finalTags = tags.join(", ");
const requestData = {
...data,
id: detail?.id,
title: data.title,
// const requestData = {
// ...data,
// id: detail?.id,
// title: data.title,
// description: htmlToString(data.description),
// htmlDescription: data.description,
// fileTypeId,
// categoryId: selectedTarget,
// subCategoryId: selectedTarget,
// uploadedBy: "2b7c8d83-d298-4b19-9f74-b07924506b58",
// statusId: "1",
// publishedFor: publishedFor.join(","),
// creatorName: data.creatorName,
// tags: finalTags,
// isYoutube: false,
// isInternationalMedia: false,
// };
const payload = {
aiArticleId: detail?.aiArticleId ?? "",
categoryIds: selectedCategory,
createdById: detail?.createdById ?? "",
description: htmlToString(data.description),
htmlDescription: data.description,
fileTypeId,
categoryId: selectedTarget,
subCategoryId: selectedTarget,
uploadedBy: "2b7c8d83-d298-4b19-9f74-b07924506b58",
statusId: "1",
publishedFor: publishedFor.join(","),
creatorName: data.creatorName,
tags: finalTags,
isYoutube: false,
isInternationalMedia: false,
isDraft: false,
isPublish: true,
slug: detail?.slug ?? data.title.toLowerCase().replace(/\s+/g, "-"),
statusId: detail?.statusId ?? 1,
tags: tags.join(","),
title: data.title,
typeId: detail?.typeId ?? 3,
};
const response = await createMedia(requestData);
console.log("Form Data Submitted:", requestData);
if (response?.error) {
error(response?.message);
return false;
const res = await updateArticle(Number(id), payload);
if (res?.error) {
error(res.message || "Gagal memperbarui data");
return;
}
const formMedia = new FormData();
const thumbnail = files[0];
formMedia.append("file", thumbnail);
const responseThumbnail = await uploadThumbnail(id, formMedia);
if (responseThumbnail?.error == true) {
error(responseThumbnail?.message);
return false;
}
if (files.length > 0) {
const formData = new FormData();
const progressInfoArr = [];
for (const item of files) {
progressInfoArr.push({ percentage: 0, fileName: item.name });
// Add all files to FormData
files.forEach((file, index) => {
formData.append("files", file);
});
const uploadResponse = await uploadArticleFiles(id, formData);
}
progressInfo = progressInfoArr;
setIsStartUpload(true);
setProgressList(progressInfoArr);
// const responseThumbnail = await uploadThumbnail(id, formMedia);
// if (responseThumbnail?.error == true) {
// error(responseThumbnail?.message);
// return false;
// }
// const progressInfoArr = [];
// for (const item of files) {
// progressInfoArr.push({ percentage: 0, fileName: item.name });
// }
// progressInfo = progressInfoArr;
// setIsStartUpload(true);
// setProgressList(progressInfoArr);
close();
// showProgress();
files.map(async (item: any, index: number) => {
await uploadResumableFile(
index,
String(id),
item,
fileTypeId == "2" || fileTypeId == "4" ? item.duration : "0"
);
});
// files.map(async (item: any, index: number) => {
// await uploadResumableFile(
// index,
// String(id),
// item,
// fileTypeId == "2" || fileTypeId == "4" ? item.duration : "0"
// );
// });
MySwal.fire({
title: "Sukses",
@ -392,7 +378,7 @@ export default function FormTeksUpdate() {
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/admin/content/document");
router.push("/admin/content/text");
});
};
@ -409,7 +395,7 @@ export default function FormTeksUpdate() {
const resCsrf = await getCsrfToken();
const csrfToken = resCsrf?.data?.token;
console.log("CSRF TOKEN : ", csrfToken);
const headers = {
"X-XSRF-TOKEN": csrfToken,
};
@ -650,36 +636,16 @@ export default function FormTeksUpdate() {
<div className="py-3 w-full space-y-2">
<Label>Category</Label>
<Select
value={selectedTarget}
onValueChange={(id) => {
console.log("Selected Category:", id);
setSelectedTarget(id);
}}
value={selectedCategory}
onValueChange={setSelectedCategory}
>
<SelectTrigger>
<SelectValue placeholder="Pilih" />
<SelectValue placeholder="Pilih kategori" />
</SelectTrigger>
<SelectContent>
{/* Show the category from details if it doesn't exist in categories list */}
{detail &&
!categories.find(
(cat) =>
String(cat.id) === String(detail.category.id)
) && (
<SelectItem
key={String(detail.category.id)}
value={String(detail.category.id)}
>
{detail.category.name}
</SelectItem>
)}
{categories.map((category) => (
<SelectItem
key={String(category.id)}
value={String(category.id)}
>
{" "}
{category.name}
{categories?.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.title}
</SelectItem>
))}
</SelectContent>
@ -861,15 +827,9 @@ export default function FormTeksUpdate() {
<Controller
control={control}
name="creatorName"
render={({ field }) => (
<Input
type="text"
value={field?.value}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
render={({ field }) => <Input {...field} />}
/>
{errors.creatorName?.message && (
<p className="text-red-400 text-sm">
{errors.creatorName.message}
@ -923,24 +883,79 @@ export default function FormTeksUpdate() {
</div>
</div>
<div className="px-3 py-3">
<div className="flex flex-col gap-6">
<div className="mt-4 space-y-2">
<Label>Publish Target</Label>
{options.map((option: any) => (
<div key={option.id} className="flex gap-2 items-center">
<Checkbox
id={option.id}
checked={
option.id === "all"
? publishedFor.length ===
<Controller
control={control}
name="publishedFor"
render={({ field }) => (
<div className="py-3">
<div className="flex flex-col gap-3 space-y-2">
{options.map((option) => {
const isAllChecked =
field.value.length ===
options.filter((opt: any) => opt.id !== "all")
.length
: publishedFor.includes(option.id)
}
onCheckedChange={() => handleCheckboxChange(option.id)}
/>
<Label htmlFor={option.id}>{option.label}</Label>
</div>
))}
.length;
const isChecked =
option.id === "all"
? isAllChecked
: field.value.includes(option.id);
const handleChange = () => {
let updated: string[] = [];
if (option.id === "all") {
updated = isAllChecked
? []
: options
.filter((opt: any) => opt.id !== "all")
.map((opt: any) => opt.id);
} else {
updated = isChecked
? field.value.filter(
(val) => val !== option.id
)
: [...field.value, option.id];
if (isAllChecked && option.id !== "all") {
updated = updated.filter(
(val) => val !== "all"
);
}
}
field.onChange(updated);
setPublishedFor(updated);
};
return (
<div
key={option.id}
className="flex gap-2 items-center"
>
<Checkbox
id={option.id}
checked={isChecked}
onCheckedChange={handleChange}
className="border"
/>
<Label htmlFor={option.id}>
{option.label}
</Label>
</div>
);
})}
{errors.publishedFor && (
<p className="text-red-500 text-sm">
{errors.publishedFor.message}
</p>
)}
</div>
</div>
)}
/>
</div>
</div>
<div className="px-3 py-3 flex flex-row items-center text-blue-500 gap-2 text-sm">

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,7 @@ import {
httpDeleteInterceptor,
httpGetInterceptor,
httpPostInterceptor,
httpPutInterceptor,
} from "../http-config/http-interceptor-service";
// Interface for Articles API filters
@ -24,6 +25,24 @@ export interface ArticleFilters {
endDate?: string;
}
// types/article.ts
export interface UpdateArticleData {
aiArticleId?: number;
categoryIDs: string;
createdAt?: string;
createdById?: number;
description?: string;
htmlDescription?: string;
isDraft: boolean;
isPublish: boolean;
slug?: string;
statusId?: number;
tags?: string;
title: string;
typeId?: number;
}
// Interface for creating new article
export interface CreateArticleData {
aiArticleId: number;
@ -228,6 +247,11 @@ export async function createMedia(data: any) {
return httpPostInterceptor(url, data);
}
export async function updateArticle(id: number, data: any) {
const url = `articles/${id}`;
return httpPutInterceptor(url, data);
}
// New Articles API - Create Article
export async function createArticle(data: CreateArticleData) {
const url = "articles";
@ -323,6 +347,11 @@ export async function deleteFile(data: any) {
return httpDeleteInterceptor(url, data);
}
export async function deleteArticleFile(id: number) {
const url = `article-files/${id}`;
return httpDeleteInterceptor(url);
}
export async function deleteSPIT(id: any) {
const url = `media/spit?id=${id}`;
return httpDeleteInterceptor(url);