fix:fixing import

This commit is contained in:
Sabda Yagra 2025-09-30 13:55:22 +07:00
parent 7012e43ef9
commit 5fd9883aba
47 changed files with 8934 additions and 127 deletions

View File

@ -24,29 +24,6 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
ChevronLeft,
ChevronRight,
Eye,
MoreVertical,
Search,
SquarePen,
Trash2,
TrendingDown,
TrendingUp,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { paginationBlog } from "@/service/blog/blog";
import { ticketingPagination } from "@/service/ticketing/ticketing";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";

View File

@ -54,14 +54,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
getWeeklyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import { getOnlyDate } from "@/utils/globals";
import { useParams } from "next/navigation";
import { getPlanningById } from "@/service/planning/planning";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { getWeeklyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
date: z.date({

View File

@ -54,14 +54,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
getWeeklyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import { getOnlyDate } from "@/utils/globals";
import { useParams } from "next/navigation";
import { getPlanningById } from "@/service/planning/planning";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { getWeeklyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
date: z.date({

View File

@ -54,12 +54,9 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
getWeeklyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import { getOnlyDate } from "@/utils/globals";
import dynamic from "next/dynamic";
import { getWeeklyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
date: z.date({

View File

@ -29,10 +29,10 @@ import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
month: z.date({

View File

@ -13,7 +13,6 @@ import { CalendarIcon } from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import {
Form,
FormControl,
@ -29,10 +28,10 @@ import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
month: z.date({

View File

@ -13,7 +13,6 @@ import { CalendarIcon } from "lucide-react";
import React, { useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import {
Form,
FormControl,
@ -28,11 +27,9 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { error } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";
import month from "react-datepicker/dist/month";
import year from "react-datepicker/dist/year";
import { close, error } from "@/config/swal";
import dynamic from "next/dynamic";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
month: z.date({

View File

@ -30,10 +30,7 @@ import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
getMonthlyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
Select,
SelectContent,
@ -42,9 +39,10 @@ import {
SelectValue,
} from "@/components/ui/select";
import dayjs from "dayjs";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/service/planning/planning";
const FormSchema = z.object({
week: z.object({

View File

@ -30,10 +30,7 @@ import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
getMonthlyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
Select,
SelectContent,
@ -42,9 +39,10 @@ import {
SelectValue,
} from "@/components/ui/select";
import dayjs from "dayjs";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/service/planning/planning";
const FormSchema = z.object({
week: z.object({

View File

@ -30,10 +30,6 @@ import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { error } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
getMonthlyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
Select,
SelectContent,
@ -43,6 +39,7 @@ import {
} from "@/components/ui/select";
import dayjs from "dayjs";
import dynamic from "next/dynamic";
import { getMonthlyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const CustomEditor = dynamic(
() => {

View File

@ -5,12 +5,12 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { close, loading } from "@/config/swal";
import { getWeeklyPlanList } from "@/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { getWeeklyPlanList } from "@/service/service/agenda-setting/agenda-setting";
const ViewEditor = dynamic(
() => {

View File

@ -24,29 +24,6 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
ChevronLeft,
ChevronRight,
Eye,
MoreVertical,
Search,
SquarePen,
Trash2,
TrendingDown,
TrendingUp,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { paginationBlog } from "@/service/blog/blog";
import { ticketingPagination } from "@/service/ticketing/ticketing";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";

View File

@ -54,14 +54,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
getWeeklyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import { getOnlyDate } from "@/utils/globals";
import { useParams } from "next/navigation";
import { getPlanningById } from "@/service/planning/planning";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { getWeeklyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
date: z.date({

View File

@ -54,14 +54,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
getWeeklyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import { getOnlyDate } from "@/utils/globals";
import { useParams } from "next/navigation";
import { getPlanningById } from "@/service/planning/planning";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { getWeeklyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
date: z.date({

View File

@ -37,10 +37,6 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
getWeeklyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import { id } from "date-fns/locale";
import { close, error, loading } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
@ -59,6 +55,7 @@ import {
} from "@/components/ui/dialog";
import { getUserLevelForAssignments } from "@/service/task";
import dynamic from "next/dynamic";
import { getWeeklyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
date: z.date({

View File

@ -29,10 +29,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
month: z.date({

View File

@ -13,7 +13,6 @@ import { CalendarIcon } from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import {
Form,
FormControl,
@ -29,10 +28,10 @@ import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
month: z.date({

View File

@ -29,8 +29,8 @@ import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { error } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";
import dynamic from "next/dynamic";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
month: z.date({

View File

@ -30,10 +30,6 @@ import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
getMonthlyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
Select,
SelectContent,
@ -42,9 +38,10 @@ import {
SelectValue,
} from "@/components/ui/select";
import dayjs from "dayjs";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/service/planning/planning";
const FormSchema = z.object({
week: z.object({

View File

@ -30,10 +30,6 @@ import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
getMonthlyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
Select,
SelectContent,
@ -42,9 +38,10 @@ import {
SelectValue,
} from "@/components/ui/select";
import dayjs from "dayjs";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { savePlanning } from "@/service/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/service/planning/planning";
const FormSchema = z.object({
week: z.object({

View File

@ -30,10 +30,6 @@ import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { error } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
getMonthlyPlanList,
savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
Select,
SelectContent,
@ -42,6 +38,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import dynamic from "next/dynamic";
import { getMonthlyPlanList, savePlanning } from "@/service/service/agenda-setting/agenda-setting";
const FormSchema = z.object({
week: z.object({

View File

@ -5,12 +5,12 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { close, loading } from "@/config/swal";
import { getWeeklyPlanList } from "@/service/agenda-setting/agenda-setting";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { getPlanningById } from "@/service/service/planning/planning";
import { getWeeklyPlanList } from "@/service/service/agenda-setting/agenda-setting";
const ViewEditor = dynamic(
() => {

View File

@ -1,6 +1,6 @@
"use client";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import FormDetailLiveReport from "@/components/form/schedule/live-report-detail-form";
import SiteBreadcrumb from "@/components/site-breadcrumb";
const LiveReportDetailPage = () => {
return (

View File

@ -0,0 +1,558 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Clock1, Eye, MapPin, Plus, User2 } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { formatDate } from "@fullcalendar/core/index.js";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Link } from "@/i18n/routing";
import { detailSchedule, getListScheduleAttachment, listScheduleNext, listScheduleToday } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
interface Attachment {
id: any;
title: string;
fileTypeId: number;
type: number;
fileTypeName: string;
}
export default function FormEventDetail() {
const [open, setOpen] = useState(false);
const { id } = useParams() as { id: string };
console.log(id);
const router = useRouter();
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [todayList, setTodayList] = useState([]);
const [nextDayList, setNextDayList] = useState([]);
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
const [lampiran, setDataLampiran] = useState<Attachment[]>([]);
async function getDataAttachment() {
const response = await getListScheduleAttachment(id);
console.log("data attach", response?.data?.data?.content);
setDataLampiran(response?.data?.data?.content);
}
async function getDataByDate() {
const resToday = await listScheduleToday();
const today = resToday?.data?.data;
setTodayList(today);
const resNext = await listScheduleNext();
const next = resNext?.data?.data;
setNextDayList(next);
}
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
}
getDataByDate();
}
}
initState();
getDataAttachment();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const handleDestinationUpload = (
type: number,
id: string | number,
setOpen: (open: boolean) => void,
router: any
) => {
setOpen(false); // Tutup modal dialog
if (id !== undefined) {
Cookies.set("scheduleId", id.toString(), { expires: 1 });
Cookies.set("scheduleType", "3", { expires: 1 });
const routes: Record<number, string> = {
1: "/in/contributor/schedule/media/image/create",
2: "/in/contributor/schedule/media/video/create",
3: "/in/contributor/schedule/media/text/create",
4: "/in/contributor/schedule/media/audio/create",
};
router.push(routes[type] || "/admin/schedule/media/audio/create");
}
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Event</p>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
value={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-6">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-6 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div className="mt-6">
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={detail?.address}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semibold mt-6">
DI SAMPAIKAN OLEH
</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className="flex justify-between">
<Button color="primary" size="sm" type="button">
<Plus /> Tambah Lampiran
</Button>
<p>{lampiran?.length || 0} Lampiran</p>
</div>
</DialogTrigger>
<DialogContent className="max-w-md p-6 bg-white rounded-lg shadow-lg h-[420px] w-[700px]">
<h2 className="text-lg font-semibold">
Pilih Jenis Lampiran
</h2>
<div className="space-y-4 gap-y-4">
{[
{
type: 2,
img: "/assets/img/upload-video.png",
label: "Audio Visual",
},
{
type: 1,
img: "/assets/img/upload-image.png",
label: "Foto",
},
{
type: 3,
img: "/assets/img/upload-text.png",
label: "Teks",
},
{
type: 4,
img: "/assets/img/upload-audio.png",
label: "Audio",
},
].map((item) => (
<a
key={item.type}
onClick={() =>
handleDestinationUpload(
item.type,
id,
setOpen,
router
)
}
>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={item.img}
alt={item.label}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">
{item.label}
</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa {item.label.toLowerCase()}{" "}
dengan format sesuai yang didukung.
</p>
</div>
</div>
</a>
))}
</div>
</DialogContent>
</Dialog>
</div>
) : (
""
)}
</div>
<div className="mt-6 mx-6">
<table className="w-full border border-gray-300 rounded-lg">
<thead className="bg-gray-200 text-left">
<tr>
<th className="p-3 font-semibold">Judul Konten</th>
<th className="p-3 font-semibold">Konten</th>
<th className="p-3 font-semibold">Tindakan</th>
<th className="p-3 font-semibold">Aksi</th>
</tr>
</thead>
<tbody>
{lampiran.map((item, index) => (
<tr key={index} className="border-t border-gray-300">
<td className="p-3 text-blue-600 cursor-pointer">
{item.title}
</td>
<td className="p-3">{item.fileTypeName}</td>
<td className="p-3 text-blue-600">Konfersi Ai</td>
<td className="p-3">
<Link
href={
Number(item.fileTypeId) == 1
? `/contributor/content/image/detail/${item.id}`
: Number(item.fileTypeId) == 2
? `/contributor/content/video/detail/${item.id}`
: Number(item.fileTypeId) == 3
? `/contributor/content/teks/detail/${item.id}`
: `/contributor/content/audio/detail/${item.id}`
}
target="_blank"
className="btn"
rel="noreferrer"
>
<Eye
className={
item.type === 1 ? "text-blue-600" : "text-black"
}
/>
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="my-4 mr-6 flex justify-end">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<Accordion type="single" collapsible>
{/* Jadwal Hari Ini */}
<AccordionItem value="today">
<AccordionTrigger className="font-semibold">
Jadwal Hari Ini
</AccordionTrigger>
<AccordionContent>
{todayList?.length > 0 ? (
<ul className="list-disc ml-4">
{todayList.map((item: any, index) => (
<li key={index} className="py-1">
{item.name}
</li>
))}
</ul>
) : (
<p className="text-gray-500">Tidak ada jadwal hari ini</p>
)}
</AccordionContent>
</AccordionItem>
{/* Jadwal Selanjutnya */}
<AccordionItem value="next">
<AccordionTrigger className="font-semibold">
Jadwal Selanjutnya
</AccordionTrigger>
<AccordionContent>
{nextDayList?.length > 0 ? (
<div className="list-disc ">
{nextDayList.map((item: any, index) => (
<div key={index} className="">
<li className="text-base font-semibold">{item.title}</li>
<p className="text-sm ml-5 flex my-2">
<CalendarIcon size={20} />
{formatDate(item?.startDate)}-
{formatDate(item?.endDate)}
</p>
<p className="text-sm ml-5 flex my-2">
<Clock1 size={20} />
{item?.startTime}-{item?.endTime}
</p>
<p className="text-sm ml-5 flex items-center my-2">
<MapPin size={50} />
{item?.address}
</p>
<p className="text-sm ml-5">Disampaikan oleh:</p>
<p className="text-sm ml-5 flex my-2">
<User2 />
{item?.speakerTitle} {item?.speakerName}
</p>
</div>
// <p>{item.startDate}</p>
))}
</div>
) : (
<p className="text-gray-500">Tidak ada jadwal selanjutnya</p>
)}
</AccordionContent>
</AccordionItem>
</Accordion>
</Card>
</div>
);
}

View File

@ -0,0 +1,394 @@
"use client";
import React, { useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Plus } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import { register } from "module";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error } from "@/lib/swal";
import Cookies from "js-cookie";
import { useRouter } from "@/i18n/routing";
import { postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
export default function FormEvent() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const editor = useRef(null);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = React.useState<DateRange | undefined>();
const handleStartTime = (e: any) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: any) => {
setEndTime(e.target.value);
};
// State for various form fields
const [assignmentType, setAssignmentType] = useState("mediahub");
const [assignmentCategory, setAssignmentCategory] = useState("publication");
const [selectedTarget, setSelectedTarget] = useState("all");
const [unitSelection, setUnitSelection] = useState({
allUnit: false,
mabes: false,
polda: false,
polres: false,
});
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
const save = async (data: TaskSchema) => {
const requestData = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime, // Start time from state
endTime, // End time from state
addressLat: "0.0", // Replace with actual latitude
addressLong: "0.0", // Replace with actual longitude
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: 2,
};
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
// Optional: Use Swal for success feedback
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/contributor/schedule/event");
});
};
const onSubmit = (data: TaskSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
const handleUploadAttachment = () => {
const scheduleId = Cookies.get("scheduleId");
if (scheduleId == undefined) {
MySwal.fire({
title: "Simpan Jadwal Terlebih Dahulu",
icon: "info",
confirmButtonColor: "#3085d6",
confirmButtonText: "Ok",
}).then((result) => {
if (result.isConfirmed) {
return true;
}
});
}
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Event</p>
<form onSubmit={handleSubmit(onSubmit)}>
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Judul"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-5">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div className="">
<div className="flex flex-row items-center">
<div className="col-6">
<Input
defaultValue="08:00"
type="time"
onChange={(e) => handleStartTime(e)}
/>
</div>
<div className="col-6">
<Input
defaultValue="09:00"
type="time"
onChange={(e) => handleEndTime(e)}
/>
</div>
</div>
</div>
</div>
</div>
<div>
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={field.value}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
<div className="flex flex-row items-center justify-between">
<Button
onClick={() => handleUploadAttachment()}
color="primary"
size="sm"
type="button"
>
<Plus />
Tambah Lampiran
</Button>
<p>0 Llampiran</p>
</div>
<div className="mt-4 flex justify-end">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,498 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Plus } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Link } from "@/i18n/routing";
import { detailSchedule, postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
export default function FormEventUpdate() {
const [open, setOpen] = useState(false);
const { id } = useParams() as { id: string };
console.log(id);
const router = useRouter();
const MySwal = withReactContent(Swal);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
}
}
}
initState();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const save = async (data: TaskSchema) => {
const requestData: {
id?: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
startTime: string;
endTime: string;
addressLat: string;
addressLong: string;
startDate: string | null;
endDate: string | null;
isYoutube: boolean;
scheduleTypeId: number;
} = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime, // Start time from state
endTime, // End time from state
addressLat: "0.0", // Replace with actual latitude
addressLong: "0.0", // Replace with actual longitude
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: 2,
};
// Add id property if it exists
if (id) {
requestData.id = parseInt(id, 10); // Ensure id is a number
}
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/en/contributor/schedule/event");
});
};
const onSubmit = (data: TaskSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Event</p>
<form onSubmit={handleSubmit(onSubmit)}>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
defaultValue={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-5">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div>
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
defaultValue={detail?.address}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className="flex justify-between">
<Button color="primary" size="sm" type="button">
<Plus /> Tambah Lampiran
</Button>
<p>0 Lampiran</p>
</div>
</DialogTrigger>
<DialogContent className="max-w-md p-6 bg-white rounded-lg shadow-lg h-[420px] w-[700px]">
<h2 className="text-lg font-semibold">
Pilih Jenis Lampiran
</h2>
<div className=" space-y-4 gap-y-4">
<Link href={"/contributor/schedule/media/video/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-video.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">
Audio Visual
</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
<Link href={"/contributor/schedule/media/image/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-image.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">Foto</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
<Link href={"/contributor/schedule/media/text/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-text.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">Teks</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
<Link href={"/contributor/schedule/media/audio/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-audio.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">Audio</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
</div>
</DialogContent>
</Dialog>
</div>
) : (
""
)}
<div className="mt-4 flex justify-end">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,521 @@
// components/TambahIklanModal.tsx
"use client";
import * as React from "react";
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { CalendarIcon, ChevronDown, ChevronUp, Plus } from "lucide-react";
import { useTranslations } from "next-intl";
import "react-datepicker/dist/react-datepicker.css";
import { zodResolver } from "@hookform/resolvers/zod";
import router from "next/router";
import { Controller, useForm } from "react-hook-form";
import { date, z } from "zod";
import { error } from "@/lib/swal";
import { DateRange } from "react-day-picker";
import Cookies from "js-cookie";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { format, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import { getUserLevelForAssignments } from "@/service/task";
import { Card } from "@/components/ui/card";
import { useParams } from "next/navigation";
import { Link } from "@/i18n/routing";
import { detailCalendar, postCalendar } from "@/service/service/schedule/schedule";
const calendarSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
description: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
description: string;
}
export function CalendarPolriAddDetail() {
const MySwal = withReactContent(Swal);
const { id } = useParams() as { id: string };
const [open, setOpen] = React.useState(false);
const t = useTranslations("Schedule");
type CalendarSchema = z.infer<typeof calendarSchema>;
const [eventDate, setEventDate] = React.useState<Date | null>(new Date());
const [listDest, setListDest] = React.useState([]);
const [checkedLevels, setCheckedLevels] = React.useState(new Set());
const [expandedPolda, setExpandedPolda] = React.useState([{}]);
const [isLoading, setIsLoading] = React.useState(false);
const [detail, setDetail] = React.useState<Detail>();
const [date, setDate] = React.useState<DateRange | undefined>();
const [refresh, setRefresh] = React.useState(false);
const [unitSelection, setUnitSelection] = React.useState({
semua: false,
mabes: false,
polda: false,
satker: false,
internasional: false,
});
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<CalendarSchema>({
resolver: zodResolver(calendarSchema),
defaultValues: {
description: "",
},
});
React.useEffect(() => {
async function initState() {
if (id) {
const response = await detailCalendar(id);
const details = response?.data?.data;
setDetail(details);
// if (details) {
// setDate({
// from: parseISO(details.startDate),
// to: parseISO(details.endDate),
// });
// }
if (details?.startDate && details?.endDate) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
} else {
// atau biarkan kosong sesuai kebutuhan
}
if (details?.assignedTo) {
const assignedToArray = details.assignedTo.split(",");
const newUnitSelection = { ...unitSelection };
assignedToArray.forEach((val: any) => {
switch (val) {
case "0":
newUnitSelection.semua = true;
break;
case "1":
newUnitSelection.mabes = true;
break;
case "2":
newUnitSelection.polda = true;
break;
case "3":
newUnitSelection.satker = true;
break;
case "4":
newUnitSelection.internasional = true;
break;
default:
break;
}
});
setUnitSelection(newUnitSelection);
}
// 2. Set checkbox wilayah
if (details?.assignedToLevel) {
const levelIds = details.assignedToLevel
.split(",")
.map((id: string) => parseInt(id));
setCheckedLevels(new Set(levelIds));
}
}
}
initState();
}, [refresh, setValue]);
React.useEffect(() => {
async function fetchPoldaPolres() {
setIsLoading(true);
try {
const response = await getUserLevelForAssignments();
setListDest(response?.data?.data.list);
console.log("polda", response?.data?.data?.list);
const initialExpandedState = response?.data?.data.list.reduce(
(acc: any, polda: any) => {
acc[polda.id] = false;
return acc;
},
{}
);
setExpandedPolda(initialExpandedState);
console.log("polres", initialExpandedState);
} catch (error) {
console.error("Error fetching Polda/Polres data:", error);
} finally {
setIsLoading(false);
}
}
fetchPoldaPolres();
}, []);
const handleCheckboxChange = (levelId: number) => {
setCheckedLevels((prev) => {
const updatedLevels = new Set(prev);
if (updatedLevels.has(levelId)) {
updatedLevels.delete(levelId);
} else {
updatedLevels.add(levelId);
}
return updatedLevels;
});
};
const handlePoldaPolresChange = () => {
return Array.from(checkedLevels).join(","); // Mengonversi Set ke string
};
const handleUnitChange = (
key: keyof typeof unitSelection,
value: boolean
) => {
if (key === "semua") {
const newState = {
semua: value,
mabes: value,
polda: value,
satker: value,
internasional: value,
};
setUnitSelection(newState);
} else {
const updatedSelection = {
...unitSelection,
[key]: value,
};
const allChecked = ["mabes", "polda", "satker", "internasional"].every(
(k) => updatedSelection[k as keyof typeof unitSelection]
);
updatedSelection.semua = allChecked;
setUnitSelection(updatedSelection);
}
};
const toggleExpand = (poldaId: any) => {
setExpandedPolda((prev: any) => ({
...prev,
[poldaId]: !prev[poldaId],
}));
};
const save = async (data: CalendarSchema) => {
const unitMapping = {
allUnit: "0",
mabes: "1",
polda: "2",
satker: "4",
internasional: "5",
};
const assignmentToString = Object.keys(unitSelection)
.filter((key) => unitSelection[key as keyof typeof unitSelection])
.map((key) => unitMapping[key as keyof typeof unitMapping])
.join(",");
const requestData = {
title: data.title,
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
description: data.description,
assignedTo: assignmentToString,
assignedToLevel: handlePoldaPolresChange(),
};
console.log("Form Data Submitted:", requestData);
const response = await postCalendar(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.reload();
});
};
const onSubmit = (data: CalendarSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div>
<Card className="px-3 py-3">
{detail !== undefined ? (
<div className="space-y-4">
<div>
<p className="font-medium mb-1">Tanggal Acara</p>
<div className="flex flex-col space-y-2">
<Popover>
<PopoverTrigger asChild className="px-0">
<Button
size="md"
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal border border-slate-300 px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
</div>
<div>
<p className="font-medium">Publish Area</p>
<div className="flex flex-row">
<div className="flex flex-wrap gap-3 lg:ml-3 ">
{Object.keys(unitSelection).map((key) => (
<div className="flex items-center gap-2" key={key}>
<Checkbox
id={key}
checked={
unitSelection[key as keyof typeof unitSelection]
}
onCheckedChange={(value) =>
handleUnitChange(
key as keyof typeof unitSelection,
value as boolean
)
}
/>
<Label htmlFor={key}>
{key.charAt(0).toUpperCase() + key.slice(1)}
</Label>
</div>
))}
</div>
<div className=" lg:pl-3">
<Dialog>
<DialogTrigger asChild>
<Button variant="soft" size="sm" color="primary">
[{t("custom", { defaultValue: "Custom" })}]
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
<DialogHeader>
<DialogTitle>
Daftar Wilayah Polda dan Polres
</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
{listDest.map((polda: any) => (
<div key={polda.id} className="border p-2">
<Label className="flex items-center">
<Checkbox
checked={checkedLevels.has(polda.id)}
onCheckedChange={() =>
handleCheckboxChange(polda.id)
}
className="mr-3"
/>
{polda.name}
<button
onClick={() => toggleExpand(polda.id)}
className="ml-2 focus:outline-none"
>
{expandedPolda[polda.id] ? (
<ChevronUp size={16} />
) : (
<ChevronDown size={16} />
)}
</button>
</Label>
{expandedPolda[polda.id] && (
<div className="ml-6 mt-2">
<Label className="block">
<Checkbox
checked={polda?.subDestination?.every(
(polres: any) =>
checkedLevels.has(polres.id)
)}
onCheckedChange={(isChecked) => {
const updatedLevels = new Set(
checkedLevels
);
polda?.subDestination?.forEach(
(polres: any) => {
if (isChecked) {
updatedLevels.add(polres.id);
} else {
updatedLevels.delete(polres.id);
}
}
);
setCheckedLevels(updatedLevels);
}}
className="mr-2"
/>
Pilih Semua Polres
</Label>
{polda?.subDestination?.map((polres: any) => (
<Label key={polres.id} className="block mt-1">
<Checkbox
checked={checkedLevels.has(polres.id)}
onCheckedChange={() =>
handleCheckboxChange(polres.id)
}
className="mr-2"
/>
{polres.name}
</Label>
))}
</div>
)}
</div>
))}
</div>
</DialogContent>
</Dialog>
</div>
</div>
</div>
<div>
<p className="font-medium">Nama Acara</p>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.title}
onChange={field.onChange}
placeholder="Masukan Judul"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="border-2 border-dashed rounded-md p-4 flex flex-col items-center justify-center text-center text-sm text-muted-foreground">
<svg
className="w-6 h-6 mb-2 text-blue-500"
fill="none"
stroke="currentColor"
strokeWidth="2"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1M12 12v9m0-9l3 3m-3-3l-3 3m6-11a4 4 0 00-8 0v1H4a2 2 0 00-2 2v4h20v-4a2 2 0 00-2-2h-4v-1z"
/>
</svg>
<div>
Drag your file(s) or{" "}
<span className="text-blue-500 underline cursor-pointer">
browse
</span>
</div>
<div className="text-xs mt-1">Max 10 MB files are allowed</div>
</div>
<div>
<p className="font-medium">Deskripsi</p>
<Controller
control={control}
name="description"
render={({ field }) => (
<Textarea
rows={3}
value={detail?.description}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
{errors.description?.message && (
<p className="text-red-400 text-sm">
{errors.description?.message}
</p>
)}
</div>
</div>
) : (
""
)}
<div className="text-right">
<Link href={"contributor/schedule/calendar-polri"}>
<Button type="button" variant={"outline"} color="primary">
Kembali
</Button>
</Link>
</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,680 @@
// components/TambahIklanModal.tsx
"use client";
import * as React from "react";
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
CalendarIcon,
ChevronDown,
ChevronUp,
CloudUpload,
Plus,
} from "lucide-react";
import { useTranslations } from "next-intl";
import "react-datepicker/dist/react-datepicker.css";
import { zodResolver } from "@hookform/resolvers/zod";
import router from "next/router";
import { Controller, useForm } from "react-hook-form";
import { date, z } from "zod";
import { error, loading } from "@/lib/swal";
import { DateRange } from "react-day-picker";
import Cookies from "js-cookie";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { format, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import { getUserLevelForAssignments } from "@/service/task";
import { Card } from "@/components/ui/card";
import { useDropzone } from "react-dropzone";
import { Icon } from "@/components/ui/icon";
import Image from "next/image";
import FileUploader from "../shared/file-uploader";
import { getCsrfToken } from "@/service/auth";
import { Upload } from "tus-js-client";
import { useParams } from "next/navigation";
import { detailCalendar, postCalendar } from "@/service/service/schedule/schedule";
const calendarSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
description: z.string().min(1, { message: "Judul diperlukan" }),
});
interface FileWithPreview extends File {
preview: string;
}
interface FileUploaded {
id: number;
url: string;
}
interface Detail {
id: number;
title: string;
description: string;
}
export function CalendarPolriAddUpdate() {
const MySwal = withReactContent(Swal);
const { id } = useParams() as { id: string };
const [open, setOpen] = React.useState(false);
const t = useTranslations("Schedule");
type CalendarSchema = z.infer<typeof calendarSchema>;
const [eventDate, setEventDate] = React.useState<Date | null>(new Date());
const [listDest, setListDest] = React.useState([]);
const [checkedLevels, setCheckedLevels] = React.useState(new Set());
const [expandedPolda, setExpandedPolda] = React.useState([{}]);
const [isLoading, setIsLoading] = React.useState(false);
const [isImageUploadFinish, setIsImageUploadFinish] = React.useState(false);
const [files, setFiles] = React.useState<FileWithPreview[]>([]);
const [imageUploadedFiles, setImageUploadedFiles] = React.useState<
FileUploaded[]
>([]);
const [detail, setDetail] = React.useState<Detail>();
const [imageFiles, setImageFiles] = React.useState<FileWithPreview[]>([]);
const [date, setDate] = React.useState<DateRange | undefined>();
const [refresh, setRefresh] = React.useState(false);
const [unitSelection, setUnitSelection] = React.useState({
semua: false,
mabes: false,
polda: false,
satker: false,
internasional: false,
});
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<CalendarSchema>({
resolver: zodResolver(calendarSchema),
defaultValues: {
description: "",
},
});
React.useEffect(() => {
async function initState() {
if (id) {
const response = await detailCalendar(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
// 1. Set unit selection
if (details?.assignedTo) {
const assignedToArray = details.assignedTo.split(",");
const newUnitSelection = { ...unitSelection };
assignedToArray.forEach((val: any) => {
switch (val) {
case "0":
newUnitSelection.semua = true;
break;
case "1":
newUnitSelection.mabes = true;
break;
case "2":
newUnitSelection.polda = true;
break;
case "3":
newUnitSelection.satker = true;
break;
case "4":
newUnitSelection.internasional = true;
break;
default:
break;
}
});
setUnitSelection(newUnitSelection);
}
// 2. Set checkbox wilayah
if (details?.assignedToLevel) {
const levelIds = details.assignedToLevel
.split(",")
.map((id: string) => parseInt(id));
setCheckedLevels(new Set(levelIds));
}
}
}
}
initState();
}, [refresh, setValue]);
React.useEffect(() => {
async function fetchPoldaPolres() {
setIsLoading(true);
try {
const response = await getUserLevelForAssignments();
setListDest(response?.data?.data.list);
console.log("polda", response?.data?.data?.list);
const initialExpandedState = response?.data?.data.list.reduce(
(acc: any, polda: any) => {
acc[polda.id] = false;
return acc;
},
{}
);
setExpandedPolda(initialExpandedState);
console.log("polres", initialExpandedState);
} catch (error) {
console.error("Error fetching Polda/Polres data:", error);
} finally {
setIsLoading(false);
}
}
fetchPoldaPolres();
}, []);
const handleCheckboxChange = (levelId: number) => {
setCheckedLevels((prev) => {
const updatedLevels = new Set(prev);
if (updatedLevels.has(levelId)) {
updatedLevels.delete(levelId);
} else {
updatedLevels.add(levelId);
}
return updatedLevels;
});
};
const handlePoldaPolresChange = () => {
return Array.from(checkedLevels).join(","); // Mengonversi Set ke string
};
const handleUnitChange = (
key: keyof typeof unitSelection,
value: boolean
) => {
if (key === "semua") {
const newState = {
semua: value,
mabes: value,
polda: value,
satker: value,
internasional: value,
};
setUnitSelection(newState);
} else {
const updatedSelection = {
...unitSelection,
[key]: value,
};
const allChecked = ["mabes", "polda", "satker", "internasional"].every(
(k) => updatedSelection[k as keyof typeof unitSelection]
);
updatedSelection.semua = allChecked;
setUnitSelection(updatedSelection);
}
};
const toggleExpand = (poldaId: any) => {
setExpandedPolda((prev: any) => ({
...prev,
[poldaId]: !prev[poldaId],
}));
};
const save = async (data: CalendarSchema) => {
const unitMapping = {
allUnit: "0",
mabes: "1",
polda: "2",
satker: "4",
internasional: "5",
};
const assignmentToString = Object.keys(unitSelection)
.filter((key) => unitSelection[key as keyof typeof unitSelection])
.map((key) => unitMapping[key as keyof typeof unitMapping])
.join(",");
const requestData = {
id: detail?.id,
title: data.title,
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
description: data.description,
assignedTo: assignmentToString,
assignedToLevel: handlePoldaPolresChange(),
};
console.log("Form Data Submitted:", requestData);
const response = await postCalendar(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
loading();
if (imageFiles?.length === 0) {
setIsImageUploadFinish(true);
}
imageFiles?.map(async (item: any, index: number) => {
await uploadResumableFile(index, String(id), item, "1", "0");
});
};
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;
console.log("CSRF TOKEN : ", csrfToken);
const headers = {
"X-XSRF-TOKEN": csrfToken,
};
const upload = new Upload(file, {
endpoint: `${process.env.NEXT_PUBLIC_API}/agenda-settings/file/upload`,
headers: headers,
retryDelays: [0, 3000, 6000, 12_000, 24_000],
chunkSize: 20_000,
metadata: {
calendarId: 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);
}
},
});
upload.start();
}
React.useEffect(() => {
successTodo();
}, [isImageUploadFinish]);
function successTodo() {
if (isImageUploadFinish) {
successSubmit("/in/contributor/agenda-setting");
}
}
const successSubmit = (redirect: string) => {
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push(redirect);
});
};
const onSubmit = (data: CalendarSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
const renderFilePreview = (url: string) => {
return (
<Image
width={48}
height={48}
alt={"file preview"}
src={url}
className=" rounded border p-0.5"
/>
);
};
const handleRemoveFile = (id: number) => {};
return (
<div>
<Card className="px-3 py-3">
{detail !== undefined ? (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-4">
<div>
<p className="font-medium mb-1">Tanggal Acara</p>
<div className="flex flex-col space-y-2">
<Popover>
<PopoverTrigger asChild className="px-0">
<Button
size="md"
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal border border-slate-300 px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
</div>
<div>
<p className="font-medium">Publish Area</p>
<div className="flex flex-row">
<div className="flex flex-wrap gap-3 lg:ml-3 ">
{Object.keys(unitSelection).map((key) => (
<div className="flex items-center gap-2" key={key}>
<Checkbox
id={key}
checked={
unitSelection[key as keyof typeof unitSelection]
}
onCheckedChange={(value) =>
handleUnitChange(
key as keyof typeof unitSelection,
value as boolean
)
}
/>
<Label htmlFor={key}>
{key.charAt(0).toUpperCase() + key.slice(1)}
</Label>
</div>
))}
</div>
<div className=" lg:pl-3">
<Dialog>
<DialogTrigger asChild>
<Button variant="soft" size="sm" color="primary">
[{t("custom", { defaultValue: "Custom" })}]
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
<DialogHeader>
<DialogTitle>
Daftar Wilayah Polda dan Polres
</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
{listDest.map((polda: any) => (
<div key={polda.id} className="border p-2">
<Label className="flex items-center">
<Checkbox
checked={checkedLevels.has(polda.id)}
onCheckedChange={() =>
handleCheckboxChange(polda.id)
}
className="mr-3"
/>
{polda.name}
<button
onClick={() => toggleExpand(polda.id)}
className="ml-2 focus:outline-none"
>
{expandedPolda[polda.id] ? (
<ChevronUp size={16} />
) : (
<ChevronDown size={16} />
)}
</button>
</Label>
{expandedPolda[polda.id] && (
<div className="ml-6 mt-2">
<Label className="block">
<Checkbox
checked={polda?.subDestination?.every(
(polres: any) =>
checkedLevels.has(polres.id)
)}
onCheckedChange={(isChecked) => {
const updatedLevels = new Set(
checkedLevels
);
polda?.subDestination?.forEach(
(polres: any) => {
if (isChecked) {
updatedLevels.add(polres.id);
} else {
updatedLevels.delete(polres.id);
}
}
);
setCheckedLevels(updatedLevels);
}}
className="mr-2"
/>
Pilih Semua Polres
</Label>
{polda?.subDestination?.map(
(polres: any) => (
<Label
key={polres.id}
className="block mt-1"
>
<Checkbox
checked={checkedLevels.has(
polres.id
)}
onCheckedChange={() =>
handleCheckboxChange(polres.id)
}
className="mr-2"
/>
{polres.name}
</Label>
)
)}
</div>
)}
</div>
))}
</div>
</DialogContent>
</Dialog>
</div>
</div>
</div>
<div>
<p className="font-medium">Nama Acara</p>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.title}
onChange={field.onChange}
placeholder="Masukan Judul"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
<div>
<Label>Foto</Label>
<FileUploader
accept={{
"image/*": [],
}}
maxSize={100}
label="Upload file dengan format .png, .jpg, atau .jpeg."
onDrop={(files) => setImageFiles(files)}
/>
{imageUploadedFiles?.map((file: any, index: number) => (
<div>
<Card className="mt-2">
<img
src={file.url}
alt="Thumbnail Gambar Utama"
className="w-full h-auto rounded-md"
/>
</Card>
<div
key={index}
className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
>
<div className="flex gap-3 items-center">
<div className="file-preview">
{renderFilePreview(file.url)}
</div>
<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>
<p className="font-medium">Deskripsi</p>
<Controller
control={control}
name="description"
render={({ field }) => (
<Textarea
rows={3}
defaultValue={detail?.description}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
{errors.description?.message && (
<p className="text-red-400 text-sm">
{errors.description?.message}
</p>
)}
</div>
<div className="text-right">
<Button
type="submit"
className="bg-blue-600 text-white hover:bg-blue-700"
>
Submit
</Button>
</div>
</div>
</form>
</div>
) : (
""
)}
</Card>
</div>
);
}

View File

@ -0,0 +1,717 @@
// components/TambahIklanModal.tsx
"use client";
import * as React from "react";
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
CalendarIcon,
ChevronDown,
ChevronUp,
CloudUpload,
Plus,
} from "lucide-react";
import { useTranslations } from "next-intl";
import "react-datepicker/dist/react-datepicker.css";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import { date, z } from "zod";
import { error, loading } from "@/lib/swal";
import { DateRange } from "react-day-picker";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { format } from "date-fns";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import { getUserLevelForAssignments } from "@/service/task";
import { Card } from "@/components/ui/card";
import { useDropzone } from "react-dropzone";
import { Icon } from "@/components/ui/icon";
import Image from "next/image";
import FileUploader from "../shared/file-uploader";
import { getCsrfToken } from "@/service/auth";
import { Upload } from "tus-js-client";
import { useRouter } from "next/navigation";
import { postCalendar } from "@/service/service/schedule/schedule";
const calendarSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
description: z.string().min(1, { message: "Judul diperlukan" }),
});
interface FileWithPreview extends File {
preview: string;
}
interface FileUploaded {
id: number;
url: string;
}
export function CalendarPolriAdd() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const [open, setOpen] = React.useState(false);
const t = useTranslations("Schedule");
type CalendarSchema = z.infer<typeof calendarSchema>;
const [eventDate, setEventDate] = React.useState<Date | null>(new Date());
const [listDest, setListDest] = React.useState([]);
const [checkedLevels, setCheckedLevels] = React.useState(new Set());
const [expandedPolda, setExpandedPolda] = React.useState([{}]);
const [isLoading, setIsLoading] = React.useState(false);
const [isImageUploadFinish, setIsImageUploadFinish] = React.useState(false);
const [files, setFiles] = React.useState<FileWithPreview[]>([]);
const [imageUploadedFiles, setImageUploadedFiles] = React.useState<
FileUploaded[]
>([]);
const [imageFiles, setImageFiles] = React.useState<FileWithPreview[]>([]);
const [date, setDate] = React.useState<DateRange | undefined>();
const levelNumber = Number(getCookiesDecrypt("ulne")) || 0;
const roleId = Number(getCookiesDecrypt("urie")) || 0;
const [unitSelection, setUnitSelection] = React.useState({
semua: false,
mabes: false,
polda: false,
satker: false,
internasional: false,
});
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<CalendarSchema>({
resolver: zodResolver(calendarSchema),
defaultValues: {
description: "",
},
});
React.useEffect(() => {
async function fetchPoldaPolres() {
setIsLoading(true);
try {
const response = await getUserLevelForAssignments();
setListDest(response?.data?.data.list);
console.log("polda", response?.data?.data?.list);
const initialExpandedState = response?.data?.data.list.reduce(
(acc: any, polda: any) => {
acc[polda.id] = false;
return acc;
},
{}
);
setExpandedPolda(initialExpandedState);
console.log("polres", initialExpandedState);
} catch (error) {
console.error("Error fetching Polda/Polres data:", error);
} finally {
setIsLoading(false);
}
}
fetchPoldaPolres();
}, []);
const handleCheckboxChange = (levelId: number) => {
setCheckedLevels((prev) => {
const updatedLevels = new Set(prev);
if (updatedLevels.has(levelId)) {
updatedLevels.delete(levelId);
} else {
updatedLevels.add(levelId);
}
return updatedLevels;
});
};
const handlePoldaPolresChange = () => {
return Array.from(checkedLevels).join(",");
};
const handleUnitChange = (
key: keyof typeof unitSelection,
value: boolean
) => {
if (key === "semua") {
const newState = {
semua: value,
mabes: value,
polda: value,
satker: value,
internasional: value,
};
setUnitSelection(newState);
} else {
const updatedSelection = {
...unitSelection,
[key]: value,
};
const allChecked = ["mabes", "polda", "satker", "internasional"].every(
(k) => updatedSelection[k as keyof typeof unitSelection]
);
updatedSelection.semua = allChecked;
setUnitSelection(updatedSelection);
}
};
const toggleExpand = (poldaId: any) => {
setExpandedPolda((prev: any) => ({
...prev,
[poldaId]: !prev[poldaId],
}));
};
const save = async (data: CalendarSchema) => {
const unitMapping = {
allUnit: "0",
mabes: "1",
polda: "2",
satker: "4",
internasional: "5",
};
const assignmentToString = Object.keys(unitSelection)
.filter((key) => unitSelection[key as keyof typeof unitSelection])
.map((key) => unitMapping[key as keyof typeof unitMapping])
.join(",");
const requestData = {
title: data.title,
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
description: data.description,
assignedTo: assignmentToString,
assignedToLevel: handlePoldaPolresChange(),
};
console.log("Form Data Submitted:", requestData);
const response = await postCalendar(requestData);
if (response?.error) {
error(response?.message);
return false;
}
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");
});
};
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}/calendars/file/upload`,
headers: headers,
retryDelays: [0, 3000, 6000, 12_000, 24_000],
chunkSize: 20_000,
metadata: {
calendarId: 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);
}
},
});
upload.start();
}
React.useEffect(() => {
successTodo();
}, [isImageUploadFinish]);
function successTodo() {
if (isImageUploadFinish) {
successSubmit("/in/contributor/schedule/calendar-polri");
}
}
const successSubmit = (redirect: string) => {
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push(redirect);
});
};
const onSubmit = (data: CalendarSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
const renderFilePreview = (url: string) => {
return (
<Image
width={48}
height={48}
alt={"file preview"}
src={url}
className=" rounded border p-0.5"
/>
);
};
const handleRemoveFile = (id: number) => {};
return (
<div>
<Card className="px-3 py-3">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-4">
<div>
<p className="font-medium mb-1">Tanggal Acara</p>
<div className="flex flex-col space-y-2">
<Popover>
<PopoverTrigger asChild className="px-0">
<Button
size="md"
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal border border-slate-300 px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
</div>
<div>
<p className="font-medium">Publish Area</p>
<div className="flex flex-row">
{/* <div className="flex flex-wrap gap-3 lg:ml-3 ">
{Object.keys(unitSelection).map((key) => (
<div className="flex items-center gap-2" key={key}>
<Checkbox
id={key}
checked={
unitSelection[key as keyof typeof unitSelection]
}
onCheckedChange={(value) =>
handleUnitChange(
key as keyof typeof unitSelection,
value as boolean
)
}
/>
<Label htmlFor={key}>
{key.charAt(0).toUpperCase() + key.slice(1)}
</Label>
</div>
))}
</div> */}
<div className="flex flex-wrap gap-3 lg:ml-3 ">
{Object.keys(unitSelection)
.filter((key) => {
// Jika login sebagai polda (2), hanya tampilkan polda
if (levelNumber === 2) return key === "polda";
// Jika login sebagai satker (4), hanya tampilkan satker
if (levelNumber === 4) return key === "satker";
// Selain itu tampilkan semua
return true;
})
.map((key) => (
<div className="flex items-center gap-2" key={key}>
<Checkbox
id={key}
checked={
unitSelection[key as keyof typeof unitSelection]
}
onCheckedChange={(value) =>
handleUnitChange(
key as keyof typeof unitSelection,
value as boolean
)
}
/>
<Label htmlFor={key}>
{key.charAt(0).toUpperCase() + key.slice(1)}
</Label>
</div>
))}
</div>
{levelNumber !== 2 && levelNumber !== 4 && (
<div className="lg:pl-3">
<Dialog>
<DialogTrigger asChild>
<Button variant="soft" size="sm" color="primary">
[{t("custom", { defaultValue: "Custom" })}]
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
<DialogHeader>
<DialogTitle>
Daftar Wilayah Polda dan Polres
</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
{listDest.map((polda: any) => (
<div key={polda.id} className="border p-2">
<Label className="flex items-center">
<Checkbox
checked={checkedLevels.has(polda.id)}
onCheckedChange={() =>
handleCheckboxChange(polda.id)
}
className="mr-3"
/>
{polda.name}
<button
onClick={() => toggleExpand(polda.id)}
className="ml-2 focus:outline-none"
>
{expandedPolda[polda.id] ? (
<ChevronUp size={16} />
) : (
<ChevronDown size={16} />
)}
</button>
</Label>
{expandedPolda[polda.id] && (
<div className="ml-6 mt-2">
<Label className="block">
<Checkbox
checked={polda?.subDestination?.every(
(polres: any) =>
checkedLevels.has(polres.id)
)}
onCheckedChange={(isChecked) => {
const updatedLevels = new Set(
checkedLevels
);
polda?.subDestination?.forEach(
(polres: any) => {
if (isChecked) {
updatedLevels.add(polres.id);
} else {
updatedLevels.delete(polres.id);
}
}
);
setCheckedLevels(updatedLevels);
}}
className="mr-2"
/>
Pilih Semua Polres
</Label>
{polda?.subDestination?.map((polres: any) => (
<Label
key={polres.id}
className="block mt-1"
>
<Checkbox
checked={checkedLevels.has(polres.id)}
onCheckedChange={() =>
handleCheckboxChange(polres.id)
}
className="mr-2"
/>
{polres.name}
</Label>
))}
</div>
)}
</div>
))}
</div>
</DialogContent>
</Dialog>
</div>
)}
{/* <div className=" lg:pl-3">
<Dialog>
<DialogTrigger asChild>
<Button variant="soft" size="sm" color="primary">
[{t("custom", { defaultValue: "Custom" })}]
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
<DialogHeader>
<DialogTitle>
Daftar Wilayah Polda dan Polres
</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
{listDest.map((polda: any) => (
<div key={polda.id} className="border p-2">
<Label className="flex items-center">
<Checkbox
checked={checkedLevels.has(polda.id)}
onCheckedChange={() =>
handleCheckboxChange(polda.id)
}
className="mr-3"
/>
{polda.name}
<button
onClick={() => toggleExpand(polda.id)}
className="ml-2 focus:outline-none"
>
{expandedPolda[polda.id] ? (
<ChevronUp size={16} />
) : (
<ChevronDown size={16} />
)}
</button>
</Label>
{expandedPolda[polda.id] && (
<div className="ml-6 mt-2">
<Label className="block">
<Checkbox
checked={polda?.subDestination?.every(
(polres: any) =>
checkedLevels.has(polres.id)
)}
onCheckedChange={(isChecked) => {
const updatedLevels = new Set(
checkedLevels
);
polda?.subDestination?.forEach(
(polres: any) => {
if (isChecked) {
updatedLevels.add(polres.id);
} else {
updatedLevels.delete(polres.id);
}
}
);
setCheckedLevels(updatedLevels);
}}
className="mr-2"
/>
Pilih Semua Polres
</Label>
{polda?.subDestination?.map((polres: any) => (
<Label key={polres.id} className="block mt-1">
<Checkbox
checked={checkedLevels.has(polres.id)}
onCheckedChange={() =>
handleCheckboxChange(polres.id)
}
className="mr-2"
/>
{polres.name}
</Label>
))}
</div>
)}
</div>
))}
</div>
</DialogContent>
</Dialog>
</div> */}
</div>
</div>
<div>
<p className="font-medium">Nama Acara</p>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Judul"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div>
<Label>Foto</Label>
<FileUploader
accept={{
"image/*": [],
}}
maxSize={100}
label="Upload file dengan format .png, .jpg, atau .jpeg."
onDrop={(files) => setImageFiles(files)}
/>
{imageUploadedFiles?.map((file: any, index: number) => (
<div>
<Card className="mt-2">
<img
src={file.url}
alt="Thumbnail Gambar Utama"
className="w-full h-auto rounded-md"
/>
</Card>
<div
key={index}
className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
>
<div className="flex gap-3 items-center">
<div className="file-preview">
{renderFilePreview(file.url)}
</div>
<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>
<p className="font-medium">Deskripsi</p>
<Controller
control={control}
name="description"
render={({ field }) => (
<Textarea
rows={3}
value={field.value}
onChange={field.onChange}
placeholder="Masukan Description"
/>
)}
/>
{errors.description?.message && (
<p className="text-red-400 text-sm">
{errors.description?.message}
</p>
)}
</div>
<div className="text-right">
<Button
type="submit"
className="bg-blue-600 text-white hover:bg-blue-700"
>
Submit
</Button>
</div>
</div>
</form>
</Card>
</div>
);
}

View File

@ -0,0 +1,647 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import { CalendarIcon, Clock1, Locate, MapPin, User2 } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { formatDateToIndonesian } from "@/utils/globals";
import { formatDate } from "@fullcalendar/core/index.js";
import { Icon } from "@iconify/react/dist/iconify.js";
import { useTranslations } from "next-intl";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { close } from "@/config/swal";
import { Checkbox } from "@/components/ui/checkbox";
import { detailSchedule, listScheduleNext, listScheduleToday, postApprovalSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
isYoutube: boolean;
youtubeUrl: string;
needApprovalFrom: number;
uploadedById: number;
}
export default function FormDetailLiveReport() {
const { id } = useParams() as { id: string };
const router = useRouter();
type TaskSchema = z.infer<typeof taskSchema>;
const userId = getCookiesDecrypt("uie");
const userLevelId = getCookiesDecrypt("ulie");
const roleId = getCookiesDecrypt("urie");
const userLevelNumber = getCookiesDecrypt("ulne");
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [todayList, setTodayList] = useState([]);
const [nextDayList, setNextDayList] = useState([]);
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const t = useTranslations("Form");
const [status, setStatus] = useState("");
const [description, setDescription] = useState("");
const [modalOpen, setModalOpen] = useState(false);
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
});
async function getDataByDate() {
const resToday = await listScheduleToday();
const today = resToday?.data?.data;
setTodayList(today);
const resNext = await listScheduleNext();
const next = resNext?.data?.data;
setNextDayList(next);
}
useEffect(() => {
initState();
}, [refresh]);
async function initState() {
if (id) {
loading();
const response = await detailSchedule(id);
close();
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
}
getDataByDate();
}
}
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const actionApproval = (e: string) => {
setStatus(e);
setDescription("");
setModalOpen(true);
};
const submit = async () => {
if (
description?.length > 1 &&
(Number(status) == 3 || Number(status) == 2 || Number(status) == 4)
) {
save();
}
};
async function save() {
const data = {
scheduleId: Number(id),
statusId: Number(status),
message: description,
isPublish: status === "2",
placements: schedulePlacements?.filter((val) => val != "all")?.join(","),
};
loading();
const response = await postApprovalSchedule(data);
close();
setModalOpen(false);
if (response?.error) {
error(response?.message);
return false;
}
initState();
return false;
}
const [schedulePlacements, setSchedulePlacements] = useState<string[]>([]);
const setupPlacement = (placement: string, checked: boolean) => {
let temp = [...schedulePlacements];
if (checked) {
if (placement === "all") {
temp = ["all", "mabes", "polda", "international"];
} else {
const now = temp;
now.push(placement);
if (now.length === 3 && !now.includes("all")) {
now.push("all");
}
temp = now;
}
} else {
if (placement === "all") {
temp = [];
} else {
const now = temp.filter((a) => a !== placement);
console.log("now", now);
temp = now;
if (now.length === 3 && now.includes("all")) {
const newData = now.filter((b) => b !== "all");
temp = newData;
}
}
}
console.log("temp");
setSchedulePlacements(temp);
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
value={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-6">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p className="text-sm">Aktifkan fitur live streaming</p>
<Switch
checked={detail.isYoutube}
color="primary"
id="c2"
/>
</div>
</div>
</div>
{detail.isYoutube && (
<div className="mt-1">
<Input
size={"md"}
type="text"
value={detail.youtubeUrl}
placeholder="Masukan ID youtube"
/>
</div>
)}
<div className="flex flex-col lg:flex-row items-start lg:items-center justify-between mt-6">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div className="mt-6">
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={detail?.address}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semiboldc mt-6">
DI SAMPAIKAN OLEH
</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
) : (
""
)}
</div>
</Card>
<Card className="w-full lg:w-3/12">
<Accordion type="single" collapsible>
{/* Jadwal Hari Ini */}
<AccordionItem value="today">
<AccordionTrigger className="font-semibold">
Jadwal Hari Ini
</AccordionTrigger>
<AccordionContent>
{todayList?.length > 0 ? (
<div className="list-disc ">
{todayList.map((item: any, index) => (
<div key={index} className="">
<li className="text-base font-semibold">{item.title}</li>
<p className="text-sm ml-5 flex my-2 gap-2">
<CalendarIcon size={20} />
{formatDate(item?.startDate)}-
{formatDate(item?.endDate)}
</p>
<p className="text-sm ml-5 flex my-2 gap-2">
<Clock1 size={20} />
{item?.startTime}-{item?.endTime}
</p>
<p className="text-sm ml-5 flex items-center my-2 gap-2">
<MapPin size={20} />
{item?.address}
</p>
<p className="text-sm ml-5">Disampaikan oleh:</p>
<p className="text-sm ml-5 flex my-2 items-center gap-2">
<User2 size={20} />
{item?.speakerTitle} {item?.speakerName}
</p>
</div>
))}
</div>
) : (
<p className="text-gray-500">Tidak ada jadwal hari ini</p>
)}
</AccordionContent>
</AccordionItem>
{/* Jadwal Selanjutnya */}
<AccordionItem value="next">
<AccordionTrigger className="font-semibold">
Jadwal Selanjutnya
</AccordionTrigger>
<AccordionContent>
{nextDayList?.length > 0 ? (
<div className="list-disc ">
{nextDayList.map((item: any, index) => (
<div key={index} className="">
<li className="text-base font-semibold">{item.title}</li>
<p className="text-sm ml-5 flex my-2 gap-2">
<CalendarIcon size={20} />
{formatDate(item?.startDate)}-
{formatDate(item?.endDate)}
</p>
<p className="text-sm ml-5 flex my-2 gap-2">
<Clock1 size={20} />
{item?.startTime}-{item?.endTime}
</p>
<p className="text-sm ml-5 flex items-center my-2 gap-2">
<MapPin size={20} />
{item?.address}
</p>
<p className="text-sm ml-5">Disampaikan oleh:</p>
<p className="text-sm ml-5 flex my-2 items-center gap-2">
<User2 size={20} />
{item?.speakerTitle} {item?.speakerName}
</p>
</div>
))}
</div>
) : (
<p className="text-gray-500">Tidak ada jadwal selanjutnya</p>
)}
</AccordionContent>
</AccordionItem>
</Accordion>
{Number(detail?.needApprovalFrom) == Number(userLevelId) &&
Number(userLevelNumber) < 2 ? (
Number(detail?.uploadedById) == Number(userId) ? (
""
) : (
<div className="flex flex-col gap-2 p-3">
<Button
onClick={() => actionApproval("2")}
color="primary"
type="button"
>
<Icon icon="fa:check" className="mr-3" />
{t("accept", { defaultValue: "Accept" })}
</Button>
<Button
onClick={() => actionApproval("3")}
className="bg-orange-400 hover:bg-orange-300"
type="button"
>
<Icon icon="fa:comment-o" className="mr-3" /> {t("revision", { defaultValue: "Revision" })}
</Button>
<Button
onClick={() => actionApproval("4")}
color="destructive"
type="button"
>
<Icon icon="fa:times" className="mr-3" />
{t("reject", { defaultValue: "Reject" })}
</Button>
</div>
)
) : (
""
)}
</Card>
<Dialog open={modalOpen} onOpenChange={setModalOpen}>
<DialogContent className="overflow-y-auto">
<DialogHeader>
<DialogTitle>{t("leave-comment", { defaultValue: "Leave Comment" })}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-1 text-sm">
<p>
{" "}
Status:{" "}
<span
className={
status === "2"
? "text-primary"
: status === "3"
? "text-warning"
: "text-destructive"
}
>
{status === "2"
? "Disetujui"
: status === "3"
? "Revisi"
: "Ditolak"}
</span>
</p>
{status === "2" && (
<div className="flex flex-row gap-2">
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
value="all"
checked={schedulePlacements?.includes("all")}
onCheckedChange={(e) => setupPlacement("all", Boolean(e))}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{t("all", { defaultValue: "All" })}
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={schedulePlacements?.includes("mabes")}
onCheckedChange={(e) => setupPlacement("mabes", Boolean(e))}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Nasional
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={schedulePlacements?.includes("polda")}
onCheckedChange={(e) => setupPlacement("polda", Boolean(e))}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Wilayah
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={schedulePlacements?.includes("international")}
onCheckedChange={(e) =>
setupPlacement("international", Boolean(e))
}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Internasional
</label>
</div>
</div>
)}
<p>Deskripsi:</p>
<div className="flex flex-col gap-4">
<Textarea
placeholder="Type your message here."
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button
type="button"
color="primary"
onClick={() => submit()}
disabled={
description.length < 1 ||
(schedulePlacements.length < 1 && status === "2")
}
>
{t("submit", { defaultValue: "Submit" })}
</Button>
<Button
type="button"
color="destructive"
onClick={() => {
setModalOpen(false);
}}
>
{t("cancel", { defaultValue: "Cancel" })}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -163,8 +163,8 @@ export default function FormLiveReport() {
};
return (
<div className="flex flex-col lg:flex-row gap-2 border rounded-lg ">
<Card className="w-full bg-slate-100">
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
<form onSubmit={handleSubmit(onSubmit)}>
@ -194,8 +194,7 @@ export default function FormLiveReport() {
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<Label>Aktifkan fitur live streaming</Label>
<Switch
className="border border-slate-100 bg-red-100"
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"

View File

@ -0,0 +1,405 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import { toast } from "sonner";
import { detailSchedule, postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul harus diisi" }),
level: z.string().min(1, { message: "Pangkat harus diisi" }),
name: z.string().min(1, { message: "Nama harus diisi" }),
location: z.string().min(1, { message: "Lokasi harus diisi" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
export default function FormUpdateLiveReport() {
const { id } = useParams() as { id: string };
const router = useRouter();
const params = useSearchParams();
const scheduleTypeId = params?.get("scheduleType");
const MySwal = withReactContent(Swal);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const [youtubeUrl, setYoutubeUrl] = useState("");
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
});
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const data = response?.data?.data;
if (data) {
setDetail(data);
setValue("title", data.title);
setValue("level", data.speakerTitle);
setValue("name", data.speakerName);
setValue("location", data.address);
setDate({
from: parseISO(data.startDate),
to: parseISO(data.endDate),
});
setStartTime(data.startTime);
setYoutubeUrl(data.youtubeUrl);
setEndTime(data.endTime);
setIsLiveStreamingEnabled(data.isYoutube);
}
}
}
initState();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const handleLocationChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
setValue("location", value);
};
const save = async (data: TaskSchema) => {
const requestData: {
id?: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
startTime: string;
endTime: string;
addressLat: string;
addressLong: string;
startDate: string | null;
endDate: string | null;
isYoutube: boolean;
scheduleTypeId: number;
youtubeUrl: string;
} = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime,
endTime,
addressLat: "0.0",
addressLong: "0.0",
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: Number(scheduleTypeId),
youtubeUrl: youtubeUrl,
};
if (id) {
requestData.id = parseInt(id, 10);
}
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/en/contributor/schedule/live-report");
});
};
const onSubmit = (data: TaskSchema) => {
if (isLiveStreamingEnabled && youtubeUrl == "") {
toast(<p className="text-red-600">Youtube ID harus diisi</p>);
return false;
}
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
<form onSubmit={handleSubmit(onSubmit)}>
{detail ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
value={field.value}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-5">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
checked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mb-2 mt-1">
<Input
size={"md"}
type="text"
value={youtubeUrl}
onChange={(e) => setYoutubeUrl(e.target.value)}
placeholder="Masukan Youtube ID"
/>
</div>
)}
<div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div>
<MapHome
draggable
setLocation={(location) => {
setValue("location", location);
}}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={field.value}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
) : (
""
)}
{/* Submit Button */}
<div className="mt-4">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
{/* <Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card> */}
</div>
);
}

View File

@ -0,0 +1,585 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Clock1, Eye, MapPin, Plus, User2 } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { formatDate } from "@fullcalendar/core/index.js";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Link } from "@/i18n/routing";
import $ from "jquery";
import { detailSchedule, getListScheduleAttachment, listScheduleNext, listScheduleToday } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
interface Attachment {
id: any;
title: string;
fileTypeId: number;
type: number;
fileTypeName: string;
}
export default function FormDetailPressRillis() {
const [open, setOpen] = useState(false);
const { id } = useParams() as { id: string };
const MySwal = withReactContent(Swal);
console.log(id);
const router = useRouter();
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [selectedTarget, setSelectedTarget] = useState("all");
const [todayList, setTodayList] = useState([]);
const [nextDayList, setNextDayList] = useState([]);
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
const [lampiran, setDataLampiran] = useState<Attachment[]>([]);
async function getDataAttachment() {
const response = await getListScheduleAttachment(id);
console.log("data attach", response?.data?.data?.content);
setDataLampiran(response?.data?.data?.content);
}
async function getDataByDate() {
const resToday = await listScheduleToday();
const today = resToday?.data?.data;
setTodayList(today);
const resNext = await listScheduleNext();
const next = resNext?.data?.data;
setNextDayList(next);
}
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
}
getDataByDate();
}
}
initState();
getDataAttachment();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const handleDestinationUpload = (
type: number,
id: string | number,
setOpen: (open: boolean) => void,
router: any
) => {
setOpen(false); // Tutup modal dialog
if (id !== undefined) {
Cookies.set("scheduleId", id.toString(), { expires: 1 });
Cookies.set("scheduleType", "3", { expires: 1 });
const routes: Record<number, string> = {
1: "/in/contributor/schedule/media/image/create",
2: "/in/contributor/schedule/media/video/create",
3: "/in/contributor/schedule/media/text/create",
4: "/in/contributor/schedule/media/audio/create",
};
router.push(routes[type] || "/admin/schedule/media/audio/create");
}
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Pers Rilis</p>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
value={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-6">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-6 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div className="mt-6">
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={detail?.address}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<div className="mt-6 space-y-2">
<Label>Invitation</Label>
<Select onValueChange={setSelectedTarget}>
<SelectTrigger size="md">
<SelectValue placeholder="Pilih" />
</SelectTrigger>
<SelectContent>
<SelectItem value="kompas">
PT. kompas Cyber Media{" "}
</SelectItem>
<SelectItem value="trans">
PT. Trans Digital Media
</SelectItem>
<SelectItem value="mnc">MNC</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-sm my-2 font-semibold mt-6">
DI SAMPAIKAN OLEH
</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className="flex justify-between">
<Button color="primary" size="sm" type="button">
<Plus /> Tambah Lampiran
</Button>
<p>{lampiran?.length || 0} Lampiran</p>
</div>
</DialogTrigger>
<DialogContent className="max-w-md p-6 bg-white rounded-lg shadow-lg h-[420px] w-[700px]">
<h2 className="text-lg font-semibold">
Pilih Jenis Lampiran
</h2>
<div className="space-y-4 gap-y-4">
{[
{
type: 2,
img: "/assets/img/upload-video.png",
label: "Audio Visual",
},
{
type: 1,
img: "/assets/img/upload-image.png",
label: "Foto",
},
{
type: 3,
img: "/assets/img/upload-text.png",
label: "Teks",
},
{
type: 4,
img: "/assets/img/upload-audio.png",
label: "Audio",
},
].map((item) => (
<a
key={item.type}
onClick={() =>
handleDestinationUpload(
item.type,
id,
setOpen,
router
)
}
>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={item.img}
alt={item.label}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">
{item.label}
</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa {item.label.toLowerCase()}{" "}
dengan format sesuai yang didukung.
</p>
</div>
</div>
</a>
))}
</div>
</DialogContent>
</Dialog>
</div>
) : (
""
)}
<div className="mt-6">
<table className="w-full border border-gray-300 rounded-lg">
<thead className="bg-gray-200 text-left">
<tr>
<th className="p-3 font-semibold">Judul Konten</th>
<th className="p-3 font-semibold">Konten</th>
<th className="p-3 font-semibold">Tindakan</th>
<th className="p-3 font-semibold">Aksi</th>
</tr>
</thead>
<tbody>
{lampiran.map((item, index) => (
<tr key={index} className="border-t border-gray-300">
<td className="p-3 text-blue-600 cursor-pointer">
{item.title}
</td>
<td className="p-3">{item.fileTypeName}</td>
<td className="p-3 text-blue-600">Konfersi Ai</td>
<td className="p-3">
<Link
href={
Number(item.fileTypeId) == 1
? `/contributor/content/image/detail/${item.id}`
: Number(item.fileTypeId) == 2
? `/contributor/content/video/detail/${item.id}`
: Number(item.fileTypeId) == 3
? `/contributor/content/teks/detail/${item.id}`
: `/contributor/content/audio/detail/${item.id}`
}
target="_blank"
className="btn"
rel="noreferrer"
>
<Eye
className={
item.type === 1 ? "text-blue-600" : "text-black"
}
/>
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="mt-4 flex justify-end">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<Accordion type="single" collapsible>
{/* Jadwal Hari Ini */}
<AccordionItem value="today">
<AccordionTrigger className="font-semibold">
Jadwal Hari Ini
</AccordionTrigger>
<AccordionContent>
{todayList?.length > 0 ? (
<ul className="list-disc ml-4">
{todayList.map((item: any, index) => (
<li key={index} className="py-1">
{item.name}
</li>
))}
</ul>
) : (
<p className="text-gray-500">Tidak ada jadwal hari ini</p>
)}
</AccordionContent>
</AccordionItem>
{/* Jadwal Selanjutnya */}
<AccordionItem value="next">
<AccordionTrigger className="font-semibold">
Jadwal Selanjutnya
</AccordionTrigger>
<AccordionContent>
{nextDayList?.length > 0 ? (
<div className="list-disc ">
{nextDayList.map((item: any, index) => (
<div key={index} className="">
<li className="text-base font-semibold">{item.title}</li>
<p className="text-sm ml-5 flex my-2">
<CalendarIcon size={20} />
{formatDate(item?.startDate)}-
{formatDate(item?.endDate)}
</p>
<p className="text-sm ml-5 flex my-2">
<Clock1 size={20} />
{item?.startTime}-{item?.endTime}
</p>
<p className="text-sm ml-5 flex items-center my-2">
<MapPin size={50} />
{item?.address}
</p>
<p className="text-sm ml-5">Disampaikan oleh:</p>
<p className="text-sm ml-5 flex my-2">
<User2 />
{item?.speakerTitle} {item?.speakerName}
</p>
</div>
// <p>{item.startDate}</p>
))}
</div>
) : (
<p className="text-gray-500">Tidak ada jadwal selanjutnya</p>
)}
</AccordionContent>
</AccordionItem>
</Accordion>
</Card>
</div>
);
}

View File

@ -0,0 +1,522 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Plus } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Link } from "@/i18n/routing";
import { detailSchedule, postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
export default function FormUpdatePressRelease() {
const [open, setOpen] = useState(false);
const { id } = useParams() as { id: string };
console.log(id);
const router = useRouter();
const MySwal = withReactContent(Swal);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [selectedTarget, setSelectedTarget] = useState("all");
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
}
}
}
initState();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const save = async (data: TaskSchema) => {
const requestData: {
id?: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
startTime: string;
endTime: string;
addressLat: string;
addressLong: string;
startDate: string | null;
endDate: string | null;
isYoutube: boolean;
scheduleTypeId: number;
} = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime, // Start time from state
endTime, // End time from state
addressLat: "0.0", // Replace with actual latitude
addressLong: "0.0", // Replace with actual longitude
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: 3,
};
// Add id property if it exists
if (id) {
requestData.id = parseInt(id, 10); // Ensure id is a number
}
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/en/contributor/schedule/press-release");
});
};
const onSubmit = (data: TaskSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
<form onSubmit={handleSubmit(onSubmit)}>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
defaultValue={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-5">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div>
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
defaultValue={detail?.address}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<div className="mt-5 space-y-2">
<Label>Invitation</Label>
<Select onValueChange={setSelectedTarget}>
<SelectTrigger size="md">
<SelectValue placeholder="Pilih" />
</SelectTrigger>
<SelectContent>
<SelectItem value="kompas">
PT. kompas Cyber Media{" "}
</SelectItem>
<SelectItem value="trans">
PT. Trans Digital Media
</SelectItem>
<SelectItem value="mnc">MNC</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className="flex justify-between">
<Button color="primary" size="sm" type="button">
<Plus /> Tambah Lampiran
</Button>
<p>0 Lampiran</p>
</div>
</DialogTrigger>
<DialogContent className="max-w-md p-6 bg-white rounded-lg shadow-lg h-[420px] w-[700px]">
<h2 className="text-lg font-semibold">
Pilih Jenis Lampiran
</h2>
<div className=" space-y-4 gap-y-4">
<Link href={"/contributor/schedule/media/video/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-video.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">
Audio Visual
</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
<Link href={"/contributor/schedule/media/image/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-image.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">Foto</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
<Link href={"/contributor/schedule/media/text/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-text.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">Teks</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
<Link href={"/contributor/schedule/media/audio/create"}>
<div className="flex flex-row items-center space-x-4">
<div className="flex flex-col w-4/12 items-center">
<img
src={"/assets/img/upload-audio.png"}
alt={"item.label"}
className="w-12 h-12"
/>
<h3 className="text-base font-semibold">Audio</h3>
</div>
<div className="w-8/12">
<p className="text-sm text-gray-600">
Unggah media berupa video dengan format avi, wmv,
atau mp4 dengan ukuran minimal 2mb dan maksimal
500mb.
</p>
</div>
</div>
</Link>
</div>
</DialogContent>
</Dialog>
</div>
) : (
""
)}
{/* Submit Button */}
<div className="mt-4">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,410 @@
"use client";
import React, { useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useRouter } from "next/navigation";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Plus } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import { register } from "module";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error } from "@/lib/swal";
import Cookies from "js-cookie";
import { postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
export default function FormPressRelease() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const editor = useRef(null);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = React.useState<DateRange | undefined>();
const handleStartTime = (e: any) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: any) => {
setEndTime(e.target.value);
};
// State for various form fields
const [assignmentType, setAssignmentType] = useState("mediahub");
const [assignmentCategory, setAssignmentCategory] = useState("publication");
const [selectedTarget, setSelectedTarget] = useState("all");
const [unitSelection, setUnitSelection] = useState({
allUnit: false,
mabes: false,
polda: false,
polres: false,
});
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
const save = async (data: TaskSchema) => {
const requestData = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime, // Start time from state
endTime, // End time from state
addressLat: "0.0", // Replace with actual latitude
addressLong: "0.0", // Replace with actual longitude
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: 3,
};
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
// Optional: Use Swal for success feedback
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/en/contributor/schedule/press-release");
});
};
const handleUploadAttachment = () => {
const scheduleId = Cookies.get("scheduleId");
if (scheduleId == undefined) {
MySwal.fire({
title: "Simpan Jadwal Terlebih Dahulu",
icon: "info",
confirmButtonColor: "#3085d6",
confirmButtonText: "Ok",
}).then((result) => {
if (result.isConfirmed) {
return true;
}
});
}
};
const onSubmit = (data: TaskSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Pers Rilis</p>
<form onSubmit={handleSubmit(onSubmit)}>
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Judul"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-5">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div className="">
<div className="flex flex-row items-center">
<div className="col-6">
<Input
defaultValue="08:00"
type="time"
onChange={(e) => handleStartTime(e)}
/>
</div>
<div className="col-6">
<Input
defaultValue="09:00"
type="time"
onChange={(e) => handleEndTime(e)}
/>
</div>
</div>
</div>
</div>
</div>
<div>
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={field.value}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<div className="mt-5 space-y-2">
<Label>Invitation</Label>
<Select onValueChange={setSelectedTarget}>
<SelectTrigger size="md">
<SelectValue placeholder="Pilih" />
</SelectTrigger>
<SelectContent>
<SelectItem value="kompas">
PT. kompas Cyber Media{" "}
</SelectItem>
<SelectItem value="trans">
PT. Trans Digital Media
</SelectItem>
<SelectItem value="mnc">MNC</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
<div className="flex flex-row items-center justify-between">
<Button
onClick={() => handleUploadAttachment()}
color="primary"
size="sm"
type="button"
>
<Plus />
Tambah Lampiran
</Button>
<p>0 Llampiran</p>
</div>
<div className="mt-4 flex justify-end">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,400 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Clock1, Locate, MapPin, User2 } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { formatDateToIndonesian } from "@/utils/globals";
import { formatDate } from "@fullcalendar/core/index.js";
import { detailSchedule, listScheduleNext, listScheduleToday } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
export default function FormDetailPressConference() {
const { id } = useParams() as { id: string };
console.log(id);
const router = useRouter();
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [todayList, setTodayList] = useState([]);
const [nextDayList, setNextDayList] = useState([]);
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
async function getDataByDate() {
const resToday = await listScheduleToday();
const today = resToday?.data?.data;
setTodayList(today);
const resNext = await listScheduleNext();
const next = resNext?.data?.data;
setNextDayList(next);
}
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
}
getDataByDate();
}
}
initState();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
value={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-6">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row items-start lg:items-center justify-between mt-6">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div className="mt-6">
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={detail?.address}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semiboldc mt-6">
DI SAMPAIKAN OLEH
</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
) : (
""
)}
{/* Submit Button
<div className="mt-4">
<Button type="submit" color="primary">
Submit
</Button>
</div> */}
</div>
</Card>
<Card className="w-full lg:w-3/12">
<Accordion type="single" collapsible>
{/* Jadwal Hari Ini */}
<AccordionItem value="today">
<AccordionTrigger className="font-semibold">
Jadwal Hari Ini
</AccordionTrigger>
<AccordionContent>
{todayList?.length > 0 ? (
<ul className="list-disc ml-4">
{todayList.map((item: any, index) => (
<li key={index} className="py-1">
{item.name}
</li>
))}
</ul>
) : (
<p className="text-gray-500">Tidak ada jadwal hari ini</p>
)}
</AccordionContent>
</AccordionItem>
{/* Jadwal Selanjutnya */}
<AccordionItem value="next">
<AccordionTrigger className="font-semibold">
Jadwal Selanjutnya
</AccordionTrigger>
<AccordionContent>
{nextDayList?.length > 0 ? (
<div className="list-disc ">
{nextDayList.map((item: any, index) => (
<div key={index} className="">
<li className="text-base font-semibold">{item.title}</li>
<p className="text-sm ml-5 flex my-2">
<CalendarIcon size={20} />
{formatDate(item?.startDate)}-
{formatDate(item?.endDate)}
</p>
<p className="text-sm ml-5 flex my-2">
<Clock1 size={20} />
{item?.startTime}-{item?.endTime}
</p>
<p className="text-sm ml-5 flex items-center my-2">
<MapPin size={50} />
{item?.address}
</p>
<p className="text-sm ml-5">Disampaikan oleh:</p>
<p className="text-sm ml-5 flex my-2">
<User2 />
{item?.speakerTitle} {item?.speakerName}
</p>
</div>
// <p>{item.startDate}</p>
))}
</div>
) : (
<p className="text-gray-500">Tidak ada jadwal selanjutnya</p>
)}
</AccordionContent>
</AccordionItem>
</Accordion>
</Card>
</div>
);
}

View File

@ -0,0 +1,357 @@
"use client";
import React, { useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import { register } from "module";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error } from "@/lib/swal";
import Cookies from "js-cookie";
import { useRouter } from "@/i18n/routing";
import { postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
export default function FormPressConference() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const editor = useRef(null);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = React.useState<DateRange | undefined>();
const handleStartTime = (e: any) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: any) => {
setEndTime(e.target.value);
};
// State for various form fields
const [assignmentType, setAssignmentType] = useState("mediahub");
const [assignmentCategory, setAssignmentCategory] = useState("publication");
const [selectedTarget, setSelectedTarget] = useState("all");
const [unitSelection, setUnitSelection] = useState({
allUnit: false,
mabes: false,
polda: false,
polres: false,
});
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
const save = async (data: TaskSchema) => {
const requestData = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime, // Start time from state
endTime, // End time from state
addressLat: "0.0", // Replace with actual latitude
addressLong: "0.0", // Replace with actual longitude
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: 1,
};
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
// Optional: Use Swal for success feedback
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/contributor/schedule/press-conference");
});
};
const onSubmit = (data: TaskSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
<form onSubmit={handleSubmit(onSubmit)}>
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Judul"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title.message}</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-4 mb-3">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<Label>Aktifkan fitur live streaming</Label>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mb-2 mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mb-4 mt-2 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild className="px-0">
<Button
size="md"
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal border border-slate-300 px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div className="">
<div className="flex flex-row items-center">
<div className="col-6">
<Input
defaultValue="08:00"
type="time"
onChange={(e) => handleStartTime(e)}
/>
</div>
<div className="col-6">
<Input
defaultValue="09:00"
type="time"
onChange={(e) => handleEndTime(e)}
/>
</div>
</div>
</div>
</div>
</div>
<div>
{/* Kirim setValue ke MapHome */}
<MapHome
draggable
setLocation={(location) => setValue("location", location)}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={field.value}
onChange={field.onChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm mt-4 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
{/* Submit Button */}
<div className="mt-4">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,409 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import { Switch } from "@/components/ui/switch";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, parseISO, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import { detailSchedule, postSchedule } from "@/service/service/schedule/schedule";
const taskSchema = z.object({
title: z.string().min(1, { message: "Judul diperlukan" }),
level: z.string().min(1, { message: "Judul diperlukan" }),
name: z.string().min(1, { message: "Judul diperlukan" }),
location: z.string().min(1, { message: "Judul diperlukan" }),
});
interface Detail {
id: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
addressLat: number;
addressLong: number;
}
export default function FormUpdatePressConference() {
const { id } = useParams() as { id: string };
console.log(id);
const router = useRouter();
const MySwal = withReactContent(Swal);
const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
type TaskSchema = z.infer<typeof taskSchema>;
const [startTime, setStartTime] = useState("08:00");
const [endTime, setEndTime] = useState("09:00");
const [date, setDate] = useState<DateRange | undefined>();
const [detail, setDetail] = useState<Detail>();
const [refresh, setRefresh] = useState(false);
const [location, setLocation] = useState("");
const {
control,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TaskSchema>({
resolver: zodResolver(taskSchema),
defaultValues: {
location: "",
},
});
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSchedule(id);
const details = response?.data?.data;
setDetail(details);
if (details) {
setDate({
from: parseISO(details.startDate),
to: parseISO(details.endDate),
});
}
if (details) {
setStartTime(details.startTime);
setEndTime(details.endTime);
setLocation(details.address);
}
}
}
initState();
}, [refresh, setValue]);
const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setStartTime(e.target.value);
};
const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
setEndTime(e.target.value);
};
const handleLocationChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
setLocation(value);
setValue("location", value);
};
const save = async (data: TaskSchema) => {
const requestData: {
id?: number;
title: string;
address: string;
speakerTitle: string;
speakerName: string;
startTime: string;
endTime: string;
addressLat: string;
addressLong: string;
startDate: string | null;
endDate: string | null;
isYoutube: boolean;
scheduleTypeId: number;
} = {
title: data.title,
address: data.location,
speakerTitle: data.level,
speakerName: data.name,
startTime,
endTime,
addressLat: "0.0",
addressLong: "0.0",
startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
isYoutube: isLiveStreamingEnabled,
scheduleTypeId: 1,
};
if (id) {
requestData.id = parseInt(id, 10);
}
console.log("Form Data Submitted:", requestData);
const response = await postSchedule(requestData);
if (response?.error) {
error(response?.message);
return false;
}
Cookies.set("scheduleId", response?.data?.data.id, {
expires: 1,
});
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/en/contributor/schedule/press-conference");
});
};
const onSubmit = (data: TaskSchema) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
return (
<div className="flex flex-col lg:flex-row gap-2">
<Card className="w-full lg:w-9/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
<form onSubmit={handleSubmit(onSubmit)}>
{detail !== undefined ? (
<div className=" gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2">
<Label>Judul Kegiatan</Label>
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
type="text"
defaultValue={detail?.title}
onChange={field.onChange}
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
<div className="flex flex-row items-center">
<div className="mt-5">
<Label>Live Streaming</Label>
<div className="flex items-center gap-3">
<p>Aktifkan fitur live streaming</p>
<Switch
defaultChecked={isLiveStreamingEnabled}
color="primary"
id="c2"
onCheckedChange={(checked) =>
setIsLiveStreamingEnabled(checked)
}
/>
</div>
</div>
</div>
{isLiveStreamingEnabled && (
<div className="mt-1">
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size={"md"}
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Masukan ID youtube"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">
{errors.title.message}
</p>
)}
</div>
)}
<div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
<div className="flex flex-col space-y-2">
<Label className="mr-3 mb-1">Tanggal</Label>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[280px] lg:w-[250px] justify-start text-left font-normal px-0 md:px-0 lg:px-4",
!date && "text-muted-foreground"
)}
>
<CalendarIcon size={15} className="mr-3" />
{date?.from ? (
date.to ? (
<>
{format(date.from, "LLL dd, y")} -{" "}
{format(date.to, "LLL dd, y")}
</>
) : (
format(date.from, "LLL dd, y")
)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="title">Rentang Waktu</Label>
<div>
<div className="flex flex-row items-center">
<div className="col-6">
<Input
value={startTime}
type="time"
onChange={handleStartTime}
/>
</div>
<div className="col-6">
<Input
value={endTime}
type="time"
onChange={handleEndTime}
/>
</div>
</div>
</div>
</div>
</div>
<div>
<MapHome
draggable
setLocation={(location) => {
setLocation(location);
setValue("location", location);
}}
/>
</div>
<div>
<Controller
control={control}
name="location"
render={({ field }) => (
<Textarea
rows={3}
value={location}
onChange={handleLocationChange}
placeholder="Masukan lokasi"
/>
)}
/>
<div className="invalid-feedback">
{errors.location?.message}
</div>
</div>
<p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
<div className="flex flex-col ">
<div className="mt-1 space-y-2">
<Label>Nama Pangkat</Label>
<Controller
control={control}
name="level"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.speakerTitle}
onChange={field.onChange}
placeholder="Masukan Nama Pangkat"
/>
)}
/>
{errors.level?.message && (
<p className="text-red-400 text-sm">
{errors.level.message}
</p>
)}
</div>
</div>
<div className="flex flex-col my-3">
<div className="mt-1 space-y-2">
<Label>Nama Lengkap</Label>
<Controller
control={control}
name="name"
render={({ field }) => (
<Input
size={"md"}
type="text"
defaultValue={detail?.speakerName}
onChange={field.onChange}
placeholder="Masukan Nama Lengkap"
/>
)}
/>
{errors.name?.message && (
<p className="text-red-400 text-sm">
{errors.name.message}
</p>
)}
</div>
</div>
</div>
) : (
""
)}
{/* Submit Button */}
<div className="mt-4">
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
</div>
</Card>
<Card className="w-full lg:w-3/12">
<div className="px-3 py-3">Jadwal Selanjutnya</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,167 @@
"use client";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { close, loading } from "@/config/swal";
import { Link } from "@/i18n/routing";
import { getPlanningPagination } from "@/service/service/agenda-setting/agenda-setting";
import { htmlToString, textEllipsis } from "@/utils/globals";
import { MoreVertical } from "lucide-react";
import { useEffect, useState } from "react";
export default function ExpandedData(props: { datas: any }) {
const { datas } = props;
const [isOpen, setIsOpen] = useState("");
const [getData, setGetData] = useState<any>();
const handleIsOpen = (id: string) => {
setIsOpen(id);
};
useEffect(() => {
if (isOpen !== "") {
fetchData();
}
}, [isOpen]);
async function fetchData() {
loading();
const response = await getPlanningPagination(0, "", 10, 1, 1, isOpen);
close();
setupData(response?.data?.data);
}
function setupData(rawData: any) {
if (rawData != undefined) {
const dataContent = rawData?.content;
const data = [];
for (const [i, element] of dataContent.entries()) {
element.no = i + 1;
data.push(element);
}
setGetData(data);
}
}
return (
<table>
<tr>
<th className="text-left">Judul Perencanaan</th>
<th>Batas Waktu</th>
<th>Status</th>
<th>Aksi</th>
</tr>
{datas?.map((data: any) => (
<>
<tr key={data.id}>
<th className="text-left font-normal text-sm">
<a onClick={() => handleIsOpen(data.id)}>{data.title}</a>
</th>
<th
className="font-normal text-sm"
onClick={() =>
`disinni igninn membuat state untuk mennyimpan data isOpen`
}
>
{data.date}
</th>
<th className="font-normal text-sm">{data.status}</th>
<th className="flex justify-center text-sm">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
>
<MoreVertical className="h-4 w-4 text-default-800" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="p-0" align="end">
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/mediahub/create-daily/detail/${data.id}`}
>
Detail
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/mediahub/create-daily/edit/${data.id}`}
>
Edit
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<a className="text-red-600">Delete</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</th>
</tr>
<Collapsible
open={isOpen === data.id}
onOpenChange={() => handleIsOpen(data.id)}
>
<CollapsibleContent className="space-y-2 w-full text-xs">
<tr className="space-x-2">
<th className="px-3">No</th>
<th className="text-left">Judul Perencanaan</th>
<th className="text-left px-3">Nama Pembuat</th>
<th className="text-left px-3">Batas Waktu</th>
<th className="text-left px-3">Status</th>
<th>Aksi</th>
</tr>
{getData?.map((row: any) => (
<tr key={row.id}>
<td className="px-3">{row.no}</td>
<td>{row.title}</td>
<td className="text-left px-3">{row.createdByName}</td>
<td className="text-left px-3">{row.date}</td>
<td className="text-left px-3">{row.status}</td>
<td className="flex justify-center text-sm">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
>
<MoreVertical className="h-4 w-4 text-default-800" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="p-0" align="end">
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/mediahub/create-weekly/detail/${data.id}`}
>
Detail
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/mediahub/create-weekly/edit/${data.id}`}
>
Edit
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<a className="text-red-600">Delete</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</td>
</tr>
))}
</CollapsibleContent>
</Collapsible>
</>
))}
</table>
);
}

View File

@ -0,0 +1,112 @@
import * as React from "react";
import { ColumnDef } from "@tanstack/react-table";
import { Eye, MoreVertical, SquarePen, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { htmlToString } from "@/utils/globals";
import { Link, useRouter } from "@/i18n/routing";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible";
import ExpandedData from "./expand-list-view";
const columns: ColumnDef<any>[] = [
{
accessorKey: "no",
header: "No",
cell: ({ row }) => <span>{row.getValue("no")}</span>,
},
{
accessorKey: "title",
header: "Judul Perencanaan",
cell: ({ row }) => {
const datas = row.original.subPlanningList;
return (
<Dialog>
<DialogTrigger asChild>
<a className="cursor-pointer">{row.getValue("title")}</a>
</DialogTrigger>
<DialogContent size="md">
<DialogHeader>
<DialogTitle>Rencanaan Mingguan</DialogTitle>
</DialogHeader>
<ExpandedData datas={datas} />
</DialogContent>
</Dialog>
);
},
},
{
accessorKey: "date",
header: "Batas Waktu",
cell: ({ row }) => <span>{row.getValue("date")}</span>,
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => <span>{row.getValue("status")}</span>,
},
{
id: "actions",
accessorKey: "action",
header: "Actions",
enableHiding: false,
cell: ({ row }) => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
>
<MoreVertical className="h-4 w-4 text-default-800" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="p-0" align="end">
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/mediahub/create-monthly/detail/${row.original.id}`}
>
Detail
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/mediahub/create-monthly/edit/${row.original.id}`}
>
Edit
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<a className="text-red-600">Delete</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];
export default columns;

View File

@ -0,0 +1,115 @@
import * as React from "react";
import { ColumnDef } from "@tanstack/react-table";
import { Eye, MoreVertical, SquarePen, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { htmlToString } from "@/utils/globals";
import { Link, useRouter } from "@/i18n/routing";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import ExpandedData from "./expand-list-view";
const columns: ColumnDef<any>[] = [
{
accessorKey: "no",
header: "No",
cell: ({ row }) => <span>{row.getValue("no")}</span>,
},
// {
// accessorKey: "title",
// header: "Judul Perencanaan",
// cell: ({ row }) => <span>{row.getValue("title")}</span>,
// },
{
accessorKey: "title",
header: "Judul Perencanaan",
cell: ({ row }) => {
const datas = row.original.subPlanningList;
return (
<Dialog>
<DialogTrigger asChild>
<a className="cursor-pointer">{row.getValue("title")}</a>
</DialogTrigger>
<DialogContent size="md">
<DialogHeader>
<DialogTitle>Rencanaan Mingguan</DialogTitle>
</DialogHeader>
<ExpandedData datas={datas} />
</DialogContent>
</Dialog>
);
},
},
{
accessorKey: "date",
header: "Batas Waktu",
cell: ({ row }) => <span>{row.getValue("date")}</span>,
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => <span>{row.getValue("status")}</span>,
},
{
id: "actions",
accessorKey: "action",
header: "Actions",
enableHiding: false,
cell: ({ row }) => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
>
<MoreVertical className="h-4 w-4 text-default-800" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="p-0" align="end">
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/medsos-mediahub/create-monthly/detail/${row.original.id}`}
>
Detail
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<Link
href={`/curator/task-plan/medsos-mediahub/create-monthly/edit/${row.original.id}`}
>
Edit
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
<a className="text-red-600">Hapus</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];
export default columns;

View File

@ -0,0 +1,156 @@
"use client";
import * as React from "react";
import {
ColumnDef,
ColumnFiltersState,
PaginationState,
SortingState,
VisibilityState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./list-view-social-media-column";
import { getPlanningPagination } from "@/service/service/agenda-setting/agenda-setting";
const ListViewSocialMediaTable = () => {
const router = useRouter();
const searchParams = useSearchParams();
const [dataTable, setDataTable] = React.useState<any[]>([]);
const [totalData, setTotalData] = React.useState<number>(1);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [rowSelection, setRowSelection] = React.useState({});
const [pagination, setPagination] = React.useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [page, setPage] = React.useState(1);
const [limit, setLimit] = React.useState(10);
const [totalPage, setTotalPage] = React.useState(1);
const table = useReactTable({
data: dataTable,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
onPaginationChange: setPagination,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
pagination,
},
});
React.useEffect(() => {
const pageFromUrl = searchParams?.get("page");
if (pageFromUrl) {
setPage(Number(pageFromUrl));
}
}, [searchParams]);
React.useEffect(() => {
fetchData();
}, [page, limit]);
async function fetchData() {
try {
const res = await getPlanningPagination(page - 1, "", 10, 2, 3);
const data = res?.data?.data;
const contentData = data?.content;
contentData.forEach((item: any, index: number) => {
item.no = (page - 1) * limit + index + 1;
});
console.log("contentData : ", data);
setDataTable(contentData);
setTotalData(data?.totalElements);
setTotalPage(data?.totalPages);
} catch (error) {
console.error("Error fetching tasks:", error);
}
}
return (
<div className="w-full overflow-x-auto">
<Table className="overflow-hidden mt-3">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="bg-default-200">
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
className="h-[75px]"
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
<TablePagination
table={table}
totalData={totalData}
totalPage={totalPage}
/>
</div>
);
};
export default ListViewSocialMediaTable;

View File

@ -0,0 +1,156 @@
"use client";
import * as React from "react";
import {
ColumnDef,
ColumnFiltersState,
PaginationState,
SortingState,
VisibilityState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./list-view-column";
import { getPlanningPagination } from "@/service/service/agenda-setting/agenda-setting";
const ListViewTable = () => {
const router = useRouter();
const searchParams = useSearchParams();
const [dataTable, setDataTable] = React.useState<any[]>([]);
const [totalData, setTotalData] = React.useState<number>(1);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [rowSelection, setRowSelection] = React.useState({});
const [pagination, setPagination] = React.useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [page, setPage] = React.useState(1);
const [limit, setLimit] = React.useState(10);
const [totalPage, setTotalPage] = React.useState(1);
const table = useReactTable({
data: dataTable,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
onPaginationChange: setPagination,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
pagination,
},
});
React.useEffect(() => {
const pageFromUrl = searchParams?.get("page");
if (pageFromUrl) {
setPage(Number(pageFromUrl));
}
}, [searchParams]);
React.useEffect(() => {
fetchData();
}, [page, limit]);
async function fetchData() {
try {
const res = await getPlanningPagination(page - 1, "", 10, 1, 3);
const data = res?.data?.data;
const contentData = data?.content;
contentData.forEach((item: any, index: number) => {
item.no = (page - 1) * limit + index + 1;
});
console.log("contentData : ", data);
setDataTable(contentData);
setTotalData(data?.totalElements);
setTotalPage(data?.totalPages);
} catch (error) {
console.error("Error fetching tasks:", error);
}
}
return (
<div className="w-full overflow-x-auto">
<Table className="overflow-hidden mt-3">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="bg-default-200">
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
className="h-[75px]"
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
<TablePagination
table={table}
totalData={totalData}
totalPage={totalPage}
/>
</div>
);
};
export default ListViewTable;

View File

@ -0,0 +1,459 @@
"use client";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import utc from "dayjs/plugin/utc";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { close, loading } from "@/config/swal";
import { useSearchParams } from "next/navigation";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/free-mode";
import "swiper/css/navigation";
import "swiper/css/thumbs";
import Image from "next/image";
import { FreeMode, Navigation, Thumbs } from "swiper/modules";
import { Swiper as SwiperType } from "swiper/types";
import weekday from "dayjs/plugin/weekday";
import { Icon } from "@iconify/react/dist/iconify.js";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import TaskPlanningSocialMediaTable from "./social-media-modal/table";
import { getMonthlyPlanList, getPlanningMonthlyPerSocmed, getWeeklyPlanList, getWeeklyPlanListByParentId } from "@/service/service/agenda-setting/agenda-setting";
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const TODAY = dayjs().format("YYYY-MM-DD");
export default function SingleViewSocialMediaTable() {
const params = useSearchParams();
const [selectedMonthItem, setSelectedMonthItem] = useState<
string | undefined
>(undefined);
const [selectedWeekly, setSelectedWeekly] = useState<string | undefined>(
undefined
);
const [selectedDate, setSelectedDate] = useState<number>(
new Date(TODAY).getDate()
);
const [nowDate, setNowDate] = useState<string>(TODAY);
const INITIAL_YEAR = dayjs().format("YYYY");
const INITIAL_MONTH = dayjs().format("M");
const size = 20;
const page: string | undefined | null = params?.get("page");
const id: string | undefined | null = params?.get("id");
const pages = page ? Number(page) - 1 : 0;
const no = (size || 10) * pages;
const [selectedMonth, setSelectedMonth] = useState<any>(
dayjs(new Date(parseInt(INITIAL_YEAR), parseInt(INITIAL_MONTH) - 1, 1))
);
const [selectedMonthTitle, setSelectedMonthTitle] = useState<string>("");
const [days, setDays] = useState<any>([]);
const weekday = require("dayjs/plugin/weekday");
const weekOfYear = require("dayjs/plugin/weekOfYear");
const [planningData, setPlanningData] = useState<any>([]);
dayjs.extend(utc);
dayjs.extend(weekday);
dayjs.extend(weekOfYear);
let currentMonthDays: any;
let previousMonthDays: any;
let nextMonthDays: any;
const [monthlyList, setMonthlyList] = useState([]);
const [weeklyList, setWeeklyList] = useState([]);
const [getData, setGetData] = useState<any>([]);
const [isOpen, setIsOpen] = useState(false);
const [selectedDateNow, setSelectedDateNow] = useState("");
const [selectedPlatform, setSelectedPlatform] = useState("");
useEffect(() => {
createCalendar("START");
}, []);
function createDaysForCurrentMonth(
year: string,
month: string,
daysInMonth: number
) {
const days: any = [];
for (let day = 1; day <= daysInMonth; day++) {
const date = dayjs(
new Date(parseInt(year), parseInt(month) - 1, day)
).format("YYYY-MM-DD");
days.push({
date,
isCurrentMonth: true,
isToday: date === TODAY,
});
}
return days;
}
async function getMonthlyPlanning(dates: number) {
const res = await getMonthlyPlanList(dates, 2);
setMonthlyList(res?.data?.data);
}
async function getWeeklyPlanning(
id: string | undefined,
date: number | undefined
) {
if (id) {
const res = await getWeeklyPlanListByParentId(id, 2);
setWeeklyList(res?.data?.data);
} else {
const res = await getWeeklyPlanList(date, 2, true);
setWeeklyList(res?.data?.data);
}
}
function createCalendar(
year: string = INITIAL_YEAR,
month: string = INITIAL_MONTH
) {
year = year === "START" ? INITIAL_YEAR : year;
fetchData(month, year);
setSelectedMonthTitle(
dayjs(new Date(parseInt(year), parseInt(month) - 1))
.utc()
.local()
.format("MMMM YYYY")
);
currentMonthDays = createDaysForCurrentMonth(
year,
month,
dayjs(`${year}-${month}-01`).daysInMonth()
);
getMonthlyPlanning(year ? currentMonthDays[0]?.date : TODAY);
getWeeklyPlanning(undefined, year ? currentMonthDays[0]?.date : TODAY);
previousMonthDays = createDaysForPreviousMonth(year, month);
nextMonthDays = createDaysForNextMonth(year, month);
const listDay = [
...previousMonthDays,
...currentMonthDays,
...nextMonthDays,
];
setDays(listDay);
}
function getWeekday(date: string | undefined) {
return dayjs(date).weekday();
}
function createDaysForPreviousMonth(year: string, month: string) {
const firstDayOfTheMonthWeekday = getWeekday(currentMonthDays[0]?.date);
const previousMonth = dayjs(`${year}-${month}-01`).subtract(1, "month");
// Cover first day of the month being sunday (firstDayOfTheMonthWeekday == 0)
const visibleNumberOfDaysFromPreviousMonth = firstDayOfTheMonthWeekday
? firstDayOfTheMonthWeekday - 1
: 6;
const previousMonthLastMondayDayOfMonth = dayjs(currentMonthDays[0].date)
.subtract(visibleNumberOfDaysFromPreviousMonth, "day")
.date();
return [...new Array(visibleNumberOfDaysFromPreviousMonth)].map(
(day, index) => ({
date: dayjs(
`${previousMonth.year()}-${previousMonth.month() + 1}-${
previousMonthLastMondayDayOfMonth + index
}`
).format("YYYY-MM-DD"),
dayOfMonth: previousMonthLastMondayDayOfMonth + index,
isCurrentMonth: false,
})
);
}
function createDaysForNextMonth(year: string, month: string) {
const lastDayOfTheMonthWeekday = getWeekday(
`${year}-${month}-${currentMonthDays.length}`
);
const nextMonth = dayjs(`${year}-${month}-01`).add(1, "month");
const visibleNumberOfDaysFromNextMonth = lastDayOfTheMonthWeekday
? 7 - lastDayOfTheMonthWeekday
: lastDayOfTheMonthWeekday;
return [...new Array(visibleNumberOfDaysFromNextMonth)].map(
(day, index) => ({
date: dayjs(
`${nextMonth.year()}-${nextMonth.month() + 1}-${index + 1}`
).format("YYYY-MM-DD"),
dayOfMonth: index + 1,
isCurrentMonth: false,
})
);
}
async function fetchData(
month: string,
year: string,
parentId?: string | undefined
) {
loading();
const res = await getPlanningMonthlyPerSocmed(month, year, 2, parentId);
close();
setPlanningData(res?.data?.data);
}
function getPrevMonth() {
const selectedMonthNew = dayjs(selectedMonth).subtract(1, "month");
createCalendar(
selectedMonthNew.format("YYYY"),
selectedMonthNew.format("M")
);
fetchData("", selectedMonthNew?.format("YYYY-MM-DD"));
setSelectedMonth(selectedMonthNew);
setSelectedDate(1);
}
function getPresentMonth() {
const selectedMonthNew = dayjs(
new Date(parseInt(INITIAL_YEAR), parseInt(INITIAL_MONTH) - 1, 1)
);
createCalendar(
selectedMonthNew.format("YYYY"),
selectedMonthNew.format("M")
);
fetchData("", TODAY);
setSelectedDate(Number(dayjs().format("D")));
setSelectedMonth(selectedMonthNew);
}
function getNextMonth() {
const selectedMonthNew = dayjs(selectedMonth).add(1, "month");
createCalendar(
selectedMonthNew.format("YYYY"),
selectedMonthNew.format("M")
);
fetchData("", selectedMonthNew?.format("YYYY-MM-DD"));
setSelectedMonth(selectedMonthNew);
setSelectedDate(1);
}
const onSelectedMonthItem = (id: string | undefined) => {
// fetchData(date)
setSelectedMonthItem(id);
getWeeklyPlanning(id, undefined);
};
const onSelectedWeekly = (id: string | undefined) => {
setSelectedWeekly(id);
fetchData("", String(id));
};
const removeSelection = () => {
setSelectedMonthItem(undefined);
setSelectedWeekly(undefined);
};
const onSelectedSocmed = async (date: string, platform: string) => {
setSelectedDateNow(date);
setSelectedPlatform(platform);
setIsOpen(true);
};
const getDataForThisDate = (day: number) => {
const todayData = planningData?.find((a: any) => a?.day == day);
if (todayData) {
return (
<div className="flex flex-col gap-1">
<a
onClick={() =>
onSelectedSocmed(todayData.planningList[0].date, "5")
}
className="flex flex-row gap-5 rounded-sm bg-[#0C0705] text-white px-3 py-1 justify-center cursor-pointer"
>
Total: {todayData.totalTwitter}
{/* <XIcon /> */}
</a>
<a
onClick={() =>
onSelectedSocmed(todayData.planningList[0].date, "1")
}
className="flex flex-row gap-5 rounded-sm bg-[#1877F2] text-white px-3 py-1 justify-center cursor-pointer"
>
Total: {todayData.totalFacebook}
{/* <FacebookIcon /> */}
</a>
<a
onClick={() =>
onSelectedSocmed(todayData.planningList[0].date, "2")
}
className="flex flex-row gap-5 rounded-sm bg-[#d62976] text-white px-3 py-1 justify-center cursor-pointer"
>
Total: {todayData.totalInstagram}
{/* <InstagramIcon /> */}
</a>
<a
onClick={() =>
onSelectedSocmed(todayData.planningList[0].date, "3")
}
className="flex flex-row gap-5 rounded-sm bg-[#FF0000] text-white px-3 py-1 justify-center cursor-pointer"
>
Total: {todayData.totalYoutube}
{/* <YoutubeIcon /> */}
</a>
<a
onClick={() =>
onSelectedSocmed(todayData.planningList[0].date, "4")
}
className="flex flex-row gap-5 rounded-sm bg-[#000000] text-white px-3 py-1 justify-center cursor-pointer"
>
Total: {todayData.totalTiktok}
{/* <TiktokIcon /> */}
</a>
</div>
);
}
};
return (
<div className="border-2 rounded-sm p-4 flex gap-3 flex-col">
<div className="flex justify-between">
<div className="flex flex-row gap-2">
<a onClick={getPrevMonth} className="cursor-pointer">
<ChevronLeft />
</a>
<a onClick={getPresentMonth} className="cursor-pointer">
Today
</a>
<a onClick={getNextMonth} className="cursor-pointer">
<ChevronRight />
</a>
</div>
<p className="text-xl font-semibold">{selectedMonthTitle}</p>
</div>
<div className="flex justify-end">
<a
className="border-2 border-primary px-2 py-1 rounded-full text-[10px] text-primary cursor-pointer"
onClick={() => removeSelection()}
>
Hapus Pilihan
</a>
</div>
<div className="px-8 flex flex-col gap-2 text-sm">
<p className="font-semibold">Rencana Bulanan</p>
{monthlyList?.length > 0 ? (
<div className="flex flex-nowrap gap-3 flex-row">
{monthlyList?.map((item: any) => (
<div
key={item.id}
className={`rounded-full px-8 py-3 cursor-pointer ${
selectedMonthItem === item.id
? "bg-sky-600 text-white "
: "bg-sky-300"
}`}
onClick={() => onSelectedMonthItem(item.id)}
>
<p>{item.title}</p>
</div>
))}
</div>
) : (
<div className="flex justify-center bg-slate-200 dark:bg-black rounded-full py-1">
Rencana Bulanan Belum Tersedia
</div>
)}
<p className="font-semibold">Rencana Mingguan</p>
{weeklyList?.length > 0 ? (
<div className="flex flex-nowrap gap-3 flex-row">
{weeklyList?.map((item: any) => (
<a
key={item.id}
className={`bg-sky-300 rounded-full px-8 py-3 cursor-pointer ${
selectedWeekly === item.id
? "bg-sky-600 text-white "
: "bg-sky-300"
}`}
onClick={() => onSelectedWeekly(item.id)}
>
<p>{item.title}</p>
</a>
))}
</div>
) : (
<div className="flex justify-center bg-slate-200 dark:bg-black rounded-full py-1">
Rencana Mingguan Belum Tersedia
</div>
)}
</div>
<div>
<div className="w-full mb-2">
<div className="overflow-auto">
<ol
id="days-of-week"
className="grid grid-cols-7 gap-1 border-y-2 py-3"
>
{WEEKDAYS.map((weekday, index) => (
<li
key={`weekday-${index}`}
className="mr-1 text-sm font-medium text-end"
>
{weekday}
</li>
))}
</ol>
<ol id="calendar-days" className="grid grid-cols-7 gap-1">
{days?.map((day: any, index: number) => (
<li
key={`day-${index}`}
className={`p-2 text-end min-h-[100px] ${
day.isCurrentMonth ? "" : "bg-slate-200 dark:bg-black text-slate-400"
}`}
>
<span
className={`block mb-1 ${
day.date == TODAY ? "font-semibold text-xl" : ""
}`}
>
{parseInt(day.date.split("-")[2])}
</span>
{day.isCurrentMonth &&
getDataForThisDate(parseInt(day.date.split("-")[2]))}
</li>
))}
</ol>
</div>
</div>
</div>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent size="lg" className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Perencanaan Medsos Harian</DialogTitle>
</DialogHeader>
<div className="flex items-center space-x-2">
<TaskPlanningSocialMediaTable
date={selectedDateNow}
platform={selectedPlatform}
/>
</div>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -0,0 +1,320 @@
"use client";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import utc from "dayjs/plugin/utc";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { close, loading } from "@/config/swal";
import { useSearchParams } from "next/navigation";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/free-mode";
import "swiper/css/navigation";
import "swiper/css/thumbs";
import { getMonthlyPlanList, getPlanningDailyByTypeId, getWeeklyPlanList, getWeeklyPlanListByParentId } from "@/service/service/agenda-setting/agenda-setting";
import TaskPlanMediahubTable from "@/app/[locale]/(admin)/admin/curator/task-plan/mediahub/components/table";
const TODAY = dayjs().format("YYYY-MM-DD"); // Pastikan Anda mendefinisikan TODAY dengan format yang konsisten
export default function SingleViewTable() {
const params = useSearchParams();
const [selectedMonthItem, setSelectedMonthItem] = useState<
string | undefined
>(undefined);
const [selectedWeekly, setSelectedWeekly] = useState<string | undefined>(
undefined
);
const [selectedDate, setSelectedDate] = useState<number>(
new Date(TODAY).getDate()
);
const [nowDate, setNowDate] = useState<string>(TODAY);
const INITIAL_YEAR = dayjs().format("YYYY");
const INITIAL_MONTH = dayjs().format("M");
const size = 20;
const page: string | undefined | null = params?.get("page");
const id: string | undefined | null = params?.get("id");
const pages = page ? Number(page) - 1 : 0;
const no = (size || 10) * pages;
const [selectedMonth, setSelectedMonth] = useState<dayjs.Dayjs>(
dayjs(new Date(parseInt(INITIAL_YEAR), parseInt(INITIAL_MONTH) - 1, 1))
);
const [selectedMonthTitle, setSelectedMonthTitle] = useState<string>("");
const [days, setDays] = useState<any>([]);
const weekday = require("dayjs/plugin/weekday");
const weekOfYear = require("dayjs/plugin/weekOfYear");
dayjs.extend(utc);
dayjs.extend(weekday);
dayjs.extend(weekOfYear);
const [monthlyList, setMonthlyList] = useState([]);
const [weeklyList, setWeeklyList] = useState([]);
const [getData, setGetData] = useState<any>([]);
const [getTotalPage, setGetTotalPage] = useState<number>(1);
const [getTOtalData, setGetTotalData] = useState(0);
useEffect(() => {
createCalendar("START");
}, []);
function createDaysForCurrentMonth(
year: string,
month: string,
daysInMonth: number
) {
const days: any = [];
for (let day = 1; day <= daysInMonth; day++) {
const date = dayjs(
new Date(parseInt(year), parseInt(month) - 1, day)
).format("YYYY-MM-DD");
days.push({
date,
isCurrentMonth: true,
isToday: date === TODAY,
});
}
return days;
}
async function getMonthlyPlanning(dates: number) {
const res = await getMonthlyPlanList(dates, 1);
console.log("monthsss", res);
setMonthlyList(res?.data?.data);
}
async function getWeeklyPlanning(
id: string | undefined,
date: number | undefined
) {
if (id) {
const res = await getWeeklyPlanListByParentId(id, 1);
setWeeklyList(res?.data?.data);
} else {
const res = await getWeeklyPlanList(date, 1, true);
setWeeklyList(res?.data?.data);
}
}
function createCalendar(
year: string = INITIAL_YEAR,
month: string = INITIAL_MONTH
) {
const state = year;
year = year === "START" ? INITIAL_YEAR : year;
setSelectedMonthTitle(
dayjs(new Date(parseInt(year), parseInt(month) - 1))
.utc()
.local()
.format("MMMM YYYY")
);
const currentMonthDays = createDaysForCurrentMonth(
year,
month,
dayjs(`${year}-${month}-01`).daysInMonth()
);
console.log("Month:", currentMonthDays);
getMonthlyPlanning(state === "START" ? TODAY : currentMonthDays[0]?.date);
getWeeklyPlanning(
undefined,
state === "START" ? TODAY : currentMonthDays[0]?.date
);
setDays(currentMonthDays);
console.log("currentMonthDays", currentMonthDays);
}
async function fetchData(
parentId: string | number | undefined,
date?: string
) {
loading();
const response = await getPlanningDailyByTypeId(
pages,
size,
parentId || selectedWeekly,
date || nowDate || TODAY,
1
);
close();
setupData(response?.data?.data);
}
function setupData(rawData: any) {
if (rawData != undefined) {
const dataContent = rawData?.content;
const data = [];
for (const [i, element] of dataContent.entries()) {
element.no = no + i + 1;
data.push(element);
}
setGetData(data);
setGetTotalPage(rawData?.totalPages);
setGetTotalData(rawData?.totalElements);
}
}
function getPrevMonth() {
const selectedMonthNew = dayjs(selectedMonth).subtract(1, "month");
createCalendar(
selectedMonthNew.format("YYYY"),
selectedMonthNew.format("M")
);
fetchData(undefined, selectedMonthNew?.format("YYYY-MM-DD"));
setSelectedMonth(selectedMonthNew);
setSelectedDate(1);
}
function getPresentMonth() {
const selectedMonthNew = dayjs(
new Date(parseInt(INITIAL_YEAR), parseInt(INITIAL_MONTH) - 1, 1)
);
createCalendar(
selectedMonthNew.format("YYYY"),
selectedMonthNew.format("M")
);
fetchData(undefined, TODAY);
setSelectedDate(Number(dayjs().format("D")));
setSelectedMonth(selectedMonthNew);
}
function getNextMonth() {
const selectedMonthNew = dayjs(selectedMonth).add(1, "month");
createCalendar(
selectedMonthNew.format("YYYY"),
selectedMonthNew.format("M")
);
fetchData(undefined, selectedMonthNew?.format("YYYY-MM-DD"));
setSelectedMonth(selectedMonthNew);
setSelectedDate(1);
}
const onSelectedMonthItem = (id: string | undefined) => {
// fetchData(date)
setSelectedMonthItem(id);
getWeeklyPlanning(id, undefined);
};
const onSelectedWeekly = (id: string | undefined) => {
setSelectedWeekly(id);
fetchData(id);
};
const onSelectedDay = (day: number, date: string) => {
fetchData(undefined, date);
setSelectedDate(day);
setNowDate(date);
};
const removeSelection = () => {
setSelectedMonthItem(undefined);
setSelectedWeekly(undefined);
};
return (
<div className="border-2 rounded-sm p-4 flex gap-3 flex-col">
<div className="flex justify-between">
<div className="flex flex-row gap-2">
<a onClick={getPrevMonth} className="cursor-pointer">
<ChevronLeft />
</a>
<a onClick={getPresentMonth} className="cursor-pointer">
Today
</a>
<a onClick={getNextMonth} className="cursor-pointer">
<ChevronRight />
</a>
</div>
<p className="text-xl font-semibold">{selectedMonthTitle}</p>
</div>
<div className="flex justify-end">
<a
className="border-2 border-primary px-2 py-1 rounded-full text-[10px] text-primary cursor-pointer"
onClick={() => removeSelection()}
>
Hapus Pilihan
</a>
</div>
<div className="px-8 flex flex-col gap-2 text-sm">
<p className="font-semibold">Rencana Bulanan</p>
{monthlyList?.length > 0 ? (
<div className="flex flex-nowrap gap-3 flex-row">
{monthlyList?.map((item: any) => (
<div
key={item.id}
className={`rounded-full px-8 py-3 cursor-pointer ${
selectedMonthItem === item.id
? "bg-sky-600 text-white "
: "bg-sky-300"
}`}
onClick={() => onSelectedMonthItem(item.id)}
>
<p>{item.title}</p>
</div>
))}
</div>
) : (
<div className="flex justify-center bg-slate-200 dark:bg-black rounded-full py-1">
Rencana Bulanan Belum Tersedia
</div>
)}
<p className="font-semibold">Rencana Mingguan</p>
{weeklyList?.length > 0 ? (
<div className="flex flex-nowrap gap-3 flex-row">
{weeklyList?.map((item: any) => (
<a
key={item.id}
className={`bg-sky-300 rounded-full px-8 py-3 cursor-pointer ${
selectedWeekly === item.id
? "bg-sky-600 text-white "
: "bg-sky-300"
}`}
onClick={() => onSelectedWeekly(item.id)}
>
<p>{item.title}</p>
</a>
))}
</div>
) : (
<div className="flex justify-center bg-slate-200 dark:bg-black rounded-full py-1">
Rencana Mingguan Belum Tersedia
</div>
)}
<p className="font-semibold">Rencana Harian</p>
</div>
<div className="custom-scrollbar-table flex flex-nowrap justify-between gap-2 overflow-x-auto">
{days.map((day: any) => (
<a
key={day.date}
className={`cursor-pointer px-2 ${
selectedDate == parseInt(day.date.split("-")[2], 10)
? "border-b-2 border-primary text-primary"
: ""
}`}
onClick={() =>
onSelectedDay(parseInt(day.date.split("-")[2], 10), day.date)
}
>
{parseInt(day.date.split("-")[2], 10)}
</a>
))}
</div>
<TaskPlanMediahubTable
data={getData}
totalPage={getTotalPage}
totalData={getTOtalData}
/>
</div>
);
}

View File

@ -0,0 +1,104 @@
import * as React from "react";
import { ColumnDef } from "@tanstack/react-table";
import { Eye, MoreVertical, SquarePen, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { htmlToString } from "@/utils/globals";
import { Link, useRouter } from "@/i18n/routing";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
const columns: ColumnDef<any>[] = [
{
accessorKey: "no",
header: "No",
cell: ({ row }) => <span>{row.getValue("no")}</span>,
},
// {
// accessorKey: "title",
// header: "Judul Perencanaan",
// cell: ({ row }) => <span>{row.getValue("title")}</span>,
// },
{
accessorKey: "title",
header: "Judul Perencanaan",
cell: ({ row }) => <span>{row.getValue("title")}</span>,
},
{
accessorKey: "createdByName",
header: "Nama Pembuat",
cell: ({ row }) => <span>{row.getValue("createdByName")}</span>,
},
{
accessorKey: "createdAt",
header: "Dibuat",
cell: ({ row }) => <span>{row.getValue("createdAt")}</span>,
},
{
accessorKey: "status",
header: "Dibuat",
cell: ({ row }) => <span>{row.getValue("status")}</span>,
},
{
accessorKey: "platformTypeId",
header: "Jenis Platform",
cell: ({ row }) => <span>{row.getValue("platformTypeId")}</span>,
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => <span>{row.getValue("status")}</span>,
},
{
accessorKey: "description",
header: "Deskripsi",
cell: ({ row }) => <span>{htmlToString(row.getValue("status"))}</span>,
},
{
id: "actions",
accessorKey: "action",
header: "Aksi",
enableHiding: false,
cell: ({ row }) => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
>
<MoreVertical className="h-4 w-4 text-default-800" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="p-0" align="end">
<DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
Detail
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];
export default columns;

View File

@ -0,0 +1,200 @@
"use client";
import * as React from "react";
import {
ColumnDef,
ColumnFiltersState,
PaginationState,
SortingState,
VisibilityState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
ChevronLeft,
ChevronRight,
Eye,
MoreVertical,
Search,
SquarePen,
Trash2,
TrendingDown,
TrendingUp,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { paginationBlog } from "@/service/blog/blog";
import { ticketingPagination } from "@/service/ticketing/ticketing";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./column";
import {
getPlanningDailyMedsosByPlatform,
getPlanningPagination,
} from "@/service/agenda-setting/agenda-setting";
const TaskPlanningSocialMediaTable = (props: {
date: string;
platform: string;
}) => {
const router = useRouter();
const searchParams = useSearchParams();
const [dataTable, setDataTable] = React.useState<any[]>([]);
const [totalData, setTotalData] = React.useState<number>(1);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [rowSelection, setRowSelection] = React.useState({});
const [pagination, setPagination] = React.useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [page, setPage] = React.useState(1);
const [limit, setLimit] = React.useState(10);
const [totalPage, setTotalPage] = React.useState(1);
const table = useReactTable({
data: dataTable,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
onPaginationChange: setPagination,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
pagination,
},
});
React.useEffect(() => {
const pageFromUrl = searchParams?.get("page");
if (pageFromUrl) {
setPage(Number(pageFromUrl));
}
}, [searchParams]);
React.useEffect(() => {
fetchData();
}, [page, limit, props]);
async function fetchData() {
try {
const response = await getPlanningDailyMedsosByPlatform(
"0",
20,
props.date,
props.platform
);
const data = response?.data?.data;
const contentData = data?.content;
contentData.forEach((item: any, index: number) => {
item.no = (page - 1) * limit + index + 1;
item.platformTypeId =
props.platform === "1"
? "Facebook"
: props.platform === "2"
? "Instagram"
: props.platform === "3"
? "Youtube"
: props.platform === "4"
? "Tiktok"
: props.platform === "3"
? "X"
: "";
});
setDataTable(contentData);
setTotalData(data?.totalElements);
setTotalPage(data?.totalPages);
} catch (error) {
console.error("Error fetching tasks:", error);
}
}
return (
<div className="w-full overflow-x-auto">
<Table className="overflow-hidden mt-3">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="bg-default-200">
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
className="h-[75px]"
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
<TablePagination
table={table}
totalData={totalData}
totalPage={totalPage}
/>
</div>
);
};
export default TaskPlanningSocialMediaTable;