Compare commits
15 Commits
3b5126d8ee
...
join
| Author | SHA1 | Date | |
|---|---|---|---|
| af504c95c0 | |||
| adee3f9e45 | |||
| 0957e554a1 | |||
| 8f38ede650 | |||
| 8a938257b7 | |||
| 026e07ac78 | |||
| 928acf2c03 | |||
| a14f07b928 | |||
| 1e02747e22 | |||
| a0bffd53cb | |||
| 8dca3e440f | |||
| 1df1d10c91 | |||
| e5891f0da3 | |||
| 619cc9a403 | |||
| 3272ecaef3 |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sistem-desa-mandiri",
|
"name": "sistem-desa-mandiri",
|
||||||
"version": "0.1.18",
|
"version": "0.1.19",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev --experimental-https",
|
"dev": "next dev --experimental-https",
|
||||||
|
|||||||
1
prisma/migrations/20260530064416_auto/migration.sql
Normal file
1
prisma/migrations/20260530064416_auto/migration.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
-- This is an empty migration.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "DiscussionCommentFile" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"idComment" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"extension" TEXT NOT NULL,
|
||||||
|
"idStorage" TEXT,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "DiscussionCommentFile_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "DiscussionCommentFile" ADD CONSTRAINT "DiscussionCommentFile_idComment_fkey" FOREIGN KEY ("idComment") REFERENCES "DiscussionComment"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
@@ -669,16 +669,29 @@ model DiscussionMember {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model DiscussionComment {
|
model DiscussionComment {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
Discussion Discussion @relation(fields: [idDiscussion], references: [id])
|
Discussion Discussion @relation(fields: [idDiscussion], references: [id])
|
||||||
idDiscussion String
|
idDiscussion String
|
||||||
User User @relation(fields: [idUser], references: [id])
|
User User @relation(fields: [idUser], references: [id])
|
||||||
idUser String
|
idUser String
|
||||||
comment String @db.Text
|
comment String @db.Text
|
||||||
isActive Boolean @default(true)
|
isActive Boolean @default(true)
|
||||||
isEdited Boolean @default(false)
|
isEdited Boolean @default(false)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
DiscussionCommentFile DiscussionCommentFile[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model DiscussionCommentFile {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
Comment DiscussionComment @relation(fields: [idComment], references: [id])
|
||||||
|
idComment String
|
||||||
|
name String
|
||||||
|
extension String
|
||||||
|
idStorage String?
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
model DiscussionFile {
|
model DiscussionFile {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { prisma } from "@/module/_global";
|
import { DIR, funDeleteFile, funUploadFile, prisma } from "@/module/_global";
|
||||||
import { funGetUserById } from "@/module/auth";
|
import { funGetUserById } from "@/module/auth";
|
||||||
import { createLogUserMobile } from "@/module/user";
|
import { createLogUserMobile } from "@/module/user";
|
||||||
import _ from "lodash";
|
import _ from "lodash";
|
||||||
@@ -10,7 +10,16 @@ import { sendFCMNotificationMany } from "../../../../../../../xsendMany";
|
|||||||
export async function POST(request: Request, context: { params: { id: string } }) {
|
export async function POST(request: Request, context: { params: { id: string } }) {
|
||||||
try {
|
try {
|
||||||
const { id } = context.params
|
const { id } = context.params
|
||||||
const { desc, user } = (await request.json());
|
const contentType = request.headers.get("content-type")
|
||||||
|
let desc, user, cekFile, body: FormData | undefined
|
||||||
|
if (contentType?.includes("multipart/form-data")) {
|
||||||
|
body = await request.formData()
|
||||||
|
const dataBody = body.get("data")
|
||||||
|
cekFile = body.has("file0")
|
||||||
|
;({ desc, user } = JSON.parse(dataBody as string))
|
||||||
|
} else {
|
||||||
|
;({ desc, user } = await request.json())
|
||||||
|
}
|
||||||
const userMobile = await funGetUserById({ id: String(user) })
|
const userMobile = await funGetUserById({ id: String(user) })
|
||||||
|
|
||||||
if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
|
if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
|
||||||
@@ -37,6 +46,28 @@ export async function POST(request: Request, context: { params: { id: string } }
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (cekFile && body) {
|
||||||
|
body.delete("data")
|
||||||
|
for (const pair of body.entries()) {
|
||||||
|
if (String(pair[0]).substring(0, 4) == "file") {
|
||||||
|
const file = body.get(pair[0]) as File
|
||||||
|
const fExt = file.name.split(".").pop()
|
||||||
|
const fName = decodeURIComponent(file.name.replace("." + fExt, ""))
|
||||||
|
const upload = await funUploadFile({ file, dirId: DIR.discussion })
|
||||||
|
if (upload.success) {
|
||||||
|
await prisma.discussionCommentFile.create({
|
||||||
|
data: {
|
||||||
|
idComment: data.id,
|
||||||
|
name: fName,
|
||||||
|
extension: String(fExt),
|
||||||
|
idStorage: upload.data.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const dataDiscussion = await prisma.discussion.findUnique({
|
const dataDiscussion = await prisma.discussion.findUnique({
|
||||||
where: {
|
where: {
|
||||||
id
|
id
|
||||||
@@ -153,7 +184,7 @@ export async function POST(request: Request, context: { params: { id: string } }
|
|||||||
export async function PUT(request: Request, context: { params: { id: string } }) {
|
export async function PUT(request: Request, context: { params: { id: string } }) {
|
||||||
try {
|
try {
|
||||||
const { id } = context.params
|
const { id } = context.params
|
||||||
const { desc, user } = (await request.json());
|
const { desc, user, filesToRemove = [] } = (await request.json());
|
||||||
const userMobile = await funGetUserById({ id: String(user) })
|
const userMobile = await funGetUserById({ id: String(user) })
|
||||||
|
|
||||||
if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
|
if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
|
||||||
@@ -161,25 +192,30 @@ export async function PUT(request: Request, context: { params: { id: string } })
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cek = await prisma.discussionComment.count({
|
const cek = await prisma.discussionComment.count({
|
||||||
where: {
|
where: { id, isActive: true }
|
||||||
id,
|
|
||||||
isActive: true
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if (cek == 0) {
|
if (cek == 0) {
|
||||||
return NextResponse.json({ success: false, message: "Gagal mengedit komentar, data tidak ditemukan" }, { status: 200 });
|
return NextResponse.json({ success: false, message: "Gagal mengedit komentar, data tidak ditemukan" }, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (filesToRemove.length > 0) {
|
||||||
const data = await prisma.discussionComment.update({
|
const files = await prisma.discussionCommentFile.findMany({
|
||||||
where: {
|
where: { id: { in: filesToRemove }, idComment: id, isActive: true },
|
||||||
id
|
select: { id: true, idStorage: true }
|
||||||
},
|
})
|
||||||
data: {
|
for (const file of files) {
|
||||||
comment: desc,
|
if (file.idStorage) await funDeleteFile({ fileId: file.idStorage })
|
||||||
isEdited: true
|
|
||||||
}
|
}
|
||||||
|
await prisma.discussionCommentFile.updateMany({
|
||||||
|
where: { id: { in: filesToRemove }, idComment: id },
|
||||||
|
data: { isActive: false }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.discussionComment.update({
|
||||||
|
where: { id },
|
||||||
|
data: { comment: desc, isEdited: true }
|
||||||
})
|
})
|
||||||
|
|
||||||
// create log user
|
// create log user
|
||||||
@@ -216,18 +252,30 @@ export async function DELETE(request: Request, context: { params: { id: string }
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const data = await prisma.discussionComment.update({
|
const commentFiles = await prisma.discussionCommentFile.findMany({
|
||||||
where: {
|
where: { idComment: id, isActive: true },
|
||||||
id
|
select: { id: true, idStorage: true }
|
||||||
},
|
})
|
||||||
data: {
|
|
||||||
isActive: false
|
for (const file of commentFiles) {
|
||||||
}
|
if (file.idStorage) await funDeleteFile({ fileId: file.idStorage })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (commentFiles.length > 0) {
|
||||||
|
await prisma.discussionCommentFile.updateMany({
|
||||||
|
where: { idComment: id },
|
||||||
|
data: { isActive: false }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.discussionComment.update({
|
||||||
|
where: { id },
|
||||||
|
data: { isActive: false }
|
||||||
})
|
})
|
||||||
|
|
||||||
// create log user
|
// create log user
|
||||||
const log = await createLogUserMobile({ act: 'DELETE', desc: 'User menghapus komentar pada diskusi umum', table: 'discussionComment', data: id, user: userMobile.id })
|
const log = await createLogUserMobile({ act: 'DELETE', desc: 'User menghapus komentar pada diskusi umum', table: 'discussionComment', data: id, user: userMobile.id })
|
||||||
return NextResponse.json({ success: true, message: "Berhasil mengedit komentar" }, { status: 200 });
|
return NextResponse.json({ success: true, message: "Berhasil menghapus komentar" }, { status: 200 });
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error)
|
console.error(error)
|
||||||
|
|||||||
@@ -76,6 +76,15 @@ export async function GET(request: Request, context: { params: { id: string } })
|
|||||||
name: true,
|
name: true,
|
||||||
img: true
|
img: true
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
DiscussionCommentFile: {
|
||||||
|
where: { isActive: true },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
extension: true,
|
||||||
|
idStorage: true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
orderBy: {
|
orderBy: {
|
||||||
@@ -84,11 +93,12 @@ export async function GET(request: Request, context: { params: { id: string } })
|
|||||||
})
|
})
|
||||||
|
|
||||||
dataFix = data.map((v: any) => ({
|
dataFix = data.map((v: any) => ({
|
||||||
..._.omit(v, ["createdAt", "User", "updatedAt"]),
|
..._.omit(v, ["createdAt", "User", "updatedAt", "DiscussionCommentFile"]),
|
||||||
createdAt: countTime(v.createdAt),
|
createdAt: countTime(v.createdAt),
|
||||||
updatedAt: moment(v.updatedAt).format("ll"),
|
updatedAt: moment(v.updatedAt).format("ll"),
|
||||||
username: v.User.name,
|
username: v.User.name,
|
||||||
img: v.User.img
|
img: v.User.img,
|
||||||
|
files: v.DiscussionCommentFile
|
||||||
}))
|
}))
|
||||||
|
|
||||||
} else if (kategori == "anggota") {
|
} else if (kategori == "anggota") {
|
||||||
|
|||||||
@@ -27,9 +27,6 @@ export async function GET(request: Request) {
|
|||||||
idUserTo: userMobile.id
|
idUserTo: userMobile.id
|
||||||
},
|
},
|
||||||
orderBy: [
|
orderBy: [
|
||||||
{
|
|
||||||
isRead: 'asc'
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
createdAt: 'desc'
|
createdAt: 'desc'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ export async function POST(request: Request, context: { params: { id: string } }
|
|||||||
if (String(pair[0]).substring(0, 4) == "file") {
|
if (String(pair[0]).substring(0, 4) == "file") {
|
||||||
const file = body.get(pair[0]) as File
|
const file = body.get(pair[0]) as File
|
||||||
const fExt = file.name.split(".").pop()
|
const fExt = file.name.split(".").pop()
|
||||||
const fName = file.name.replace("." + fExt, "")
|
const fName = decodeURIComponent(file.name.replace("." + fExt, ""))
|
||||||
|
|
||||||
const upload = await funUploadFile({ file: file, dirId: DIR.project })
|
const upload = await funUploadFile({ file: file, dirId: DIR.project })
|
||||||
if (upload.success) {
|
if (upload.success) {
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ export async function POST(request: Request, context: { params: { id: string } }
|
|||||||
|
|
||||||
const file = body.get(key) as File;
|
const file = body.get(key) as File;
|
||||||
const fExt = file.name.split(".").pop();
|
const fExt = file.name.split(".").pop();
|
||||||
const fName = file.name.replace("." + fExt, "");
|
const fName = decodeURIComponent(file.name.replace("." + fExt, ""));
|
||||||
|
|
||||||
const upload = await funUploadFile({ file, dirId: DIR.project });
|
const upload = await funUploadFile({ file, dirId: DIR.project });
|
||||||
if (!upload.success) continue;
|
if (!upload.success) continue;
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ export async function POST(request: Request, context: { params: { id: string } }
|
|||||||
if (String(pair[0]).substring(0, 4) == "file") {
|
if (String(pair[0]).substring(0, 4) == "file") {
|
||||||
const file = body.get(pair[0]) as File
|
const file = body.get(pair[0]) as File
|
||||||
const fExt = file.name.split(".").pop()
|
const fExt = file.name.split(".").pop()
|
||||||
const fName = file.name.replace("." + fExt, "")
|
const fName = decodeURIComponent(file.name.replace("." + fExt, ""))
|
||||||
|
|
||||||
|
|
||||||
const upload = await funUploadFile({ file: file, dirId: DIR.task })
|
const upload = await funUploadFile({ file: file, dirId: DIR.task })
|
||||||
|
|||||||
@@ -213,7 +213,7 @@ export async function POST(request: Request) {
|
|||||||
if (String(pair[0]).substring(0, 4) == "file") {
|
if (String(pair[0]).substring(0, 4) == "file") {
|
||||||
const file = body.get(pair[0]) as File
|
const file = body.get(pair[0]) as File
|
||||||
const fExt = file.name.split(".").pop()
|
const fExt = file.name.split(".").pop()
|
||||||
const fName = file.name.replace("." + fExt, "")
|
const fName = decodeURIComponent(file.name.replace("." + fExt, ""))
|
||||||
|
|
||||||
const upload = await funUploadFile({ file: file, dirId: DIR.task })
|
const upload = await funUploadFile({ file: file, dirId: DIR.task })
|
||||||
if (upload.success) {
|
if (upload.success) {
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ export async function POST(request: Request, context: { params: { id: string } }
|
|||||||
|
|
||||||
const file = body.get(key) as File;
|
const file = body.get(key) as File;
|
||||||
const fExt = file.name.split(".").pop();
|
const fExt = file.name.split(".").pop();
|
||||||
const fName = file.name.replace("." + fExt, "");
|
const fName = decodeURIComponent(file.name.replace("." + fExt, ""));
|
||||||
|
|
||||||
const upload = await funUploadFile({ file, dirId: DIR.task });
|
const upload = await funUploadFile({ file, dirId: DIR.task });
|
||||||
if (!upload.success) continue;
|
if (!upload.success) continue;
|
||||||
|
|||||||
@@ -1149,6 +1149,7 @@ const MonitoringServer = new Elysia({ prefix: "/api/monitoring" })
|
|||||||
name: true,
|
name: true,
|
||||||
Village: {
|
Village: {
|
||||||
select: {
|
select: {
|
||||||
|
id: true,
|
||||||
name: true,
|
name: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1171,6 +1172,7 @@ const MonitoringServer = new Elysia({ prefix: "/api/monitoring" })
|
|||||||
desc: item.desc,
|
desc: item.desc,
|
||||||
username: item.User.name,
|
username: item.User.name,
|
||||||
village: item.User.Village.name,
|
village: item.User.Village.name,
|
||||||
|
idVillage: item.User.Village.id,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
||||||
@@ -1274,6 +1276,11 @@ const MonitoringServer = new Elysia({ prefix: "/api/monitoring" })
|
|||||||
name: true,
|
name: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
UserLog: {
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
select: { createdAt: true },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
orderBy: {
|
orderBy: {
|
||||||
[safeOrderBy]: safeOrderDir,
|
[safeOrderBy]: safeOrderDir,
|
||||||
@@ -1302,6 +1309,7 @@ const MonitoringServer = new Elysia({ prefix: "/api/monitoring" })
|
|||||||
idVillage: item.idVillage,
|
idVillage: item.idVillage,
|
||||||
idGroup: item.idGroup,
|
idGroup: item.idGroup,
|
||||||
idPosition: item.idPosition,
|
idPosition: item.idPosition,
|
||||||
|
lastActivity: item.UserLog[0]?.createdAt ?? null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1504,6 +1512,439 @@ const MonitoringServer = new Elysia({ prefix: "/api/monitoring" })
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
.get("/stale-villages", async ({ query, set }) => {
|
||||||
|
const VALID_DAYS = [7, 14, 30];
|
||||||
|
const days = VALID_DAYS.includes(Number(query.days)) ? Number(query.days) : 7;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await prisma.$queryRaw`
|
||||||
|
SELECT
|
||||||
|
v."id",
|
||||||
|
v."name",
|
||||||
|
MAX(ul."createdAt") AS "lastActivity"
|
||||||
|
FROM "Village" v
|
||||||
|
LEFT JOIN "User" u ON u."idVillage" = v."id" AND u."idUserRole" != 'developer'
|
||||||
|
LEFT JOIN "UserLog" ul ON ul."idUser" = u."id"
|
||||||
|
WHERE v."isDummy" = false AND v."isActive" = true
|
||||||
|
GROUP BY v."id", v."name"
|
||||||
|
HAVING MAX(ul."createdAt") < NOW() - (${days} * INTERVAL '1 day')
|
||||||
|
OR MAX(ul."createdAt") IS NULL
|
||||||
|
ORDER BY "lastActivity" ASC NULLS FIRST
|
||||||
|
` as any[];
|
||||||
|
|
||||||
|
const result = data.map((v: any) => ({
|
||||||
|
id: v.id,
|
||||||
|
name: v.name,
|
||||||
|
lastActivity: v.lastActivity ?? null,
|
||||||
|
daysSince: v.lastActivity
|
||||||
|
? Math.floor((Date.now() - new Date(v.lastActivity).getTime()) / (1000 * 60 * 60 * 24))
|
||||||
|
: null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Berhasil mendapatkan data",
|
||||||
|
data: {
|
||||||
|
count: result.length,
|
||||||
|
days,
|
||||||
|
villages: result,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[stale-villages] error:", error);
|
||||||
|
set.status = 500;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Terjadi kesalahan pada server",
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
query: t.Object({
|
||||||
|
days: t.Optional(t.String({ description: "Threshold hari tidak aktif: 7, 14, atau 30 (default: 7)" })),
|
||||||
|
}),
|
||||||
|
detail: {
|
||||||
|
summary: "Stale Villages",
|
||||||
|
description: "Mendapatkan daftar desa aktif yang tidak ada aktivitas dalam X hari terakhir (atau belum pernah ada aktivitas sama sekali).",
|
||||||
|
tags: ["villages"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
.get("/inactive-users", async ({ query, set }) => {
|
||||||
|
const VALID_DAYS = [7, 14, 30];
|
||||||
|
const days = VALID_DAYS.includes(Number(query.days)) ? Number(query.days) : 7;
|
||||||
|
const pageNum = Number(query.page ?? 1) || 1;
|
||||||
|
const take = 15;
|
||||||
|
const { idVillage } = query;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const users = await prisma.user.findMany({
|
||||||
|
where: {
|
||||||
|
idUserRole: { not: 'developer' },
|
||||||
|
...(idVillage && { idVillage }),
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
nik: true,
|
||||||
|
email: true,
|
||||||
|
phone: true,
|
||||||
|
gender: true,
|
||||||
|
isActive: true,
|
||||||
|
isWithoutOTP: true,
|
||||||
|
isApprover: true,
|
||||||
|
idUserRole: true,
|
||||||
|
idVillage: true,
|
||||||
|
idGroup: true,
|
||||||
|
idPosition: true,
|
||||||
|
UserRole: { select: { name: true } },
|
||||||
|
Village: { select: { id: true, name: true } },
|
||||||
|
Group: { select: { name: true } },
|
||||||
|
Position: { select: { name: true } },
|
||||||
|
UserLog: {
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
select: { createdAt: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const threshold = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||||
|
|
||||||
|
const inactive = users
|
||||||
|
.map((u) => ({
|
||||||
|
id: u.id,
|
||||||
|
name: u.name,
|
||||||
|
nik: u.nik,
|
||||||
|
email: u.email,
|
||||||
|
phone: u.phone,
|
||||||
|
gender: u.gender,
|
||||||
|
isActive: u.isActive,
|
||||||
|
isWithoutOTP: u.isWithoutOTP,
|
||||||
|
isApprover: u.isApprover,
|
||||||
|
role: u.UserRole?.name ?? null,
|
||||||
|
idUserRole: u.idUserRole,
|
||||||
|
village: u.Village?.name ?? null,
|
||||||
|
idVillage: u.Village?.id ?? null,
|
||||||
|
group: u.Group?.name ?? null,
|
||||||
|
position: u.Position?.name ?? null,
|
||||||
|
idGroup: u.idGroup,
|
||||||
|
idPosition: u.idPosition,
|
||||||
|
lastActivity: u.UserLog[0]?.createdAt ?? null,
|
||||||
|
daysSince: u.UserLog[0]?.createdAt
|
||||||
|
? Math.floor((Date.now() - u.UserLog[0].createdAt.getTime()) / (1000 * 60 * 60 * 24))
|
||||||
|
: null,
|
||||||
|
}))
|
||||||
|
.filter((u) => u.lastActivity === null || u.lastActivity < threshold)
|
||||||
|
.sort((a, b) => {
|
||||||
|
if (a.lastActivity === null) return -1;
|
||||||
|
if (b.lastActivity === null) return 1;
|
||||||
|
return a.lastActivity.getTime() - b.lastActivity.getTime();
|
||||||
|
});
|
||||||
|
|
||||||
|
const total = inactive.length;
|
||||||
|
const paginated = inactive.slice((pageNum - 1) * take, pageNum * take);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Berhasil mendapatkan data",
|
||||||
|
data: {
|
||||||
|
users: paginated,
|
||||||
|
total,
|
||||||
|
totalPage: Math.ceil(total / take),
|
||||||
|
currentPage: pageNum,
|
||||||
|
days,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[inactive-users] error:", error);
|
||||||
|
set.status = 500;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Terjadi kesalahan pada server",
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
query: t.Object({
|
||||||
|
days: t.Optional(t.String({ description: "Threshold hari tidak aktif: 7, 14, atau 30 (default: 7)" })),
|
||||||
|
idVillage: t.Optional(t.String({ description: "Filter berdasarkan ID desa" })),
|
||||||
|
page: t.Optional(t.String({ description: "Halaman (default: 1)" })),
|
||||||
|
}),
|
||||||
|
detail: {
|
||||||
|
summary: "Inactive Users",
|
||||||
|
description: "Mendapatkan daftar user yang tidak ada aktivitas dalam X hari terakhir, atau belum pernah ada aktivitas sama sekali.",
|
||||||
|
tags: ["user"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
.get("/peak-hours", async ({ query, set }) => {
|
||||||
|
const { idVillage } = query;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await prisma.$queryRaw`
|
||||||
|
SELECT
|
||||||
|
EXTRACT(HOUR FROM ul."createdAt")::int AS hour,
|
||||||
|
COUNT(*)::int AS count
|
||||||
|
FROM "UserLog" ul
|
||||||
|
JOIN "User" u ON ul."idUser" = u."id"
|
||||||
|
WHERE (${idVillage ?? null}::text IS NULL OR u."idVillage" = ${idVillage ?? null})
|
||||||
|
GROUP BY hour
|
||||||
|
ORDER BY hour
|
||||||
|
` as { hour: number; count: number }[];
|
||||||
|
|
||||||
|
const map = new Map(data.map((d) => [d.hour, d.count]));
|
||||||
|
const result = Array.from({ length: 24 }, (_, i) => ({
|
||||||
|
hour: i,
|
||||||
|
label: `${String(i).padStart(2, '0')}:00`,
|
||||||
|
count: map.get(i) ?? 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const peak = result.reduce((max, item) => (item.count > max.count ? item : max), result[0]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Berhasil mendapatkan data",
|
||||||
|
data: {
|
||||||
|
hours: result,
|
||||||
|
peak,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[peak-hours] error:", error);
|
||||||
|
set.status = 500;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Terjadi kesalahan pada server",
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
query: t.Object({
|
||||||
|
idVillage: t.Optional(t.String({ description: "ID desa (kosong = semua desa)" })),
|
||||||
|
}),
|
||||||
|
detail: {
|
||||||
|
summary: "Peak Hours",
|
||||||
|
description: "Mendapatkan distribusi aktivitas per jam dalam sehari (0-23) untuk desa tertentu atau semua desa.",
|
||||||
|
tags: ["villages"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// ─── CSV EXPORT ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
.get("/export-logs", async ({ query, set }) => {
|
||||||
|
const { search, action, idVillage, dateFrom, dateTo } = query;
|
||||||
|
|
||||||
|
const whereClause = {
|
||||||
|
...(action && { action: action.toUpperCase() }),
|
||||||
|
...(idVillage && { User: { idVillage } }),
|
||||||
|
...((dateFrom || dateTo) && {
|
||||||
|
createdAt: {
|
||||||
|
...(dateFrom && { gte: new Date(dateFrom) }),
|
||||||
|
...(dateTo && { lte: new Date(new Date(dateTo).setHours(23, 59, 59, 999)) }),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
...(search && {
|
||||||
|
OR: [
|
||||||
|
{ User: { name: { contains: search, mode: "insensitive" as const } } },
|
||||||
|
{ User: { Village: { name: { contains: search, mode: "insensitive" as const } } } },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await prisma.userLog.findMany({
|
||||||
|
where: whereClause,
|
||||||
|
select: {
|
||||||
|
createdAt: true,
|
||||||
|
action: true,
|
||||||
|
desc: true,
|
||||||
|
User: {
|
||||||
|
select: {
|
||||||
|
name: true,
|
||||||
|
Village: { select: { name: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = data.map((item) => ({
|
||||||
|
timestamp: moment(item.createdAt).format('DD MMM YYYY HH:mm'),
|
||||||
|
username: item.User.name,
|
||||||
|
village: item.User.Village.name,
|
||||||
|
action: item.action,
|
||||||
|
desc: item.desc,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { success: true, data: result };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[export-logs] error:", error);
|
||||||
|
set.status = 500;
|
||||||
|
return { success: false, message: "Terjadi kesalahan pada server", data: null };
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
query: t.Object({
|
||||||
|
search: t.Optional(t.String()),
|
||||||
|
action: t.Optional(t.String()),
|
||||||
|
idVillage: t.Optional(t.String()),
|
||||||
|
dateFrom: t.Optional(t.String()),
|
||||||
|
dateTo: t.Optional(t.String()),
|
||||||
|
}),
|
||||||
|
detail: { summary: "Export Logs CSV", tags: ["log-activity"] },
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/export-users", async ({ query, set }) => {
|
||||||
|
const { search, isActive, idUserRole, idVillage } = query;
|
||||||
|
|
||||||
|
const whereClause = {
|
||||||
|
...(isActive !== undefined && { isActive: isActive === 'true' }),
|
||||||
|
...(idUserRole && { idUserRole }),
|
||||||
|
...(idVillage && { idVillage }),
|
||||||
|
...(search && {
|
||||||
|
OR: [
|
||||||
|
{ name: { contains: search, mode: "insensitive" as const } },
|
||||||
|
{ phone: { contains: search, mode: "insensitive" as const } },
|
||||||
|
{ email: { contains: search, mode: "insensitive" as const } },
|
||||||
|
{ nik: { contains: search, mode: "insensitive" as const } },
|
||||||
|
{ Village: { name: { contains: search, mode: "insensitive" as const } } },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await prisma.user.findMany({
|
||||||
|
where: whereClause,
|
||||||
|
select: {
|
||||||
|
name: true,
|
||||||
|
nik: true,
|
||||||
|
phone: true,
|
||||||
|
email: true,
|
||||||
|
gender: true,
|
||||||
|
isActive: true,
|
||||||
|
UserRole: { select: { name: true } },
|
||||||
|
Village: { select: { name: true } },
|
||||||
|
Group: { select: { name: true } },
|
||||||
|
Position: { select: { name: true } },
|
||||||
|
UserLog: {
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
select: { createdAt: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = data.map((item) => ({
|
||||||
|
name: item.name,
|
||||||
|
nik: item.nik,
|
||||||
|
email: item.email,
|
||||||
|
phone: item.phone,
|
||||||
|
gender: item.gender === 'M' ? 'Male' : item.gender === 'F' ? 'Female' : item.gender,
|
||||||
|
role: item.UserRole?.name ?? '',
|
||||||
|
village: item.Village?.name ?? '',
|
||||||
|
group: item.Group?.name ?? '',
|
||||||
|
position: item.Position?.name ?? '',
|
||||||
|
status: item.isActive ? 'Active' : 'Inactive',
|
||||||
|
lastActivity: item.UserLog[0]?.createdAt ? moment(item.UserLog[0].createdAt).format('DD MMM YYYY HH:mm') : '',
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { success: true, data: result };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[export-users] error:", error);
|
||||||
|
set.status = 500;
|
||||||
|
return { success: false, message: "Terjadi kesalahan pada server", data: null };
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
query: t.Object({
|
||||||
|
search: t.Optional(t.String()),
|
||||||
|
isActive: t.Optional(t.String()),
|
||||||
|
idUserRole: t.Optional(t.String()),
|
||||||
|
idVillage: t.Optional(t.String()),
|
||||||
|
}),
|
||||||
|
detail: { summary: "Export Users CSV", tags: ["user"] },
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/village-report", async ({ query, set }) => {
|
||||||
|
const VALID_RANGES = [7, 30, 90];
|
||||||
|
const range = VALID_RANGES.includes(Number(query.range)) ? Number(query.range) : 7;
|
||||||
|
const doubleRange = range * 2;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await prisma.$queryRaw`
|
||||||
|
SELECT
|
||||||
|
v."id",
|
||||||
|
v."name",
|
||||||
|
v."isActive",
|
||||||
|
COUNT(CASE WHEN ul."createdAt" >= NOW() - (${range} * INTERVAL '1 day') THEN 1 END)::int AS activity_count,
|
||||||
|
COUNT(CASE WHEN ul."createdAt" < NOW() - (${range} * INTERVAL '1 day') THEN 1 END)::int AS prev_activity_count,
|
||||||
|
MAX(ul."createdAt") AS last_activity,
|
||||||
|
(
|
||||||
|
SELECT u2."name" FROM "User" u2
|
||||||
|
WHERE u2."idVillage" = v."id" AND u2."idUserRole" = 'supadmin'
|
||||||
|
LIMIT 1
|
||||||
|
) AS perbekel,
|
||||||
|
(
|
||||||
|
SELECT COUNT(*)::int FROM "User" u3
|
||||||
|
WHERE u3."idVillage" = v."id" AND u3."isActive" = true AND u3."idUserRole" != 'developer'
|
||||||
|
) AS active_users,
|
||||||
|
(
|
||||||
|
SELECT COUNT(*)::int FROM "User" u4
|
||||||
|
WHERE u4."idVillage" = v."id" AND u4."isActive" = false AND u4."idUserRole" != 'developer'
|
||||||
|
) AS inactive_users
|
||||||
|
FROM "Village" v
|
||||||
|
LEFT JOIN "User" u ON u."idVillage" = v."id" AND u."idUserRole" != 'developer'
|
||||||
|
LEFT JOIN "UserLog" ul ON ul."idUser" = u."id"
|
||||||
|
AND ul."createdAt" >= NOW() - (${doubleRange} * INTERVAL '1 day')
|
||||||
|
WHERE v."isDummy" = false
|
||||||
|
GROUP BY v."id", v."name", v."isActive"
|
||||||
|
ORDER BY activity_count DESC, v."name" ASC
|
||||||
|
` as any[];
|
||||||
|
|
||||||
|
const result = data.map((v: any) => {
|
||||||
|
const curr = Number(v.activity_count);
|
||||||
|
const prev = Number(v.prev_activity_count);
|
||||||
|
const trend = prev > 0 ? Math.round(((curr - prev) / prev) * 100) : curr > 0 ? 100 : 0;
|
||||||
|
return {
|
||||||
|
id: v.id,
|
||||||
|
name: v.name,
|
||||||
|
isActive: v.isActive,
|
||||||
|
perbekel: v.perbekel ?? '-',
|
||||||
|
activeUsers: Number(v.active_users),
|
||||||
|
inactiveUsers: Number(v.inactive_users),
|
||||||
|
activityCount: curr,
|
||||||
|
prevActivityCount: prev,
|
||||||
|
trend,
|
||||||
|
lastActivity: v.last_activity ? moment(v.last_activity).format('DD MMM YYYY HH:mm') : null,
|
||||||
|
daysSince: v.last_activity
|
||||||
|
? Math.floor((Date.now() - new Date(v.last_activity).getTime()) / (1000 * 60 * 60 * 24))
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Berhasil mendapatkan data",
|
||||||
|
data: { villages: result, range, generatedAt: moment().format('DD MMM YYYY HH:mm') },
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[village-report] error:", error);
|
||||||
|
set.status = 500;
|
||||||
|
return { success: false, message: "Terjadi kesalahan pada server", data: null };
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
query: t.Object({
|
||||||
|
range: t.Optional(t.String({ description: "Rentang hari: 7, 30, atau 90 (default: 7)" })),
|
||||||
|
}),
|
||||||
|
detail: { summary: "Village Report", description: "Data semua desa untuk keperluan laporan PDF.", tags: ["villages"] },
|
||||||
|
})
|
||||||
|
|
||||||
// ─── API KEY MANAGEMENT ──────────────────────────────────────────────────
|
// ─── API KEY MANAGEMENT ──────────────────────────────────────────────────
|
||||||
|
|
||||||
.get("/api-keys", async ({ set }) => {
|
.get("/api-keys", async ({ set }) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user