upd: mobile

Deskripsi:
- api mobile home
- server action detect user

No Issues
This commit is contained in:
amel
2025-04-28 17:04:34 +08:00
parent aa6898d887
commit 80b08629ad
10 changed files with 1784 additions and 6 deletions

View File

@@ -0,0 +1,250 @@
import { DIR, funDeleteFile, funUploadFile, prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } from "@/module/user";
import _ from "lodash";
import { NextResponse } from "next/server";
import sharp from "sharp";
// GET ONE MEMBER / USER
export async function GET(request: Request, context: { params: { id: string } }) {
try {
const { id } = context.params;
const users = await prisma.user.findUnique({
where: {
id: id,
},
select: {
id: true,
nik: true,
name: true,
phone: true,
email: true,
gender: true,
img: true,
idGroup: true,
isActive: true,
idPosition: true,
UserRole: {
select: {
name: true,
id: true
}
},
Position: {
select: {
name: true,
id: true
},
},
Group: {
select: {
name: true,
id: true
},
},
},
});
const { ...userData } = users;
const group = users?.Group.name
const position = users?.Position?.name
const idUserRole = users?.UserRole.id
const phone = users?.phone.substr(2)
const role = users?.UserRole.name
const result = { ...userData, group, position, idUserRole, phone, role };
const omitData = _.omit(result, ["Group", "Position", "UserRole"]);
return NextResponse.json(
{
success: true,
message: "Berhasil mendapatkan anggota",
data: omitData,
},
{ status: 200 }
);
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal mendapatkan anggota, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
}
}
// DELETE / ACTIVE & NON ACTIVE MEMBER / USER
export async function DELETE(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 { isActive } = (await request.json());
const data = await prisma.user.count({
where: {
id: id,
},
});
if (data == 0) {
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan anggota, data tidak ditemukan",
},
{ status: 404 }
);
}
const result = await prisma.user.update({
where: {
id: id,
},
data: {
isActive: !isActive,
},
select: {
id: true,
idGroup: true,
},
});
// create log user
const log = await createLogUser({ act: 'UPDATE', desc: 'User mengupdate status anggota', table: 'user', data: id })
return NextResponse.json(
{
success: true,
message: "Berhasil mengupdate status anggota",
data: result,
},
{ status: 200 }
);
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal mengupdate status anggota, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
}
}
// UPDATE MEMBER
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 body = await request.formData()
const file = body.get("file") as File
const data = body.get("data")
const {
name,
email,
phone,
nik,
gender,
idGroup,
idPosition,
idUserRole
} = JSON.parse(data as string)
const cekNIK = await prisma.user.count({
where: {
nik: nik,
NOT: {
id: id
}
},
});
const cekEmail = await prisma.user.count({
where: {
email: email,
NOT: {
id: id
}
},
});
const cekPhone = await prisma.user.count({
where: {
phone: "62" + phone,
NOT: {
id: id
}
},
});
if (cekNIK == 0 && cekEmail == 0 && cekPhone == 0) {
const updates = await prisma.user.update({
where: {
id: id
},
data: {
nik: nik,
name: name,
phone: "62" + phone,
email: email,
gender: gender,
idGroup: idGroup,
idPosition: idPosition,
idUserRole: idUserRole,
},
select: {
img: true
}
});
if (String(file) != "undefined" && String(file) != "null") {
const fExt = file.name.split(".").pop()
const fileName = id + '.' + fExt;
// Resize ukuran
const imageBuffer = await file.arrayBuffer();
const resize = await sharp(imageBuffer).resize(300).toBuffer();
// Convert buffer ke Blob
const blob = new Blob([resize], { type: file.type });
// Convert Blob ke File
const resizedFile = new File([blob], fileName, {
type: file.type,
lastModified: new Date().getTime(),
});
// const newFile = new File([file], fileName, { type: file.type });
await funDeleteFile({ fileId: String(updates.img) })
const upload = await funUploadFile({ file: resizedFile, dirId: DIR.user })
await prisma.user.update({
where: {
id: id
},
data: {
img: upload.data.id
}
})
}
// create log user
const log = await createLogUser({ act: 'UPDATE', desc: 'User mengupdate data anggota', table: 'user', data: user.id })
return Response.json(
{ success: true, message: "Sukses update anggota" },
{ status: 200 }
);
} else {
return Response.json({ success: false, message: "Anggota sudah ada" }, { status: 400 });
}
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal mengupdate data anggota, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
}
}

