From 60edcc288fa6db9656d5aa47c0b4d5547cf3273a Mon Sep 17 00:00:00 2001 From: Anang Yusman Date: Sat, 7 Dec 2024 01:37:45 +0700 Subject: [PATCH] fix:login page, table:image,audio,audio-visual,teks --- .../audio-visual/table-video/index.tsx | 299 ++++++++++++++++- .../content/audio/table-audio/index.tsx | 303 ++++++++++++++++- .../content/image/table-image/index.tsx | 43 ++- .../content/spit/table-spit/index.tsx | 304 ++++++++++++++++- .../content/teks/table-teks/index.tsx | 310 +++++++++++++++++- app/[locale]/(protected)/task/page.tsx | 14 +- .../task/table-task/task-table.tsx | 25 +- app/[locale]/page.tsx | 1 - components/form/task/task-form.tsx | 4 - components/landing-page/SearchSection.tsx | 61 +++- components/partials/auth/login-form.tsx | 218 +++++++++--- config/api.ts | 1 - lib/swal.ts | 92 ++++++ lib/utils.ts | 82 ++--- service/auth.ts | 102 ++---- service/content/content-image.ts | 19 -- service/content/content.ts | 85 +++++ .../http-config/axios-interceptor-instance.ts | 2 + service/http-config/http-base-service.ts | 154 +++++---- service/task.ts | 12 +- 20 files changed, 1773 insertions(+), 358 deletions(-) create mode 100644 lib/swal.ts delete mode 100644 service/content/content-image.ts create mode 100644 service/content/content.ts diff --git a/app/[locale]/(protected)/content/audio-visual/table-video/index.tsx b/app/[locale]/(protected)/content/audio-visual/table-video/index.tsx index 15500f7e..136b25f7 100644 --- a/app/[locale]/(protected)/content/audio-visual/table-video/index.tsx +++ b/app/[locale]/(protected)/content/audio-visual/table-video/index.tsx @@ -2,7 +2,9 @@ import * as React from "react"; import { + ColumnDef, ColumnFiltersState, + PaginationState, SortingState, VisibilityState, flexRender, @@ -12,7 +14,6 @@ import { getSortedRowModel, useReactTable, } from "@tanstack/react-table"; -import { columns } from "./columns"; import { Input } from "@/components/ui/input"; import { @@ -26,8 +27,177 @@ import { import { data } from "./data"; import TablePagination from "./table-pagination"; +import { Button } from "@/components/ui/button"; +import { format } from "date-fns"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + ChevronLeft, + ChevronRight, + Eye, + MoreVertical, + Trash2, +} from "lucide-react"; +import { title } from "process"; + +import { getCookiesDecrypt } from "@/lib/utils"; +import { listDataImage, listDataVideo } from "@/service/content/content"; + +export type CompanyData = { + no: number; + title: string; + categoryName: string; + createdAt: string; + creatorGroup: string; + publishedOn: string; + isPublish: any; + isPublishOnPolda: any; + isDone: string; +}; + +export const columns: ColumnDef[] = [ + { + accessorKey: "no", + header: "No", + cell: ({ row }) => ( +
+
+

+ {row.getValue("no")} +

+
+
+ ), + }, + { + accessorKey: "title", + header: "Judul", + cell: ({ row }) => ( +
+
+

+ {row.getValue("title")} +

+
+
+ ), + }, + { + accessorKey: "categoryName", + header: "Kategori", + cell: ({ row }) => ( + {row.getValue("categoryName")} + ), + }, + { + accessorKey: "createdAt", + header: "Tanggal Unggah", + cell: ({ row }) => { + const createdAt = row.getValue("createdAt") as + | string + | number + | undefined; + + const formattedDate = + createdAt && !isNaN(new Date(createdAt).getTime()) + ? format(new Date(createdAt), "dd-MM-yyyy HH:mm:ss") + : "-"; + return {formattedDate}; + }, + }, + { + accessorKey: "creatorGroup", + header: "Sumber ", + cell: ({ row }) => ( + {row.getValue("creatorGroup")} + ), + }, + { + accessorKey: "publishedOn", + header: "Penempatan File", + cell: ({ row }) => { + const isPublish = row.original.isPublish; + const isPublishOnPolda = row.original.isPublishOnPolda; + + let displayText = "-"; + if (isPublish && !isPublishOnPolda) { + displayText = "Mabes"; + } else if (isPublish && isPublishOnPolda) { + displayText = "Mabes & Polda"; + } else if (!isPublish && isPublishOnPolda) { + displayText = "Polda"; + } + + return ( +
+ {displayText} +
+ ); + }, + }, + + { + accessorKey: "isDone", + header: "Status", + cell: ({ row }) => { + const isDone = row.getValue("isDone"); + return ( +
+ +
+ ); + }, + }, + { + id: "actions", + accessorKey: "action", + header: "Actions", + enableHiding: false, + cell: ({ row }) => { + return ( + + + + + + + + + View + + + + + Delete + + + + ); + }, + }, +]; const TableVideo = () => { + const [videoTable, setVideoTable] = React.useState([]); const [sorting, setSorting] = React.useState([]); const [columnFilters, setColumnFilters] = React.useState( [] @@ -35,9 +205,29 @@ const TableVideo = () => { const [columnVisibility, setColumnVisibility] = React.useState({}); const [rowSelection, setRowSelection] = React.useState({}); + const [pagination, setPagination] = React.useState({ + pageIndex: 0, // Halaman pertama + pageSize: 10, // Jumlah baris per halaman + }); + const [page, setPage] = React.useState(1); // Halaman aktif + const [totalPage, setTotalPage] = React.useState(1); // Total halaman + const [limit, setLimit] = React.useState(6); // Jumlah baris per halaman + const [search, setSearch] = React.useState(title); + const userId = getCookiesDecrypt("uie"); + const userLevelId = getCookiesDecrypt("ulie"); + + const [categories, setCategories] = React.useState(); + const [categoryFilter, setCategoryFilter] = React.useState([]); + const [statusFilter, setStatusFilter] = React.useState([]); + const [startDateString, setStartDateString] = React.useState(""); + const [endDateString, setEndDateString] = React.useState(""); + const [filterByCreator, setFilterByCreator] = React.useState(""); + const [filterBySource, setFilterBySource] = React.useState(""); + + const roleId = getCookiesDecrypt("urie"); const table = useReactTable({ - data, + data: videoTable, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, @@ -55,6 +245,48 @@ const TableVideo = () => { }, }); + React.useEffect(() => { + initState(); + }, [page, limit]); + + async function initState() { + try { + const isForSelf = Number(roleId) == 4; + const res = await listDataVideo( + limit, + page, + isForSelf, + !isForSelf, + categoryFilter?.sort().join(","), + statusFilter?.sort().join(",").includes("1") + ? "1,2" + : statusFilter?.sort().join(","), + statusFilter?.sort().join(",").includes("1") ? userLevelId : "", + filterByCreator, + filterBySource, + startDateString, + endDateString + ); + const data = res.data.data.content.map((item: any, index: number) => ({ + no: (page - 1) * limit + index + 1, + title: item.title, + categoryName: item.categoryName, + creatorGroup: item.creatorGroup, + assignmentType: item.assignmentType?.name || "-", + createdAt: item.createdAt, + isDone: item.isDone, + publishedOn: item.publishedOn, + isPublish: item.isPublish, + isPublishOnPolda: item.isPublishOnPolda, + })); + + setVideoTable(data); + setTotalPage(res.data.totalPages); + } catch (error) { + console.error("Error fetching tasks:", error); + } + } + return (
@@ -72,22 +304,20 @@ const TableVideo = () => {
- +
{table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => { - return ( - - {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} - - ); - })} + + {headerGroup.headers.map((header) => ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ))} ))} @@ -97,6 +327,7 @@ const TableVideo = () => { {row.getVisibleCells().map((cell) => ( @@ -114,7 +345,41 @@ const TableVideo = () => { )}
- +
+ + {table.getPageOptions().map((page, pageIndex) => ( + + ))} + +
); }; diff --git a/app/[locale]/(protected)/content/audio/table-audio/index.tsx b/app/[locale]/(protected)/content/audio/table-audio/index.tsx index 38813a4d..760a8ab7 100644 --- a/app/[locale]/(protected)/content/audio/table-audio/index.tsx +++ b/app/[locale]/(protected)/content/audio/table-audio/index.tsx @@ -2,7 +2,9 @@ import * as React from "react"; import { + ColumnDef, ColumnFiltersState, + PaginationState, SortingState, VisibilityState, flexRender, @@ -12,7 +14,6 @@ import { getSortedRowModel, useReactTable, } from "@tanstack/react-table"; -import { columns } from "./columns"; import { Input } from "@/components/ui/input"; import { @@ -26,8 +27,181 @@ import { import { data } from "./data"; import TablePagination from "./table-pagination"; +import { Button } from "@/components/ui/button"; +import { format } from "date-fns"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + ChevronLeft, + ChevronRight, + Eye, + MoreVertical, + Trash2, +} from "lucide-react"; +import { title } from "process"; + +import { getCookiesDecrypt } from "@/lib/utils"; +import { + listDataAudio, + listDataImage, + listDataVideo, +} from "@/service/content/content"; + +export type CompanyData = { + no: number; + title: string; + categoryName: string; + createdAt: string; + creatorGroup: string; + publishedOn: string; + isPublish: any; + isPublishOnPolda: any; + isDone: string; +}; + +export const columns: ColumnDef[] = [ + { + accessorKey: "no", + header: "No", + cell: ({ row }) => ( +
+
+

+ {row.getValue("no")} +

+
+
+ ), + }, + { + accessorKey: "title", + header: "Judul", + cell: ({ row }) => ( +
+
+

+ {row.getValue("title")} +

+
+
+ ), + }, + { + accessorKey: "categoryName", + header: "Kategori", + cell: ({ row }) => ( + {row.getValue("categoryName")} + ), + }, + { + accessorKey: "createdAt", + header: "Tanggal Unggah", + cell: ({ row }) => { + const createdAt = row.getValue("createdAt") as + | string + | number + | undefined; + + const formattedDate = + createdAt && !isNaN(new Date(createdAt).getTime()) + ? format(new Date(createdAt), "dd-MM-yyyy HH:mm:ss") + : "-"; + return {formattedDate}; + }, + }, + { + accessorKey: "creatorGroup", + header: "Sumber ", + cell: ({ row }) => ( + {row.getValue("creatorGroup")} + ), + }, + { + accessorKey: "publishedOn", + header: "Penempatan File", + cell: ({ row }) => { + const isPublish = row.original.isPublish; + const isPublishOnPolda = row.original.isPublishOnPolda; + + let displayText = "-"; + if (isPublish && !isPublishOnPolda) { + displayText = "Mabes"; + } else if (isPublish && isPublishOnPolda) { + displayText = "Mabes & Polda"; + } else if (!isPublish && isPublishOnPolda) { + displayText = "Polda"; + } + + return ( +
+ {displayText} +
+ ); + }, + }, + + { + accessorKey: "isDone", + header: "Status", + cell: ({ row }) => { + const isDone = row.getValue("isDone"); + return ( +
+ +
+ ); + }, + }, + { + id: "actions", + accessorKey: "action", + header: "Actions", + enableHiding: false, + cell: ({ row }) => { + return ( + + + + + + + + + View + + + + + Delete + + + + ); + }, + }, +]; const TableAudio = () => { + const [videoTable, setVideoTable] = React.useState([]); const [sorting, setSorting] = React.useState([]); const [columnFilters, setColumnFilters] = React.useState( [] @@ -35,9 +209,29 @@ const TableAudio = () => { const [columnVisibility, setColumnVisibility] = React.useState({}); const [rowSelection, setRowSelection] = React.useState({}); + const [pagination, setPagination] = React.useState({ + pageIndex: 0, // Halaman pertama + pageSize: 10, // Jumlah baris per halaman + }); + const [page, setPage] = React.useState(1); // Halaman aktif + const [totalPage, setTotalPage] = React.useState(1); // Total halaman + const [limit, setLimit] = React.useState(6); // Jumlah baris per halaman + const [search, setSearch] = React.useState(title); + const userId = getCookiesDecrypt("uie"); + const userLevelId = getCookiesDecrypt("ulie"); + + const [categories, setCategories] = React.useState(); + const [categoryFilter, setCategoryFilter] = React.useState([]); + const [statusFilter, setStatusFilter] = React.useState([]); + const [startDateString, setStartDateString] = React.useState(""); + const [endDateString, setEndDateString] = React.useState(""); + const [filterByCreator, setFilterByCreator] = React.useState(""); + const [filterBySource, setFilterBySource] = React.useState(""); + + const roleId = getCookiesDecrypt("urie"); const table = useReactTable({ - data, + data: videoTable, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, @@ -55,6 +249,48 @@ const TableAudio = () => { }, }); + React.useEffect(() => { + initState(); + }, [page, limit]); + + async function initState() { + try { + const isForSelf = Number(roleId) == 4; + const res = await listDataAudio( + limit, + page, + isForSelf, + !isForSelf, + categoryFilter?.sort().join(","), + statusFilter?.sort().join(",").includes("1") + ? "1,2" + : statusFilter?.sort().join(","), + statusFilter?.sort().join(",").includes("1") ? userLevelId : "", + filterByCreator, + filterBySource, + startDateString, + endDateString + ); + const data = res.data.data.content.map((item: any, index: number) => ({ + no: (page - 1) * limit + index + 1, + title: item.title, + categoryName: item.categoryName, + creatorGroup: item.creatorGroup, + assignmentType: item.assignmentType?.name || "-", + createdAt: item.createdAt, + isDone: item.isDone, + publishedOn: item.publishedOn, + isPublish: item.isPublish, + isPublishOnPolda: item.isPublishOnPolda, + })); + + setVideoTable(data); + setTotalPage(res.data.totalPages); + } catch (error) { + console.error("Error fetching tasks:", error); + } + } + return (
@@ -72,22 +308,20 @@ const TableAudio = () => {
- +
{table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => { - return ( - - {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} - - ); - })} + + {headerGroup.headers.map((header) => ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ))} ))} @@ -97,6 +331,7 @@ const TableAudio = () => { {row.getVisibleCells().map((cell) => ( @@ -114,7 +349,41 @@ const TableAudio = () => { )}
- +
+ + {table.getPageOptions().map((page, pageIndex) => ( + + ))} + +
); }; diff --git a/app/[locale]/(protected)/content/image/table-image/index.tsx b/app/[locale]/(protected)/content/image/table-image/index.tsx index ef80c67a..9c6f6261 100644 --- a/app/[locale]/(protected)/content/image/table-image/index.tsx +++ b/app/[locale]/(protected)/content/image/table-image/index.tsx @@ -45,7 +45,8 @@ import { import { title } from "process"; import { getCookiesDecrypt } from "@/lib/utils"; -import { listDataImage } from "@/service/content/content-image"; +import { listDataImage } from "@/service/content/content"; +import page from "../page"; export type CompanyData = { no: number; @@ -197,7 +198,6 @@ export const columns: ColumnDef[] = [ ]; const TableImage = () => { - const [imageTable, setImageTable] = React.useState([]); const [sorting, setSorting] = React.useState([]); const [columnFilters, setColumnFilters] = React.useState( [] @@ -205,14 +205,14 @@ const TableImage = () => { const [columnVisibility, setColumnVisibility] = React.useState({}); const [rowSelection, setRowSelection] = React.useState({}); + const [imageTable, setImageTable] = React.useState([]); const [pagination, setPagination] = React.useState({ pageIndex: 0, // Halaman pertama pageSize: 10, // Jumlah baris per halaman }); - const [page, setPage] = React.useState(1); // Halaman aktif - const [totalPage, setTotalPage] = React.useState(1); // Total halaman - const [limit, setLimit] = React.useState(10); // Jumlah baris per halaman - const [search, setSearch] = React.useState(title); + const [totalPage, setTotalPage] = React.useState(1); + const [limit, setLimit] = React.useState(10); // Jumlah baris per halaman + const [search, setSearch] = React.useState(""); const userId = getCookiesDecrypt("uie"); const userLevelId = getCookiesDecrypt("ulie"); @@ -247,14 +247,14 @@ const TableImage = () => { React.useEffect(() => { initState(); - }, [page, limit]); + }, [limit]); async function initState() { try { - const isForSelf = Number(roleId) == 4; + const isForSelf = Number(roleId) === 4; const res = await listDataImage( - limit, - page, + pagination.pageSize, // Ambil nilai dari pagination.pageSize + pagination.pageIndex + 1, // API sering menggunakan page 1-based isForSelf, !isForSelf, categoryFilter?.sort().join(","), @@ -267,12 +267,24 @@ const TableImage = () => { startDateString, endDateString ); - const data = res.data.data.content.map((item: any, index: number) => ({ - no: (page - 1) * limit + index + 1, + + setupData(res.data?.data); + } catch (error) { + console.error("Error fetching tasks:", error); + } + } + + function setupData(rawData: { + content: any[]; + totalPages: number; + totalElements: number; + }) { + if (rawData?.content) { + const data: CompanyData[] = rawData.content.map((item, index) => ({ + no: pagination.pageIndex * pagination.pageSize + index + 1, title: item.title, categoryName: item.categoryName, creatorGroup: item.creatorGroup, - assignmentType: item.assignmentType?.name || "-", createdAt: item.createdAt, isDone: item.isDone, publishedOn: item.publishedOn, @@ -281,9 +293,8 @@ const TableImage = () => { })); setImageTable(data); - setTotalPage(res.data.totalPages); - } catch (error) { - console.error("Error fetching tasks:", error); + setTotalPage(rawData.totalPages); + console.log(data, "dataImage"); } } diff --git a/app/[locale]/(protected)/content/spit/table-spit/index.tsx b/app/[locale]/(protected)/content/spit/table-spit/index.tsx index d7d8ee97..f45b1930 100644 --- a/app/[locale]/(protected)/content/spit/table-spit/index.tsx +++ b/app/[locale]/(protected)/content/spit/table-spit/index.tsx @@ -2,7 +2,9 @@ import * as React from "react"; import { + ColumnDef, ColumnFiltersState, + PaginationState, SortingState, VisibilityState, flexRender, @@ -12,7 +14,6 @@ import { getSortedRowModel, useReactTable, } from "@tanstack/react-table"; -import { columns } from "./columns"; import { Input } from "@/components/ui/input"; import { @@ -26,8 +27,183 @@ import { import { data } from "./data"; import TablePagination from "./table-pagination"; +import { Button } from "@/components/ui/button"; +import { format } from "date-fns"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + ChevronLeft, + ChevronRight, + Eye, + MoreVertical, + Trash2, +} from "lucide-react"; +import { title } from "process"; + +import { getCookiesDecrypt } from "@/lib/utils"; +import { + listDataAudio, + listDataImage, + listDataVideo, + listSPIT, +} from "@/service/content/content"; +import { pages } from "next/dist/build/templates/app-page"; + +export type CompanyData = { + no: number; + title: string; + categoryName: string; + createdAt: string; + creatorGroup: string; + publishedOn: string; + isPublish: any; + isPublishOnPolda: any; + isDone: string; +}; + +export const columns: ColumnDef[] = [ + { + accessorKey: "no", + header: "No", + cell: ({ row }) => ( +
+
+

+ {row.getValue("no")} +

+
+
+ ), + }, + { + accessorKey: "title", + header: "Judul", + cell: ({ row }) => ( +
+
+

+ {row.getValue("title")} +

+
+
+ ), + }, + { + accessorKey: "categoryName", + header: "Kategori", + cell: ({ row }) => ( + {row.getValue("categoryName")} + ), + }, + { + accessorKey: "createdAt", + header: "Tanggal Unggah", + cell: ({ row }) => { + const createdAt = row.getValue("createdAt") as + | string + | number + | undefined; + + const formattedDate = + createdAt && !isNaN(new Date(createdAt).getTime()) + ? format(new Date(createdAt), "dd-MM-yyyy HH:mm:ss") + : "-"; + return {formattedDate}; + }, + }, + { + accessorKey: "creatorGroup", + header: "Sumber ", + cell: ({ row }) => ( + {row.getValue("creatorGroup")} + ), + }, + { + accessorKey: "publishedOn", + header: "Penempatan File", + cell: ({ row }) => { + const isPublish = row.original.isPublish; + const isPublishOnPolda = row.original.isPublishOnPolda; + + let displayText = "-"; + if (isPublish && !isPublishOnPolda) { + displayText = "Mabes"; + } else if (isPublish && isPublishOnPolda) { + displayText = "Mabes & Polda"; + } else if (!isPublish && isPublishOnPolda) { + displayText = "Polda"; + } + + return ( +
+ {displayText} +
+ ); + }, + }, + + { + accessorKey: "isDone", + header: "Status", + cell: ({ row }) => { + const isDone = row.getValue("isDone"); + return ( +
+ +
+ ); + }, + }, + { + id: "actions", + accessorKey: "action", + header: "Actions", + enableHiding: false, + cell: ({ row }) => { + return ( + + + + + + + + + View + + + + + Delete + + + + ); + }, + }, +]; const TableSPIT = () => { + const [spitTable, setSpitTable] = React.useState([]); const [sorting, setSorting] = React.useState([]); const [columnFilters, setColumnFilters] = React.useState( [] @@ -35,9 +211,29 @@ const TableSPIT = () => { const [columnVisibility, setColumnVisibility] = React.useState({}); const [rowSelection, setRowSelection] = React.useState({}); + const [pagination, setPagination] = React.useState({ + pageIndex: 0, // Halaman pertama + pageSize: 10, // Jumlah baris per halaman + }); + const [page, setPage] = React.useState(1); // Halaman aktif + const [totalPage, setTotalPage] = React.useState(1); // Total halaman + const [limit, setLimit] = React.useState(6); // Jumlah baris per halaman + const [search, setSearch] = React.useState(title); + const userId = getCookiesDecrypt("uie"); + const userLevelId = getCookiesDecrypt("ulie"); + + const [categories, setCategories] = React.useState(); + const [categoryFilter, setCategoryFilter] = React.useState([]); + const [statusFilter, setStatusFilter] = React.useState([1, 2]); + const [startDateString, setStartDateString] = React.useState(""); + const [endDateString, setEndDateString] = React.useState(""); + const [filterByCreator, setFilterByCreator] = React.useState(""); + const [filterBySource, setFilterBySource] = React.useState(""); + + const roleId = getCookiesDecrypt("urie"); const table = useReactTable({ - data, + data: spitTable, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, @@ -55,6 +251,47 @@ const TableSPIT = () => { }, }); + React.useEffect(() => { + initState(); + }, [page, limit]); + + async function initState() { + try { + const isForSelf = Number(roleId) == 4; + + let isPublish; + if (statusFilter.length > 1) { + isPublish = ""; + } else if (statusFilter.length === 1) { + if (statusFilter.includes(1)) { + isPublish = false; + } else { + isPublish = true; + } + } else { + isPublish = undefined; + } + const res = await listSPIT(pages, limit, search, isPublish); + const data = res.data.data.content.map((item: any, index: number) => ({ + no: (page - 1) * limit + index + 1, + title: item.title, + categoryName: item.categoryName, + creatorGroup: item.creatorGroup, + assignmentType: item.assignmentType?.name || "-", + createdAt: item.createdAt, + isDone: item.isDone, + publishedOn: item.publishedOn, + isPublish: item.isPublish, + isPublishOnPolda: item.isPublishOnPolda, + })); + + setSpitTable(data); + setTotalPage(res.data.totalPages); + } catch (error) { + console.error("Error fetching tasks:", error); + } + } + return (
@@ -72,22 +309,20 @@ const TableSPIT = () => {
- +
{table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => { - return ( - - {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} - - ); - })} + + {headerGroup.headers.map((header) => ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ))} ))} @@ -97,6 +332,7 @@ const TableSPIT = () => { {row.getVisibleCells().map((cell) => ( @@ -114,7 +350,41 @@ const TableSPIT = () => { )}
- +
+ + {table.getPageOptions().map((page, pageIndex) => ( + + ))} + +
); }; diff --git a/app/[locale]/(protected)/content/teks/table-teks/index.tsx b/app/[locale]/(protected)/content/teks/table-teks/index.tsx index a2b1e4cc..02823c01 100644 --- a/app/[locale]/(protected)/content/teks/table-teks/index.tsx +++ b/app/[locale]/(protected)/content/teks/table-teks/index.tsx @@ -2,7 +2,9 @@ import * as React from "react"; import { + ColumnDef, ColumnFiltersState, + PaginationState, SortingState, VisibilityState, flexRender, @@ -12,7 +14,6 @@ import { getSortedRowModel, useReactTable, } from "@tanstack/react-table"; -import { columns } from "./columns"; import { Input } from "@/components/ui/input"; import { @@ -26,6 +27,175 @@ import { import { data } from "./data"; import TablePagination from "./table-pagination"; +import { Button } from "@/components/ui/button"; +import { format } from "date-fns"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + ChevronLeft, + ChevronRight, + Eye, + MoreVertical, + Trash2, +} from "lucide-react"; +import { title } from "process"; + +import { getCookiesDecrypt } from "@/lib/utils"; +import { listDataImage, listDataTeks } from "@/service/content/content"; +import page from "../page"; + +export type CompanyData = { + no: number; + title: string; + categoryName: string; + createdAt: string; + creatorGroup: string; + publishedOn: string; + isPublish: any; + isPublishOnPolda: any; + isDone: string; +}; + +export const columns: ColumnDef[] = [ + { + accessorKey: "no", + header: "No", + cell: ({ row }) => ( +
+
+

+ {row.getValue("no")} +

+
+
+ ), + }, + { + accessorKey: "title", + header: "Judul", + cell: ({ row }) => ( +
+
+

+ {row.getValue("title")} +

+
+
+ ), + }, + { + accessorKey: "categoryName", + header: "Kategori", + cell: ({ row }) => ( + {row.getValue("categoryName")} + ), + }, + { + accessorKey: "createdAt", + header: "Tanggal Unggah", + cell: ({ row }) => { + const createdAt = row.getValue("createdAt") as + | string + | number + | undefined; + + const formattedDate = + createdAt && !isNaN(new Date(createdAt).getTime()) + ? format(new Date(createdAt), "dd-MM-yyyy HH:mm:ss") + : "-"; + return {formattedDate}; + }, + }, + { + accessorKey: "creatorGroup", + header: "Sumber ", + cell: ({ row }) => ( + {row.getValue("creatorGroup")} + ), + }, + { + accessorKey: "publishedOn", + header: "Penempatan File", + cell: ({ row }) => { + const isPublish = row.original.isPublish; + const isPublishOnPolda = row.original.isPublishOnPolda; + + let displayText = "-"; + if (isPublish && !isPublishOnPolda) { + displayText = "Mabes"; + } else if (isPublish && isPublishOnPolda) { + displayText = "Mabes & Polda"; + } else if (!isPublish && isPublishOnPolda) { + displayText = "Polda"; + } + + return ( +
+ {displayText} +
+ ); + }, + }, + + { + accessorKey: "isDone", + header: "Status", + cell: ({ row }) => { + const isDone = row.getValue("isDone"); + return ( +
+ +
+ ); + }, + }, + { + id: "actions", + accessorKey: "action", + header: "Actions", + enableHiding: false, + cell: ({ row }) => { + return ( + + + + + + + + + View + + + + + Delete + + + + ); + }, + }, +]; const TableTeks = () => { const [sorting, setSorting] = React.useState([]); @@ -35,9 +205,29 @@ const TableTeks = () => { const [columnVisibility, setColumnVisibility] = React.useState({}); const [rowSelection, setRowSelection] = React.useState({}); + const [imageTable, setImageTable] = React.useState([]); + const [pagination, setPagination] = React.useState({ + pageIndex: 0, // Halaman pertama + pageSize: 10, // Jumlah baris per halaman + }); + const [totalPage, setTotalPage] = React.useState(1); + const [limit, setLimit] = React.useState(10); // Jumlah baris per halaman + const [search, setSearch] = React.useState(""); + const userId = getCookiesDecrypt("uie"); + const userLevelId = getCookiesDecrypt("ulie"); + + const [categories, setCategories] = React.useState(); + const [categoryFilter, setCategoryFilter] = React.useState([]); + const [statusFilter, setStatusFilter] = React.useState([]); + const [startDateString, setStartDateString] = React.useState(""); + const [endDateString, setEndDateString] = React.useState(""); + const [filterByCreator, setFilterByCreator] = React.useState(""); + const [filterBySource, setFilterBySource] = React.useState(""); + + const roleId = getCookiesDecrypt("urie"); const table = useReactTable({ - data, + data: imageTable, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, @@ -55,6 +245,59 @@ const TableTeks = () => { }, }); + React.useEffect(() => { + initState(); + }, [limit]); + + async function initState() { + try { + const isForSelf = Number(roleId) === 4; + const res = await listDataTeks( + pagination.pageSize, // Ambil nilai dari pagination.pageSize + pagination.pageIndex + 1, // API sering menggunakan page 1-based + isForSelf, + !isForSelf, + categoryFilter?.sort().join(","), + statusFilter?.sort().join(",").includes("1") + ? "1,2" + : statusFilter?.sort().join(","), + statusFilter?.sort().join(",").includes("1") ? userLevelId : "", + filterByCreator, + filterBySource, + startDateString, + endDateString + ); + + setupData(res.data?.data); + } catch (error) { + console.error("Error fetching tasks:", error); + } + } + + function setupData(rawData: { + content: any[]; + totalPages: number; + totalElements: number; + }) { + if (rawData?.content) { + const data: CompanyData[] = rawData.content.map((item, index) => ({ + no: pagination.pageIndex * pagination.pageSize + index + 1, + title: item.title, + categoryName: item.categoryName, + creatorGroup: item.creatorGroup, + createdAt: item.createdAt, + isDone: item.isDone, + publishedOn: item.publishedOn, + isPublish: item.isPublish, + isPublishOnPolda: item.isPublishOnPolda, + })); + + setImageTable(data); + setTotalPage(rawData.totalPages); + console.log(data, "dataImage"); + } + } + return (
@@ -72,22 +315,20 @@ const TableTeks = () => {
- +
{table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => { - return ( - - {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} - - ); - })} + + {headerGroup.headers.map((header) => ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ))} ))} @@ -97,6 +338,7 @@ const TableTeks = () => { {row.getVisibleCells().map((cell) => ( @@ -114,7 +356,41 @@ const TableTeks = () => { )}
- +
+ + {table.getPageOptions().map((page, pageIndex) => ( + + ))} + +
); }; diff --git a/app/[locale]/(protected)/task/page.tsx b/app/[locale]/(protected)/task/page.tsx index 7b62e7dd..5be51476 100644 --- a/app/[locale]/(protected)/task/page.tsx +++ b/app/[locale]/(protected)/task/page.tsx @@ -1,11 +1,23 @@ +"use client"; import { Card, CardContent } from "@/components/ui/card"; import TaskTable from "./table-task/task-table"; import { Button } from "@/components/ui/button"; import { UploadIcon } from "lucide-react"; import SiteBreadcrumb from "@/components/site-breadcrumb"; import { Link } from "@/components/navigation"; +import { checkAuthorization, checkLoginSession } from "@/lib/utils"; +import React, { useEffect } from "react"; + +const TaskPage = () => { + useEffect(() => { + function initState() { + checkAuthorization("admin"); // Specify the page, e.g., "admin" or another value + checkLoginSession(); + } + + initState(); + }, []); -const TaskPage = async () => { return (
diff --git a/app/[locale]/(protected)/task/table-task/task-table.tsx b/app/[locale]/(protected)/task/table-task/task-table.tsx index 030651cc..d4593b2a 100644 --- a/app/[locale]/(protected)/task/table-task/task-table.tsx +++ b/app/[locale]/(protected)/task/table-task/task-table.tsx @@ -51,6 +51,13 @@ import { title } from "process"; import search from "../../app/chat/components/search"; import { format } from "date-fns"; import { listTask } from "@/service/task"; +import { getCookiesDecrypt } from "@/lib/utils"; +import { + Select, + SelectContent, + SelectGroup, + SelectItem, +} from "@/components/ui/select"; export type CompanyData = { no: number; @@ -202,9 +209,13 @@ const TaskTable = () => { }); const [page, setPage] = React.useState(1); const [totalPage, setTotalPage] = React.useState(1); - const [limit, setLimit] = React.useState(100); + const [limit, setLimit] = React.useState(10); const [search, setSearch] = React.useState(title); + const userId = getCookiesDecrypt("uie"); + const userLevelNumber = getCookiesDecrypt("ulne"); + const userRoleId = getCookiesDecrypt("urie"); + const table = useReactTable({ data: taskTable, columns, @@ -261,6 +272,18 @@ const TaskTable = () => { />
+
+ {/* */} +
{ @@ -8,10 +13,15 @@ const SearchSection = () => {
{/* Heading */}

- Eksplorasi dan Download Liputan Resmi Kami + Eksplorasiii{" "} + dan Download{" "} + Liputan Resmi Kami

-

Liputan resmi yang bersumber dari kegiatan Polri di Mabes dan Polda seluruh Indonesia

+

+ Liputan resmi yang bersumber dari kegiatan Polri di Mabes dan Polda + seluruh Indonesia +

{/* Search Form */}
@@ -20,19 +30,39 @@ const SearchSection = () => { - + Konten - - + + - + @@ -64,18 +94,29 @@ const SearchSection = () => { {/* Search Input */}
- + - +
{/* Button */} - +
diff --git a/components/partials/auth/login-form.tsx b/components/partials/auth/login-form.tsx index 5e8f39aa..37ff1abc 100644 --- a/components/partials/auth/login-form.tsx +++ b/components/partials/auth/login-form.tsx @@ -4,65 +4,184 @@ import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; -import { Link } from "@/i18n/routing"; +import Cookies from "js-cookie"; import { Icon } from "@/components/ui/icon"; import { useForm, SubmitHandler } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; -import { cn } from "@/lib/utils"; +import { cn, setCookiesEncrypt } from "@/lib/utils"; import { Loader2 } from "lucide-react"; -import { loginUser } from "@/action/auth-action"; +import { getProfile, setLogin } from "@/service/auth"; import { toast } from "sonner"; -import { useRouter } from "@/components/navigation"; +import { Link, useRouter } from "@/components/navigation"; +import { warning } from "@/lib/swal"; +// Schema validasi menggunakan zod const schema = z.object({ - email: z.string().email({ message: "Your email is invalid." }), - password: z.string().min(4), + username: z.string().min(1, { message: "Judul diperlukan" }), + password: z + .string() + .min(4, { message: "Password must be at least 4 characters." }), }); + +// Tipe untuk form values +type LoginFormValues = { + username: string; + password: string; +}; + const LoginForm = () => { const [isPending, startTransition] = React.useTransition(); const router = useRouter(); const [passwordType, setPasswordType] = React.useState("password"); const togglePasswordType = () => { - if (passwordType === "text") { - setPasswordType("password"); - } else if (passwordType === "password") { - setPasswordType("text"); - } + setPasswordType((prevType) => + prevType === "password" ? "text" : "password" + ); }; + const { register, handleSubmit, - reset, formState: { errors }, - } = useForm({ + } = useForm({ resolver: zodResolver(schema), mode: "all", - defaultValues: { - email: "dashcode@codeshaper.net", - password: "password", - }, }); - const [isVisible, setIsVisible] = React.useState(false); - const toggleVisibility = () => setIsVisible(!isVisible); - - const onSubmit = (data: z.infer) => { + // Fungsi submit form + const onSubmit: SubmitHandler = async (data) => { startTransition(async () => { try { - const response = await loginUser(data); + const response = await setLogin({ + ...data, + grant_type: "password", + client_id: "mediahub-app", + }); - if (!!response.error) { - toast("Event has been created", { - description: "Sunday, December 03, 2023 at 9:00 AM", - }); + if (response.error) { + toast.error("Username / Password Tidak Sesuai"); } else { - router.push("/dashboard"); - toast.success("Successfully logged in"); + const { access_token } = response.data; + const { refresh_token } = response.data; + const dateTime = new Date(); + const newTime = dateTime.getTime() + 10 * 60 * 1000; + + Cookies.set("access_token", access_token, { + expires: 1, + }); + Cookies.set("refresh_token", refresh_token, { + expires: 1, + }); + Cookies.set("time_refresh", new Date(newTime).toISOString(), { + expires: 1, + }); + + Cookies.set("is_first_login", String(true), { + secure: true, + sameSite: "strict", + }); + const profile = await getProfile(access_token); + console.log("PROFILE : ", profile?.data?.data); + + if ( + profile?.data?.data?.isInternational == true || + profile?.data?.data?.isActive == false || + profile?.data?.data?.isDelete == true + ) { + Object.keys(Cookies.get()).forEach((cookieName) => { + Cookies.remove(cookieName); + }); + warning( + "Akun Anda tidak dapat digunakan untuk masuk ke MediaHub Polri", + "/auth/login" + ); + } else { + Cookies.set("home_path", profile.data?.data?.homePath, { + expires: 1, + }); + Cookies.set( + "profile_picture", + profile.data?.data?.profilePictureUrl, + { + expires: 1, + } + ); + Cookies.set("state", profile.data?.data?.userLevel?.name, { + expires: 1, + }); + setCookiesEncrypt("uie", profile.data.data?.id, { + expires: 1, + }); + setCookiesEncrypt("urie", profile.data.data?.roleId, { + expires: 1, + }); + setCookiesEncrypt("urne", profile.data.data?.role?.name, { + expires: 1, + }); + setCookiesEncrypt("ulie", profile.data.data?.userLevel?.id, { + expires: 1, + }); + setCookiesEncrypt( + "ulplie", + profile.data.data?.userLevel?.parentLevelId, + { + expires: 1, + } + ); + setCookiesEncrypt( + "ulne", + profile.data.data?.userLevel?.levelNumber, + { + expires: 1, + } + ); + setCookiesEncrypt("ufne", profile.data.data?.fullname, { + expires: 1, + }); + setCookiesEncrypt("ulnae", profile.data.data?.userLevel?.name, { + expires: 1, + }); + setCookiesEncrypt("uinse", profile.data.data?.instituteId, { + expires: 1, + }); + + if ( + Number(profile.data.data?.roleId) == 2 || + Number(profile.data.data?.roleId) == 3 || + Number(profile.data.data?.roleId) == 4 || + Number(profile.data.data?.roleId) == 9 || + Number(profile.data.data?.roleId) == 10 || + Number(profile.data.data?.roleId) == 11 || + Number(profile.data.data?.roleId) == 12 + ) { + if ( + profile.data.data?.userLevel?.id == 761 || + profile.data.data?.userLevel?.parentLevelId == 761 + ) { + window.location.href = "/admin/welcome"; + // router.push('/admin/dashboard'); + Cookies.set("status", "login", { + expires: 1, + }); + } else { + window.location.href = "/en/dashboard"; + // router.push('/admin/dashboard'); + Cookies.set("status", "login", { + expires: 1, + }); + } + } else { + window.location.href = "/"; + Cookies.set("status", "login", { + expires: 1, + }); + } + } } } catch (err: any) { - toast.error(err.message); + toast.error(err.message || "An unexpected error occurred."); } }); }; @@ -70,41 +189,39 @@ const LoginForm = () => { return (
-
- {errors.email && ( -
- {errors.email.message} -
- )}
-
{ )}
+ {errors.password?.message && ( +
+ {errors.password.message} +
+ )}
- {errors.password && ( -
- {errors.password.message} -
- )}
@@ -145,4 +262,5 @@ const LoginForm = () => { ); }; + export default LoginForm; diff --git a/config/api.ts b/config/api.ts index 1e2317f1..318ee032 100644 --- a/config/api.ts +++ b/config/api.ts @@ -123,7 +123,6 @@ export async function getAPIInterceptor(url: any) { data: null, }; } - // Fungsi postAPIInterceptor export async function postAPIInterceptor(url: string, data: any) { const response = await axiosInterceptor diff --git a/lib/swal.ts b/lib/swal.ts new file mode 100644 index 00000000..965be403 --- /dev/null +++ b/lib/swal.ts @@ -0,0 +1,92 @@ +import Swal from "sweetalert2"; +import withReactContent from "sweetalert2-react-content"; + +const MySwal = withReactContent(Swal); + +const Toast = MySwal.mixin({ + toast: true, + position: "top-end", + showConfirmButton: false, + timer: 3000, + timerProgressBar: true, + didOpen: (toast) => { + toast.addEventListener("mouseenter", Swal.stopTimer); + toast.addEventListener("mouseleave", Swal.resumeTimer); + }, +}); + +export function loading(msg?: any) { + let timerInterval: any; + MySwal.fire({ + title: msg || "Loading...", + allowOutsideClick: false, + timerProgressBar: true, + didOpen: () => { + MySwal.showLoading(); + timerInterval = setInterval(() => {}, 100); + }, + willClose: () => { + clearInterval(timerInterval); + }, + }); +} + +export function error(msg?: any) { + MySwal.fire({ + icon: "error", + title: "Failed...", + text: msg || "Unknown Error", + }); +} + +export function successRouter(redirect: string, router?: any) { + MySwal.fire({ + title: "Success!", + icon: "success", + confirmButtonColor: "#3085d6", + confirmButtonText: "Ok", + allowOutsideClick: false, + }).then((result) => { + if (result.isConfirmed) { + router.push(redirect); + } + }); +} + +export function success(title: string) { + MySwal.fire({ + title: title || "Success!", + icon: "success", + confirmButtonColor: "#3085d6", + confirmButtonText: "OK", + }).then((result) => { + if (result.isConfirmed) { + return true; + } + }); +} + +export function close() { + MySwal.close(); +} + +export function warning(text: string, redirect: string, router?: any) { + MySwal.fire({ + title: text, + icon: "warning", + confirmButtonColor: "#3085d6", + confirmButtonText: "OK", + }).then((result) => { + if (result.isConfirmed) { + router.push(redirect); + } + }); +} + +export function successToast(title: string, text: string) { + Toast.fire({ + icon: "error", + title: title, + text: text, + }); +} diff --git a/lib/utils.ts b/lib/utils.ts index ab1b1953..23fd63c4 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -36,6 +36,47 @@ export const hexToRGB = (hex: any, alpha?: number): any => { } }; +export function getCookiesDecrypt(param: any) { + const cookiesEncrypt = Cookies.get(param); + try { + if (cookiesEncrypt != undefined) { + const output = CryptoJS.AES.decrypt( + cookiesEncrypt.toString(), + `${param}_EncryptKey@mediahub` + ).toString(CryptoJS.enc.Utf8); + if (output.startsWith('"')) { + return output.slice(1, -1); + } + return output; + } + } catch (e) { + console.log("Error", cookiesEncrypt); + } +} + +export function successToast(title: string, text: string) { + Toast.fire({ + icon: "error", + title: title, + text: text, + }); +} + +export function setCookiesEncrypt( + param: string, + data: any, + options?: Cookies.CookieAttributes +) { + // Enkripsi data + const cookiesEncrypt = CryptoJS.AES.encrypt( + JSON.stringify(data), + `${param}_EncryptKey@mediahub` + ).toString(); // Tambahkan .toString() di sini + + // Simpan data terenkripsi di cookie + Cookies.set(param, cookiesEncrypt, options); +} + export function checkAuthorization(page: any) { const roleId = getCookiesDecrypt("urie"); const levelNumber = getCookiesDecrypt("ulne"); @@ -64,44 +105,3 @@ export function checkLoginSession() { }; // doCheckSession(data); } - -export function getCookiesDecrypt(param: any) { - const cookiesEncrypt = Cookies.get(param); - try { - if (cookiesEncrypt != undefined) { - const output = CryptoJS.AES.decrypt( - cookiesEncrypt.toString(), - `${param}_EncryptKey@mediahub` - ).toString(CryptoJS.enc.Utf8); - if (output.startsWith('"')) { - return output.slice(1, -1); - } - return output; - } - } catch (e) { - console.log("Error", cookiesEncrypt); - } -} - -export function successToast(title: string, text: string) { - Toast.fire({ - icon: "error", - title: title, - text: text, - }); -} - -export function setCookiesEncrypt(param: any, data: any) { - // Enkripsi data - const cookiesEncrypt = CryptoJS.AES.encrypt( - JSON.stringify(data), - `${param}_EncryptKey@mediahub` - ).toString(); // Tambahkan .toString() di sini - - // Simpan data terenkripsi di cookie - Cookies.set(param, cookiesEncrypt, { expires: 1 }); -} - -export function error(msg: any) { - MySwal.fire("Gagal", msg, "error"); -} diff --git a/service/auth.ts b/service/auth.ts index 952742d9..aec9b966 100644 --- a/service/auth.ts +++ b/service/auth.ts @@ -3,92 +3,30 @@ import Cookies from "js-cookie"; import { getAPI, postAPI, postAPIWithJson } from "../config/api"; import { getAPIDummy } from "./http-config/axiosCustom"; -export async function setLogin(data) { - const url = "signin"; - return postAPI({ url, data }); +import { + httpGetInterceptorWithToken, + httpPostInterceptor, +} from "./http-config/http-interceptor-service"; + +export async function setLogin(data: any) { + const pathUrl = "signin"; + return postAPI(pathUrl, data); } -export async function getProfile(token) { +export async function getProfile(token: any) { const url = "users/info"; - return getAPI({ url, token }); + return getAPI(url, token); } -export async function saveSession(data) { - const url = "users/save-session"; - return postAPIWithJson({ url, data }); -} +// export async function setLogin(data: any) { +// const pathUrl = `signin`; +// const headers = { +// "content-type": "application/json", +// }; +// return await httpPost(pathUrl, headers, data); +// } -export async function checkSession(data) { - const url = "users/check-session"; - return postAPIWithJson({ url, data }); -} - -export async function listProvince() { - const url = "public/users/provinces"; - return getAPI({ url }); -} - -export async function listCity(id) { - const url = `public/users/cities?provId=${id}`; - return getAPI({ url }); -} - -export async function listDistricts(id) { - const url = `public/users/districts?cityId=${id}`; - return getAPI({ url }); -} - -export async function listInstitusi(roleId) { - const url = `public/users/institutes?categoryRoleId=${roleId}`; - return getAPI({ url }); -} - -export async function listRole() { - const url = "public/users/roles"; - return getAPI({ url }); -} - -export async function refreshToken() { - const url = "signin"; - const data = { - grant_type: "refresh_token", - client_id: "mediahub-app", - refresh_token: Cookies.get("refresh_token"), - }; - return postAPI({ url, data }); -} - -export async function postRegistration(data) { - const url = "public/users/save"; - return postAPIWithJson({ url, data }); -} - -export async function saveInstitutes(data) { - const url = "public/users/save-institutes"; - return postAPIWithJson({ url, data }); -} - -export async function forgotPassword(username) { - const url = `forgot-password?username=${username}`; - return postAPIWithJson({ url }); -} - -export async function getDataByNIK(reqid, nik) { - const url = `http://spitpolri.com/api/back_end/get_ktp?reqid=${reqid}&nik=${nik}`; - return getAPIDummy({ url }); -} - -export async function getDataByNRP(reqid, nrp) { - const url = `http://spitpolri.com/api/back_end/get_nrp?reqid=${reqid}&nrp=${nrp}`; - return getAPIDummy({ url }); -} - -export async function getDataJournalist(cert) { - const url = `public/users/search-journalist?cert=${cert}`; - return getAPI({ url }); -} - -export async function getDataPersonil(nrp) { - const url = `public/users/search-personil?nrp=${nrp}`; - return getAPI({ url }); +export async function userInfo(token: any) { + const pathUrl = `users/info`; + return await httpGetInterceptorWithToken(pathUrl, token); } diff --git a/service/content/content-image.ts b/service/content/content-image.ts deleted file mode 100644 index 93f1f6b6..00000000 --- a/service/content/content-image.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { httpGetInterceptor } from "../http-config/http-interceptor-service"; - -export async function listDataImage( - page: any, - limit: any, - isForSelf: any, - isApproval: any, - categoryFilter: any, - statusFilter: any, - needApprovalFromLevel: any, - creator: any, - source: any, - startDate: any, - endDate: any -) { - return await httpGetInterceptor( - `media/list?enablePage=1&sortBy=createdAt&sort=desc&size=${limit}&page=${page}&typeId=1&isForSelf=${isForSelf}&isApproval=${isApproval}&categoryId=${categoryFilter}&statusId=${statusFilter}&needApprovalFromLevel=${needApprovalFromLevel}&creatorUserLevelName=${source}&creatorName=${creator}&startDate=${startDate}&endDate=${endDate}` - ); -} diff --git a/service/content/content.ts b/service/content/content.ts new file mode 100644 index 00000000..c218a2cb --- /dev/null +++ b/service/content/content.ts @@ -0,0 +1,85 @@ +import { getAPIInterceptor } from "@/config/api"; +import { httpGetInterceptor } from "../http-config/http-interceptor-service"; + +export async function listDataImage( + page: any, + limit: any, + isForSelf: any, + isApproval: any, + categoryFilter: any, + statusFilter: any, + needApprovalFromLevel: any, + creator: any, + source: any, + startDate: any, + endDate: any +) { + return await httpGetInterceptor( + `media/list?enablePage=1&sortBy=createdAt&sort=desc&size=${limit}&page=${page}&typeId=1&isForSelf=${isForSelf}&isApproval=${isApproval}&categoryId=${categoryFilter}&statusId=${statusFilter}&needApprovalFromLevel=${needApprovalFromLevel}&creatorUserLevelName=${source}&creatorName=${creator}&startDate=${startDate}&endDate=${endDate}` + ); +} + +export async function listDataVideo( + page: any, + limit: any, + isForSelf: any, + isApproval: any, + categoryFilter: any, + statusFilter: any, + needApprovalFromLevel: any, + creator: any, + source: any, + startDate: any, + endDate: any +) { + return await httpGetInterceptor( + `media/list?enablePage=1&sortBy=createdAt&sort=desc&size=${limit}&page=${page}&typeId=2&isForSelf=${isForSelf}&isApproval=${isApproval}&categoryId=${categoryFilter}&statusId=${statusFilter}&needApprovalFromLevel=${needApprovalFromLevel}&creatorUserLevelName=${source}&creatorName=${creator}&startDate=${startDate}&endDate=${endDate}` + ); +} + +export async function listDataTeks( + page: any, + limit: any, + isForSelf: any, + isApproval: any, + categoryFilter: any, + statusFilter: any, + needApprovalFromLevel: any, + creator: any, + source: any, + startDate: any, + endDate: any +) { + return await httpGetInterceptor( + `media/list?enablePage=1&sortBy=createdAt&sort=desc&size=${limit}&page=${page}&typeId=3&isForSelf=${isForSelf}&isApproval=${isApproval}&categoryId=${categoryFilter}&statusId=${statusFilter}&needApprovalFromLevel=${needApprovalFromLevel}&creatorUserLevelName=${source}&creatorName=${creator}&startDate=${startDate}&endDate=${endDate}` + ); +} + +export async function listDataAudio( + page: any, + limit: any, + isForSelf: any, + isApproval: any, + categoryFilter: any, + statusFilter: any, + needApprovalFromLevel: any, + creator: any, + source: any, + startDate: any, + endDate: any +) { + return await httpGetInterceptor( + `media/list?enablePage=1&sortBy=createdAt&sort=desc&size=${limit}&page=${page}&typeId=4&isForSelf=${isForSelf}&isApproval=${isApproval}&categoryId=${categoryFilter}&statusId=${statusFilter}&needApprovalFromLevel=${needApprovalFromLevel}&creatorUserLevelName=${source}&creatorName=${creator}&startDate=${startDate}&endDate=${endDate}` + ); +} + +export async function listSPIT( + page: any, + limit: any, + title = "", + isPublish: any +) { + return await httpGetInterceptor( + `media/spit/pagination?enablePage=1&page=${page}&size=${limit}&sort=desc&sortBy=contentTitleId&title=${title}&isPublish=${isPublish}` + ); +} diff --git a/service/http-config/axios-interceptor-instance.ts b/service/http-config/axios-interceptor-instance.ts index 09b7b146..51fcb1e9 100644 --- a/service/http-config/axios-interceptor-instance.ts +++ b/service/http-config/axios-interceptor-instance.ts @@ -40,6 +40,8 @@ axiosInterceptorInstance.interceptors.response.use( originalRequest._retry = true; const data = { refreshToken: refreshToken, + grant_type: "refresh_token", + client_id: "mediahub-app", }; const res = await login(data); if (res.data?.data?.access_token) { diff --git a/service/http-config/http-base-service.ts b/service/http-config/http-base-service.ts index 3af62f08..d1f22381 100644 --- a/service/http-config/http-base-service.ts +++ b/service/http-config/http-base-service.ts @@ -1,70 +1,100 @@ +import axiosInstance from "@/config/axiosInstance"; import axiosBaseInstance from "./axios-base-instance"; +import axios from "axios"; +import Cookies from "js-cookie"; +import qs from "qs"; -export async function httpPost(pathUrl: any, headers: any, data?: any) { - const response = await axiosBaseInstance - .post(pathUrl, data, { headers }) - .catch(function (error: any) { - console.log(error); - return error.response; - }); - console.log("Response base svc : ", response); - if (response?.status == 200 || response?.status == 201) { - return { - error: false, - message: "success", - data: response?.data, - }; - } else { - return { - error: true, - message: response?.data?.message || response?.data || null, - data: null, - }; - } +// export async function httpPost(pathUrl: any, headers: any, data?: any) { +// const response = await axiosBaseInstance +// .post(pathUrl, data, { headers }) +// .catch(function (error: any) { +// console.log(error); +// return error.response; +// }); +// console.log("Response base svc : ", response); +// if (response?.status == 200 || response?.status == 201) { +// return { +// error: false, +// message: "success", +// data: response?.data, +// }; +// } else { +// return { +// error: true, +// message: response?.data?.message || response?.data || null, +// data: null, +// }; +// } +// } + +const baseURL = "https://netidhub.com/api/"; +const tokenAuth = Cookies.get("access_token") + ? Cookies.get("access_token") + : null; + +export async function postAPI(url: any, data: any) { + const headers = { + Authorization: `Bearer ${tokenAuth}`, + }; + const response = await axiosInstance + .post(url, qs.stringify(data), { headers }) + .catch((error) => error.response); + if (response?.status > 300) { + return { + error: true, + message: response?.data.error_description, + data: null, + }; + } + return { + error: false, + message: "success", + data: response?.data, + }; } export async function httpGet(pathUrl: any, headers: any) { - const response = await axiosBaseInstance - .get(pathUrl, { headers }) - .catch(function (error: any) { - console.log(error); - return error.response; - }); - console.log("Response base svc : ", response); - if (response?.status == 200 || response?.status == 201) { - return { - error: false, - message: "success", - data: response?.data, - }; - } else { - return { - error: true, - message: response?.data?.message || response?.data || null, - data: null, - }; - } + const response = await axiosBaseInstance + .get(pathUrl, { headers }) + .catch(function (error: any) { + console.log(error); + return error.response; + }); + console.log("Response base svc : ", response); + if (response?.status == 200 || response?.status == 201) { + return { + error: false, + message: "success", + data: response?.data, + }; + } else { + return { + error: true, + message: response?.data?.message || response?.data || null, + data: null, + }; + } } export async function httpPut(pathUrl: any, headers: any, data?: any) { - const response = await axiosBaseInstance - .put(pathUrl, data, { headers }) - .catch(function (error: any) { - console.log(error); - return error.response; - }); - console.log("Response base svc : ", response); - if (response?.status == 200 || response?.status == 201) { - return { - error: false, - message: "success", - data: response?.data, - }; - } else { - return { - error: true, - message: response?.data?.message || response?.data || null, - data: null, - }; - } -} \ No newline at end of file + const response = await axiosBaseInstance + .put(pathUrl, data, { headers }) + .catch(function (error: any) { + console.log(error); + return error.response; + }); + console.log("Response base svc : ", response); + if (response?.status == 200 || response?.status == 201) { + return { + error: false, + message: "success", + data: response?.data, + }; + } else { + return { + error: true, + message: response?.data?.message || response?.data || null, + data: null, + }; + } +} diff --git a/service/task.ts b/service/task.ts index d02dbb88..369f407c 100644 --- a/service/task.ts +++ b/service/task.ts @@ -1,3 +1,4 @@ +import { title } from "process"; import { deleteAPIInterceptor, getAPIInterceptor, @@ -8,8 +9,15 @@ import { httpPostInterceptor, } from "./http-config/http-interceptor-service"; -export async function listTask(size: number, page: number) { - return await httpGetInterceptor(`assignment/list?size=${size}&page=${page}`); +// export async function listTask(size: number, page: number) { +// return await httpGetInterceptor( +// `assignment/list?enablePage=1&title=${title}&size=${limit}&page=${page}` +// ); +// } + +export async function listTask(page: any, limit: any) { + const url = `assignment/list?size=${limit}&page=${page}`; + return getAPIInterceptor(url); } export async function createTask(data: any) {