mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-06 22:26:27 +00:00
initial commit for new hats app
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
import axios from "axios";
|
||||
|
||||
export const BASE_URL = process.env.BASE_URL_API
|
||||
|
||||
export default axios.create({
|
||||
baseURL: BASE_URL,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
export const axiosAuth = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useEffect } from "react";
|
||||
import { useRefreshToken } from "./useRefreshToken";
|
||||
import { axiosAuth } from "../axios";
|
||||
|
||||
const useAxiosAuth = () => {
|
||||
const { data: session } = useSession();
|
||||
const refreshToken = useRefreshToken();
|
||||
|
||||
// SET COMMON DEFAULT HEADER
|
||||
axiosAuth.defaults.headers.common['Authorization'] = `Bearer ${session?.user?.access_token}`;
|
||||
|
||||
useEffect(() => {
|
||||
const requestIntercept = axiosAuth.interceptors.request.use(
|
||||
(config) => {
|
||||
if (!config.headers["Authorization"]) {
|
||||
config.headers["Authorization"] = `Bearer ${session?.user?.access_token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
const responseIntercept = axiosAuth.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const prevRequest = error?.config;
|
||||
if (error?.response?.status === 401 && !prevRequest?.sent) {
|
||||
prevRequest.sent = true;
|
||||
await refreshToken();
|
||||
|
||||
axiosAuth.defaults.headers.common['Authorization'] = `Bearer ${session?.user?.access_token}`;
|
||||
prevRequest.headers["Authorization"] = `Bearer ${session?.user.access_token}`;
|
||||
|
||||
return axiosAuth(prevRequest);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
axiosAuth.interceptors.request.eject(requestIntercept);
|
||||
axiosAuth.interceptors.response.eject(responseIntercept);
|
||||
};
|
||||
}, [session, refreshToken]);
|
||||
|
||||
|
||||
return axiosAuth;
|
||||
};
|
||||
|
||||
|
||||
|
||||
export default useAxiosAuth;
|
||||
@@ -0,0 +1,40 @@
|
||||
import useSWR from 'swr'
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import useAxiosAuth from './useAxiosAuth';
|
||||
|
||||
|
||||
export default function useFetch(endpoint: string) {
|
||||
const BASE_URL = process.env.BASE_URL_API
|
||||
const { data: session } = useSession()
|
||||
|
||||
const fetcher = (endpoint: string) => fetch(BASE_URL + endpoint, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${session?.user.access_token}`,
|
||||
}
|
||||
}).then(res => res.json())
|
||||
|
||||
const { data, error, isLoading, mutate } = useSWR<ResponseData<any>>(endpoint, fetcher)
|
||||
|
||||
return {
|
||||
data: data?.data,
|
||||
isLoading,
|
||||
error,
|
||||
mutate
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function useFetchWithAxios(url: string) {
|
||||
const axios = useAxiosAuth();
|
||||
const fetcher = () => axios.get(url).then(res => res.data)
|
||||
|
||||
const { data, error, isLoading, mutate } = useSWR<ResponseData<any>>(url, fetcher)
|
||||
|
||||
return {
|
||||
data,
|
||||
isLoading,
|
||||
error,
|
||||
mutate
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { signOut, useSession } from "next-auth/react";
|
||||
import axios from "../axios";
|
||||
import { EXP_SESSION } from "@/pages/api/auth/[...nextauth]";
|
||||
|
||||
export const useRefreshToken = () => {
|
||||
const { data: session, update } = useSession();
|
||||
|
||||
const refreshToken = async () => {
|
||||
try {
|
||||
const payload = {
|
||||
email: session?.user.detail.email
|
||||
}
|
||||
const res = await axios.post("/auth/refresh-token", payload, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Refresh-Token": session?.user.refresh_token,
|
||||
"Device-Code": '40001'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('REFRESH TOKEN FROM CLIENT')
|
||||
console.log(res)
|
||||
|
||||
if (session) {
|
||||
session.user.access_token = res.data.data.access_token;
|
||||
session.user.refresh_token = res.data.data.refresh_token;
|
||||
session.user.expired_at = Math.floor(Date.now() + EXP_SESSION * 1000) // UPDATE NEXTAUTH SESSION EXP
|
||||
await update(session.user)
|
||||
// await update((prev: any) => {...prev, foo: "new session value"})
|
||||
// await update((prev: any) => ({ ...prev, access_token: res.data.data.access_token, refresh_token: res.data.data.refresh_token }))
|
||||
}
|
||||
else signOut();
|
||||
|
||||
} catch (error) {
|
||||
signOut()
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return refreshToken;
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
export const createImage = (url: string) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const image = new Image()
|
||||
image.addEventListener('load', () => resolve(image))
|
||||
image.addEventListener('error', (error) => reject(error))
|
||||
image.setAttribute('crossOrigin', 'anonymous') // needed to avoid cross-origin issues on CodeSandbox
|
||||
image.src = url
|
||||
})
|
||||
|
||||
export function getRadianAngle(degreeValue: number) {
|
||||
return (degreeValue * Math.PI) / 180
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the new bounding area of a rotated rectangle.
|
||||
*/
|
||||
export function rotateSize(width: number, height: number, rotation: any) {
|
||||
const rotRad = getRadianAngle(rotation)
|
||||
|
||||
return {
|
||||
width:
|
||||
Math.abs(Math.cos(rotRad) * width) + Math.abs(Math.sin(rotRad) * height),
|
||||
height:
|
||||
Math.abs(Math.sin(rotRad) * width) + Math.abs(Math.cos(rotRad) * height),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function was adapted from the one in the ReadMe of https://github.com/DominicTobias/react-image-crop
|
||||
*/
|
||||
export async function getCroppedImg(
|
||||
imageSrc: any,
|
||||
pixelCrop: any,
|
||||
rotation = 0,
|
||||
flip = { horizontal: false, vertical: false }
|
||||
) {
|
||||
const image: any = await createImage(imageSrc)
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx: any = canvas.getContext('2d')
|
||||
|
||||
if (!ctx) {
|
||||
return null
|
||||
}
|
||||
|
||||
const rotRad = getRadianAngle(rotation)
|
||||
|
||||
// calculate bounding box of the rotated image
|
||||
const { width: bBoxWidth, height: bBoxHeight } = rotateSize(
|
||||
image.width,
|
||||
image.height,
|
||||
rotation
|
||||
)
|
||||
|
||||
// set canvas size to match the bounding box
|
||||
canvas.width = bBoxWidth
|
||||
canvas.height = bBoxHeight
|
||||
|
||||
// translate canvas context to a central location to allow rotating and flipping around the center
|
||||
ctx.translate(bBoxWidth / 2, bBoxHeight / 2)
|
||||
ctx.rotate(rotRad)
|
||||
ctx.scale(flip.horizontal ? -1 : 1, flip.vertical ? -1 : 1)
|
||||
ctx.translate(-image.width / 2, -image.height / 2)
|
||||
|
||||
// draw rotated image
|
||||
ctx.drawImage(image, 0, 0)
|
||||
|
||||
// croppedAreaPixels values are bounding box relative
|
||||
// extract the cropped image using these values
|
||||
const data = ctx.getImageData(
|
||||
pixelCrop.x,
|
||||
pixelCrop.y,
|
||||
pixelCrop.width,
|
||||
pixelCrop.height
|
||||
)
|
||||
|
||||
// set canvas width to final desired crop size - this will clear existing context
|
||||
canvas.width = pixelCrop.width
|
||||
canvas.height = pixelCrop.height
|
||||
|
||||
// paste generated rotate image at the top left corner
|
||||
ctx.putImageData(data, 0, 0)
|
||||
|
||||
// As Base64 string
|
||||
// return canvas.toDataURL('image/jpeg');
|
||||
|
||||
// As a blob
|
||||
// canvas.toBlob((blob: any) => {
|
||||
// let file = new File([blob], new Date().getTime() + ".jpg", { type: "image/jpeg" })
|
||||
// console.log(file)
|
||||
// }, 'image/jpeg');
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// canvas.toBlob((file) => { // as blob "blob:http://localhost:1010/d3e1215b-11e4-48ac-8c10-b0b910422488"
|
||||
// resolve(URL.createObjectURL(file))
|
||||
// }, 'image/jpeg')
|
||||
// resolve(canvas.toDataURL('image/jpeg', 1)) // as base64
|
||||
canvas.toBlob((blob: any) => {
|
||||
let file = new File([blob], new Date().getTime() + ".jpg", { type: "image/jpeg" })
|
||||
resolve({
|
||||
base64: canvas.toDataURL('image/jpeg', 1),
|
||||
file: file
|
||||
})
|
||||
}, 'image/jpeg');
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRotatedImage(imageSrc: any, rotation = 0) {
|
||||
const image: any = await createImage(imageSrc)
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx: any = canvas.getContext('2d')
|
||||
|
||||
const orientationChanged =
|
||||
rotation === 90 || rotation === -90 || rotation === 270 || rotation === -270
|
||||
if (orientationChanged) {
|
||||
canvas.width = image.height
|
||||
canvas.height = image.width
|
||||
} else {
|
||||
canvas.width = image.width
|
||||
canvas.height = image.height
|
||||
}
|
||||
|
||||
ctx.translate(canvas.width / 2, canvas.height / 2)
|
||||
ctx.rotate((rotation * Math.PI) / 180)
|
||||
ctx.drawImage(image, -image.width / 2, -image.height / 2)
|
||||
|
||||
return new Promise((resolve) => {
|
||||
canvas.toBlob((file: any) => {
|
||||
resolve(URL.createObjectURL(file))
|
||||
}, 'image/png')
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
const FOOTER_MENU = [
|
||||
{
|
||||
title: 'Home',
|
||||
path: '/',
|
||||
icon: 'ti ti-home-stats icon'
|
||||
},
|
||||
{
|
||||
title: 'History',
|
||||
path: '/history',
|
||||
icon: 'ti ti-history-toggle icon'
|
||||
},
|
||||
{
|
||||
title: 'Presence',
|
||||
path: '/presence-v2',
|
||||
icon: 'ti ti-face-id icon'
|
||||
},
|
||||
{
|
||||
title: 'Task',
|
||||
path: '/task',
|
||||
icon: 'ti ti-checklist icon'
|
||||
},
|
||||
{
|
||||
title: 'Profile',
|
||||
path: '/profile',
|
||||
icon: 'ti ti-user-circle icon'
|
||||
}
|
||||
]
|
||||
|
||||
export default FOOTER_MENU
|
||||
@@ -0,0 +1,169 @@
|
||||
import { LayoutDashboard, Settings, MonitorSmartphone, Database, ShieldAlert, FileText, Circle, ScanFace, MenuSquare, CalendarX2 } from 'lucide-react'
|
||||
|
||||
const SIDEBAR_MENU = [
|
||||
{
|
||||
title: "Dashboard",
|
||||
Icon: <LayoutDashboard size={18} />,
|
||||
path: ''
|
||||
},
|
||||
{
|
||||
title: "Administration",
|
||||
Icon: <ShieldAlert size={18} />,
|
||||
submenuId: 1,
|
||||
submenuItems: [
|
||||
{
|
||||
title: "Company",
|
||||
path: '/administration/company'
|
||||
},
|
||||
{
|
||||
title: "Area",
|
||||
path: '/administration/area'
|
||||
},
|
||||
{
|
||||
title: "Division",
|
||||
path: '/administration/division'
|
||||
},
|
||||
{
|
||||
title: "User",
|
||||
path: '/administration/user'
|
||||
},
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Device",
|
||||
Icon: <MonitorSmartphone size={18} />,
|
||||
submenuId: 2,
|
||||
submenuItems: [
|
||||
{
|
||||
title: "Device",
|
||||
path: '/device/device'
|
||||
},
|
||||
{
|
||||
title: "Device Type",
|
||||
path: '/device/device-type'
|
||||
},
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Global Parameter",
|
||||
Icon: <Settings size={18} />,
|
||||
path: '/global-parameter'
|
||||
},
|
||||
{
|
||||
title: "Menu",
|
||||
Icon: <MenuSquare size={18} />,
|
||||
path: '/menu'
|
||||
},
|
||||
{
|
||||
title: "Day Off",
|
||||
Icon: <CalendarX2 size={18} />,
|
||||
path: '/day-off'
|
||||
},
|
||||
{
|
||||
title: "Report",
|
||||
Icon: <Database size={18} />,
|
||||
submenuId: 3,
|
||||
submenuItems: [
|
||||
{
|
||||
title: "Attendance History",
|
||||
path: '/report/history'
|
||||
},
|
||||
{
|
||||
title: "Attendance Distribution",
|
||||
path: '/report/distribution'
|
||||
},
|
||||
{
|
||||
title: "Leave, Permit & Sick",
|
||||
path: '/report/leave-permit-sick'
|
||||
},
|
||||
{
|
||||
title: "Summary Report",
|
||||
path: '/report/monthly-presence'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Audit Trail",
|
||||
Icon: <FileText size={18} />,
|
||||
path: '/audit-trail'
|
||||
},
|
||||
{
|
||||
title: "Manual Attendance & Approval",
|
||||
submenuId: 4,
|
||||
Icon: <ScanFace size={18} />,
|
||||
submenuItems: [
|
||||
{
|
||||
title: "Manual Attendance",
|
||||
path: '/manual/manual-presence'
|
||||
},
|
||||
{
|
||||
title: "Approval Non WFO",
|
||||
path: '/manual/approval'
|
||||
},
|
||||
{
|
||||
title: "Approval Auto Checkout",
|
||||
path: '/manual/approval-autocheckout'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Information",
|
||||
Icon: <ShieldAlert size={18} />,
|
||||
submenuId: 5,
|
||||
submenuItems: [
|
||||
{
|
||||
title: "Master Status",
|
||||
path: '/information/master-status'
|
||||
},
|
||||
{
|
||||
title: "Working Status",
|
||||
path: '/information/working-status'
|
||||
},
|
||||
{
|
||||
title: "User Role",
|
||||
path: '/information/user-role'
|
||||
},
|
||||
{
|
||||
title: "Employee Position",
|
||||
path: '/information/position'
|
||||
},
|
||||
{
|
||||
title: "Employee Type",
|
||||
path: '/information/employee-type'
|
||||
},
|
||||
]
|
||||
},
|
||||
// {
|
||||
// title: "Test",
|
||||
// Icon: <Circle size={18} />,
|
||||
// submenuId: 3,
|
||||
// submenuItems: [
|
||||
// {
|
||||
// title: "Submenu 1",
|
||||
// path: '/submenu-1'
|
||||
// },
|
||||
// {
|
||||
// title: "Submenu 2",
|
||||
// path: '/submenu-2'
|
||||
// },
|
||||
// {
|
||||
// title: "Submenu 3",
|
||||
// submenu: true,
|
||||
// submenuId: 101,
|
||||
// submenuItems: [
|
||||
// {
|
||||
// title: "Test",
|
||||
// path: '/submenu'
|
||||
// },
|
||||
// {
|
||||
// title: "Sub Submenu 2",
|
||||
// path: '/sub-submenu-2'
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// },
|
||||
|
||||
]
|
||||
|
||||
export default SIDEBAR_MENU
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
export const LIST_TEAM_LEADER = [
|
||||
{ value: 9, label: 'Stevanus Akbar Alexander' },
|
||||
{ value: 16, label: 'Heri Saffarudin Ariyani' },
|
||||
{ value: 17, label: 'Septo Sunaryono' },
|
||||
{ value: 18, label: 'Fajar Rahmatullah' },
|
||||
{ value: 19, label: 'Luthfi Aditama' },
|
||||
{ value: 20, label: 'Mohamad Saeful Ihsan' },
|
||||
]
|
||||
|
||||
//// FOR DEV
|
||||
// export const LIST_TEAM_LEADER = [
|
||||
// { value: 4, label: 'Evan Arifial Hidayat' },
|
||||
// { value: 3, label: 'Luthfi Aditama' },
|
||||
// { value: 2, label: 'Ories C' },
|
||||
// { value: 1, label: 'SYSADMIN HIS' }
|
||||
// ]
|
||||
|
||||
export const LIST_ACTION_DATA = [
|
||||
{
|
||||
"id": 1,
|
||||
"code": "A01",
|
||||
"name": "CREATE",
|
||||
"description": "ADD NEW DATA",
|
||||
"status_id": 1
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"code": "A02",
|
||||
"name": "UPDATE",
|
||||
"description": "UPDATE EXISTING DATA",
|
||||
"status_id": 1
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"code": "A03",
|
||||
"name": "DELETE",
|
||||
"description": "DELETE EXISTING DATA",
|
||||
"status_id": 1
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"code": "A04",
|
||||
"name": "VIEW",
|
||||
"description": "VIEW DATA",
|
||||
"status_id": 1
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"code": "A05",
|
||||
"name": "EXPORT",
|
||||
"description": "EXPORT DATA",
|
||||
"status_id": 1
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"code": "A06",
|
||||
"name": "APPROVAL",
|
||||
"description": "APPROVAL DATA",
|
||||
"status_id": 1
|
||||
}
|
||||
]
|
||||
|
||||
export const DUMMY_MENU_LIST = [
|
||||
{
|
||||
"id": 1,
|
||||
"code": "M01",
|
||||
"name": "Dashboard",
|
||||
"menu_parent_id": null,
|
||||
"icon": "ti ti-layout-dashboard",
|
||||
"path_url": "/",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "dashboard"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"code": "M02",
|
||||
"name": "Administration",
|
||||
"menu_parent_id": null,
|
||||
"icon": "ti ti-layout-dashboard",
|
||||
"path_url": "#",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "menu parent administration"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"code": "M05",
|
||||
"name": "Device",
|
||||
"menu_parent_id": null,
|
||||
"icon": null,
|
||||
"path_url": "device",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "menu device"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"code": "M06",
|
||||
"name": "Global Parameter",
|
||||
"menu_parent_id": null,
|
||||
"icon": null,
|
||||
"path_url": "global-parameter",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "menu global parameter"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"code": "M07",
|
||||
"name": "Manual Presence & Approval",
|
||||
"menu_parent_id": null,
|
||||
"icon": null,
|
||||
"path_url": "manual-presence",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "menu manual presence & approval"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"code": "M08",
|
||||
"name": "Report",
|
||||
"menu_parent_id": null,
|
||||
"icon": null,
|
||||
"path_url": "#",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "menu parent report"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"code": "M09",
|
||||
"name": "Daily Presence Report",
|
||||
"menu_parent_id": 8,
|
||||
"icon": null,
|
||||
"path_url": "report/daily-presence",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu report"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"code": "M10",
|
||||
"name": "Monthly Presence Report",
|
||||
"menu_parent_id": 8,
|
||||
"icon": null,
|
||||
"path_url": "report/monthly-presence",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu report"
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"code": "M11",
|
||||
"name": "Annual Presence Report",
|
||||
"menu_parent_id": 8,
|
||||
"icon": null,
|
||||
"path_url": "report/annual-presence",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu report"
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"code": "M12",
|
||||
"name": "Audit Trail",
|
||||
"menu_parent_id": null,
|
||||
"icon": null,
|
||||
"path_url": "audit-trail",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "menu audit trail"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"code": "M03",
|
||||
"name": "User",
|
||||
"menu_parent_id": 2,
|
||||
"icon": null,
|
||||
"path_url": "administration/user",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu administration"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"code": "M04",
|
||||
"name": "Role",
|
||||
"menu_parent_id": 2,
|
||||
"icon": null,
|
||||
"path_url": "administration/role",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu administration"
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"code": "M14",
|
||||
"name": "Summary Report",
|
||||
"menu_parent_id": 11,
|
||||
"icon": null,
|
||||
"path_url": "report/annual-presence/summary",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu report/annual-presence",
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"code": "M15",
|
||||
"name": "Test Report",
|
||||
"menu_parent_id": 11,
|
||||
"icon": null,
|
||||
"path_url": "report/annual-presence/test",
|
||||
"hidden_data": false,
|
||||
"status": {
|
||||
"id": 1,
|
||||
"code": "A",
|
||||
"name": "active"
|
||||
},
|
||||
"description": "child menu report/annual-presence",
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,494 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { Workbook } from "exceljs";
|
||||
import { type IHistory } from '@/app/(dashboard)/history/components/type';
|
||||
import { type IUser } from '@/app/admin/administration/user/component/type';
|
||||
import { type IExcelJSColumnType } from '@/types/types';
|
||||
|
||||
export const toDataURL = (url: any) => fetch(url)
|
||||
.then(response => response.blob())
|
||||
.then(blob => new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => resolve(reader.result)
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(blob)
|
||||
}
|
||||
))
|
||||
|
||||
export const exportTable = async (user: IUser, srcDataTable: any[], columns: IExcelJSColumnType[], title: string) => {
|
||||
try {
|
||||
const workbook = new Workbook();
|
||||
const worksheet = workbook.addWorksheet("Sheet1", { pageSetup: { orientation: 'portrait' } });
|
||||
|
||||
const base64Img = await toDataURL('/assets/projects/nutech.png')
|
||||
const logo = workbook.addImage({
|
||||
base64: base64Img as string,
|
||||
extension: 'png',
|
||||
});
|
||||
worksheet.addImage(logo, {
|
||||
tl: { col: 1, row: 1 },
|
||||
ext: { width: 250, height: 75 }
|
||||
})
|
||||
|
||||
worksheet.mergeCells('B6:K6')
|
||||
const titleCell = worksheet.getCell('B6')
|
||||
titleCell.font = {
|
||||
size: 15,
|
||||
underline: true,
|
||||
bold: true
|
||||
}
|
||||
titleCell.alignment = {
|
||||
horizontal: 'center'
|
||||
}
|
||||
titleCell.value = title || 'Export Data'
|
||||
|
||||
|
||||
// Table Headers
|
||||
worksheet.getRow(8).values = columns.map(item => item.header);
|
||||
worksheet.getRow(8).font = { bold: true }
|
||||
worksheet.getRow(8).eachCell({ includeEmpty: false }, (cell: any) => {
|
||||
cell.border = border
|
||||
})
|
||||
worksheet.columns = columns.map(item => {
|
||||
return {
|
||||
key: item.key,
|
||||
width: item.width || 20,
|
||||
style: item.style || { numFmt: 'General' }
|
||||
}
|
||||
})
|
||||
|
||||
// Set table value
|
||||
srcDataTable.forEach((item, index: number) => {
|
||||
|
||||
const obj = columns.map(column => {
|
||||
if (column.key === 'number') {
|
||||
return {
|
||||
[column.key]: index + 1
|
||||
}
|
||||
} else if (column.value) {
|
||||
let columnValue;
|
||||
|
||||
if (column.value) {
|
||||
const nestedValue = column.value?.split('.');
|
||||
if (nestedValue.length === 1) {
|
||||
columnValue = item[column.value];
|
||||
} else {
|
||||
let currentItem = item;
|
||||
for (const part of nestedValue) {
|
||||
currentItem = currentItem[part];
|
||||
if (!currentItem) break;
|
||||
}
|
||||
columnValue = currentItem;
|
||||
}
|
||||
}
|
||||
|
||||
if (column.style?.numFmt === 'dd/mm/yyyy') {
|
||||
return {
|
||||
[column.key]: columnValue ? new Date(columnValue).toLocaleDateString("id-ID", { timeZone: "Asia/Jakarta" }) : ' '
|
||||
};
|
||||
} else if (column.style?.numFmt === '[$-13809]hh:mm:ss;@') {
|
||||
return {
|
||||
[column.key]: columnValue ? dayjs(columnValue).format('HH:mm A') : ' '
|
||||
};
|
||||
} else if (column.hyperlink) {
|
||||
return {
|
||||
[column.key]: columnValue ? { text: 'View Photo', hyperlink: process.env.BASE_URL_IMG + columnValue, font: { color: { argb: '0000FF' } } } : ' '
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
[column.key]: columnValue || ' '
|
||||
};
|
||||
}
|
||||
} else {
|
||||
const value = item[column.key]
|
||||
if (column.style?.numFmt === 'dd/mm/yyyy') {
|
||||
return {
|
||||
[column.key]: value ? new Date(value).toLocaleDateString("id-ID", { timeZone: "Asia/Jakarta" }) : ' '
|
||||
};
|
||||
} else if (column.style?.numFmt === '[$-13809]hh:mm:ss;@') {
|
||||
return {
|
||||
[column.key]: value ? dayjs(value).format('HH:mm A') : ' '
|
||||
};
|
||||
} else if (column.hyperlink) {
|
||||
return {
|
||||
[column.key]: value ? { text: 'View Photo', hyperlink: process.env.BASE_URL_IMG + value, font: { color: { argb: '0000FF' } } } : ' '
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
[column.key]: value || ' '
|
||||
};
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const convertedJson: any = {};
|
||||
|
||||
obj.forEach((item: any) => {
|
||||
const key = Object.keys(item)[0]
|
||||
const value = item[key]
|
||||
convertedJson[key] = value
|
||||
});
|
||||
|
||||
const result = [convertedJson]
|
||||
|
||||
const row = worksheet.addRow(result[0])
|
||||
// console.log(row)
|
||||
row.eachCell((cell: any) => {
|
||||
cell.border = border
|
||||
})
|
||||
|
||||
row.eachCell(function (cell: any, colNumber: any) {
|
||||
if (cell.value && cell.value.hyperlink)
|
||||
row.getCell(colNumber).font = { underline: true, color: { argb: "004e47cc" } };
|
||||
});
|
||||
})
|
||||
|
||||
// Signature
|
||||
let lastRowTable = 0
|
||||
await worksheet.eachRow({ includeEmpty: false }, async function (row: any, rowNumber: number) {
|
||||
lastRowTable = await rowNumber
|
||||
});
|
||||
|
||||
const generateAtCellTitle = worksheet.getCell(`${columnToLetter(columns.length - 1)}${lastRowTable + 2}`)
|
||||
generateAtCellTitle.value = 'Generate at'
|
||||
generateAtCellTitle.border = border
|
||||
generateAtCellTitle.font = { bold: true }
|
||||
const generateAtCellValue = worksheet.getCell(`${columnToLetter(columns.length)}${lastRowTable + 2}`)
|
||||
generateAtCellValue.value = dayjs().format('MMM DD, YYYY HH:mm:ss')
|
||||
generateAtCellValue.border = border
|
||||
const generateByCellTitle = worksheet.getCell(`${columnToLetter(columns.length - 1)}${lastRowTable + 3}`)
|
||||
generateByCellTitle.value = 'Generate by'
|
||||
generateByCellTitle.border = border
|
||||
generateByCellTitle.font = { bold: true }
|
||||
const generateByCellValue = worksheet.getCell(`${columnToLetter(columns.length)}${lastRowTable + 3}`)
|
||||
generateByCellValue.value = user?.fullname
|
||||
generateByCellValue.border = border
|
||||
|
||||
|
||||
workbook.creator = user?.fullname;
|
||||
workbook.lastModifiedBy = user?.fullname;
|
||||
workbook.created = new Date(1985, 8, 30);
|
||||
workbook.modified = new Date();
|
||||
workbook.lastPrinted = new Date(2016, 9, 27);
|
||||
|
||||
|
||||
|
||||
const fileBuffer = await workbook.xlsx.writeBuffer()
|
||||
const blob = new Blob([fileBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-excel
|
||||
return blob
|
||||
} catch (error: any) {
|
||||
console.log("ERROR GENERATE EXCEL :", error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const exportEmployeeHistory = async (user: IUser, srcDataTable: IHistory[]) => {
|
||||
try {
|
||||
const columns = [
|
||||
{ header: 'No', key: 'number', width: 5, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Presence code', key: 'presence_checkin_code' },
|
||||
{ header: 'Date', key: 'presence_date', style: { numFmt: 'dd/mm/yyyy' } },
|
||||
{ header: 'Working Status', key: 'working_status' },
|
||||
{ header: 'Check-in Time', key: 'working_hours_start', style: { numFmt: '[$-13809]hh:mm:ss;@' } },
|
||||
{ header: 'Check-in Location', key: 'location_name' },
|
||||
{ header: 'Check-in Device', key: 'device' },
|
||||
{ header: 'Check-in Note', key: 'note' },
|
||||
{ header: 'Check-in Photo', key: 'face_image' },
|
||||
{ header: 'Check-out Time', key: 'working_hours_end', style: { numFmt: '[$-13809]hh:mm:ss;@' } },
|
||||
{ header: 'Check-out Location', key: 'co_location_name' },
|
||||
{ header: 'Check-out Device', key: 'co_device' },
|
||||
{ header: 'Check-out Note', key: 'co_note' },
|
||||
{ header: 'Check-out Photo', key: 'co_face_image' },
|
||||
{ header: 'Auto Checkout', key: 'autocheckout' },
|
||||
{ header: 'Approval', key: 'approval' },
|
||||
];
|
||||
|
||||
const workbook = new Workbook();
|
||||
const worksheet = workbook.addWorksheet("Sheet1", { pageSetup: { orientation: 'portrait' } });
|
||||
|
||||
// @ts-ignore
|
||||
// const base64Img = new Buffer.from(imageBuffer).toString('base64')
|
||||
const base64Img = await toDataURL('/assets/projects/nutech.png')
|
||||
const logo = workbook.addImage({
|
||||
base64: base64Img as string,
|
||||
extension: 'png',
|
||||
});
|
||||
worksheet.addImage(logo, {
|
||||
tl: { col: 1, row: 1 },
|
||||
ext: { width: 250, height: 75 }
|
||||
})
|
||||
|
||||
worksheet.mergeCells('B6:K6')
|
||||
const titleCell = worksheet.getCell('B6')
|
||||
titleCell.font = {
|
||||
size: 15,
|
||||
underline: true,
|
||||
bold: true
|
||||
}
|
||||
titleCell.alignment = {
|
||||
horizontal: 'center'
|
||||
}
|
||||
titleCell.value = "Presence History Report"
|
||||
|
||||
|
||||
// Table Headers
|
||||
worksheet.getRow(8).values = columns.map(item => item.header);
|
||||
worksheet.getRow(8).font = { bold: true }
|
||||
worksheet.getRow(8).eachCell({ includeEmpty: false }, (cell: any) => {
|
||||
cell.border = border
|
||||
})
|
||||
worksheet.columns = columns.map(item => {
|
||||
return {
|
||||
key: item.key,
|
||||
width: item.width || 20,
|
||||
style: item.style || { numFmt: 'General' }
|
||||
}
|
||||
})
|
||||
|
||||
// Set table value
|
||||
srcDataTable.forEach((item, index: number) => {
|
||||
const row = worksheet.addRow({
|
||||
number: index + 1,
|
||||
presence_checkin_code: item.presence_checkin_code,
|
||||
working_status: item.working_status,
|
||||
presence_date: new Date(item.presence_date as string).toLocaleDateString("id-ID", { timeZone: "Asia/Jakarta" }),
|
||||
device: item.device?.name,
|
||||
working_hours_start: dayjs(item.working_hours_start).format('HH:mm A'),
|
||||
location_name: item.location_name,
|
||||
note: item.note,
|
||||
face_image: item.face_image ? { text: 'View Photo', hyperlink: process.env.BASE_URL_IMG + item.face_image, font: { color: { argb: '0000FF' } } } : ' ',
|
||||
working_hours_end: item.presence_checkout ? dayjs(item.presence_checkout?.working_hours_end).format('HH:mm A') : 'Not check-out yet',
|
||||
co_location_name: item.presence_checkout?.location_name || ' ',
|
||||
co_device: item.presence_checkout?.device?.name || ' ',
|
||||
co_note: item.presence_checkout?.note || ' ',
|
||||
co_face_image: item.presence_checkout?.face_image ? { text: 'View Photo', hyperlink: process.env.BASE_URL_IMG + item.presence_checkout?.face_image, font: { color: { argb: '0000FF' } } } : ' ',
|
||||
autocheckout: item.presence_checkout?.auto_checkout ? 'Yes' : ' ',
|
||||
approval: item.status?.code === 'AP' || item.status?.code === 'NA' || item.status?.code === 'R' ? item.status?.name : ' '
|
||||
})
|
||||
// console.log(row)
|
||||
row.eachCell((cell: any) => {
|
||||
cell.border = border
|
||||
})
|
||||
|
||||
row.eachCell(function (cell: any, colNumber: any) {
|
||||
if (cell.value && cell.value.hyperlink)
|
||||
row.getCell(colNumber).font = { underline: true, color: { argb: "004e47cc" } };
|
||||
});
|
||||
})
|
||||
|
||||
// Signature
|
||||
let lastRowTable = 0
|
||||
await worksheet.eachRow({ includeEmpty: false }, async function (row: any, rowNumber: number) {
|
||||
lastRowTable = await rowNumber
|
||||
});
|
||||
|
||||
// const lastCellTable = `${columnToLetter(columns.length - 1)}${lastRowTable + 2}`
|
||||
// const signCell = `${columnToLetter(columns.length)}${lastRowTable + 4}`
|
||||
// worksheet.mergeCells(signCell, lastCellTable)
|
||||
|
||||
// const signCellValue = worksheet.getCell(signCell)
|
||||
// signCellValue.font = signFont
|
||||
// signCellValue.alignment = {
|
||||
// horizontal: 'center',
|
||||
// wrapText: true
|
||||
// }
|
||||
// signCellValue.border = border
|
||||
// signCellValue.value = `Export by:\n${user?.fullname}`
|
||||
|
||||
const generateAtCellTitle = worksheet.getCell(`${columnToLetter(columns.length - 1)}${lastRowTable + 2}`)
|
||||
generateAtCellTitle.value = 'Generate at'
|
||||
generateAtCellTitle.border = border
|
||||
generateAtCellTitle.font = { bold: true }
|
||||
const generateAtCellValue = worksheet.getCell(`${columnToLetter(columns.length)}${lastRowTable + 2}`)
|
||||
generateAtCellValue.value = dayjs().format('MMM DD, YYYY HH:mm:ss')
|
||||
generateAtCellValue.border = border
|
||||
const generateByCellTitle = worksheet.getCell(`${columnToLetter(columns.length - 1)}${lastRowTable + 3}`)
|
||||
generateByCellTitle.value = 'Generate by'
|
||||
generateByCellTitle.border = border
|
||||
generateByCellTitle.font = { bold: true }
|
||||
const generateByCellValue = worksheet.getCell(`${columnToLetter(columns.length)}${lastRowTable + 3}`)
|
||||
generateByCellValue.value = user?.fullname
|
||||
generateByCellValue.border = border
|
||||
|
||||
|
||||
workbook.creator = user?.fullname;
|
||||
workbook.lastModifiedBy = user?.fullname;
|
||||
workbook.created = new Date(1985, 8, 30);
|
||||
workbook.modified = new Date();
|
||||
workbook.lastPrinted = new Date(2016, 9, 27);
|
||||
|
||||
|
||||
// const fileName = `Presence History - ${user.nik} - ${dayjs().format('YYMMDDHHMMSS')}.xlsx`;
|
||||
|
||||
const fileBuffer = await workbook.xlsx.writeBuffer()
|
||||
const blob = new Blob([fileBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-excel
|
||||
return blob
|
||||
// const res = await blobToBase64(blob) // => return as base64
|
||||
// return res
|
||||
} catch (error: any) {
|
||||
console.log("ERROR GENERATE EXCEL :", error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const exportAllEmployeeHistory = async (user: IUser, srcDataTable: IHistory[]) => {
|
||||
try {
|
||||
const columns = [
|
||||
{ header: 'No', key: 'number', width: 5, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Presence code', key: 'presence_checkin_code' },
|
||||
{ header: 'Date', key: 'presence_date', style: { numFmt: 'dd/mm/yyyy' } },
|
||||
{ header: 'Employee', key: 'employee' },
|
||||
{ header: 'Working Status', key: 'working_status' },
|
||||
{ header: 'Check-in Time', key: 'working_hours_start', style: { numFmt: '[$-13809]hh:mm:ss;@' } },
|
||||
{ header: 'Check-in Location', key: 'location_name' },
|
||||
{ header: 'Check-in Device', key: 'device' },
|
||||
{ header: 'Check-in Note', key: 'note' },
|
||||
{ header: 'Check-in Photo', key: 'face_image' },
|
||||
{ header: 'Check-out Time', key: 'working_hours_end', style: { numFmt: '[$-13809]hh:mm:ss;@' } },
|
||||
{ header: 'Check-out Location', key: 'co_location_name' },
|
||||
{ header: 'Check-out Device', key: 'co_device' },
|
||||
{ header: 'Check-out Note', key: 'co_note' },
|
||||
{ header: 'Check-out Photo', key: 'co_face_image' },
|
||||
{ header: 'Auto Checkout', key: 'autocheckout' },
|
||||
{ header: 'Approval', key: 'approval' },
|
||||
];
|
||||
|
||||
const workbook = new Workbook();
|
||||
const worksheet = workbook.addWorksheet("Sheet1", { pageSetup: { orientation: 'portrait' } });
|
||||
|
||||
// @ts-ignore
|
||||
// const base64Img = new Buffer.from(imageBuffer).toString('base64')
|
||||
const base64Img = await toDataURL('/assets/projects/nutech.png')
|
||||
const logo = workbook.addImage({
|
||||
base64: base64Img as string,
|
||||
extension: 'png',
|
||||
});
|
||||
worksheet.addImage(logo, {
|
||||
tl: { col: 1, row: 1 },
|
||||
ext: { width: 250, height: 75 }
|
||||
})
|
||||
|
||||
worksheet.mergeCells('B6:K6')
|
||||
const titleCell = worksheet.getCell('B6')
|
||||
titleCell.font = {
|
||||
size: 15,
|
||||
underline: true,
|
||||
bold: true
|
||||
}
|
||||
titleCell.alignment = {
|
||||
horizontal: 'center'
|
||||
}
|
||||
titleCell.value = "Attendance History Report"
|
||||
|
||||
|
||||
// Table Headers
|
||||
worksheet.getRow(8).values = columns.map(item => item.header);
|
||||
worksheet.getRow(8).font = { bold: true }
|
||||
worksheet.getRow(8).eachCell({ includeEmpty: false }, (cell: any) => {
|
||||
cell.border = border
|
||||
})
|
||||
worksheet.columns = columns.map(item => {
|
||||
return {
|
||||
key: item.key,
|
||||
width: item.width || 20,
|
||||
style: item.style || { numFmt: 'General' }
|
||||
}
|
||||
})
|
||||
|
||||
// Set table value
|
||||
srcDataTable.forEach((item, index: number) => {
|
||||
const row = worksheet.addRow({
|
||||
number: index + 1,
|
||||
presence_checkin_code: item.presence_checkin_code,
|
||||
presence_date: new Date(item.presence_date as string).toLocaleDateString("id-ID", { timeZone: "Asia/Jakarta" }),
|
||||
employee: item.user?.fullname,
|
||||
working_status: item.working_status,
|
||||
device: item.device?.name,
|
||||
working_hours_start: dayjs(item.working_hours_start).format('HH:mm'),
|
||||
location_name: item.location_name,
|
||||
note: item.note,
|
||||
face_image: item.face_image ? { text: 'View Photo', hyperlink: process.env.BASE_URL_IMG + item.face_image, font: { color: { argb: '0000FF' } } } : ' ',
|
||||
working_hours_end: item.presence_checkout ? dayjs(item.presence_checkout?.working_hours_end).format('HH:mm') : 'Not check-out yet',
|
||||
co_location_name: item.presence_checkout?.location_name || ' ',
|
||||
co_device: item.presence_checkout?.device?.name || ' ',
|
||||
co_note: item.presence_checkout?.note || ' ',
|
||||
co_face_image: item.presence_checkout?.face_image ? { text: 'View Photo', hyperlink: process.env.BASE_URL_IMG + item.presence_checkout?.face_image, font: { color: { argb: '0000FF' } } } : ' ',
|
||||
autocheckout: item.presence_checkout?.auto_checkout ? 'Yes' : ' ',
|
||||
approval: item.status?.code === 'AP' || item.status?.code === 'NA' || item.status?.code === 'R' ? item.status?.name : ' '
|
||||
})
|
||||
// console.log(row)
|
||||
row.eachCell((cell: any) => {
|
||||
cell.border = border
|
||||
})
|
||||
|
||||
row.eachCell(function (cell: any, colNumber: any) {
|
||||
if (cell.value && cell.value.hyperlink)
|
||||
row.getCell(colNumber).font = { underline: true, color: { argb: "004e47cc" } };
|
||||
});
|
||||
})
|
||||
|
||||
// Signature
|
||||
let lastRowTable = 0
|
||||
await worksheet.eachRow({ includeEmpty: false }, async function (row: any, rowNumber: number) {
|
||||
lastRowTable = await rowNumber
|
||||
});
|
||||
|
||||
const generateAtCellTitle = worksheet.getCell(`${columnToLetter(columns.length - 1)}${lastRowTable + 2}`)
|
||||
generateAtCellTitle.value = 'Generate at'
|
||||
generateAtCellTitle.border = border
|
||||
generateAtCellTitle.font = { bold: true }
|
||||
const generateAtCellValue = worksheet.getCell(`${columnToLetter(columns.length)}${lastRowTable + 2}`)
|
||||
generateAtCellValue.value = dayjs().format('MMM DD, YYYY HH:mm:ss')
|
||||
generateAtCellValue.border = border
|
||||
const generateByCellTitle = worksheet.getCell(`${columnToLetter(columns.length - 1)}${lastRowTable + 3}`)
|
||||
generateByCellTitle.value = 'Generate by'
|
||||
generateByCellTitle.border = border
|
||||
generateByCellTitle.font = { bold: true }
|
||||
const generateByCellValue = worksheet.getCell(`${columnToLetter(columns.length)}${lastRowTable + 3}`)
|
||||
generateByCellValue.value = user?.fullname
|
||||
generateByCellValue.border = border
|
||||
|
||||
|
||||
workbook.creator = user?.fullname;
|
||||
workbook.lastModifiedBy = user?.fullname;
|
||||
workbook.created = new Date(1985, 8, 30);
|
||||
workbook.modified = new Date();
|
||||
workbook.lastPrinted = new Date(2016, 9, 27);
|
||||
|
||||
|
||||
// const fileName = `Presence History - ${user.nik} - ${dayjs().format('YYMMDDHHMMSS')}.xlsx`;
|
||||
|
||||
const fileBuffer = await workbook.xlsx.writeBuffer()
|
||||
const blob = new Blob([fileBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-excel
|
||||
return blob
|
||||
// const res = await blobToBase64(blob) // => return as base64
|
||||
// return res
|
||||
} catch (error: any) {
|
||||
console.log("ERROR GENERATE EXCEL :", error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const border: any = {
|
||||
top: { style: 'thin' },
|
||||
left: { style: 'thin' },
|
||||
bottom: { style: 'thin' },
|
||||
right: { style: 'thin' },
|
||||
}
|
||||
|
||||
const signFont = {
|
||||
name: "Comic Sans MS",
|
||||
family: 4,
|
||||
size: 11,
|
||||
underline: true,
|
||||
bold: true
|
||||
}
|
||||
|
||||
export function columnToLetter(column: number) {
|
||||
var temp, letter = '';
|
||||
while (column > 0) {
|
||||
temp = (column - 1) % 26;
|
||||
letter = String.fromCharCode(temp + 65) + letter;
|
||||
column = (column - temp - 1) / 26;
|
||||
}
|
||||
return letter;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { getServerSession } from "next-auth"
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
||||
import { redirect } from "next/navigation"
|
||||
import { ResponseData } from "@/types/types"
|
||||
|
||||
export default async function fetchData(url: string = '/', cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) {
|
||||
const { BASE_URL_API } = process.env
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const res = await fetch(BASE_URL_API + url, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${session?.user.access_token}`,
|
||||
},
|
||||
cache: cache,
|
||||
next: next
|
||||
})
|
||||
|
||||
const data: ResponseData = await res.json()
|
||||
|
||||
// Recommendation: handle errors
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) return redirect(`/auth?error=Session error or has expired !`)
|
||||
// This will activate the closest `error.js` Error Boundary
|
||||
throw new Error(`(${data.code || res.status}) ${data.message || res.statusText}`)
|
||||
}
|
||||
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function fetchDataWithPost(url: string = '/', payload: any = {}, cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) {
|
||||
const { BASE_URL_API } = process.env
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const res = await fetch(BASE_URL_API + url, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${session?.user.access_token}`,
|
||||
},
|
||||
method: 'POST',
|
||||
cache: cache,
|
||||
next: next,
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
|
||||
// Read raw body once
|
||||
const raw = await res.text();
|
||||
|
||||
// Try parse as JSON if possible
|
||||
let data: any;
|
||||
try {
|
||||
data = raw ? JSON.parse(raw) : {};
|
||||
} catch {
|
||||
data = { message: raw };
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) redirect(`/auth?error=Session error or has expired !`);
|
||||
|
||||
throw new Error(`(${data?.code || res.status} ${res.statusText}) ${data?.message}`);
|
||||
}
|
||||
|
||||
return data.data
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Import the functions you need from the SDKs you need
|
||||
import { initializeApp } from 'firebase/app';
|
||||
|
||||
export const firebaseConfig = {
|
||||
apiKey: process.env.FIREBASE_API_KEY,
|
||||
authDomain: "hats-8319e.firebaseapp.com",
|
||||
projectId: "hats-8319e",
|
||||
storageBucket: "hats-8319e.appspot.com",
|
||||
messagingSenderId: "422528660020",
|
||||
appId: process.env.FIREBASE_APP_ID,
|
||||
measurementId: "G-RN0NQKCM2F"
|
||||
};
|
||||
|
||||
// Initialize Firebase
|
||||
const firebaseApp = initializeApp(firebaseConfig);
|
||||
export default firebaseApp;
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
import { type ReactNode } from "react"
|
||||
import dayjs from "dayjs";
|
||||
|
||||
export const wait = (ms: number) => new Promise((rs) => setTimeout(rs, ms))
|
||||
|
||||
export const toastError = (toast: any, message: string | ReactNode) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Oops! Something went wrong.",
|
||||
description: message,
|
||||
})
|
||||
}
|
||||
|
||||
export const toastInfo = (toast: any, message: string | ReactNode) => {
|
||||
toast({
|
||||
title: "Success",
|
||||
description: message,
|
||||
})
|
||||
}
|
||||
|
||||
export const revalidateTag = async (tag: string) => {
|
||||
return fetch(`/api/revalidate/${tag}`).then(res => res.text())
|
||||
}
|
||||
|
||||
export function deleteAllCookies() {
|
||||
const cookies = document.cookie.split(";");
|
||||
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
const cookie = cookies[i];
|
||||
const eqPos = cookie.indexOf("=");
|
||||
const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
|
||||
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
|
||||
}
|
||||
}
|
||||
|
||||
export function randomIntFromInterval(min: number, max: number) { // min and max included
|
||||
return Math.floor(Math.random() * (max - min + 1) + min)
|
||||
}
|
||||
|
||||
export function getRandomNumber(min: number, max: number) {
|
||||
return Math.random() * (max - min) + min;
|
||||
}
|
||||
|
||||
export function getArrayRandomNumber(n: number, min: number, max: number) {
|
||||
const randomNumbers = [];
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const randomNumber = getRandomNumber(min, max);
|
||||
randomNumbers.push(randomNumber);
|
||||
}
|
||||
|
||||
return randomNumbers
|
||||
}
|
||||
|
||||
export function getLastNDays(n: any) {
|
||||
const today = new Date(); // Get the current date
|
||||
const last30Days = [];
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const date = new Date(today);
|
||||
date.setDate(today.getDate() - i); // Subtract 'i' days from the current date
|
||||
last30Days.push(dayjs(date).format('YYYY-MM-DD'));
|
||||
}
|
||||
|
||||
return last30Days;
|
||||
}
|
||||
|
||||
export const getVariantApproved = (code: 'R' | 'NA' | 'AP' | 'A') => {
|
||||
switch (code) {
|
||||
case 'NA':
|
||||
return 'default'
|
||||
case 'A':
|
||||
return 'default'
|
||||
case 'R':
|
||||
return 'destructive'
|
||||
default:
|
||||
return 'secondary'
|
||||
}
|
||||
}
|
||||
|
||||
export const getVariantWorkingStatus = (code: string) => {
|
||||
const res = code?.toUpperCase()
|
||||
switch (res) {
|
||||
case 'WFO':
|
||||
return 'outline'
|
||||
case 'WFS':
|
||||
return 'default'
|
||||
case 'SKT':
|
||||
return 'warn'
|
||||
case 'SAKIT':
|
||||
return 'warn'
|
||||
case 'I':
|
||||
return 'info'
|
||||
case 'IZIN':
|
||||
return 'info'
|
||||
case 'WFH':
|
||||
return 'secondary'
|
||||
default:
|
||||
return 'violet'
|
||||
}
|
||||
}
|
||||
|
||||
export const getIconWorkingStatus = (code: string) => {
|
||||
switch (code) {
|
||||
case 'WFH':
|
||||
return 'ti ti-home'
|
||||
case 'WFS':
|
||||
return 'ti ti-building-community'
|
||||
case 'SKT':
|
||||
return 'ti ti-stethoscope'
|
||||
case 'SAKIT':
|
||||
return 'ti ti-stethoscope'
|
||||
case 'CT01':
|
||||
return 'ti ti-speedboat'
|
||||
default:
|
||||
return 'ti ti-speedboat'
|
||||
}
|
||||
}
|
||||
|
||||
export const generateHourMinutes = (totalTime: any) => {
|
||||
try {
|
||||
const hours = Math.floor(totalTime / 3600);
|
||||
const remainingSeconds = totalTime % 3600;
|
||||
const minutes = Math.floor(remainingSeconds / 60);
|
||||
|
||||
// Create the formatted string
|
||||
const formattedTime = `${hours} hour${hours !== 1 ? 's' : ''} ${minutes} minute${minutes !== 1 ? 's' : ''}`;
|
||||
return formattedTime
|
||||
} catch (error) {
|
||||
return '0 hour'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function titleCase(str: string) {
|
||||
var splitStr = str.toLowerCase().split(' ');
|
||||
for (var i = 0; i < splitStr.length; i++) {
|
||||
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
|
||||
}
|
||||
return splitStr.join(' ');
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function readFile(file: any) {
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader()
|
||||
reader.addEventListener('load', () => resolve(reader.result), false)
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
export const toDataURL = (url: any) => fetch(url)
|
||||
.then(response => response.blob())
|
||||
.then(blob => new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => resolve(reader.result)
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(blob)
|
||||
}
|
||||
))
|
||||
|
||||
export const blobToBase64 = (blob: any) => {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(blob);
|
||||
return new Promise(resolve => {
|
||||
reader.onloadend = () => {
|
||||
resolve(reader.result);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export function generateCalendar(month: any = dayjs().month()) {
|
||||
month = Math.floor(month)
|
||||
|
||||
const year = dayjs().year()
|
||||
const firstDayOfTheMonth = dayjs(new Date(year, month, 1)).day()
|
||||
|
||||
let currentMonthCount = 0 - firstDayOfTheMonth
|
||||
const daysMatrix = new Array(5).fill([]).map(() => {
|
||||
return new Array(7).fill(null).map(() => {
|
||||
currentMonthCount++
|
||||
return dayjs(new Date(year, month, currentMonthCount))
|
||||
})
|
||||
})
|
||||
|
||||
return daysMatrix
|
||||
}
|
||||
|
||||
function getDeviceType() {
|
||||
if (navigator?.userAgent.includes('Mobile')) {
|
||||
return 'Mobile';
|
||||
} else if (navigator.userAgent.includes('Tablet')) {
|
||||
return 'Tablet';
|
||||
} else {
|
||||
return 'Computer';
|
||||
}
|
||||
}
|
||||
|
||||
function getOperatingSystemInfo() {
|
||||
const platform = navigator ? navigator.platform : '';
|
||||
let osInfo = 'Unknown';
|
||||
|
||||
if (platform.startsWith('Win')) {
|
||||
osInfo = 'Windows';
|
||||
} else if (platform.startsWith('Mac')) {
|
||||
osInfo = 'macOS';
|
||||
} else if (platform === 'Linux' || platform.startsWith('Linux')) {
|
||||
osInfo = 'Linux';
|
||||
} else if (platform === 'iPhone' || platform === 'iPad' || platform === 'iPod') {
|
||||
osInfo = 'iOS';
|
||||
} else if (platform.startsWith('Android')) {
|
||||
osInfo = 'Android';
|
||||
}
|
||||
return osInfo;
|
||||
}
|
||||
|
||||
function getBrowserInfo() {
|
||||
const userAgent = navigator ? navigator.userAgent : '';
|
||||
const match = userAgent.match(/(Chrome|Firefox|Edge|IE|Opera|Safari)\/(\S+)/);
|
||||
|
||||
if (match) {
|
||||
return `${match[1]} ${match[2]}`;
|
||||
} else {
|
||||
return 'Unknown';
|
||||
}
|
||||
}
|
||||
|
||||
export const getUserAgent = () => {
|
||||
try {
|
||||
const deviceType = getDeviceType();
|
||||
const deviceModel = navigator.userAgent.match(/\(([^)]+)\)/)![1] || 'Unknown';
|
||||
const osInfo = getOperatingSystemInfo();
|
||||
const agentType = 'Browser';
|
||||
const browserInfo = getBrowserInfo();
|
||||
const renderingEngine = 'Webkit';
|
||||
|
||||
return {
|
||||
deviceType, deviceModel, osInfo, agentType, browserInfo, renderingEngine
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
deviceType: '', deviceModel: '', osInfo: '', agentType: '', browserInfo: '', renderingEngine: ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const getDeviceFCM = () => {
|
||||
const { deviceType, osInfo } = getUserAgent()
|
||||
|
||||
const device = deviceType.toUpperCase()
|
||||
const os = osInfo.toUpperCase()
|
||||
if (device === 'MOBILE') {
|
||||
if (os === 'IOS') {
|
||||
return 'ios'
|
||||
} else {
|
||||
return 'browser mobile'
|
||||
}
|
||||
} else {
|
||||
return 'browser'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
Reference in New Issue
Block a user