View File

@@ -0,0 +1,168 @@
import { DIR, funDeleteFile, funUploadFile, prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } from "@/module/user";
import _ from "lodash";
import { NextResponse } from "next/server";
import sharp from "sharp";
// GET PROFILE BY COOKIES
export async function GET(request: Request) {
try {
const user = await funGetUserByCookies()
if (user.id == undefined) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const data = await prisma.user.findUnique({
where: {
id: user.id
},
select: {
id: true,
idUserRole: true,
name: true,
email: true,
phone: true,
nik: true,
gender: true,
idGroup: true,
idPosition: true,
img: true,
Group: {
select: {
name: true
}
},
Position: {
select: {
name: true
}
},
UserRole:{
select:{
name: true
}
}
}
})
const { ...userData } = data;
const group = data?.Group.name
const position = data?.Position?.name
const phone = data?.phone.substr(2)
const role = data?.UserRole.name
const omitData = _.omit(data, ["Group", "Position", "phone", "UserRole"]);
const result = { ...userData, group, position, phone, role };
return NextResponse.json({ success: true, data: result });
} catch (error) {
return NextResponse.json({ success: false, message: "Gagal mendapatkan data profile (error: 500)" }, { status: 500 });
}
}
// UPDATE PROFILE BY COOKIES
export async function PUT(request: Request) {
try {
const user = await funGetUserByCookies()
if (user.id == undefined) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const body = await request.formData()
const file = body.get("file") as File;
const data = body.get("data");
const { name, email, phone, nik, gender, idPosition } = 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: "62" + phone,
nik: nik,
gender: gender,
idPosition: idPosition
},
select: {
img: true
}
})
if (String(file) != "undefined" && String(file) != "null") {
const fExt = file.name.split(".").pop()
const fileName = user.id + '.' + fExt;
// Resize ukuran
const imageBuffer = await file.arrayBuffer();
const resize = await sharp(imageBuffer).resize(300).toBuffer();
// Convert buffer ke Blob
const blob = new Blob([resize], { type: file.type });
// Convert Blob ke File
const resizedFile = new File([blob], fileName, {
type: file.type,
lastModified: new Date().getTime(),
});
// const newFile = new File([file], fileName, { type: file.type });
await funDeleteFile({ fileId: String(update.img) })
const upload = await funUploadFile({ file: resizedFile, dirId: DIR.user })
if (upload.success) {
await prisma.user.update({
where: {
id: user.id
},
data: {
img: upload.data.id
}
})
}
}
const log = await createLogUser({ act: 'UPDATE', desc: 'User mengupdate data profile', table: 'user', data: user.id })
return NextResponse.json({ success: true, message: "Berhasil ubah profile" });
} catch (error) {
return NextResponse.json({ success: false, message: "Gagal mengubah profile (error: 500)" }, { status: 500 });
}
}

View File

