Compare commits

...

36 Commits

Author SHA1 Message Date
67db39ccee feat: tambah dukungan file attachment, hapus file, dan response files pada komentar diskusi divisi 2026-06-10 15:00:35 +08:00
076e7f564f feat: tambah model DivisionDiscussionCommentFile pada schema prisma 2026-06-10 15:00:31 +08:00
af504c95c0 Merge pull request 'amalia/09-jun-26' (#56) from amalia/09-jun-26 into join
Reviewed-on: #56
2026-06-09 17:44:08 +08:00
adee3f9e45 feat: hapus file dari storage saat komentar dihapus atau diedit
- DELETE: soft-delete DiscussionCommentFile dan hapus file dari storage via funDeleteFile
- PUT: terima filesToRemove[], hapus file dari storage dan soft-delete record terkait
- Backward compatible: app lama tanpa filesToRemove tidak terpengaruh
2026-06-09 17:35:46 +08:00
0957e554a1 feat: tambah model DiscussionCommentFile dan endpoint attachment komentar
- Tambah model DiscussionCommentFile dengan relasi ke DiscussionComment
- Jalankan migrasi 20260609083038_add_discussion_comment_file
- POST komentar mendukung multipart/form-data untuk upload file (backward compatible)
- GET cat=komentar menyertakan data DiscussionCommentFile dalam response
2026-06-09 17:35:38 +08:00
8f38ede650 Merge pull request 'amalia/08-jun-26' (#55) from amalia/08-jun-26 into join
Reviewed-on: #55
2026-06-08 17:28:48 +08:00
8a938257b7 fix: ubah orderBy notifikasi ke createdAt desc agar pagination urut tanggal terbaru 2026-06-08 14:42:22 +08:00
026e07ac78 fix: decode URI component pada nama file upload di endpoint mobile 2026-06-08 11:22:28 +08:00
928acf2c03 bump: version 0.1.19 + migration 2026-05-30 14:44:16 +08:00
a14f07b928 Merge pull request 'amalia/28-mei-26' (#54) from amalia/28-mei-26 into join
Reviewed-on: #54
2026-05-28 17:24:09 +08:00
1e02747e22 feat: tambahkan village-report endpoint dengan perbandingan periode sebelumnya
- Endpoint /village-report kini menghitung activity_count periode saat ini
  dan prev_activity_count periode sebelumnya dalam satu query (doubleRange)
- Tambahkan kalkulasi trend persentase perubahan antar periode
- Sertakan data perbekel, active_users, inactive_users, lastActivity, dan daysSince
- Tambahkan endpoint /export-logs dan /export-users untuk ekspor CSV
2026-05-28 15:39:47 +08:00
a0bffd53cb feat: tambah endpoint export-logs dan export-users untuk CSV download 2026-05-28 15:06:23 +08:00
8dca3e440f feat: tambah endpoint peak-hours untuk distribusi aktivitas per jam 2026-05-28 14:47:11 +08:00
1df1d10c91 feat: tambah endpoint inactive-users dan lengkapi field response-nya 2026-05-28 14:32:49 +08:00
e5891f0da3 feat: tambah idVillage ke response log-all-villages 2026-05-28 14:18:03 +08:00
619cc9a403 feat: tambah endpoint stale-villages untuk deteksi desa tidak aktif 2026-05-28 14:14:35 +08:00
3272ecaef3 feat: tambah field lastActivity ke endpoint monitoring /user 2026-05-28 14:09:42 +08:00
3b5126d8ee Merge pull request 'amalia/25-mei-26' (#53) from amalia/25-mei-26 into join
Reviewed-on: #53
2026-05-25 17:32:47 +08:00
552957282b bump: version 0.1.18 + migration 2026-05-25 15:36:30 +08:00
22555079f3 feat: graph-log-villages support dateFrom/dateTo + recent-village-logs endpoint 2026-05-25 15:08:30 +08:00
6cf6486172 feat: tambah endpoint GET /api-keys/:id untuk ambil full key 2026-05-25 12:00:53 +08:00
35e51028db Merge pull request 'amalia/22-mei-26' (#52) from amalia/22-mei-26 into join
Reviewed-on: #52
2026-05-22 17:41:21 +08:00
37ea4e37e7 bump: version 0.1.17 + migration 2026-05-22 14:46:33 +08:00
e270db3bfa feat: add range param to daily-activity and comparison-activity endpoints
Both endpoints now accept ?range=7|30|90 (default 7).
comparison-activity result now follows SQL ORDER BY instead of being
remapped through villages array.
2026-05-22 14:16:36 +08:00
32dac32532 feat: add village and date range filter on /log-all-villages endpoint 2026-05-22 11:37:42 +08:00
d369a71eb6 feat: add filter and orderBy support on /user monitoring endpoint 2026-05-22 11:17:42 +08:00
7334831d61 Merge pull request 'bump: version 0.1.16 + migration' (#51) from amalia/21-mei-26 into join
Reviewed-on: #51
2026-05-21 17:25:52 +08:00
c0a4d584af bump: version 0.1.16 + migration 2026-05-21 11:07:23 +08:00
9ac105e7bc Merge pull request 'amalia/20-mei-26' (#50) from amalia/20-mei-26 into join
Reviewed-on: #50
2026-05-20 17:22:20 +08:00
10457e96e8 feat: tambah autentikasi x-api-key pada NOC API dan ekstrak isValidApiKey ke shared lib 2026-05-20 12:23:38 +08:00
9ad934c99f bump: version 0.1.15 + migration 2026-05-19 16:05:35 +08:00
5bfcde32ed Merge pull request 'amalia/18-mei-26' (#49) from amalia/18-mei-26 into join
Reviewed-on: #49
2026-05-18 17:26:42 +08:00
8240d608ad feat: tambah field isApprover pada endpoint get & edit user 2026-05-18 16:42:33 +08:00
fd7d08d38a bump: version 0.1.14 + migration 2026-05-18 15:15:07 +08:00
b95fd9543c feat: filter approver berdasarkan group pada project dan division task
- project/task approval: filter isApprover berdasarkan desa + group project
- project/task approval: supadmin tetap hanya filter desa
- division/task approval: expose idGroup dari Division pada response cat=data
- division/task approval: filter isApprover berdasarkan desa + group division
- division/task approval PUT: ganti getApproverStatus dengan cek langsung
  berdasarkan village, group, dan keanggotaan division admin
2026-05-18 14:52:38 +08:00
7622c58ce4 Merge pull request 'amalia/15-mei-26' (#48) from amalia/15-mei-26 into join
Reviewed-on: #48
2026-05-15 14:20:52 +08:00
27 changed files with 990 additions and 347 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "sistem-desa-mandiri",
"version": "0.1.13",
"version": "0.1.19",
"private": true,
"scripts": {
"dev": "next dev --experimental-https",

View File

@@ -0,0 +1 @@
-- This is an empty migration.

View File

@@ -0,0 +1 @@
-- This is an empty migration.

View File

@@ -0,0 +1 @@
-- This is an empty migration.

View File

@@ -0,0 +1 @@
-- This is an empty migration.

View File

@@ -0,0 +1 @@
-- This is an empty migration.

View File

@@ -0,0 +1 @@
-- This is an empty migration.

View File

@@ -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;

View File

@@ -0,0 +1,16 @@
-- CreateTable
CREATE TABLE "DivisionDiscussionCommentFile" (
"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 "DivisionDiscussionCommentFile_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "DivisionDiscussionCommentFile" ADD CONSTRAINT "DivisionDiscussionCommentFile_idComment_fkey" FOREIGN KEY ("idComment") REFERENCES "DivisionDisscussionComment"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@@ -461,16 +461,29 @@ model DivisionDisscussion {
}
model DivisionDisscussionComment {
id String @id @default(cuid())
DivisionDisscussion DivisionDisscussion @relation(fields: [idDisscussion], references: [id])
idDisscussion String
comment String @db.Text
isActive Boolean @default(true)
User User @relation(fields: [createdBy], references: [id])
createdBy String
isEdited Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(cuid())
DivisionDisscussion DivisionDisscussion @relation(fields: [idDisscussion], references: [id])
idDisscussion String
comment String @db.Text
isActive Boolean @default(true)
User User @relation(fields: [createdBy], references: [id])
createdBy String
isEdited Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
DivisionDiscussionCommentFile DivisionDiscussionCommentFile[]
}
model DivisionDiscussionCommentFile {
id String @id @default(cuid())
DivisionDisscussionComment DivisionDisscussionComment @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 DivisionDiscussionFile {
id String @id @default(cuid())
@@ -669,16 +682,29 @@ model DiscussionMember {
}
model DiscussionComment {
id String @id @default(cuid())
Discussion Discussion @relation(fields: [idDiscussion], references: [id])
idDiscussion String
User User @relation(fields: [idUser], references: [id])
idUser String
comment String @db.Text
isActive Boolean @default(true)
isEdited Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(cuid())
Discussion Discussion @relation(fields: [idDiscussion], references: [id])
idDiscussion String
User User @relation(fields: [idUser], references: [id])
idUser String
comment String @db.Text
isActive Boolean @default(true)
isEdited Boolean @default(false)
createdAt DateTime @default(now())
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 {

View File

@@ -1,3 +1,4 @@
import { isValidApiKey } from "@/lib/apiKey";
import { prisma } from "@/module/_global";
import cors from "@elysiajs/cors";
import { swagger } from "@elysiajs/swagger";
@@ -6,20 +7,6 @@ import _ from "lodash";
import moment from "moment";
import "moment/locale/id";
const CACHE_TTL_MS = 60_000;
let apiKeyCache: Set<string> = new Set();
let cacheExpiresAt = 0;
async function isValidApiKey(incoming: string): Promise<boolean> {
const now = Date.now();
if (now > cacheExpiresAt) {
const rows = await prisma.apiKey.findMany({ where: { isActive: true }, select: { key: true } });
apiKeyCache = new Set(rows.map((r) => r.key));
cacheExpiresAt = now + CACHE_TTL_MS;
}
return apiKeyCache.has(incoming);
}
const AiServer = new Elysia({ prefix: "/api/ai" })
.use(cors({
origin: "*",

View File

@@ -1,4 +1,4 @@
import { prisma } from "@/module/_global";
import { DIR, funDeleteFile, funUploadFile, prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUserMobile } from "@/module/user";
import _ from "lodash";
@@ -10,7 +10,16 @@ import { sendFCMNotificationMany } from "../../../../../../../xsendMany";
export async function POST(request: Request, context: { params: { id: string } }) {
try {
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) })
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({
where: {
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 } }) {
try {
const { id } = context.params
const { desc, user } = (await request.json());
const { desc, user, filesToRemove = [] } = (await request.json());
const userMobile = await funGetUserById({ id: String(user) })
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({
where: {
id,
isActive: true
}
where: { id, isActive: true }
})
if (cek == 0) {
return NextResponse.json({ success: false, message: "Gagal mengedit komentar, data tidak ditemukan" }, { status: 200 });
}
const data = await prisma.discussionComment.update({
where: {
id
},
data: {
comment: desc,
isEdited: true
if (filesToRemove.length > 0) {
const files = await prisma.discussionCommentFile.findMany({
where: { id: { in: filesToRemove }, idComment: id, isActive: true },
select: { id: true, idStorage: true }
})
for (const file of files) {
if (file.idStorage) await funDeleteFile({ fileId: file.idStorage })
}
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
@@ -216,18 +252,30 @@ export async function DELETE(request: Request, context: { params: { id: string }
}
const data = await prisma.discussionComment.update({
where: {
id
},
data: {
isActive: false
}
const commentFiles = await prisma.discussionCommentFile.findMany({
where: { idComment: id, isActive: true },
select: { id: true, idStorage: true }
})
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
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) {
console.error(error)

View File

@@ -76,6 +76,15 @@ export async function GET(request: Request, context: { params: { id: string } })
name: true,
img: true
}
},
DiscussionCommentFile: {
where: { isActive: true },
select: {
id: true,
name: true,
extension: true,
idStorage: true
}
}
},
orderBy: {
@@ -84,11 +93,12 @@ export async function GET(request: Request, context: { params: { id: string } })
})
dataFix = data.map((v: any) => ({
..._.omit(v, ["createdAt", "User", "updatedAt"]),
..._.omit(v, ["createdAt", "User", "updatedAt", "DiscussionCommentFile"]),
createdAt: countTime(v.createdAt),
updatedAt: moment(v.updatedAt).format("ll"),
username: v.User.name,
img: v.User.img
img: v.User.img,
files: v.DiscussionCommentFile
}))
} else if (kategori == "anggota") {

View File

@@ -1,4 +1,4 @@
import { prisma } from "@/module/_global";
import { DIR, funDeleteFile, funUploadFile, prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUserMobile } from "@/module/user";
import _ from "lodash";
@@ -9,7 +9,18 @@ import { sendFCMNotificationMany } from "../../../../../../../xsendMany";
export async function POST(request: Request, context: { params: { id: string } }) {
try {
const { id } = context.params
const { comment, user } = (await request.json());
const contentType = request.headers.get("content-type")
let comment: string, user: string, body: FormData | undefined, cekFile = false
if (contentType?.includes("multipart/form-data")) {
body = await request.formData()
const dataBody = body.get("data")
cekFile = body.has("file0");
({ comment, user } = JSON.parse(dataBody as string))
} else {
({ comment, user } = await request.json())
}
const userMobile = await funGetUserById({ id: String(user) })
@@ -44,6 +55,28 @@ export async function POST(request: Request, context: { params: { id: string } }
}
})
if (cekFile && body) {
body.delete("data")
for (var 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: file, dirId: DIR.discussionDivision })
if (upload.success) {
await prisma.divisionDiscussionCommentFile.create({
data: {
idStorage: upload.data.id,
idComment: data.id,
name: fName,
extension: String(fExt)
}
})
}
}
}
}
const dataDivision = await prisma.divisionDisscussion.findUnique({
where: {
id: id
@@ -162,7 +195,7 @@ export async function POST(request: Request, context: { params: { id: string } }
export async function PUT(request: Request, context: { params: { id: string } }) {
try {
const { id } = context.params
const { comment, user } = (await request.json());
const { comment, user, filesToRemove } = (await request.json());
const userMobile = await funGetUserById({ id: String(user) })
@@ -187,14 +220,17 @@ export async function PUT(request: Request, context: { params: { id: string } })
);
}
const data = await prisma.divisionDisscussionComment.update({
where: {
id: id
},
data: {
comment: comment,
isEdited: true
if (filesToRemove && filesToRemove.length > 0) {
for (const fileId of filesToRemove) {
const file = await prisma.divisionDiscussionCommentFile.findUnique({ where: { id: fileId } })
if (file?.idStorage) await funDeleteFile({ id: file.idStorage })
await prisma.divisionDiscussionCommentFile.update({ where: { id: fileId }, data: { isActive: false } })
}
}
await prisma.divisionDisscussionComment.update({
where: { id: id },
data: { comment: comment, isEdited: true }
})
// create log user
@@ -237,13 +273,17 @@ export async function DELETE(request: Request, context: { params: { id: string }
);
}
const data = await prisma.divisionDisscussionComment.update({
where: {
id: id
},
data: {
isActive: false
}
const commentFiles = await prisma.divisionDiscussionCommentFile.findMany({
where: { idComment: id, isActive: true }
})
for (const file of commentFiles) {
if (file.idStorage) await funDeleteFile({ id: file.idStorage })
await prisma.divisionDiscussionCommentFile.update({ where: { id: file.id }, data: { isActive: false } })
}
await prisma.divisionDisscussionComment.update({
where: { id: id },
data: { isActive: false }
})
// create log user

View File

@@ -53,6 +53,15 @@ export async function GET(request: Request, context: { params: { id: string } })
name: true,
img: true
}
},
DivisionDiscussionCommentFile: {
where: { isActive: true },
select: {
id: true,
name: true,
extension: true,
idStorage: true
}
}
},
orderBy: {
@@ -61,12 +70,13 @@ export async function GET(request: Request, context: { params: { id: string } })
})
const omitMember = data.map((v: any) => ({
..._.omit(v, ["User", "createdBy", "createdAt", "updatedAt"]),
..._.omit(v, ["User", "createdBy", "createdAt", "updatedAt", "DivisionDiscussionCommentFile"]),
idUser: v.createdBy,
username: v.User.name,
img: v.User.img,
createdAt: countTime(v.createdAt),
updatedAt: moment(v.updatedAt).format("ll")
updatedAt: moment(v.updatedAt).format("ll"),
files: v.DivisionDiscussionCommentFile
}))
return NextResponse.json({ success: true, message: "Berhasil mendapatkan komentar", data: omitMember }, { status: 200 });

View File

@@ -27,9 +27,6 @@ export async function GET(request: Request) {
idUserTo: userMobile.id
},
orderBy: [
{
isRead: 'asc'
},
{
createdAt: 'desc'
}

View File

@@ -164,7 +164,7 @@ export async function POST(request: Request, context: { params: { id: string } }
if (String(pair[0]).substring(0, 4) == "file") {
const file = body.get(pair[0]) as File
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 })
if (upload.success) {

View File

@@ -96,13 +96,13 @@ async function sendNotification({
}
}
async function getApproversInVillage(idVillage: string): Promise<NotifTarget[]> {
async function getApproversInVillage(idVillage: string, idGroup: string): Promise<NotifTarget[]> {
const approvers = await prisma.user.findMany({
where: {
isActive: true,
idVillage,
OR: [
{ isApprover: true },
{ isApprover: true, idGroup },
{ UserRole: { id: 'supadmin' } }
]
},
@@ -198,7 +198,10 @@ export async function POST(request: Request, context: { params: { id: string } }
const task = await prisma.projectTask.findUnique({
where: { id, isActive: true },
select: { id: true, status: true, idProject: true, title: true }
select: {
id: true, status: true, title: true,
Project: { select: { id: true, idGroup: true } }
}
});
if (!task) {
@@ -227,14 +230,14 @@ export async function POST(request: Request, context: { params: { id: string } }
})
]);
await recalculateProjectStatus(task.idProject);
await recalculateProjectStatus(task.Project.id);
// Notifikasi ke semua approver
const approverTargets = await getApproversInVillage(String(userMobile.idVillage));
// Notifikasi ke semua approver di desa dan group yang sama
const approverTargets = await getApproversInVillage(String(userMobile.idVillage), task.Project.idGroup);
await sendNotification({
targets: approverTargets,
idUserFrom: userMobile.id,
idContent: task.idProject,
idContent: task.Project.id,
title: 'Pengajuan Penyelesaian Tugas',
desc: task.title,
});
@@ -271,7 +274,7 @@ export async function PUT(request: Request, context: { params: { id: string } })
const task = await prisma.projectTask.findUnique({
where: { id, isActive: true },
select: { id: true, status: true, idProject: true, title: true }
select: { id: true, status: true, title: true, Project: { select: { id: true } } }
});
if (!task) {
@@ -304,7 +307,7 @@ export async function PUT(request: Request, context: { params: { id: string } })
})
]);
await recalculateProjectStatus(task.idProject);
await recalculateProjectStatus(task.Project.id);
// Notifikasi ke submitter
const submitterTarget = await getUserNotifTarget(pendingApproval.idUser);
@@ -312,7 +315,7 @@ export async function PUT(request: Request, context: { params: { id: string } })
await sendNotification({
targets: [submitterTarget],
idUserFrom: userMobile.id,
idContent: task.idProject,
idContent: task.Project.id,
title: 'Tugas Disetujui',
desc: task.title,
});
@@ -339,7 +342,7 @@ export async function PUT(request: Request, context: { params: { id: string } })
})
]);
await recalculateProjectStatus(task.idProject);
await recalculateProjectStatus(task.Project.id);
// Notifikasi ke submitter
const submitterTarget = await getUserNotifTarget(pendingApproval.idUser);
@@ -347,7 +350,7 @@ export async function PUT(request: Request, context: { params: { id: string } })
await sendNotification({
targets: [submitterTarget],
idUserFrom: userMobile.id,
idContent: task.idProject,
idContent: task.Project.id,
title: 'Tugas Ditolak',
desc: task.title,
});

View File

@@ -84,7 +84,7 @@ export async function POST(request: Request, context: { params: { id: string } }
const file = body.get(key) as File;
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 });
if (!upload.success) continue;

View File

@@ -25,6 +25,9 @@ export async function GET(request: Request, context: { params: { id: string } })
where: {
id: String(id),
isActive: true
},
include: {
Division: { select: { idGroup: true } }
}
});
@@ -33,7 +36,7 @@ export async function GET(request: Request, context: { params: { id: string } })
}
if (kategori == "data") {
allData = data
allData = { ...data, idGroup: data.Division.idGroup }
} else if (kategori == "progress") {
const dataProgress = await prisma.divisionProjectTask.findMany({
where: {

View File

@@ -114,7 +114,7 @@ export async function POST(request: Request, context: { params: { id: string } }
if (String(pair[0]).substring(0, 4) == "file") {
const file = body.get(pair[0]) as File
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 })

View File

@@ -213,7 +213,7 @@ export async function POST(request: Request) {
if (String(pair[0]).substring(0, 4) == "file") {
const file = body.get(pair[0]) as File
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 })
if (upload.success) {

View File

@@ -96,13 +96,19 @@ async function sendNotification({
}
async function getApproversForDivision(idVillage: string, idDivision: string): Promise<NotifTarget[]> {
const division = await prisma.division.findUnique({
where: { id: idDivision },
select: { idGroup: true }
});
const idGroup = division?.idGroup;
const [globalApprovers, divisionAdmins] = await Promise.all([
prisma.user.findMany({
where: {
isActive: true,
idVillage,
OR: [
{ isApprover: true },
{ isApprover: true, idGroup },
{ UserRole: { id: 'supadmin' } }
]
},
@@ -285,23 +291,35 @@ export async function PUT(request: Request, context: { params: { id: string } })
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
}
const canApprove = await getApproverStatus(userMobile.id);
if (!canApprove) {
// Check if division admin
const task = await prisma.divisionProjectTask.findUnique({
where: { id, isActive: true },
select: { idDivision: true }
});
if (task) {
const isDivAdmin = await prisma.divisionMember.count({
where: { idDivision: task.idDivision, idUser: userMobile.id, isAdmin: true, isActive: true }
});
if (isDivAdmin === 0) {
return NextResponse.json({ success: false, message: "Anda tidak memiliki izin untuk menyetujui atau menolak tugas" }, { status: 200 });
}
} else {
return NextResponse.json({ success: false, message: "Tugas tidak ditemukan" }, { status: 200 });
}
const taskForAuth = await prisma.divisionProjectTask.findUnique({
where: { id, isActive: true },
select: { idDivision: true }
});
if (!taskForAuth) {
return NextResponse.json({ success: false, message: "Tugas tidak ditemukan" }, { status: 200 });
}
const [division, userFull, isDivAdmin] = await Promise.all([
prisma.division.findUnique({
where: { id: taskForAuth.idDivision },
select: { idGroup: true, idVillage: true }
}),
prisma.user.findUnique({
where: { id: userMobile.id },
select: { isApprover: true, idGroup: true, idVillage: true, UserRole: { select: { id: true } } }
}),
prisma.divisionMember.count({
where: { idDivision: taskForAuth.idDivision, idUser: userMobile.id, isAdmin: true, isActive: true }
})
]);
const isSupadmin = APPROVER_ROLES.includes(userFull?.UserRole?.id ?? '');
const isGroupApprover = !!(userFull?.isApprover &&
userFull.idVillage === division?.idVillage &&
userFull.idGroup === division?.idGroup);
if (!isSupadmin && !isGroupApprover && isDivAdmin === 0) {
return NextResponse.json({ success: false, message: "Anda tidak memiliki izin untuk menyetujui atau menolak tugas" }, { status: 200 });
}
const task = await prisma.divisionProjectTask.findUnique({

View File

@@ -87,7 +87,7 @@ export async function POST(request: Request, context: { params: { id: string } }
const file = body.get(key) as File;
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 });
if (!upload.success) continue;

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,4 @@
import { isValidApiKey } from "@/lib/apiKey";
import { prisma } from "@/module/_global";
import cors from "@elysiajs/cors";
import { swagger } from "@elysiajs/swagger";
@@ -11,20 +12,40 @@ const NocServer = new Elysia({ prefix: "/api/noc" })
.use(cors({
origin: "*",
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Content-Type", "x-api-key"],
}))
.use(swagger({
path: "/docs", // Karena prefix instance adalah /api/noc, maka ini akan diakses di /api/noc/docs
path: "/docs",
documentation: {
info: {
title: "Sistem Desa Mandiri - NOC API",
version: "1.0.0",
description: "API Khusus untuk kebutuhan NOC (Network Operation Center) dan Monitoring Desa",
},
components: {
securitySchemes: {
ApiKeyAuth: {
type: "apiKey",
in: "header",
name: "x-api-key",
},
},
},
security: [{ ApiKeyAuth: [] }],
tags: [
{ name: "NOC", description: "Endpoint khusus monitoring" }
]
}
}))
.onBeforeHandle(async ({ request, set, path }) => {
if (path.startsWith("/api/noc/docs")) return;
const incoming = request.headers.get("x-api-key");
if (!incoming || !(await isValidApiKey(incoming))) {
set.status = 401;
return { success: false, message: "Unauthorized" };
}
})
// ── GET /api/noc/active-divisions ──────────────────────────────────────────
.get(

15
src/lib/apiKey.ts Normal file
View File

@@ -0,0 +1,15 @@
import { prisma } from "@/module/_global";
const CACHE_TTL_MS = 60_000;
let apiKeyCache: Set<string> = new Set();
let cacheExpiresAt = 0;
export async function isValidApiKey(incoming: string): Promise<boolean> {
const now = Date.now();
if (now > cacheExpiresAt) {
const rows = await prisma.apiKey.findMany({ where: { isActive: true }, select: { key: true } });
apiKeyCache = new Set(rows.map((r) => r.key));
cacheExpiresAt = now + CACHE_TTL_MS;
}
return apiKeyCache.has(incoming);
}