import apiFetch from "@/lib/apiFetch"; import { Button, Divider, Flex, Group, Input, Modal, Stack, Title, } from "@mantine/core"; import type { JsonValue } from "generated/prisma/runtime/library"; import { useEffect, useState } from "react"; import notification from "./notificationGlobal"; export default function ProfileUser({ permissions, }: { permissions: JsonValue[]; }) { const [opened, setOpened] = useState(false); const [openedPassword, setOpenedPassword] = useState(false); const [pwdBaru, setPwdBaru] = useState(""); const [host, setHost] = useState({ id: "", name: "", phone: "", roleId: "", email: "", }); const [error, setError] = useState({ name: false, email: false, phone: false, }); useEffect(() => { async function fetchHost() { const { data } = await apiFetch.api.user.find.get(); setHost({ id: data?.user?.id ?? "", name: data?.user?.name ?? "", phone: data?.user?.phone ?? "", roleId: data?.user?.roleId ?? "", email: data?.user?.email ?? "", }); } fetchHost(); }, []); function onValidation({ kat, value, }: { kat: "name" | "email" | "phone"; value: string; }) { if (value.length < 1) { setError({ ...error, [kat]: true }); } else { setError({ ...error, [kat]: false }); } setHost({ ...host, [kat]: value }); } async function handleUpdate() { try { const res = await apiFetch.api.user.update.post(host); if (res.status === 200) { setOpened(false); notification({ title: "Success", message: "Your profile have been saved", type: "success", }); } else { notification({ title: "Error", message: "Failed to update profile", type: "error", }); } } catch (error) { console.error(error); notification({ title: "Error", message: "Failed to update profile", type: "error", }); } } async function handleUpdatePassword() { try { const res = await apiFetch.api.user["update-password"].post({ password: pwdBaru, id: host.id, }); if (res.status === 200) { setPwdBaru(""); setOpenedPassword(false); notification({ title: "Success", message: "Your password have been saved", type: "success", }); } else { notification({ title: "Error", message: "Failed to update password", type: "error", }); } } catch (error) { console.error(error); notification({ title: "Error", message: "Failed to update password", type: "error", }); } } return ( <> Profile Pengguna {permissions.includes("setting.profile.edit") && ( )} {permissions.includes("setting.profile.password") && ( )} setOpened(false)} title={"Edit Profile"} size={"lg"} overlayProps={{ backgroundOpacity: 0.55, blur: 3 }} > onValidation({ kat: "name", value: e.target.value }) } /> onValidation({ kat: "phone", value: e.target.value }) } /> onValidation({ kat: "email", value: e.target.value }) } /> setOpenedPassword(false)} title={"Ubah Password"} overlayProps={{ backgroundOpacity: 0.55, blur: 3 }} > setPwdBaru(e.target.value)} /> ); }