@@ -0,0 +1,245 @@
import { DIR, funUploadFile, prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } from "@/module/user";
import _ from "lodash";
import { NextResponse } from "next/server";
import sharp from "sharp";
// GET ALL MEMBER / USER
export async function GET(request: Request) {
try {
let fixGroup
const { searchParams } = new URL(request.url);
const name = searchParams.get('search')
const idGroup = searchParams.get("group");
const active = searchParams.get("active");
const page = searchParams.get('page');
const dataSkip = Number(page) * 10 - 10;
const user = await funGetUserByCookies()
if (user.id == undefined) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
if (idGroup == "null" || idGroup == undefined || idGroup == "") {
fixGroup = user.idGroup
} else {
fixGroup = idGroup
}
const filter = await prisma.group.findUnique({
where: {
id: fixGroup
},
select: {
id: true,
name: true
}
})
if (page != undefined) {
const users = await prisma.user.findMany({
skip: dataSkip,
take: 10,
where: {
isActive: active == 'false' ? false : true,
idGroup: String(fixGroup),
name: {
contains: (name == undefined || name == null) ? "" : name,
mode: "insensitive",
},
NOT: {
idUserRole: 'developer'
}
},
select: {
id: true,
idUserRole: true,
isActive: true,
nik: true,
name: true,
phone: true,
email: true,
gender: true,
img: true,
Position: {
select: {
name: true,
},
},
Group: {
select: {
name: true,
},
},
},
orderBy: {
name: 'asc'
}
});
const allData = users.map((v: any) => ({
..._.omit(v, ["Group", "Position"]),
group: v.Group.name,
position: v?.Position?.name
}))
return NextResponse.json({ success: true, message: "Berhasil member", data: allData, filter }, { status: 200 });
} else {
const users = await prisma.user.findMany({
where: {
isActive: active == 'false' ? false : true,
idGroup: String(fixGroup),
name: {
contains: (name == undefined || name == null) ? "" : name,
mode: "insensitive",
},
NOT: {
idUserRole: 'developer'
}
},
select: {
id: true,
idUserRole: true,
isActive: true,
nik: true,
name: true,
phone: true,
email: true,
gender: true,
img: true,
Position: {
select: {
name: true,
},
},
Group: {
select: {
name: true,
},
},
},
orderBy: {
name: 'asc'
}
});
const allData = users.map((v: any) => ({
..._.omit(v, ["Group", "Position"]),
group: v.Group.name,
position: v?.Position?.name
}))
return NextResponse.json({ success: true, message: "Berhasil member", data: allData, filter }, { status: 200 });
}
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal mendapatkan anggota, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
}
}
// CREATE MEMBER / USER
export async function POST(request: Request) {
try {
const user = await funGetUserByCookies()
if (user.id == undefined) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const body = await request.formData()
const data = JSON.parse(body.get("data") as string)
const file = body.get("file") as File
const village = String(user.idVillage)
let groupFix = data.idGroup
if (groupFix == null || groupFix == undefined || groupFix == "") {
groupFix = user.idGroup
}
const cekNIK = await prisma.user.count({
where: {
nik: data.nik
},
});
const cekEmail = await prisma.user.count({
where: {
email: data.email
},
});
const cekPhone = await prisma.user.count({
where: {
phone: "62" + data.phone
},
});
if (cekNIK == 0 && cekEmail == 0 && cekPhone == 0) {
const users = await prisma.user.create({
data: {
nik: data.nik,
name: data.name,
phone: "62" + data.phone,
email: data.email,
gender: data.gender,
idGroup: groupFix,
idVillage: village,
idPosition: data.idPosition,
idUserRole: data.idUserRole,
},
select: {
id: true,
idGroup: true,
},
});
if (String(file) != "undefined" && String(file) != "null") {
const fExt = file.name.split(".").pop()
const fileName = user.id + '.' + fExt;
// Resize ukuran
const imageBuffer = await file.arrayBuffer();
const resize = await sharp(imageBuffer).resize(300).toBuffer();
// Convert buffer ke Blob
const blob = new Blob([resize], { type: file.type });
// Convert Blob ke File
const resizedFile = new File([blob], fileName, {
type: file.type,
lastModified: new Date().getTime(),
});
// const newFile = new File([file], fileName, { type: file.type });
const upload = await funUploadFile({ file: resizedFile, dirId: DIR.user })
if (upload.success) {
await prisma.user.update({
where: {
id: users.id
},
data: {
img: upload.data.id
}
})
}
}
// create log user
const log = await createLogUser({ act: 'CREATE', desc: 'User membuat data user baru', table: 'user', data: users.id })
return Response.json({ success: true, message: 'Sukses membuat user', data: users }, { status: 200 });
} else {
return Response.json({ success: false, message: "User sudah ada" }, { status: 400 });
}
} catch (error) {
console.error(error);
return Response.json({ success: false, message: "Gagal membuat anggota, coba lagi nanti (error: 500)" }, { status: 500 });
}
}