upd: profile

Deskripsi:
- edit profile
- api image
- folder image user

No Issues
This commit is contained in:
amel
2024-08-29 15:50:04 +08:00
parent 9eb2b1e4af
commit 44ea8c6510
14 changed files with 181 additions and 132 deletions

View File

@@ -100,6 +100,7 @@ model User {
phone String @unique
email String? @unique
gender String @default("M") //M= Male, F= Female
img String?
isFirstLogin Boolean @default(true)
isActive Boolean @default(true)
createdAt DateTime @default(now())

View File

View File

@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from "next/server"
import fs from 'fs'
export async function GET(request: Request) {
let fl;
try {
const { searchParams } = new URL(request.url);
const kategori = searchParams.get('cat');
const file = searchParams.get('file');
fl = fs.readFileSync(`./public/image/${kategori}/${file}`)
} catch (err: any) {
throw err;
}
return new NextResponse(fl, {
headers: {
"Content-Type": "image/png"
}
})
}

View File

@@ -122,7 +122,6 @@ export async function POST(request: Request) {
const f: any = file[index].get('file')
const fName = f.name
const fExt = fName.split(".").pop()
// funUploadFile(fName, f)
const dataFile = {
name: fName,

View File

@@ -1,4 +1,4 @@
import { funUploadFile, prisma } from "@/module/_global";
import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import _, { ceil } from "lodash";
import moment from "moment";
@@ -148,7 +148,6 @@ export async function POST(request: Request) {
const f: any = file[index].get('file')
const fName = f.name
const fExt = fName.split(".").pop()
// funUploadFile(fName, f)
const dataFile = {
name: fName,

View File

@@ -1,59 +0,0 @@
import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { NextResponse } from "next/server";
// UPDATE PROFILE BY COOKIES
export async function PUT(request: Request, context: { params: { id: string } }) {
try {
const user = await funGetUserByCookies()
if (user.id == undefined) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const { id } = context.params;
const data = await request.json();
const cek = await prisma.user.count({
where: {
id: id,
nik: data.nik,
email: data.email,
phone: data.phone
}
})
if (cek == 0) {
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan profile, data tidak ditemukan",
},
{ status: 404 }
);
}
const result = await prisma.user.update({
where: {
id: id,
},
data: {
nik: data.nik,
name: data.name,
email: data.email,
phone: data.phone,
gender: data.gender,
},
});
return NextResponse.json(
{
success: true,
message: "Berhasil mendapatkan profile",
result,
},
{ status: 200 }
);
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal mendapatkan anggota, coba lagi nanti", reason: (error as Error).message, }, { status: 500 });
}
}

View File

@@ -2,6 +2,8 @@ import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import _ from "lodash";
import { NextResponse } from "next/server";
import path from "path";
import fs from "fs";
// GET PROFILE BY COOKIES
@@ -24,6 +26,7 @@ export async function GET(request: Request) {
gender: true,
idGroup: true,
idPosition: true,
img: true,
Group: {
select: {
name: true
@@ -39,16 +42,17 @@ export async function GET(request: Request) {
const { ...userData } = data;
const group = data?.Group.name
const position = data?.Position.name
const phone = data?.phone.substr(2)
const result = { ...userData, group, position };
const omitData = _.omit(data, ["Group", "Position", "phone"])
const omitData = _.omit(result, ["Group", "Position",])
const result = { ...userData, group, position, phone };
return NextResponse.json({ success: true, data: omitData });
return NextResponse.json({ success: true, data: result });
} catch (error) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
}
// UPDATE PROFILE BY COOKIES
@@ -59,24 +63,85 @@ export async function PUT(request: Request) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const body = await request.json();
const { name, email, phone, nik, gender } = body;
const data = await prisma.user.update({
const body = await request.formData()
const file = body.get("file") as File;
const data = body.get("data");
const { name, email, phone, nik, gender } = JSON.parse(data as string)
const cekNIK = await prisma.user.count({
where: {
nik: nik,
NOT: {
id: user.id
}
},
});
const cekEmail = await prisma.user.count({
where: {
email: email,
NOT: {
id: user.id
}
},
});
const cekPhone = await prisma.user.count({
where: {
phone: "62" + phone,
NOT: {
id: user.id
}
},
});
if (cekNIK > 0 || cekEmail > 0 || cekPhone > 0) {
return NextResponse.json({ success: false, message: "Gagal ubah profile, NIK/email/phone sudah terdaftar" }, { status: 401 });
}
const update = await prisma.user.update({
where: {
id: user.id
},
data: {
name: name,
email: email,
phone: phone,
phone: "62" + phone,
nik: nik,
gender: gender
},
select: {
img: true
}
})
return NextResponse.json({ success: true, message: "Berhasil ubah profile", data: data });
if (String(file) != "undefined" && String(file) != "null") {
fs.unlink(`./public/image/user/${update.img}`, (err) => { })
const root = path.join(process.cwd(), "./public/image/user/");
const fExt = file.name.split(".").pop()
const fileName = user.id + '.' + fExt;
const filePath = path.join(root, fileName);
// Konversi ArrayBuffer ke Buffer
const buffer = Buffer.from(await file.arrayBuffer());
// Tulis file ke sistem
fs.writeFileSync(filePath, buffer);
await prisma.user.update({
where: {
id: user.id
},
data: {
img: fileName
}
})
}
return NextResponse.json({ success: true, message: "Berhasil ubah profile" });
} catch (error) {
return NextResponse.json({ success: false, message: "Gagal ubah profile" }, { status: 401 });
return NextResponse.json({ success: false, message: "Gagal ubah profile" }, { status: 500 });
}
}

View File

@@ -1,6 +0,0 @@
'use server'
import fs from 'fs'
export async function funUploadFile(fName: any, f: any) {
const filenya = Buffer.from(await f.arrayBuffer())
fs.writeFileSync(`./public/assets/file/${fName}`, filenya)
}

View File

@@ -5,7 +5,6 @@ import SkeletonDetailDiscussionMember from "./components/skeleton_detail_discuss
import SkeletonDetailListTugasTask from "./components/skeleton_detail_list_tugas_task";
import SkeletonDetailProfile from "./components/skeleton_detail_profile";
import SkeletonSingle from "./components/skeleton_single";
import { funUploadFile } from "./fun/upload-file";
import { WARNA } from "./fun/WARNA";
import LayoutDrawer from "./layout/layout_drawer";
import LayoutIconBack from "./layout/layout_icon_back";
@@ -28,6 +27,5 @@ export { pwd_key_config };
export { SkeletonSingle }
export { SkeletonDetailDiscussionComment }
export { SkeletonDetailDiscussionMember }
export { funUploadFile }
export { SkeletonDetailProfile }
export {SkeletonDetailListTugasTask}
export { SkeletonDetailListTugasTask }

View File

@@ -343,7 +343,7 @@ export default function CreateMember() {
size="md"
type="number"
radius={30}
placeholder="xxx xxxx xxxx"
placeholder="8xx xxxx xxxx"
leftSection={<Text>+62</Text>}
withAsterisk
label="Nomor Telepon"

View File

@@ -5,13 +5,10 @@ export const funGetProfileByCookies = async (path?: string) => {
return await response.json().catch(() => null);
}
export const funEditProfileByCookies = async ( data: IEditDataProfile) => {
export const funEditProfileByCookies = async (data: FormData) => {
const response = await fetch(`/api/user/profile/`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
body: data,
});
return await response.json().catch(() => null);
}

View File

@@ -1,21 +1,22 @@
export interface IProfileById {
id: string
name: string
email: string
phone: string
nik: string
gender: string
idGroup: string
idPosition: string
group: string
position: string
}
export interface IEditDataProfile {
id: string;
nik: string;
name: string;
phone: string;
email: string;
gender: string;
}
id: string
name: string
email: string
phone: string
nik: string
gender: string
idGroup: string
idPosition: string
group: string
position: string
}
export interface IEditDataProfile {
id: string;
nik: string;
name: string;
phone: string;
email: string;
gender: string;
img: string;
}

View File

@@ -1,18 +1,25 @@
"use client"
import { LayoutNavbarNew, WARNA } from "@/module/_global";
import { Box, Button, Flex, Modal, Select, Stack, Text, TextInput } from "@mantine/core";
import { HiUser } from "react-icons/hi2";
import { Avatar, Box, Button, Flex, Indicator, Modal, Select, Stack, Text, TextInput } from "@mantine/core";
import toast from "react-hot-toast";
import LayoutModal from "@/module/_global/layout/layout_modal";
import { useState } from "react";
import { useRef, useState } from "react";
import { IEditDataProfile, IProfileById } from "../lib/type_profile";
import { funEditProfileByCookies, funGetProfileByCookies } from "../lib/api_profile";
import { useShallowEffect } from "@mantine/hooks";
import { funGetUserByCookies } from "@/module/auth";
import { FaCamera, FaShare } from "react-icons/fa6";
import { Dropzone } from "@mantine/dropzone";
import _ from "lodash";
import { useRouter } from "next/navigation";
export default function EditProfile() {
const [isValModal, setValModal] = useState(false)
const [isDataEdit, setDataEdit] = useState<IProfileById[]>([])
const openRef = useRef<() => void>(null)
const [img, setIMG] = useState<any | null>()
const [imgForm, setImgForm] = useState<any>()
const router = useRouter()
const [touched, setTouched] = useState({
nik: false,
name: false,
@@ -20,6 +27,7 @@ export default function EditProfile() {
email: false,
gender: false,
});
const [data, setData] = useState<IEditDataProfile>({
id: "",
nik: "",
@@ -27,12 +35,15 @@ export default function EditProfile() {
phone: "",
email: "",
gender: "",
img: "",
})
async function getAllProfile() {
try {
const res = await funGetProfileByCookies()
setData(res.data)
setIMG(`/api/file/img?cat=user&file=${res.data.img}`)
} catch (error) {
console.error(error);
}
@@ -45,17 +56,15 @@ export default function EditProfile() {
async function onEditProfile(val: boolean) {
try {
if (val) {
const res = await funEditProfileByCookies({
id: data.id,
nik: data.nik,
name: data.name,
phone: data.phone,
email: data.email,
gender: data.gender,
})
const fd = new FormData();
fd.append("file", imgForm)
fd.append("data", JSON.stringify(data))
const res = await funEditProfileByCookies(fd)
if (res.success) {
setValModal(false)
toast.success(res.message)
router.push('/profile')
} else {
toast.error(res.message)
}
@@ -77,12 +86,31 @@ export default function EditProfile() {
pt={30}
px={20}
>
<Box bg={WARNA.biruTua} py={30} px={50}
style={{
borderRadius: 10,
}}>
<HiUser size={100} color={WARNA.bgWhite} />
</Box>
<Dropzone
openRef={openRef}
onDrop={async (files) => {
if (!files || _.isEmpty(files))
return toast.error('Tidak ada gambar yang dipilih')
setImgForm(files[0])
const buffer = URL.createObjectURL(new Blob([new Uint8Array(await files[0].arrayBuffer())]))
setIMG(buffer)
}}
activateOnClick={false}
maxSize={1 * 1024 ** 2}
accept={['image/png', 'image/jpeg', 'image/heic']}
onReject={(files) => {
return toast.error('File yang diizinkan: .png, .jpg, dan .heic dengan ukuran maksimal 1 MB')
}}
>
</Dropzone>
<Indicator offset={20} withBorder inline color={WARNA.borderBiruMuda} position="bottom-end" label={<FaCamera size={20} />} size={40} onClick={() => openRef.current?.()}>
<Avatar
size="150"
radius={"100"}
src={img}
/>
</Indicator>
<TextInput
size="md" type="number" radius={30} placeholder="NIK" withAsterisk label="NIK" w={"100%"}
styles={{
@@ -149,7 +177,7 @@ export default function EditProfile() {
}
/>
<TextInput
size="md" type="number" radius={30} placeholder="+62...." withAsterisk label="Nomor Telepon" w={"100%"}
size="md" type="number" radius={30} placeholder="8xx xxxx xxxx" withAsterisk label="Nomor Telepon" w={"100%"}
styles={{
input: {
color: WARNA.biruTua,
@@ -157,6 +185,7 @@ export default function EditProfile() {
borderColor: WARNA.biruTua,
},
}}
leftSection={<Text>+62</Text>}
onChange={(e) => {
setData({ ...data, phone: e.target.value })
setTouched({ ...touched, phone: false })
@@ -198,7 +227,7 @@ export default function EditProfile() {
onBlur={() => setTouched({ ...touched, gender: true })}
error={
touched.gender && (
data.gender == "" ? "Gender Tidak Boleh Kosong" : null
data.gender == "" ? "Jenis Kelamin Tidak Boleh Kosong" : null
)
}
/>

View File

@@ -1,12 +1,10 @@
"use client"
import { LayoutIconBack, LayoutNavbarHome, SkeletonDetailProfile, WARNA } from "@/module/_global";
import { ActionIcon, Anchor, Box, Button, Flex, Group, Skeleton, Stack, Text } from "@mantine/core";
import { BsInfo } from "react-icons/bs";
import { ActionIcon, Anchor, Avatar, Box, Button, Flex, Group, Skeleton, Stack, Text } from "@mantine/core";
import { HiUser } from "react-icons/hi2";
import { RiIdCardFill } from "react-icons/ri";
import { FaSquarePhone } from "react-icons/fa6";
import { MdEmail } from "react-icons/md";
import { InfoTitleProfile } from "../component/ui/ui_profile";
import { IoMaleFemale } from "react-icons/io5";
import toast from "react-hot-toast";
import { LuLogOut } from "react-icons/lu";
@@ -22,12 +20,14 @@ export default function Profile() {
const [isData, setData] = useState<IProfileById>()
const router = useRouter()
const [loading, setLoading] = useState(true)
const [img, setIMG] = useState<any | null>()
async function getData() {
try {
setLoading(true)
const res = await funGetProfileByCookies()
setData(res.data)
setIMG(`/api/file/img?cat=user&file=${res.data.img}`)
setLoading(false)
} catch (error) {
console.error(error);
@@ -62,7 +62,6 @@ export default function Profile() {
<LayoutNavbarHome>
<Group justify="space-between">
<LayoutIconBack />
<ActionIcon onClick={() => { setOpenModal(true) }} variant="light" bg={WARNA.bgIcon} size="lg" radius="lg" aria-label="Info">
<LuLogOut size={20} color='white' />
</ActionIcon>
@@ -72,7 +71,11 @@ export default function Profile() {
justify="center"
gap="xs"
>
<HiUser size={100} color='white' />
<Avatar
size="150"
radius={"100"}
src={img}
/>
{loading ?
<Skeleton height={62} mt={10} width={"40%"} />
: