Compare commits
6 Commits
nico/21-ju
...
nico/23-ju
| Author | SHA1 | Date | |
|---|---|---|---|
| bdf751ec3d | |||
| 1bc6dd8dbf | |||
| 88a10538a7 | |||
| d4efcacf1b | |||
| 9b2201ea57 | |||
| 80a7df663e |
8
prisma/data/landing-page/profile.json
Normal file
8
prisma/data/landing-page/profile.json
Normal file
@@ -0,0 +1,8 @@
|
||||
[
|
||||
{
|
||||
"id": "edit",
|
||||
"name": "I.B Surya Prabhawa Manuaba, S.H., M.H.",
|
||||
"position": "Perbekel Darmasaba periode 2021-2027"
|
||||
}
|
||||
]
|
||||
|
||||
144
prisma/migrations/20250721095104_nico_21_jul_25/migration.sql
Normal file
144
prisma/migrations/20250721095104_nico_21_jul_25/migration.sql
Normal file
@@ -0,0 +1,144 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProgramPenghijauan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"icon" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "ProgramPenghijauan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "DataLingkunganDesa" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"jumlah" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"icon" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "DataLingkunganDesa_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "KegiatanDesa" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsiSingkat" TEXT NOT NULL,
|
||||
"deskripsiLengkap" TEXT NOT NULL,
|
||||
"tanggal" TIMESTAMP(3) NOT NULL,
|
||||
"lokasi" TEXT NOT NULL,
|
||||
"partisipan" INTEGER NOT NULL,
|
||||
"imageId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"kategoriKegiatanId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "KegiatanDesa_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "KategoriKegiatan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nama" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "KategoriKegiatan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TujuanEdukasiLingkungan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "TujuanEdukasiLingkungan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MateriEdukasiLingkungan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "MateriEdukasiLingkungan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ContohEdukasiLingkungan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "ContohEdukasiLingkungan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FilosofiTriHita" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "FilosofiTriHita_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "BentukKonservasiBerdasarkanAdat" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "BentukKonservasiBerdasarkanAdat_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "NilaiKonservasiAdat" (
|
||||
"id" TEXT NOT NULL,
|
||||
"judul" TEXT NOT NULL,
|
||||
"deskripsi" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "NilaiKonservasiAdat_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KegiatanDesa" ADD CONSTRAINT "KegiatanDesa_imageId_fkey" FOREIGN KEY ("imageId") REFERENCES "FileStorage"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KegiatanDesa" ADD CONSTRAINT "KegiatanDesa_kategoriKegiatanId_fkey" FOREIGN KEY ("kategoriKegiatanId") REFERENCES "KategoriKegiatan"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,56 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "PejabatDesa" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" VARCHAR(255) NOT NULL,
|
||||
"position" TEXT NOT NULL,
|
||||
"imageId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "PejabatDesa_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProgramInovasi" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" VARCHAR(255) NOT NULL,
|
||||
"description" TEXT,
|
||||
"imageId" TEXT,
|
||||
"link" VARCHAR(255),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "ProgramInovasi_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MediaSosial" (
|
||||
"id" TEXT NOT NULL,
|
||||
"imageId" TEXT NOT NULL,
|
||||
"iconUrl" VARCHAR(255),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3),
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
|
||||
CONSTRAINT "MediaSosial_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PejabatDesa_name_key" ON "PejabatDesa"("name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ProgramInovasi_name_key" ON "ProgramInovasi"("name");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PejabatDesa" ADD CONSTRAINT "PejabatDesa_imageId_fkey" FOREIGN KEY ("imageId") REFERENCES "FileStorage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ProgramInovasi" ADD CONSTRAINT "ProgramInovasi_imageId_fkey" FOREIGN KEY ("imageId") REFERENCES "FileStorage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MediaSosial" ADD CONSTRAINT "MediaSosial_imageId_fkey" FOREIGN KEY ("imageId") REFERENCES "FileStorage"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -60,6 +60,7 @@ model FileStorage {
|
||||
deletedAt DateTime?
|
||||
isActive Boolean @default(true)
|
||||
link String
|
||||
category String // "image" / "document" / "other"
|
||||
Berita Berita[]
|
||||
PotensiDesa PotensiDesa[]
|
||||
Posyandu Posyandu[]
|
||||
@@ -86,6 +87,75 @@ model FileStorage {
|
||||
KolaborasiInovasi KolaborasiInovasi[]
|
||||
InfoTekno InfoTekno[]
|
||||
PengaduanMasyarakat PengaduanMasyarakat[]
|
||||
KegiatanDesa KegiatanDesa[]
|
||||
ProgramInovasi ProgramInovasi[]
|
||||
PejabatDesa PejabatDesa[]
|
||||
MediaSosial MediaSosial[]
|
||||
DesaAntiKorupsi DesaAntiKorupsi[]
|
||||
}
|
||||
|
||||
//========================================= MENU LANDING PAGE ========================================= //
|
||||
//========================================= PROFILE ========================================= //
|
||||
model PejabatDesa {
|
||||
id String @id @default(cuid())
|
||||
name String @unique @db.VarChar(255)
|
||||
position String
|
||||
image FileStorage? @relation(fields: [imageId], references: [id])
|
||||
imageId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime @default(now())
|
||||
isActive Boolean @default(true)
|
||||
}
|
||||
|
||||
model ProgramInovasi {
|
||||
id String @id @default(cuid())
|
||||
name String @unique @db.VarChar(255)
|
||||
description String? @db.Text
|
||||
image FileStorage? @relation(fields: [imageId], references: [id])
|
||||
imageId String?
|
||||
link String? @db.VarChar(255)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime? @default(now())
|
||||
isActive Boolean @default(true)
|
||||
}
|
||||
|
||||
model MediaSosial {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
image FileStorage @relation(fields: [imageId], references: [id])
|
||||
imageId String
|
||||
iconUrl String? @db.VarChar(255)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
isActive Boolean @default(true)
|
||||
}
|
||||
|
||||
//========================================= PROFILE ========================================= //
|
||||
model DesaAntiKorupsi {
|
||||
id String @id @default(cuid())
|
||||
name String @unique
|
||||
deskripsi String @db.Text
|
||||
kategori KategoriDesaAntiKorupsi @relation(fields: [kategoriId], references: [id])
|
||||
kategoriId String
|
||||
file FileStorage @relation(fields: [fileId], references: [id])
|
||||
fileId String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime @default(now())
|
||||
isActive Boolean @default(true)
|
||||
}
|
||||
|
||||
model KategoriDesaAntiKorupsi {
|
||||
id String @id @default(cuid())
|
||||
name String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime @default(now())
|
||||
isActive Boolean @default(true)
|
||||
DesaAntiKorupsi DesaAntiKorupsi[]
|
||||
}
|
||||
|
||||
//========================================= MENU PPID ========================================= //
|
||||
@@ -1499,6 +1569,35 @@ model DataLingkunganDesa {
|
||||
isActive Boolean @default(true)
|
||||
}
|
||||
|
||||
// ========================================= GOTONG ROYONG ========================================= //
|
||||
model KegiatanDesa {
|
||||
id String @id @default(uuid())
|
||||
judul String
|
||||
deskripsiSingkat String
|
||||
deskripsiLengkap String
|
||||
tanggal DateTime
|
||||
lokasi String
|
||||
partisipan Int
|
||||
image FileStorage @relation(fields: [imageId], references: [id])
|
||||
imageId String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime @default(now())
|
||||
isActive Boolean @default(true)
|
||||
kategoriKegiatan KategoriKegiatan @relation(fields: [kategoriKegiatanId], references: [id])
|
||||
kategoriKegiatanId String
|
||||
}
|
||||
|
||||
model KategoriKegiatan {
|
||||
id String @id @default(cuid())
|
||||
nama String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime @default(now())
|
||||
isActive Boolean @default(true)
|
||||
KegiatanDesa KegiatanDesa[]
|
||||
}
|
||||
|
||||
// ========================================= EDUKASI LINGKUNGAN ========================================= //
|
||||
model TujuanEdukasiLingkungan {
|
||||
id String @id @default(cuid())
|
||||
|
||||
@@ -28,7 +28,7 @@ import contohEdukasiLingkungan from './data/lingkungan/edukasi-lingkungan/contoh
|
||||
import nilaiKonservasiAdat from './data/lingkungan/konservasi-adat-bali/nilai-konservasi-adat.json';
|
||||
import bentukKonservasiBerdasarkanAdat from './data/lingkungan/konservasi-adat-bali/bentuk-konservasi.json';
|
||||
import filosofiTriHita from './data/lingkungan/konservasi-adat-bali/filosofi-tri-hita.json';
|
||||
|
||||
import profilePejabatDesa from './data/landing-page/profile.json';
|
||||
|
||||
(async () => {
|
||||
for (const l of layanan) {
|
||||
@@ -578,6 +578,22 @@ import filosofiTriHita from './data/lingkungan/konservasi-adat-bali/filosofi-tri
|
||||
|
||||
console.log("nilai konservasi adat success ...");
|
||||
|
||||
for (const p of profilePejabatDesa) {
|
||||
await prisma.pejabatDesa.upsert({
|
||||
where: { id: p.id },
|
||||
update: {
|
||||
name: p.name,
|
||||
position: p.position,
|
||||
},
|
||||
create: {
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
position: p.position,
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log("✅ profilePejabatDesa seeded without imageId (editable later via UI)");
|
||||
|
||||
})()
|
||||
.then(() => prisma.$disconnect())
|
||||
.catch((e) => {
|
||||
|
||||
BIN
public/assets/images/sosmed/telephone-call.png
Normal file
BIN
public/assets/images/sosmed/telephone-call.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,485 @@
|
||||
import ApiFetch from "@/lib/api-fetch";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { toast } from "react-toastify";
|
||||
import { proxy } from "valtio";
|
||||
import { z } from "zod";
|
||||
|
||||
const templateDesaAntiKorupsiForm = z.object({
|
||||
name: z.string().min(1, "Judul minimal 1 karakter"),
|
||||
deskripsi: z.string().min(1, "Deskripsi minimal 1 karakter"),
|
||||
kategoriId: z.string().min(1, "Kategori minimal 1"),
|
||||
fileId: z.string().min(1, "File minimal 1"),
|
||||
});
|
||||
|
||||
const defaultDesaAntiKorupsiForm = {
|
||||
name: "",
|
||||
deskripsi: "",
|
||||
kategoriId: "",
|
||||
fileId: "",
|
||||
};
|
||||
|
||||
const desaAntikorupsi = proxy({
|
||||
create: {
|
||||
form: { ...defaultDesaAntiKorupsiForm },
|
||||
loading: false,
|
||||
async create() {
|
||||
const cek = templateDesaAntiKorupsiForm.safeParse(
|
||||
desaAntikorupsi.create.form
|
||||
);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
try {
|
||||
desaAntikorupsi.create.loading = true;
|
||||
const res = await ApiFetch.api.landingpage.desaantikorupsi[
|
||||
"create"
|
||||
].post({
|
||||
...desaAntikorupsi.create.form,
|
||||
});
|
||||
|
||||
if (res.status === 200) {
|
||||
desaAntikorupsi.findMany.load();
|
||||
return toast.success("Data berhasil ditambahkan");
|
||||
}
|
||||
return toast.error("Gagal menambahkan data");
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
toast.error("Gagal menambahkan data");
|
||||
} finally {
|
||||
desaAntikorupsi.create.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
findMany: {
|
||||
data: null as Array<
|
||||
Prisma.DesaAntiKorupsiGetPayload<{
|
||||
include: {
|
||||
file: true;
|
||||
kategori: true;
|
||||
};
|
||||
}>
|
||||
> | null,
|
||||
async load() {
|
||||
const res = await ApiFetch.api.landingpage.desaantikorupsi[
|
||||
"find-many"
|
||||
].get();
|
||||
if (res.status === 200) {
|
||||
desaAntikorupsi.findMany.data = res.data?.data ?? [];
|
||||
}
|
||||
},
|
||||
},
|
||||
findUnique: {
|
||||
data: null as Prisma.DesaAntiKorupsiGetPayload<{
|
||||
include: {
|
||||
file: true;
|
||||
kategori: true;
|
||||
};
|
||||
}> | null,
|
||||
async load(id: string) {
|
||||
try {
|
||||
const res = await fetch(`/api/landingpage/desaantikorupsi/${id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
desaAntikorupsi.findUnique.data = data.data ?? null;
|
||||
} else {
|
||||
console.error("Failed to fetch data", res.status, res.statusText);
|
||||
desaAntikorupsi.findUnique.data = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
desaAntikorupsi.findUnique.data = null;
|
||||
}
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
loading: false,
|
||||
async byId(id: string) {
|
||||
if (!id) return toast.warn("ID tidak valid");
|
||||
|
||||
try {
|
||||
desaAntikorupsi.delete.loading = true;
|
||||
|
||||
const response = await fetch(
|
||||
`/api/landingpage/desaantikorupsi/del/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result?.success) {
|
||||
toast.success(result.message || "desa anti korupsi berhasil dihapus");
|
||||
await desaAntikorupsi.findMany.load(); // refresh list
|
||||
} else {
|
||||
toast.error(result?.message || "Gagal menghapus desa anti korupsi");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Gagal delete:", error);
|
||||
toast.error("Terjadi kesalahan saat menghapus desa anti korupsi");
|
||||
} finally {
|
||||
desaAntikorupsi.delete.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
edit: {
|
||||
id: "",
|
||||
form: { ...defaultDesaAntiKorupsiForm },
|
||||
loading: false,
|
||||
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
desaAntikorupsi.edit.loading = true;
|
||||
|
||||
const response = await fetch(`/api/landingpage/desaantikorupsi/${id}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result?.success) {
|
||||
const data = result.data;
|
||||
this.id = data.id;
|
||||
this.form = {
|
||||
name: data.name,
|
||||
deskripsi: data.deskripsi,
|
||||
kategoriId: data.kategoriId,
|
||||
fileId: data.fileId,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
throw new Error(result?.message || "Gagal memuat data");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading desa anti korupsi:", error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Gagal memuat data"
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
desaAntikorupsi.edit.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async update() {
|
||||
const cek = templateDesaAntiKorupsiForm.safeParse(
|
||||
desaAntikorupsi.edit.form
|
||||
);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
|
||||
try {
|
||||
desaAntikorupsi.edit.loading = true;
|
||||
const response = await fetch(
|
||||
`/api/landingpage/desaantikorupsi/${this.id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: this.form.name,
|
||||
deskripsi: this.form.deskripsi,
|
||||
kategoriId: this.form.kategoriId,
|
||||
fileId: this.form.fileId,
|
||||
}),
|
||||
}
|
||||
);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
errorData.message || `HTTP error! status: ${response.status}`
|
||||
);
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
toast.success("Berhasil update desa anti korupsi");
|
||||
await desaAntikorupsi.findMany.load(); // refresh list
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(
|
||||
result.message || "Gagal mengupdate desa anti korupsi"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating desa anti korupsi:", error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Gagal mengupdate desa anti korupsi"
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
desaAntikorupsi.edit.loading = false;
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
desaAntikorupsi.edit.id = "";
|
||||
desaAntikorupsi.edit.form = { ...defaultDesaAntiKorupsiForm };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// ========================================= KATEGORI desa anti korupsi ========================================= //
|
||||
const kategoriDesaAntiKorupsiForm = z.object({
|
||||
name: z.string().min(1, "Nama minimal 1 karakter"),
|
||||
});
|
||||
|
||||
const kategoriDesaAntiKorupsiDefaultForm = {
|
||||
name: "",
|
||||
};
|
||||
|
||||
const kategoriDesaAntiKorupsi = proxy({
|
||||
create: {
|
||||
form: { ...kategoriDesaAntiKorupsiDefaultForm },
|
||||
loading: false,
|
||||
async create() {
|
||||
const cek = kategoriDesaAntiKorupsiForm.safeParse(
|
||||
kategoriDesaAntiKorupsi.create.form
|
||||
);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
try {
|
||||
kategoriDesaAntiKorupsi.create.loading = true;
|
||||
const res = await ApiFetch.api.landingpage.kategoridak["create"].post(
|
||||
kategoriDesaAntiKorupsi.create.form
|
||||
);
|
||||
if (res.status === 200) {
|
||||
kategoriDesaAntiKorupsi.findMany.load();
|
||||
return toast.success("Data berhasil ditambahkan");
|
||||
}
|
||||
return toast.error("Gagal menambahkan data");
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
toast.error("Gagal menambahkan data");
|
||||
} finally {
|
||||
kategoriDesaAntiKorupsi.create.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
findMany: {
|
||||
data: null as Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
}> | null,
|
||||
async load() {
|
||||
const res = await ApiFetch.api.landingpage.kategoridak["find-many"].get();
|
||||
if (res.status === 200) {
|
||||
kategoriDesaAntiKorupsi.findMany.data = res.data?.data ?? [];
|
||||
}
|
||||
},
|
||||
},
|
||||
findUnique: {
|
||||
data: null as Prisma.KategoriDesaAntiKorupsiGetPayload<{
|
||||
omit: { isActive: true };
|
||||
}> | null,
|
||||
async load(id: string) {
|
||||
try {
|
||||
const res = await fetch(`/api/landingpage/kategoridak/${id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
kategoriDesaAntiKorupsi.findUnique.data = data.data ?? null;
|
||||
} else {
|
||||
console.error("Failed to fetch data", res.status, res.statusText);
|
||||
kategoriDesaAntiKorupsi.findUnique.data = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
kategoriDesaAntiKorupsi.findUnique.data = null;
|
||||
}
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
loading: false,
|
||||
async byId(id: string) {
|
||||
if (!id) return toast.warn("ID tidak valid");
|
||||
|
||||
try {
|
||||
kategoriDesaAntiKorupsi.delete.loading = true;
|
||||
|
||||
const response = await fetch(
|
||||
`/api/landingpage/kategoridak/del/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result?.success) {
|
||||
toast.success(result.message || "Kategori desa anti korupsi berhasil dihapus");
|
||||
await kategoriDesaAntiKorupsi.findMany.load(); // refresh list
|
||||
} else {
|
||||
toast.error(result?.message || "Gagal menghapus kategori desa anti korupsi");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Gagal delete:", error);
|
||||
toast.error("Terjadi kesalahan saat menghapus kategori desa anti korupsi");
|
||||
} finally {
|
||||
kategoriDesaAntiKorupsi.delete.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
edit: {
|
||||
id: "",
|
||||
form: { ...kategoriDesaAntiKorupsiDefaultForm },
|
||||
loading: false,
|
||||
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/landingpage/kategoridak/${id}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result?.success) {
|
||||
const data = result.data;
|
||||
this.id = data.id;
|
||||
this.form = {
|
||||
name: data.name,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
throw new Error(result?.message || "Gagal memuat data");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading kategori desa anti korupsi:", error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Gagal memuat data"
|
||||
);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
async update() {
|
||||
const cek = kategoriDesaAntiKorupsiForm.safeParse(
|
||||
kategoriDesaAntiKorupsi.edit.form
|
||||
);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
toast.error(err);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
kategoriDesaAntiKorupsi.edit.loading = true;
|
||||
const response = await fetch(
|
||||
`/api/landingpage/kategoridak/${kategoriDesaAntiKorupsi.edit.id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: kategoriDesaAntiKorupsi.edit.form.name,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
// Clone the response to avoid 'body already read' error
|
||||
const responseClone = response.clone();
|
||||
|
||||
try {
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
"Update failed with status:",
|
||||
response.status,
|
||||
"Response:",
|
||||
result
|
||||
);
|
||||
throw new Error(
|
||||
result?.message ||
|
||||
`Gagal mengupdate kategori desa anti korupsi (${response.status})`
|
||||
);
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
toast.success(
|
||||
result.message ||
|
||||
"Berhasil memperbarui kategori desa anti korupsi"
|
||||
);
|
||||
await kategoriDesaAntiKorupsi.findMany.load(); // refresh list
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(
|
||||
result.message || "Gagal mengupdate kategori desa anti korupsi"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// If JSON parsing fails, try to get the response text for better error messages
|
||||
try {
|
||||
const text = await responseClone.text();
|
||||
console.error("Error response text:", text);
|
||||
throw new Error(`Gagal memproses respons dari server: ${text}`);
|
||||
} catch (textError) {
|
||||
console.error("Error parsing response as text:", textError);
|
||||
console.error("Original error:", error);
|
||||
throw new Error("Gagal memproses respons dari server");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating kategori desa anti korupsi:", error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Gagal mengupdate kategori desa anti korupsi"
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
kategoriDesaAntiKorupsi.edit.loading = false;
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
kategoriDesaAntiKorupsi.edit.id = "";
|
||||
kategoriDesaAntiKorupsi.edit.form = {
|
||||
...kategoriDesaAntiKorupsiDefaultForm,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const korupsiState = proxy({
|
||||
desaAntikorupsi,
|
||||
kategoriDesaAntiKorupsi,
|
||||
});
|
||||
export default korupsiState;
|
||||
634
src/app/admin/(dashboard)/_state/landing-page/profile.ts
Normal file
634
src/app/admin/(dashboard)/_state/landing-page/profile.ts
Normal file
@@ -0,0 +1,634 @@
|
||||
import ApiFetch from "@/lib/api-fetch";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { toast } from "react-toastify";
|
||||
import { proxy } from "valtio";
|
||||
import { z } from "zod";
|
||||
|
||||
const templateProgramInovasi = z.object({
|
||||
name: z.string().min(3, "Nama minimal 3 karakter"),
|
||||
description: z.string().min(3, "Deskripsi minimal 3 karakter"),
|
||||
imageId: z.string().min(1, "Gambar wajib dipilih"),
|
||||
link: z.string().min(3, "Link minimal 3 karakter"),
|
||||
});
|
||||
|
||||
type ProgramInovasiForm = Prisma.ProgramInovasiGetPayload<{
|
||||
select: {
|
||||
name: true;
|
||||
description: true;
|
||||
imageId: true;
|
||||
link: true;
|
||||
};
|
||||
}>;
|
||||
|
||||
const programInovasi = proxy({
|
||||
create: {
|
||||
form: {} as ProgramInovasiForm,
|
||||
loading: false,
|
||||
async create() {
|
||||
// Ensure all required fields are non-null
|
||||
const formData = {
|
||||
name: programInovasi.create.form.name || "",
|
||||
description: programInovasi.create.form.description || "",
|
||||
imageId: programInovasi.create.form.imageId || "",
|
||||
link: programInovasi.create.form.link || "",
|
||||
};
|
||||
|
||||
const cek = templateProgramInovasi.safeParse(formData);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
try {
|
||||
programInovasi.create.loading = true;
|
||||
const res = await ApiFetch.api.landingpage.programinovasi[
|
||||
"create"
|
||||
].post(formData);
|
||||
if (res.status === 200) {
|
||||
programInovasi.findMany.load();
|
||||
return toast.success("success create");
|
||||
}
|
||||
console.log(res);
|
||||
return toast.error("failed create");
|
||||
} catch (error) {
|
||||
console.log((error as Error).message);
|
||||
} finally {
|
||||
programInovasi.create.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
findMany: {
|
||||
data: null as
|
||||
| Prisma.ProgramInovasiGetPayload<{ include: { image: true } }>[]
|
||||
| null,
|
||||
async load() {
|
||||
const res = await ApiFetch.api.landingpage.programinovasi[
|
||||
"find-many"
|
||||
].get();
|
||||
if (res.status === 200) {
|
||||
programInovasi.findMany.data = res.data?.data ?? [];
|
||||
}
|
||||
},
|
||||
},
|
||||
findUnique: {
|
||||
data: null as Prisma.ProgramInovasiGetPayload<{
|
||||
include: {
|
||||
image: true;
|
||||
};
|
||||
}> | null,
|
||||
async load(id: string) {
|
||||
try {
|
||||
const res = await fetch(`/api/landingpage/programinovasi/${id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
programInovasi.findUnique.data = data.data ?? null;
|
||||
} else {
|
||||
console.error("Failed to fetch program inovasi:", res.statusText);
|
||||
programInovasi.findUnique.data = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching program inovasi:", error);
|
||||
programInovasi.findUnique.data = null;
|
||||
}
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
loading: false,
|
||||
async byId(id: string) {
|
||||
if (!id) return toast.warn("ID tidak valid");
|
||||
|
||||
try {
|
||||
programInovasi.delete.loading = true;
|
||||
|
||||
const response = await fetch(
|
||||
`/api/landingpage/programinovasi/del/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result?.success) {
|
||||
toast.success(result.message || "Program inovasi berhasil dihapus");
|
||||
await programInovasi.findMany.load(); // refresh list
|
||||
} else {
|
||||
toast.error(result?.message || "Gagal menghapus program inovasi");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Gagal delete:", error);
|
||||
toast.error("Terjadi kesalahan saat menghapus program inovasi");
|
||||
} finally {
|
||||
programInovasi.delete.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
update: {
|
||||
id: "",
|
||||
form: {} as ProgramInovasiForm,
|
||||
loading: false,
|
||||
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/landingpage/programinovasi/${id}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result?.success) {
|
||||
const data = result.data;
|
||||
this.id = data.id;
|
||||
this.form = {
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
imageId: data.imageId,
|
||||
link: data.link,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
throw new Error(
|
||||
result?.message || "Gagal mengambil data program inovasi"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error((error as Error).message);
|
||||
toast.error("Terjadi kesalahan saat mengambil data program inovasi");
|
||||
} finally {
|
||||
programInovasi.update.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async update() {
|
||||
const cek = templateProgramInovasi.safeParse(programInovasi.update.form);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
toast.error(err);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
programInovasi.update.loading = true;
|
||||
|
||||
const response = await fetch(
|
||||
`/api/landingpage/programinovasi/${this.id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: this.form.name,
|
||||
description: this.form.description,
|
||||
imageId: this.form.imageId,
|
||||
link: this.form.link,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
errorData.message || `HTTP error! status: ${response.status}`
|
||||
);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
toast.success("Berhasil update program inovasi");
|
||||
await programInovasi.findMany.load(); // refresh list
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(result.message || "Gagal update program inovasi");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating program inovasi:", error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Terjadi kesalahan saat update program inovasi"
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
programInovasi.update.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const templatePejabatDesa = z.object({
|
||||
name: z.string().min(3, "Nama minimal 3 karakter"),
|
||||
position: z.string().min(3, "Posisi minimal 3 karakter"),
|
||||
imageId: z.string().min(1, "Gambar wajib dipilih"),
|
||||
});
|
||||
|
||||
const defaultFormPejabatDesa = {
|
||||
name: "",
|
||||
position: "",
|
||||
imageId: "",
|
||||
};
|
||||
|
||||
type PejabatDesaForm = {
|
||||
id: string;
|
||||
name: string;
|
||||
position: string;
|
||||
imageId: string | null;
|
||||
image?: {
|
||||
id: string;
|
||||
name: string;
|
||||
link: string;
|
||||
path: string;
|
||||
mimeType: string;
|
||||
realName: string;
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
deletedAt: Date | null;
|
||||
} | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
deletedAt: Date | null;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
const pejabatDesa = proxy({
|
||||
findUnique: {
|
||||
data: null as PejabatDesaForm | null,
|
||||
loading: false,
|
||||
error: null as string | null,
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/landingpage/pejabatdesa/${id}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
this.data = result.data;
|
||||
return result.data;
|
||||
} else {
|
||||
throw new Error(
|
||||
result.message || "Gagal mengambil data pejabat desa"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = (error as Error).message;
|
||||
this.error = errorMessage;
|
||||
console.error("Load pejabat desa error:", errorMessage);
|
||||
toast.error("Terjadi kesalahan saat mengambil data pejabat desa");
|
||||
return null;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
reset() {
|
||||
this.data = null;
|
||||
this.error = null;
|
||||
this.loading = false;
|
||||
},
|
||||
},
|
||||
edit: {
|
||||
id: "",
|
||||
form: { ...defaultFormPejabatDesa },
|
||||
loading: false,
|
||||
error: null as string | null,
|
||||
isReadOnly: false,
|
||||
|
||||
initialize(profileData: PejabatDesaForm) {
|
||||
this.id = profileData.id;
|
||||
this.isReadOnly = false; // Semua data bisa diedit
|
||||
this.form = {
|
||||
name: profileData.name || "",
|
||||
position: profileData.position || "",
|
||||
imageId: profileData.imageId || "",
|
||||
};
|
||||
},
|
||||
|
||||
// Update form field
|
||||
updateField(field: keyof typeof defaultFormPejabatDesa, value: string) {
|
||||
this.form[field] = value;
|
||||
},
|
||||
|
||||
// Submit form
|
||||
async submit() {
|
||||
// Validate form
|
||||
const validation = templatePejabatDesa.safeParse(this.form);
|
||||
|
||||
if (!validation.success) {
|
||||
const errors = validation.error.issues
|
||||
.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
|
||||
.join(", ");
|
||||
toast.error(`Form tidak valid: ${errors}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/landingpage/pejabatdesa/${this.id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(this.form),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
errorData.message || `HTTP error! status: ${response.status}`
|
||||
);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
toast.success("Berhasil update profile");
|
||||
// Refresh profile data
|
||||
await pejabatDesa.findUnique.load(this.id);
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(result.message || "Gagal update profile");
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = (error as Error).message;
|
||||
this.error = errorMessage;
|
||||
console.error("Update profile error:", errorMessage);
|
||||
toast.error("Terjadi kesalahan saat update profile");
|
||||
return false;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
reset() {
|
||||
this.id = "";
|
||||
this.form = { ...defaultFormPejabatDesa };
|
||||
this.error = null;
|
||||
this.loading = false;
|
||||
this.isReadOnly = false;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const templateMediaSosial = z.object({
|
||||
name: z.string().min(3, "Nama minimal 3 karakter"),
|
||||
imageId: z.string().min(1, "Gambar wajib dipilih"),
|
||||
iconUrl: z.string().min(3, "Icon URL minimal 3 karakter"),
|
||||
});
|
||||
|
||||
type MediaSosialForm = {
|
||||
name: string;
|
||||
imageId: string;
|
||||
iconUrl: string;
|
||||
};
|
||||
|
||||
const mediaSosial = proxy({
|
||||
create: {
|
||||
form: {} as MediaSosialForm,
|
||||
loading: false,
|
||||
async create() {
|
||||
// Ensure all required fields are non-null
|
||||
const formData = {
|
||||
name: mediaSosial.create.form.name || "",
|
||||
imageId: mediaSosial.create.form.imageId || "",
|
||||
iconUrl: mediaSosial.create.form.iconUrl || "",
|
||||
};
|
||||
|
||||
const cek = templateMediaSosial.safeParse(formData);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
try {
|
||||
mediaSosial.create.loading = true;
|
||||
const res = await ApiFetch.api.landingpage.mediasosial["create"].post(
|
||||
formData
|
||||
);
|
||||
if (res.status === 200) {
|
||||
mediaSosial.findMany.load();
|
||||
return toast.success("success create");
|
||||
}
|
||||
console.log(res);
|
||||
return toast.error("failed create");
|
||||
} catch (error) {
|
||||
console.log((error as Error).message);
|
||||
} finally {
|
||||
mediaSosial.create.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
findMany: {
|
||||
data: null as
|
||||
| Prisma.MediaSosialGetPayload<{ include: { image: true } }>[]
|
||||
| null,
|
||||
async load() {
|
||||
const res = await ApiFetch.api.landingpage.mediasosial["find-many"].get();
|
||||
if (res.status === 200) {
|
||||
mediaSosial.findMany.data = res.data?.data ?? [];
|
||||
}
|
||||
},
|
||||
},
|
||||
findUnique: {
|
||||
data: null as Prisma.MediaSosialGetPayload<{
|
||||
include: {
|
||||
image: true;
|
||||
};
|
||||
}> | null,
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
mediaSosial.update.loading = true;
|
||||
try {
|
||||
const res = await fetch(`/api/landingpage/mediasosial/${id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
mediaSosial.findUnique.data = data.data ?? null;
|
||||
} else {
|
||||
console.error("Failed to fetch media sosial:", res.statusText);
|
||||
mediaSosial.findUnique.data = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching media sosial:", error);
|
||||
mediaSosial.findUnique.data = null;
|
||||
}
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
loading: false,
|
||||
async byId(id: string) {
|
||||
if (!id) return toast.warn("ID tidak valid");
|
||||
|
||||
try {
|
||||
mediaSosial.delete.loading = true;
|
||||
|
||||
const response = await fetch(`/api/landingpage/mediasosial/del/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result?.success) {
|
||||
toast.success(result.message || "Media Sosial berhasil dihapus");
|
||||
await mediaSosial.findMany.load(); // refresh list
|
||||
} else {
|
||||
toast.error(result?.message || "Gagal menghapus media sosial");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Gagal delete:", error);
|
||||
toast.error("Terjadi kesalahan saat menghapus media sosial");
|
||||
} finally {
|
||||
mediaSosial.delete.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
update: {
|
||||
id: "",
|
||||
form: {} as MediaSosialForm,
|
||||
loading: false,
|
||||
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
mediaSosial.update.loading = true; // ✅ Tambahkan ini di awal
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/landingpage/mediasosial/${id}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result?.success) {
|
||||
const data = result.data;
|
||||
this.id = data.id;
|
||||
this.form = {
|
||||
name: data.name || "",
|
||||
imageId: data.imageId || "",
|
||||
iconUrl: data.iconUrl || "",
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
throw new Error(result?.message || "Gagal mengambil data media sosial");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error((error as Error).message);
|
||||
toast.error("Terjadi kesalahan saat mengambil data media sosial");
|
||||
} finally {
|
||||
mediaSosial.update.loading = false; // ✅ Supaya berhenti loading walau error
|
||||
}
|
||||
},
|
||||
|
||||
async update() {
|
||||
const cek = templateMediaSosial.safeParse(mediaSosial.update.form);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
toast.error(err);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
mediaSosial.update.loading = true;
|
||||
|
||||
const response = await fetch(`/api/landingpage/mediasosial/${this.id}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: this.form.name,
|
||||
imageId: this.form.imageId,
|
||||
iconUrl: this.form.iconUrl,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
errorData.message || `HTTP error! status: ${response.status}`
|
||||
);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
toast.success("Berhasil update media sosial");
|
||||
await mediaSosial.findMany.load(); // refresh list
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(result.message || "Gagal update media sosial");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating media sosial:", error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Terjadi kesalahan saat update media sosial"
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
mediaSosial.update.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const profileLandingPageState = proxy({
|
||||
programInovasi,
|
||||
pejabatDesa,
|
||||
mediaSosial,
|
||||
});
|
||||
|
||||
export default profileLandingPageState;
|
||||
492
src/app/admin/(dashboard)/_state/lingkungan/gotong-royong.ts
Normal file
492
src/app/admin/(dashboard)/_state/lingkungan/gotong-royong.ts
Normal file
@@ -0,0 +1,492 @@
|
||||
import ApiFetch from "@/lib/api-fetch";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { toast } from "react-toastify";
|
||||
import { proxy } from "valtio";
|
||||
import { z } from "zod";
|
||||
|
||||
const templateKegiatanDesaForm = z.object({
|
||||
judul: z.string().min(1, "Judul minimal 1 karakter"),
|
||||
deskripsiSingkat: z.string().min(1, "Deskripsi singkat minimal 1 karakter"),
|
||||
deskripsiLengkap: z.string().min(1, "Deskripsi lengkap minimal 1 karakter"),
|
||||
tanggal: z.date(),
|
||||
lokasi: z.string().min(1, "Lokasi minimal 1 karakter"),
|
||||
partisipan: z.number().min(1, "Partisipan minimal 1"),
|
||||
imageId: z.string().min(1, "Gambar wajib dipilih"),
|
||||
kategoriKegiatanId: z.string().min(1, "Kategori kegiatan minimal 1"),
|
||||
});
|
||||
|
||||
const defaultKegiatanDesaForm = {
|
||||
judul: "",
|
||||
deskripsiSingkat: "",
|
||||
deskripsiLengkap: "",
|
||||
tanggal: new Date(),
|
||||
lokasi: "",
|
||||
partisipan: 0,
|
||||
imageId: "",
|
||||
kategoriKegiatanId: "",
|
||||
};
|
||||
|
||||
const kegiatanDesa = proxy({
|
||||
create: {
|
||||
form: { ...defaultKegiatanDesaForm },
|
||||
loading: false,
|
||||
async create() {
|
||||
const cek = templateKegiatanDesaForm.safeParse(kegiatanDesa.create.form);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
try {
|
||||
kegiatanDesa.create.loading = true;
|
||||
const res = await ApiFetch.api.lingkungan.kegiatandesa["create"].post({
|
||||
...kegiatanDesa.create.form,
|
||||
tanggal: kegiatanDesa.create.form.tanggal.toISOString(), // ✅ convert Date -> string
|
||||
});
|
||||
|
||||
if (res.status === 200) {
|
||||
kegiatanDesa.findMany.load();
|
||||
return toast.success("Data berhasil ditambahkan");
|
||||
}
|
||||
return toast.error("Gagal menambahkan data");
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
toast.error("Gagal menambahkan data");
|
||||
} finally {
|
||||
kegiatanDesa.create.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
findMany: {
|
||||
data: null as Array<
|
||||
Prisma.KegiatanDesaGetPayload<{
|
||||
include: {
|
||||
image: true;
|
||||
kategoriKegiatan: true;
|
||||
};
|
||||
}>
|
||||
> | null,
|
||||
async load() {
|
||||
const res = await ApiFetch.api.lingkungan.kegiatandesa["find-many"].get();
|
||||
if (res.status === 200) {
|
||||
kegiatanDesa.findMany.data = res.data?.data ?? [];
|
||||
}
|
||||
},
|
||||
},
|
||||
findUnique: {
|
||||
data: null as Prisma.KegiatanDesaGetPayload<{
|
||||
include: {
|
||||
image: true;
|
||||
kategoriKegiatan: true;
|
||||
};
|
||||
}> | null,
|
||||
async load(id: string) {
|
||||
try {
|
||||
const res = await fetch(`/api/lingkungan/kegiatandesa/${id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
kegiatanDesa.findUnique.data = data.data ?? null;
|
||||
} else {
|
||||
console.error("Failed to fetch data", res.status, res.statusText);
|
||||
kegiatanDesa.findUnique.data = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
kegiatanDesa.findUnique.data = null;
|
||||
}
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
loading: false,
|
||||
async byId(id: string) {
|
||||
if (!id) return toast.warn("ID tidak valid");
|
||||
|
||||
try {
|
||||
kegiatanDesa.delete.loading = true;
|
||||
|
||||
const response = await fetch(`/api/lingkungan/kegiatandesa/del/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result?.success) {
|
||||
toast.success(result.message || "kegiatan desa berhasil dihapus");
|
||||
await kegiatanDesa.findMany.load(); // refresh list
|
||||
} else {
|
||||
toast.error(result?.message || "Gagal menghapus pasar desa");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Gagal delete:", error);
|
||||
toast.error("Terjadi kesalahan saat menghapus pasar desa");
|
||||
} finally {
|
||||
kegiatanDesa.delete.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
edit: {
|
||||
id: "",
|
||||
form: { ...defaultKegiatanDesaForm },
|
||||
loading: false,
|
||||
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
kegiatanDesa.edit.loading = true;
|
||||
|
||||
const response = await fetch(`/api/lingkungan/kegiatandesa/${id}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result?.success) {
|
||||
const data = result.data;
|
||||
this.id = data.id;
|
||||
this.form = {
|
||||
judul: data.judul,
|
||||
deskripsiSingkat: data.deskripsiSingkat,
|
||||
deskripsiLengkap: data.deskripsiLengkap,
|
||||
tanggal: data.tanggal,
|
||||
lokasi: data.lokasi,
|
||||
partisipan: data.partisipan,
|
||||
imageId: data.imageId,
|
||||
kategoriKegiatanId: data.kategoriKegiatanId,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
throw new Error(result?.message || "Gagal memuat data");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading kegiatan desa:", error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Gagal memuat data"
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
kegiatanDesa.edit.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async update() {
|
||||
const cek = templateKegiatanDesaForm.safeParse(kegiatanDesa.edit.form);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
|
||||
try {
|
||||
kegiatanDesa.edit.loading = true;
|
||||
const response = await fetch(
|
||||
`/api/lingkungan/kegiatandesa/${this.id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
judul: this.form.judul,
|
||||
deskripsiSingkat: this.form.deskripsiSingkat,
|
||||
deskripsiLengkap: this.form.deskripsiLengkap,
|
||||
tanggal:
|
||||
typeof this.form.tanggal === "string"
|
||||
? this.form.tanggal
|
||||
: this.form.tanggal.toISOString(),
|
||||
lokasi: this.form.lokasi,
|
||||
partisipan: this.form.partisipan,
|
||||
imageId: this.form.imageId,
|
||||
kategoriKegiatanId: this.form.kategoriKegiatanId,
|
||||
}),
|
||||
}
|
||||
);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
errorData.message || `HTTP error! status: ${response.status}`
|
||||
);
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
toast.success("Berhasil update kegiatan desa");
|
||||
await kegiatanDesa.findMany.load(); // refresh list
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(result.message || "Gagal mengupdate kegiatan desa");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating kegiatan desa:", error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Gagal mengupdate kegiatan desa"
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
kegiatanDesa.edit.loading = false;
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
kegiatanDesa.edit.id = "";
|
||||
kegiatanDesa.edit.form = { ...defaultKegiatanDesaForm };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// ========================================= KATEGORI kegiatan ========================================= //
|
||||
const kategoriKegiatanForm = z.object({
|
||||
nama: z.string().min(1, "Nama minimal 1 karakter"),
|
||||
});
|
||||
|
||||
const kategoriKegiatanDefaultForm = {
|
||||
nama: "",
|
||||
};
|
||||
|
||||
const kategoriKegiatan = proxy({
|
||||
create: {
|
||||
form: { ...kategoriKegiatanDefaultForm },
|
||||
loading: false,
|
||||
async create() {
|
||||
const cek = kategoriKegiatanForm.safeParse(kategoriKegiatan.create.form);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
return toast.error(err);
|
||||
}
|
||||
try {
|
||||
kategoriKegiatan.create.loading = true;
|
||||
const res = await ApiFetch.api.lingkungan.kategorikegiatan[
|
||||
"create"
|
||||
].post(kategoriKegiatan.create.form);
|
||||
if (res.status === 200) {
|
||||
kategoriKegiatan.findMany.load();
|
||||
return toast.success("Data berhasil ditambahkan");
|
||||
}
|
||||
return toast.error("Gagal menambahkan data");
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
toast.error("Gagal menambahkan data");
|
||||
} finally {
|
||||
kategoriKegiatan.create.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
findMany: {
|
||||
data: null as Array<{
|
||||
id: string;
|
||||
nama: string;
|
||||
}> | null,
|
||||
async load() {
|
||||
const res = await ApiFetch.api.lingkungan.kategorikegiatan[
|
||||
"find-many"
|
||||
].get();
|
||||
if (res.status === 200) {
|
||||
kategoriKegiatan.findMany.data = res.data?.data ?? [];
|
||||
}
|
||||
},
|
||||
},
|
||||
findUnique: {
|
||||
data: null as Prisma.KategoriKegiatanGetPayload<{
|
||||
omit: { isActive: true };
|
||||
}> | null,
|
||||
async load(id: string) {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/lingkungan/kategorikegiatan/${id}`
|
||||
);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
kategoriKegiatan.findUnique.data = data.data ?? null;
|
||||
} else {
|
||||
console.error("Failed to fetch data", res.status, res.statusText);
|
||||
kategoriKegiatan.findUnique.data = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
kategoriKegiatan.findUnique.data = null;
|
||||
}
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
loading: false,
|
||||
async byId(id: string) {
|
||||
if (!id) return toast.warn("ID tidak valid");
|
||||
|
||||
try {
|
||||
kategoriKegiatan.delete.loading = true;
|
||||
|
||||
const response = await fetch(
|
||||
`/api/lingkungan/kategorikegiatan/del/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result?.success) {
|
||||
toast.success(result.message || "Kategori kegiatan berhasil dihapus");
|
||||
await kategoriKegiatan.findMany.load(); // refresh list
|
||||
} else {
|
||||
toast.error(result?.message || "Gagal menghapus kategori kegiatan");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Gagal delete:", error);
|
||||
toast.error("Terjadi kesalahan saat menghapus kategori kegiatan");
|
||||
} finally {
|
||||
kategoriKegiatan.delete.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
edit: {
|
||||
id: "",
|
||||
form: { ...kategoriKegiatanDefaultForm },
|
||||
loading: false,
|
||||
|
||||
async load(id: string) {
|
||||
if (!id) {
|
||||
toast.warn("ID tidak valid");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/lingkungan/kategorikegiatan/${id}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result?.success) {
|
||||
const data = result.data;
|
||||
this.id = data.id;
|
||||
this.form = {
|
||||
nama: data.nama,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
throw new Error(result?.message || "Gagal memuat data");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading kategori kegiatan:", error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Gagal memuat data"
|
||||
);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
async update() {
|
||||
const cek = kategoriKegiatanForm.safeParse(kategoriKegiatan.edit.form);
|
||||
if (!cek.success) {
|
||||
const err = `[${cek.error.issues
|
||||
.map((v) => `${v.path.join(".")}`)
|
||||
.join("\n")}] required`;
|
||||
toast.error(err);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
kategoriKegiatan.edit.loading = true;
|
||||
const response = await fetch(
|
||||
`/api/lingkungan/kategorikegiatan/${kategoriKegiatan.edit.id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
nama: kategoriKegiatan.edit.form.nama,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
// Clone the response to avoid 'body already read' error
|
||||
const responseClone = response.clone();
|
||||
|
||||
try {
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
"Update failed with status:",
|
||||
response.status,
|
||||
"Response:",
|
||||
result
|
||||
);
|
||||
throw new Error(
|
||||
result?.message ||
|
||||
`Gagal mengupdate kategori kegiatan (${response.status})`
|
||||
);
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
toast.success(
|
||||
result.message || "Berhasil memperbarui kategori kegiatan"
|
||||
);
|
||||
await kategoriKegiatan.findMany.load(); // refresh list
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(
|
||||
result.message || "Gagal mengupdate kategori kegiatan"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// If JSON parsing fails, try to get the response text for better error messages
|
||||
try {
|
||||
const text = await responseClone.text();
|
||||
console.error("Error response text:", text);
|
||||
throw new Error(`Gagal memproses respons dari server: ${text}`);
|
||||
} catch (textError) {
|
||||
console.error("Error parsing response as text:", textError);
|
||||
console.error("Original error:", error);
|
||||
throw new Error("Gagal memproses respons dari server");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating kategori kegiatan:", error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Gagal mengupdate kategori kegiatan"
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
kategoriKegiatan.edit.loading = false;
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
kategoriKegiatan.edit.id = "";
|
||||
kategoriKegiatan.edit.form = { ...kategoriKegiatanDefaultForm };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const gotongRoyongState = proxy({
|
||||
kegiatanDesa,
|
||||
kategoriKegiatan,
|
||||
});
|
||||
export default gotongRoyongState;
|
||||
@@ -0,0 +1,62 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Stack, Tabs, TabsList, TabsPanel, TabsTab, Title } from '@mantine/core';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
function LayoutTabs({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const tabs = [
|
||||
{
|
||||
label: "List Desa Anti Korupsi",
|
||||
value: "listDesaAntiKorupsi",
|
||||
href: "/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi"
|
||||
},
|
||||
{
|
||||
label: "Kategori Desa Anti Korupsi",
|
||||
value: "kategoriDesaAntiKorupsi",
|
||||
href: "/admin/landing-page/desa-anti-korupsi/kategori-desa-anti-korupsi"
|
||||
},
|
||||
];
|
||||
const curentTab = tabs.find(tab => tab.href === pathname)
|
||||
const [activeTab, setActiveTab] = useState<string | null>(curentTab?.value || tabs[0].value);
|
||||
|
||||
const handleTabChange = (value: string | null) => {
|
||||
const tab = tabs.find(t => t.value === value)
|
||||
if (tab) {
|
||||
router.push(tab.href)
|
||||
}
|
||||
setActiveTab(value)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const match = tabs.find(tab => tab.href === pathname)
|
||||
if (match) {
|
||||
setActiveTab(match.value)
|
||||
}
|
||||
}, [pathname])
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={3}>Desa Anti Korupsi</Title>
|
||||
<Tabs color={colors['blue-button']} variant='pills' value={activeTab} onChange={handleTabChange}>
|
||||
<TabsList p={"xs"} bg={"#BBC8E7FF"}>
|
||||
{tabs.map((e, i) => (
|
||||
<TabsTab key={i} value={e.value}>{e.label}</TabsTab>
|
||||
))}
|
||||
</TabsList>
|
||||
{tabs.map((e, i) => (
|
||||
<TabsPanel key={i} value={e.value}>
|
||||
{/* Konten dummy, bisa diganti tergantung routing */}
|
||||
<></>
|
||||
</TabsPanel>
|
||||
))}
|
||||
</Tabs>
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export default LayoutTabs;
|
||||
@@ -0,0 +1,98 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import korupsiState from '@/app/admin/(dashboard)/_state/landing-page/desa-anti-korupsi';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { IconArrowBack } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function EditKategoriDesaAntiKorupsi() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const id = params?.id as string;
|
||||
const stateKategori = useProxy(korupsiState.kategoriDesaAntiKorupsi);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const loadKategorikegiatan = async () => {
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
const data = await stateKategori.edit.load(id);
|
||||
|
||||
if (data) {
|
||||
// pastikan id-nya masuk ke state edit
|
||||
stateKategori.edit.id = id;
|
||||
setFormData({
|
||||
name: data.name || '',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading kategori desa anti korupsi:", error);
|
||||
toast.error("Gagal memuat data kategori desa anti korupsi");
|
||||
}
|
||||
};
|
||||
|
||||
loadKategorikegiatan();
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
if (!formData.name.trim()) {
|
||||
toast.error('Nama kategori desa anti korupsi tidak boleh kosong');
|
||||
return;
|
||||
}
|
||||
|
||||
stateKategori.edit.form = {
|
||||
name: formData.name.trim(),
|
||||
};
|
||||
|
||||
// Safety check tambahan: pastikan ID tidak kosong
|
||||
if (!stateKategori.edit.id) {
|
||||
stateKategori.edit.id = id; // fallback
|
||||
}
|
||||
|
||||
const success = await stateKategori.edit.update();
|
||||
|
||||
if (success) {
|
||||
router.push("/admin/landing-page/desa-anti-korupsi/kategori-desa-anti-korupsi");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating kategori desa anti korupsi:", error);
|
||||
// toast akan ditampilkan dari fungsi update
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Edit Kategori Desa Anti Korupsi</Title>
|
||||
<TextInput
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Kategori Desa Anti Korupsi</Text>}
|
||||
placeholder='Masukkan nama kategori desa anti korupsi'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditKategoriDesaAntiKorupsi;
|
||||
@@ -0,0 +1,61 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { IconArrowBack } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import korupsiState from '../../../../_state/landing-page/desa-anti-korupsi';
|
||||
|
||||
function CreateKategoriDesaAntiKorupsi() {
|
||||
const router = useRouter();
|
||||
const stateKategori = useProxy(korupsiState.kategoriDesaAntiKorupsi)
|
||||
|
||||
useEffect(() => {
|
||||
stateKategori.findMany.load();
|
||||
}, []);
|
||||
|
||||
const resetForm = () => {
|
||||
stateKategori.create.form = {
|
||||
name: "",
|
||||
};
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
await stateKategori.create.create();
|
||||
resetForm();
|
||||
router.push("/admin/landing-page/desa-anti-korupsi/kategori-desa-anti-korupsi")
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Create Kategori Desa Anti Korupsi</Title>
|
||||
<TextInput
|
||||
value={stateKategori.create.form.name}
|
||||
onChange={(val) => {
|
||||
stateKategori.create.form.name = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Kategori Desa Anti Korupsi</Text>}
|
||||
placeholder='Masukkan nama kategori desa anti korupsi'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateKategoriDesaAntiKorupsi;
|
||||
@@ -0,0 +1,112 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconEdit, IconSearch, IconX } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import HeaderSearch from '../../../_com/header';
|
||||
import JudulList from '../../../_com/judulList';
|
||||
import { ModalKonfirmasiHapus } from '../../../_com/modalKonfirmasiHapus';
|
||||
import korupsiState from '../../../_state/landing-page/desa-anti-korupsi';
|
||||
|
||||
|
||||
function KategoriDesaAntiKorupsi() {
|
||||
const [search, setSearch] = useState("")
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='Kategori Desa Anti Korupsi'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<ListKategoriKegiatan search={search} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListKategoriKegiatan({ search }: { search: string }) {
|
||||
const stateKategori = useProxy(korupsiState.kategoriDesaAntiKorupsi)
|
||||
const [modalHapus, setModalHapus] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
|
||||
const handleHapus = () => {
|
||||
if (selectedId) {
|
||||
stateKategori.delete.byId(selectedId)
|
||||
setModalHapus(false)
|
||||
setSelectedId(null)
|
||||
}
|
||||
}
|
||||
|
||||
useShallowEffect(() => {
|
||||
stateKategori.findMany.load()
|
||||
}, [])
|
||||
|
||||
const filteredData = (stateKategori.findMany.data || []).filter(item => {
|
||||
const keyword = search.toLowerCase();
|
||||
return (
|
||||
item.name.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
|
||||
if (!stateKategori.findMany.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<JudulList
|
||||
title='List Kategori Kegiatan'
|
||||
href='/admin/landing-page/desa-anti-korupsi/kategori-desa-anti-korupsi/create'
|
||||
/>
|
||||
<Table striped withTableBorder withRowBorders>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Nama Kategori</TableTh>
|
||||
<TableTh>Edit</TableTh>
|
||||
<TableTh>Delete</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{filteredData.map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd>{item.name}</TableTd>
|
||||
<TableTd>
|
||||
<Button color="green" onClick={() => router.push(`/admin/landing-page/desa-anti-korupsi/kategori-desa-anti-korupsi/${item.id}`)}>
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
<TableTd>
|
||||
<Button color="red" onClick={() => {
|
||||
setSelectedId(item.id)
|
||||
setModalHapus(true)
|
||||
}}>
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Paper>
|
||||
{/* Modal Konfirmasi Hapus */}
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text='Apakah anda yakin ingin menghapus kategori kegiatan ini?'
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default KategoriDesaAntiKorupsi
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import LayoutTabs from './_lib/layouTabs';
|
||||
|
||||
function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<LayoutTabs>
|
||||
{children}
|
||||
</LayoutTabs>
|
||||
);
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,229 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
import { Box, Button, Group, Paper, Select, Stack, Text, TextInput } from '@mantine/core';
|
||||
import { IconArrowBack, IconFile, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import colors from '@/con/colors';
|
||||
|
||||
import korupsiState from '@/app/admin/(dashboard)/_state/landing-page/desa-anti-korupsi';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { toast } from 'react-toastify';
|
||||
import EditEditor from '@/app/admin/(dashboard)/_com/editEditor';
|
||||
|
||||
interface FormDesaAntiKorupsi {
|
||||
name: string;
|
||||
deskripsi: string;
|
||||
kategoriId: string;
|
||||
fileId: string;
|
||||
}
|
||||
|
||||
function EditDesaAntiKorupsi() {
|
||||
const desaAntiKorupsiState = useProxy(korupsiState.desaAntikorupsi)
|
||||
const [previewFile, setPreviewFile] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const params = useParams()
|
||||
const router = useRouter()
|
||||
const [formData, setFormData] = useState<FormDesaAntiKorupsi>({
|
||||
name: '',
|
||||
deskripsi: '',
|
||||
kategoriId: '',
|
||||
fileId: '',
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const loadDesaAntiKorupsi = async () => {
|
||||
const id = params?.id as string;
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
const data = await desaAntiKorupsiState.edit.load(id);
|
||||
if (data) {
|
||||
// ⬇️ FIX PENTING: tambahkan ini
|
||||
desaAntiKorupsiState.edit.id = id;
|
||||
|
||||
desaAntiKorupsiState.edit.form = {
|
||||
name: data.name,
|
||||
deskripsi: data.deskripsi,
|
||||
kategoriId: data.kategoriId,
|
||||
fileId: data.fileId,
|
||||
};
|
||||
|
||||
setFormData({
|
||||
name: data.name,
|
||||
deskripsi: data.deskripsi,
|
||||
kategoriId: data.kategoriId,
|
||||
fileId: data.fileId,
|
||||
});
|
||||
|
||||
if (data?.file?.link) {
|
||||
setPreviewFile(data.file.link)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading program penghijauan:", error);
|
||||
toast.error("Gagal memuat data program penghijauan");
|
||||
}
|
||||
}
|
||||
|
||||
loadDesaAntiKorupsi();
|
||||
}, [params?.id]);
|
||||
|
||||
|
||||
const handleSubmit = async () => {
|
||||
|
||||
try {
|
||||
// Update global state with form data
|
||||
desaAntiKorupsiState.edit.form = {
|
||||
...desaAntiKorupsiState.edit.form,
|
||||
name: formData.name,
|
||||
deskripsi: formData.deskripsi,
|
||||
kategoriId: formData.kategoriId || '',
|
||||
fileId: formData.fileId // Keep existing imageId if not changed
|
||||
};
|
||||
|
||||
// Jika ada file baru, upload
|
||||
if (file) {
|
||||
const res = await ApiFetch.api.fileStorage.create.post({ file, name: file.name });
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal upload gambar");
|
||||
}
|
||||
|
||||
// Update imageId in global state
|
||||
desaAntiKorupsiState.edit.form.fileId = uploaded.id;
|
||||
}
|
||||
|
||||
await desaAntiKorupsiState.edit.update();
|
||||
toast.success("desa anti korupsi berhasil diperbarui!");
|
||||
router.push("/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi");
|
||||
} catch (error) {
|
||||
console.error("Error updating desa anti korupsi:", error);
|
||||
toast.error("Terjadi kesalahan saat memperbarui desa anti korupsi");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<Text fz={"xl"} fw={"bold"}>Edit List Desa Anti Korupsi</Text>
|
||||
{desaAntiKorupsiState.findUnique.data ? (
|
||||
<Paper key={desaAntiKorupsiState.findUnique.data.id}>
|
||||
<Stack gap={"xs"}>
|
||||
<TextInput
|
||||
value={formData.name}
|
||||
onChange={(val) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
name: val.target.value
|
||||
})
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Judul</Text>}
|
||||
placeholder='Masukkan judul'
|
||||
/>
|
||||
<Box>
|
||||
<Text fz={"sm"} fw={"bold"}>Deskripsi</Text>
|
||||
<EditEditor
|
||||
value={formData.deskripsi}
|
||||
onChange={(val) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
deskripsi: val
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Select
|
||||
value={formData.kategoriId}
|
||||
onChange={(val) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
kategoriId: val ?? ""
|
||||
})
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Kategori</Text>}
|
||||
placeholder="Pilih kategori"
|
||||
data={
|
||||
korupsiState.kategoriDesaAntiKorupsi.findMany.data?.map((v) => ({
|
||||
value: v.id,
|
||||
label: v.name,
|
||||
})) || []
|
||||
}
|
||||
/>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>File Document</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewFile(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{
|
||||
'application/*': ['.pdf', '.doc', '.docx'],
|
||||
}}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconFile size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag file ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format document
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Dokumen</Text>
|
||||
{previewFile ? (
|
||||
<iframe
|
||||
src={previewFile}
|
||||
width="100%"
|
||||
height="500px"
|
||||
style={{ border: "1px solid #ccc", borderRadius: "8px" }}
|
||||
/>
|
||||
) : (
|
||||
<Text>Tidak ada dokumen tersedia</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
) : null}
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditDesaAntiKorupsi;
|
||||
@@ -0,0 +1,122 @@
|
||||
'use client'
|
||||
import { ModalKonfirmasiHapus } from '@/app/admin/(dashboard)/_com/modalKonfirmasiHapus';
|
||||
import korupsiState from '@/app/admin/(dashboard)/_state/landing-page/desa-anti-korupsi';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Flex, Paper, Skeleton, Stack, Text } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconArrowBack, IconEdit, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
|
||||
function DetailKegiatanDesa() {
|
||||
const detailState = useProxy(korupsiState.desaAntikorupsi)
|
||||
const [modalHapus, setModalHapus] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const params = useParams()
|
||||
const router = useRouter()
|
||||
|
||||
useShallowEffect(() => {
|
||||
detailState.findUnique.load(params?.id as string)
|
||||
}, [])
|
||||
|
||||
|
||||
const handleHapus = () => {
|
||||
if (selectedId) {
|
||||
detailState.delete.byId(selectedId)
|
||||
setModalHapus(false)
|
||||
setSelectedId(null)
|
||||
router.push("/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi")
|
||||
}
|
||||
}
|
||||
|
||||
if (!detailState.findUnique.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Paper bg={colors['white-1']} w={{ base: "100%", md: "100%", lg: "50%" }} p={'md'}>
|
||||
<Stack>
|
||||
<Text fz={"xl"} fw={"bold"}>Detail List Desa Anti Korupsi</Text>
|
||||
{detailState.findUnique.data ? (
|
||||
<Paper key={detailState.findUnique.data.id} bg={colors['BG-trans']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Judul</Text>
|
||||
<Text fz={"lg"}>{detailState.findUnique.data?.name}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Deskripsi</Text>
|
||||
<Text fz={"lg"} dangerouslySetInnerHTML={{ __html: detailState.findUnique.data?.deskripsi }} />
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Kategori</Text>
|
||||
<Text fz={"lg"}>{detailState.findUnique.data?.kategori?.name}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Dokumen</Text>
|
||||
{detailState.findUnique.data?.file?.link ? (
|
||||
<iframe
|
||||
src={detailState.findUnique.data.file.link}
|
||||
width="100%"
|
||||
height="500px"
|
||||
style={{ border: "1px solid #ccc", borderRadius: "8px" }}
|
||||
/>
|
||||
) : (
|
||||
<Text>Tidak ada dokumen tersedia</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Flex gap={"xs"} mt={10}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (detailState.findUnique.data) {
|
||||
setSelectedId(detailState.findUnique.data.id);
|
||||
setModalHapus(true);
|
||||
}
|
||||
}}
|
||||
disabled={detailState.delete.loading || !detailState.findUnique.data}
|
||||
color={"red"}
|
||||
>
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (detailState.findUnique.data) {
|
||||
router.push(`/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi/${detailState.findUnique.data.id}/edit`);
|
||||
}
|
||||
}}
|
||||
disabled={!detailState.findUnique.data}
|
||||
color={"green"}
|
||||
>
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</Flex>
|
||||
</Stack>
|
||||
</Paper>
|
||||
) : null}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Modal Konfirmasi Hapus */}
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text='Apakah anda yakin ingin menghapus desa anti korupsi ini?'
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default DetailKegiatanDesa;
|
||||
@@ -0,0 +1,166 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import CreateEditor from '@/app/admin/(dashboard)/_com/createEditor';
|
||||
import korupsiState from '@/app/admin/(dashboard)/_state/landing-page/desa-anti-korupsi';
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Paper, Select, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconFile, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
|
||||
function CreateDesaAntiKorupsi() {
|
||||
const router = useRouter();
|
||||
const stateKorupsi = useProxy(korupsiState.desaAntikorupsi)
|
||||
const [previewFile, setPreviewFile] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
stateKorupsi.findMany.load();
|
||||
korupsiState.kategoriDesaAntiKorupsi.findMany.load();
|
||||
}, []);
|
||||
|
||||
const resetForm = () => {
|
||||
stateKorupsi.create.form = {
|
||||
name: "",
|
||||
deskripsi: "",
|
||||
kategoriId: "",
|
||||
fileId: "",
|
||||
};
|
||||
setFile(null);
|
||||
setPreviewFile(null);
|
||||
};
|
||||
const handleSubmit = async () => {
|
||||
if (!file) {
|
||||
return toast.warn("Pilih file pdf terlebih dahulu");
|
||||
}
|
||||
|
||||
const res = await ApiFetch.api.fileStorage.create.post({
|
||||
file,
|
||||
name: file.name,
|
||||
})
|
||||
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal mengupload file");
|
||||
}
|
||||
|
||||
stateKorupsi.create.form.fileId = uploaded.id;
|
||||
|
||||
await stateKorupsi.create.create();
|
||||
|
||||
resetForm();
|
||||
router.push("/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi")
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Create Kegiatan Desa</Title>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>File Document</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewFile(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{
|
||||
'application/*': ['.pdf', '.doc', '.docx'],
|
||||
}}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconFile size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag file ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format document
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Dokumen</Text>
|
||||
{previewFile ? (
|
||||
<iframe
|
||||
src={previewFile}
|
||||
width="100%"
|
||||
height="500px"
|
||||
style={{ border: "1px solid #ccc", borderRadius: "8px" }}
|
||||
/>
|
||||
) : (
|
||||
<Text>Tidak ada dokumen tersedia</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
<TextInput
|
||||
value={stateKorupsi.create.form.name}
|
||||
onChange={(val) => {
|
||||
stateKorupsi.create.form.name = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Judul</Text>}
|
||||
placeholder='Masukkan judul'
|
||||
/>
|
||||
<Box>
|
||||
<Text fz={"sm"} fw={"bold"}>Deskripsi</Text>
|
||||
<CreateEditor
|
||||
value={stateKorupsi.create.form.deskripsi}
|
||||
onChange={(val) => {
|
||||
stateKorupsi.create.form.deskripsi = val;
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Select
|
||||
value={stateKorupsi.create.form.kategoriId}
|
||||
onChange={(val) => {
|
||||
stateKorupsi.create.form.kategoriId = val ?? "";
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Kategori</Text>}
|
||||
placeholder="Pilih kategori"
|
||||
data={
|
||||
korupsiState.kategoriDesaAntiKorupsi.findMany.data?.map((v) => ({
|
||||
value: v.id,
|
||||
label: v.name,
|
||||
})) || []
|
||||
}
|
||||
/>
|
||||
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateDesaAntiKorupsi;
|
||||
@@ -0,0 +1,99 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Text } from '@mantine/core';
|
||||
import { IconDeviceImacCog, IconSearch } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import HeaderSearch from '../../../_com/header';
|
||||
import JudulList from '../../../_com/judulList';
|
||||
import korupsiState from '../../../_state/landing-page/desa-anti-korupsi';
|
||||
|
||||
function DesaAntiKorupsi() {
|
||||
const [search, setSearch] = useState('');
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='List Desa Anti Korupsi'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<ListDesaAntiKorupsi search={search} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListDesaAntiKorupsi({ search }: { search: string }) {
|
||||
const listState = useProxy(korupsiState.desaAntikorupsi)
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
listState.findMany.load()
|
||||
}, [])
|
||||
|
||||
const filteredData = (listState.findMany.data || []).filter(item => {
|
||||
const keyword = search.toLowerCase();
|
||||
return (
|
||||
item.name.toLowerCase().includes(keyword) ||
|
||||
item.deskripsi.toLowerCase().includes(keyword) ||
|
||||
item.kategori?.name?.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
|
||||
if (!listState.findMany.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<JudulList
|
||||
title='List Desa Anti Korupsi'
|
||||
href='/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi/create'
|
||||
/>
|
||||
<Box style={{ overflowX: 'auto' }}>
|
||||
<Table striped withRowBorders withTableBorder style={{ minWidth: '700px' }}>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Nama Desa Anti Korupsi</TableTh>
|
||||
<TableTh>Deskripsi Desa Anti Korupsi</TableTh>
|
||||
<TableTh>Kategori Desa Anti Korupsi</TableTh>
|
||||
<TableTh>Detail</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{filteredData.map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd>
|
||||
<Box w={100}>
|
||||
<Text truncate="end" fz={"sm"}>{item.name}</Text>
|
||||
</Box>
|
||||
</TableTd>
|
||||
<TableTd>
|
||||
<Text truncate="end" fz={"sm"} dangerouslySetInnerHTML={{ __html: item.deskripsi }} />
|
||||
</TableTd>
|
||||
<TableTd>{item.kategori?.name}</TableTd>
|
||||
<TableTd>
|
||||
<Button onClick={() => router.push(`/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi/${item.id}`)}>
|
||||
<IconDeviceImacCog size={25} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default DesaAntiKorupsi;
|
||||
@@ -1,11 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
Desa Anti Korupsi
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Page;
|
||||
@@ -1,23 +0,0 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Stack, Text, Textarea, Title } from '@mantine/core';
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<Box>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={2}>Layanan</Title>
|
||||
<Textarea
|
||||
label={<Text>Deskripsi</Text>}
|
||||
placeholder='tambah deskripsi'
|
||||
/>
|
||||
<Group>
|
||||
<Button
|
||||
bg={colors['blue-button']} fz={'md'}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default Page;
|
||||
@@ -1,11 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
Penghargaan
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Page;
|
||||
@@ -1,11 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
Potensi
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Page;
|
||||
@@ -0,0 +1,67 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Stack, Tabs, TabsList, TabsPanel, TabsTab, Title } from '@mantine/core';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
function LayoutTabs({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const tabs = [
|
||||
{
|
||||
label: "Program Inovasi",
|
||||
value: "program-inovasi",
|
||||
href: "/admin/landing-page/profile/program-inovasi"
|
||||
},
|
||||
{
|
||||
label: "Pejabat Desa",
|
||||
value: "pejabat-desa",
|
||||
href: "/admin/landing-page/profile/pejabat-desa"
|
||||
},
|
||||
{
|
||||
label: "Media Sosial",
|
||||
value: "media-sosial",
|
||||
href: "/admin/landing-page/profile/media-sosial"
|
||||
},
|
||||
];
|
||||
const curentTab = tabs.find(tab => tab.href === pathname)
|
||||
const [activeTab, setActiveTab] = useState<string | null>(curentTab?.value || tabs[0].value);
|
||||
|
||||
const handleTabChange = (value: string | null) => {
|
||||
const tab = tabs.find(t => t.value === value)
|
||||
if (tab) {
|
||||
router.push(tab.href)
|
||||
}
|
||||
setActiveTab(value)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const match = tabs.find(tab => tab.href === pathname)
|
||||
if (match) {
|
||||
setActiveTab(match.value)
|
||||
}
|
||||
}, [pathname])
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={3}>Profile</Title>
|
||||
<Tabs color={colors['blue-button']} variant='pills' value={activeTab} onChange={handleTabChange}>
|
||||
<TabsList p={"xs"} bg={"#BBC8E7FF"}>
|
||||
{tabs.map((e, i) => (
|
||||
<TabsTab key={i} value={e.value}>{e.label}</TabsTab>
|
||||
))}
|
||||
</TabsList>
|
||||
{tabs.map((e, i) => (
|
||||
<TabsPanel key={i} value={e.value}>
|
||||
{/* Konten dummy, bisa diganti tergantung routing */}
|
||||
<></>
|
||||
</TabsPanel>
|
||||
))}
|
||||
</Tabs>
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export default LayoutTabs;
|
||||
11
src/app/admin/(dashboard)/landing-page/profile/layout.tsx
Normal file
11
src/app/admin/(dashboard)/landing-page/profile/layout.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import React from 'react';
|
||||
import LayoutTabs from './_lib/layoutTabs';
|
||||
|
||||
function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<LayoutTabs>
|
||||
{children}
|
||||
</LayoutTabs>
|
||||
);
|
||||
}
|
||||
export default Layout;
|
||||
@@ -0,0 +1,174 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import profileLandingPageState from '@/app/admin/(dashboard)/_state/landing-page/profile';
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Image, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function EditMediaSosial() {
|
||||
const stateMediaSosial = useProxy(profileLandingPageState.mediaSosial)
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
name: stateMediaSosial.update.form.name || "",
|
||||
iconUrl: stateMediaSosial.update.form.iconUrl || "",
|
||||
imageId: stateMediaSosial.update.form.imageId || ""
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const id = params?.id as string;
|
||||
if (!id) return;
|
||||
|
||||
const loadMediaSosial = async () => {
|
||||
try {
|
||||
const data = await stateMediaSosial.update.load(id);
|
||||
|
||||
if (data) {
|
||||
setFormData({
|
||||
name: data.name || "",
|
||||
iconUrl: data.iconUrl || "",
|
||||
imageId: data.imageId || "",
|
||||
});
|
||||
// Tampilkan preview gambar
|
||||
if (data.image?.link) {
|
||||
setPreviewImage(data.image.link);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading program inovasi:", error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Gagal mengambil data program inovasi"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
loadMediaSosial();
|
||||
}, [params?.id]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
stateMediaSosial.update.form = {
|
||||
...stateMediaSosial.update.form,
|
||||
name: formData.name,
|
||||
iconUrl: formData.iconUrl,
|
||||
imageId: formData.imageId ?? "",
|
||||
}
|
||||
if (file) {
|
||||
const res = await ApiFetch.api.fileStorage.create.post({ file, name: file.name });
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal upload gambar");
|
||||
}
|
||||
|
||||
// Update imageId in global state
|
||||
stateMediaSosial.update.form.imageId = uploaded.id;
|
||||
}
|
||||
|
||||
await stateMediaSosial.update.update();
|
||||
toast.success("Media Sosial berhasil diperbarui!");
|
||||
router.push("/admin/landing-page/profile/media-sosial");
|
||||
} catch (error) {
|
||||
console.error("Error updating media sosial:", error);
|
||||
toast.error("Terjadi kesalahan saat memperbarui media sosial");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Edit Media Sosial</Title>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewImage(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
<TextInput
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Media Sosial / Nama Kontak</Text>}
|
||||
placeholder='Masukkan nama media sosial'
|
||||
/>
|
||||
<TextInput
|
||||
value={formData.iconUrl}
|
||||
onChange={(e) => setFormData({ ...formData, iconUrl: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Icon URL / No Telephone</Text>}
|
||||
placeholder='Masukkan icon url'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditMediaSosial;
|
||||
@@ -0,0 +1,107 @@
|
||||
'use client'
|
||||
import { ModalKonfirmasiHapus } from '@/app/admin/(dashboard)/_com/modalKonfirmasiHapus';
|
||||
import profileLandingPageState from '@/app/admin/(dashboard)/_state/landing-page/profile';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Flex, Image, Paper, Skeleton, Stack, Text } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconArrowBack, IconEdit, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function DetailMediaSosial() {
|
||||
const stateMediaSosial = useProxy(profileLandingPageState.mediaSosial)
|
||||
const [modalHapus, setModalHapus] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const params = useParams()
|
||||
const router = useRouter();
|
||||
|
||||
useShallowEffect(() => {
|
||||
stateMediaSosial.findUnique.load(params?.id as string)
|
||||
}, [])
|
||||
|
||||
const handleHapus = () => {
|
||||
if (selectedId) {
|
||||
stateMediaSosial.delete.byId(selectedId)
|
||||
setModalHapus(false)
|
||||
setSelectedId(null)
|
||||
router.push("/admin/landing-page/profile/media-sosial")
|
||||
}
|
||||
}
|
||||
|
||||
if (!stateMediaSosial.findUnique.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Paper w={{ base: "100%", md: "50%" }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<Text fz={"xl"} fw={"bold"}>Detail Media Sosial</Text>
|
||||
<Paper bg={colors['BG-trans']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Nama Media Sosial / Nama Kontak</Text>
|
||||
<Text fz={"lg"}>{stateMediaSosial.findUnique.data?.name}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Icon URL / No Telephone</Text>
|
||||
<Text fz={"lg"}>{stateMediaSosial.findUnique.data?.iconUrl}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Gambar</Text>
|
||||
<Box w={100} h={100}>
|
||||
<Image src={stateMediaSosial.findUnique.data?.image?.link} alt="gambar" />
|
||||
</Box>
|
||||
</Box>
|
||||
<Box>
|
||||
<Flex gap={"xs"}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (stateMediaSosial.findUnique.data) {
|
||||
setSelectedId(stateMediaSosial.findUnique.data.id);
|
||||
setModalHapus(true);
|
||||
}
|
||||
}}
|
||||
disabled={!stateMediaSosial.findUnique.data}
|
||||
color="red">
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (stateMediaSosial.findUnique.data) {
|
||||
router.push(`/admin/landing-page/profile/media-sosial/${stateMediaSosial.findUnique.data.id}/edit`);
|
||||
}
|
||||
}}
|
||||
disabled={!stateMediaSosial.findUnique.data}
|
||||
color="green">
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</Flex>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Modal Hapus */}
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text="Apakah anda yakin ingin menghapus media sosial ini?"
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default DetailMediaSosial;
|
||||
@@ -0,0 +1,148 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Image, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import profileLandingPageState from '../../../../_state/landing-page/profile';
|
||||
|
||||
function CreateMediaSosial() {
|
||||
const router = useRouter();
|
||||
const stateMediaSosial = useProxy(profileLandingPageState.mediaSosial)
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
stateMediaSosial.findMany.load();
|
||||
}, []);
|
||||
|
||||
const resetForm = () => {
|
||||
stateMediaSosial.create.form = {
|
||||
name: "",
|
||||
imageId: "",
|
||||
iconUrl: "",
|
||||
};
|
||||
setPreviewImage(null);
|
||||
setFile(null);
|
||||
};
|
||||
const handleSubmit = async () => {
|
||||
if (!file) {
|
||||
return toast.warn("Pilih file gambar terlebih dahulu");
|
||||
}
|
||||
|
||||
const res = await ApiFetch.api.fileStorage.create.post({
|
||||
file,
|
||||
name: file.name,
|
||||
})
|
||||
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal mengupload file");
|
||||
}
|
||||
|
||||
stateMediaSosial.create.form.imageId = uploaded.id;
|
||||
|
||||
await stateMediaSosial.create.create();
|
||||
|
||||
resetForm();
|
||||
router.push("/admin/landing-page/profile/media-sosial")
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Create Media Sosial</Title>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewImage(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
<TextInput
|
||||
value={stateMediaSosial.create.form.name || ''}
|
||||
onChange={(val) => {
|
||||
stateMediaSosial.create.form.name = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Media Sosial / Nama Kontak</Text>}
|
||||
placeholder='Masukkan nama media sosial / nama kontak'
|
||||
/>
|
||||
<TextInput
|
||||
value={stateMediaSosial.create.form.iconUrl || ''}
|
||||
onChange={(val) => {
|
||||
stateMediaSosial.create.form.iconUrl = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Link Media Sosial / No Telephone</Text>}
|
||||
placeholder='Masukkan link media sosial / no telephone'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateMediaSosial;
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Image, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconDeviceImac, IconSearch } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import HeaderSearch from '../../../_com/header';
|
||||
import JudulList from '../../../_com/judulList';
|
||||
import profileLandingPageState from '../../../_state/landing-page/profile';
|
||||
|
||||
function MediaSosial() {
|
||||
const [search, setSearch] = useState("");
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='Media Sosial'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<ListMediaSosial search={search} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListMediaSosial({ search }: { search: string }) {
|
||||
const stateMediaSosial = useProxy(profileLandingPageState.mediaSosial)
|
||||
const router = useRouter();
|
||||
|
||||
useShallowEffect(() => {
|
||||
stateMediaSosial.findMany.load()
|
||||
}, [])
|
||||
|
||||
const filteredData = (stateMediaSosial.findMany.data || []).filter(item => {
|
||||
const keyword = search.toLowerCase();
|
||||
return (
|
||||
item.name.toLowerCase().includes(keyword) ||
|
||||
item.iconUrl?.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
|
||||
if (!stateMediaSosial.findMany.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<JudulList
|
||||
title='List Media Sosial'
|
||||
href='/admin/landing-page/profile/media-sosial/create'
|
||||
/>
|
||||
<Table striped withTableBorder withRowBorders>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Nama Media Sosial / Nama Kontak</TableTh>
|
||||
<TableTh>Image</TableTh>
|
||||
<TableTh>Icon URL / No Telephone</TableTh>
|
||||
<TableTh>Detail</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{filteredData.map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd>{item.name}</TableTd>
|
||||
<TableTd>
|
||||
<Box w={50} h={50}>
|
||||
<Image src={item.image?.link} alt={item.name} />
|
||||
</Box>
|
||||
</TableTd>
|
||||
<TableTd>{item.iconUrl}</TableTd>
|
||||
<TableTd>
|
||||
<Button onClick={() => router.push(`/admin/landing-page/profile/media-sosial/${item.id}`)}>
|
||||
<IconDeviceImac size={20} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default MediaSosial;
|
||||
@@ -1,11 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
Profile
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Page;
|
||||
@@ -0,0 +1,270 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Alert, Box, Button, Center, Group, Image, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
import profileLandingPageState from '@/app/admin/(dashboard)/_state/landing-page/profile';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconAlertCircle, IconArrowBack, IconImageInPicture, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
function EditPejabatDesa() {
|
||||
const allState = useProxy(profileLandingPageState.pejabatDesa);
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
|
||||
// UI States
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// Load data on mount
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
const id = params?.id as string;
|
||||
if (!id) {
|
||||
toast.error("ID tidak valid");
|
||||
router.push("/admin/landing-page/profile/pejabat-desa");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const profileData = await profileLandingPageState.pejabatDesa.findUnique.load(id);
|
||||
profileLandingPageState.pejabatDesa.edit.initialize(profileData);
|
||||
|
||||
|
||||
if (profileData && profileData.image?.link) {
|
||||
setPreviewImage(profileData.image.link);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading profile:", error);
|
||||
toast.error("Gagal memuat data profile");
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
|
||||
return () => {
|
||||
profileLandingPageState.pejabatDesa.edit.reset(); // cleanup form
|
||||
};
|
||||
}, [params?.id, router]);
|
||||
|
||||
const handleFieldChange = (field: string, value: string) => {
|
||||
profileLandingPageState.pejabatDesa.edit.updateField(field as any, value);
|
||||
};
|
||||
|
||||
const handleFileChange = (newFile: File | null) => {
|
||||
if (!newFile) {
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setFile(newFile);
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setPreviewImage(event.target?.result as string);
|
||||
};
|
||||
reader.readAsDataURL(newFile);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (isSubmitting || !profileLandingPageState.pejabatDesa.edit.form.name.trim()) {
|
||||
toast.error("Nama wajib diisi");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Upload file jika ada
|
||||
if (file) {
|
||||
const uploadResponse = await ApiFetch.api.fileStorage.create.post({ file, name: file.name });
|
||||
const uploaded = uploadResponse.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
toast.error("Gagal upload gambar");
|
||||
return;
|
||||
}
|
||||
|
||||
profileLandingPageState.pejabatDesa.edit.form.imageId = uploaded.id;
|
||||
}
|
||||
|
||||
// Submit form
|
||||
const success = await profileLandingPageState.pejabatDesa.edit.submit();
|
||||
|
||||
if (success) {
|
||||
toast.success("Berhasil menyimpan perubahan");
|
||||
router.push("/admin/landing-page/profile/pejabat-desa");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error submitting form:", error);
|
||||
toast.error("Gagal menyimpan profile");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
router.back();
|
||||
};
|
||||
|
||||
// Loading state
|
||||
if (allState.edit.loading) {
|
||||
return (
|
||||
<Box>
|
||||
<Center h={400}>
|
||||
<Text>Memuat data profile...</Text>
|
||||
</Center>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (allState.edit.error) {
|
||||
return (
|
||||
<Box>
|
||||
<Stack gap="md">
|
||||
<Button variant="subtle" onClick={handleBack}>
|
||||
<IconArrowBack color={colors['blue-button']} size={20} />
|
||||
</Button>
|
||||
<Alert icon={<IconAlertCircle size={16} />} color="red">
|
||||
<Text fw="bold">Error</Text>
|
||||
<Text>{allState.edit.error}</Text>
|
||||
</Alert>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Stack gap="xs">
|
||||
<Box>
|
||||
<Button variant="subtle" onClick={handleBack}>
|
||||
<IconArrowBack color={colors['blue-button']} size={20} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Paper w={{ base: "100%", md: "50%" }} bg={colors['white-1']} p="md" radius={10}>
|
||||
<Stack gap="xs">
|
||||
<Title order={3}>Edit Profile Pejabat Desa</Title>
|
||||
|
||||
{/* Nama Field */}
|
||||
<TextInput
|
||||
label={<Text fw="bold">Nama Perbekel</Text>}
|
||||
placeholder="Masukkan nama perbekel"
|
||||
value={allState.edit.form.name}
|
||||
onChange={(e) => handleFieldChange('name', e.currentTarget.value)}
|
||||
error={!allState.edit.form.name && "Nama wajib diisi"}
|
||||
/>
|
||||
|
||||
{/* Posisi Field */}
|
||||
<TextInput
|
||||
label={<Text fw="bold">Posisi</Text>}
|
||||
placeholder="Masukkan posisi"
|
||||
value={allState.edit.form.position}
|
||||
onChange={(e) => handleFieldChange('position', e.currentTarget.value)}
|
||||
error={!allState.edit.form.position && "Posisi wajib diisi"}
|
||||
/>
|
||||
|
||||
{/* File Upload */}
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => handleFileChange(files[0])}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Preview Gambar */}
|
||||
<Box>
|
||||
<Text fz="sm" fw="bold" mb="xs">Preview Gambar</Text>
|
||||
{previewImage ? (
|
||||
<Image alt="Profile preview" src={previewImage} w={200} h={200} fit="cover" radius="md" />
|
||||
) : (
|
||||
<Center w={200} h={200} bg="gray.2">
|
||||
<Stack align="center" gap="xs">
|
||||
<IconImageInPicture size={48} color="gray" />
|
||||
<Text size="sm" c="gray">Tidak ada gambar</Text>
|
||||
</Stack>
|
||||
</Center>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Group>
|
||||
<Button
|
||||
bg={colors['blue-button']}
|
||||
onClick={handleSubmit}
|
||||
loading={isSubmitting || allState.edit.loading}
|
||||
disabled={!allState.edit.form.name}
|
||||
>
|
||||
{isSubmitting ? 'Menyimpan...' : 'Simpan Perubahan'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleBack}
|
||||
disabled={isSubmitting || allState.edit.loading}
|
||||
>
|
||||
Batal
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditPejabatDesa;
|
||||
@@ -0,0 +1,104 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Center, Divider, Grid, GridCol, Image, Paper, Skeleton, Stack, Text, Title } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconEdit } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import profileLandingPageState from '@/app/admin/(dashboard)/_state/landing-page/profile';
|
||||
|
||||
|
||||
function Page() {
|
||||
const router = useRouter()
|
||||
const allList = useProxy(profileLandingPageState.pejabatDesa)
|
||||
useShallowEffect(() => {
|
||||
allList.findUnique.load("edit") // Assuming "1" is your default ID, adjust as needed
|
||||
}, [])
|
||||
|
||||
if (!allList.findUnique.data) {
|
||||
return <Stack>
|
||||
<Skeleton radius={10} h={800} />
|
||||
</Stack>
|
||||
}
|
||||
|
||||
const dataArray = Array.isArray(allList.findUnique.data)
|
||||
? allList.findUnique.data
|
||||
: [allList.findUnique.data];
|
||||
|
||||
return (
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Grid>
|
||||
<GridCol span={{ base: 12, md: 11 }}>
|
||||
<Title order={3}>Preview Pejabat Desa</Title>
|
||||
</GridCol>
|
||||
<GridCol span={{ base: 12, md: 1 }}>
|
||||
<Button bg={colors['blue-button']} onClick={() => router.push(`/admin/landing-page/profile/pejabat-desa/${allList.findUnique.data?.id}`)}>
|
||||
<IconEdit size={16} />
|
||||
</Button>
|
||||
</GridCol>
|
||||
</Grid>
|
||||
{dataArray.map((item) => (
|
||||
<Box key={item.id} >
|
||||
<Paper p={"xl"} bg={colors['BG-trans']}>
|
||||
<Box px={{ base: "md", md: 100 }}>
|
||||
<Grid>
|
||||
<GridCol span={{ base: 12, md: 12 }}>
|
||||
<Center>
|
||||
<Image src={"/darmasaba-icon.png"} w={{ base: 100, md: 150 }} alt='' />
|
||||
</Center>
|
||||
</GridCol>
|
||||
<GridCol span={{ base: 12, md: 12 }}>
|
||||
<Text ta={"center"} fz={{ base: "1.2rem", md: "1.8rem" }} fw={'bold'}>PROFIL PIMPINAN BADAN PUBLIK DESA DARMASABA </Text>
|
||||
</GridCol>
|
||||
</Grid>
|
||||
</Box>
|
||||
<Divider my={"md"} color={colors['blue-button']} />
|
||||
{/* biodata perbekel */}
|
||||
<Box px={{ base: 0, md: 50 }} pb={30}>
|
||||
<Box pb={20} px={{ base: 0, md: 50 }}>
|
||||
<Paper bg={colors['BG-trans']} w={{ base: "100%", md: "100%" }}>
|
||||
<Stack gap={0}>
|
||||
<Center>
|
||||
<Image
|
||||
pt={{ base: 0, md: 90 }}
|
||||
src={item.image?.link || "/perbekel.png"}
|
||||
w={{ base: 250, md: 350 }}
|
||||
alt='Foto Profil PPID'
|
||||
onError={(e) => {
|
||||
e.currentTarget.src = "/perbekel.png";
|
||||
}}
|
||||
/>
|
||||
</Center>
|
||||
<Paper
|
||||
bg={colors['blue-button']}
|
||||
py={20}
|
||||
className="glass3"
|
||||
px={{ base: 10, md: 10 }}
|
||||
|
||||
>
|
||||
<Text ta={"center"} c={colors['white-1']} fw={"bolder"} fz={{ base: "1.2rem", md: "1.6rem" }}>
|
||||
{item.name}
|
||||
</Text>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
<Box pt={10}>
|
||||
<Box>
|
||||
<Text fz={{ base: "1.125rem", md: "1.6rem" }} fw={'bold'}>Position</Text>
|
||||
<Text fz={{ base: "1rem", md: "1.5rem" }} ta={"justify"}>{item.position}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
export default Page;
|
||||
@@ -0,0 +1,182 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import profileLandingPageState from '@/app/admin/(dashboard)/_state/landing-page/profile';
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Image, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function EditProgramInovasi() {
|
||||
const stateProgramInovasi = useProxy(profileLandingPageState.programInovasi)
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
name: stateProgramInovasi.update.form.name || "",
|
||||
description: stateProgramInovasi.update.form.description || "",
|
||||
imageId: stateProgramInovasi.update.form.imageId || "",
|
||||
link: stateProgramInovasi.update.form.link || "",
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const id = params?.id as string;
|
||||
if (!id) return;
|
||||
|
||||
const loadProgramInovasi = async () => {
|
||||
try {
|
||||
const data = await stateProgramInovasi.update.load(id);
|
||||
if (data) {
|
||||
setFormData({
|
||||
name: data.name || "",
|
||||
description: data.description || "",
|
||||
imageId: data.imageId || "",
|
||||
link: data.link || ""
|
||||
});
|
||||
// Tampilkan preview gambar
|
||||
if (data.image?.link) {
|
||||
setPreviewImage(data.image.link);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading program inovasi:", error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Gagal mengambil data program inovasi"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
loadProgramInovasi();
|
||||
}, [params?.id]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
stateProgramInovasi.update.form = {
|
||||
...stateProgramInovasi.update.form,
|
||||
name: formData.name,
|
||||
description: formData.description,
|
||||
imageId: formData.imageId,
|
||||
link: formData.link,
|
||||
}
|
||||
if (file) {
|
||||
const res = await ApiFetch.api.fileStorage.create.post({ file, name: file.name });
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal upload gambar");
|
||||
}
|
||||
|
||||
// Update imageId in global state
|
||||
stateProgramInovasi.update.form.imageId = uploaded.id;
|
||||
}
|
||||
|
||||
await stateProgramInovasi.update.update();
|
||||
toast.success("Program Inovasi berhasil diperbarui!");
|
||||
router.push("/admin/landing-page/profile/program-inovasi");
|
||||
} catch (error) {
|
||||
console.error("Error updating program inovasi:", error);
|
||||
toast.error("Terjadi kesalahan saat memperbarui program inovasi");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Edit Program Inovasi</Title>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewImage(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
<TextInput
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Produk</Text>}
|
||||
placeholder='Masukkan nama produk'
|
||||
/>
|
||||
<TextInput
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Deskripsi</Text>}
|
||||
placeholder='Masukkan deskripsi'
|
||||
/>
|
||||
<TextInput
|
||||
value={formData.link}
|
||||
onChange={(e) => setFormData({ ...formData, link: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Link</Text>}
|
||||
placeholder='Masukkan link'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditProgramInovasi;
|
||||
@@ -0,0 +1,109 @@
|
||||
'use client'
|
||||
import { ModalKonfirmasiHapus } from '@/app/admin/(dashboard)/_com/modalKonfirmasiHapus';
|
||||
import profileLandingPageState from '@/app/admin/(dashboard)/_state/landing-page/profile';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Flex, Image, Paper, Skeleton, Stack, Text } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconArrowBack, IconEdit, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function DetailProgramInovasi() {
|
||||
const stateProgramInovasi = useProxy(profileLandingPageState.programInovasi)
|
||||
const [modalHapus, setModalHapus] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const params = useParams()
|
||||
const router = useRouter();
|
||||
|
||||
useShallowEffect(() => {
|
||||
stateProgramInovasi.findUnique.load(params?.id as string)
|
||||
}, [])
|
||||
|
||||
const handleHapus = () => {
|
||||
if (selectedId) {
|
||||
stateProgramInovasi.delete.byId(selectedId)
|
||||
setModalHapus(false)
|
||||
setSelectedId(null)
|
||||
router.push("/admin/landing-page/profile/program-inovasi")
|
||||
}
|
||||
}
|
||||
|
||||
if (!stateProgramInovasi.findUnique.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Paper w={{ base: "100%", md: "50%" }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<Text fz={"xl"} fw={"bold"}>Detail Program Inovasi</Text>
|
||||
<Paper bg={colors['BG-trans']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Nama Program Inovasi</Text>
|
||||
<Text fz={"lg"}>{stateProgramInovasi.findUnique.data?.name}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Deskripsi</Text>
|
||||
<Text fz={"lg"}>{stateProgramInovasi.findUnique.data?.description}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Link</Text>
|
||||
<Text fz={"lg"}>{stateProgramInovasi.findUnique.data?.link}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Gambar</Text>
|
||||
<Image src={stateProgramInovasi.findUnique.data?.image?.link} alt="gambar" />
|
||||
</Box>
|
||||
<Box>
|
||||
<Flex gap={"xs"}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (stateProgramInovasi.findUnique.data) {
|
||||
setSelectedId(stateProgramInovasi.findUnique.data.id);
|
||||
setModalHapus(true);
|
||||
}
|
||||
}}
|
||||
disabled={!stateProgramInovasi.findUnique.data}
|
||||
color="red">
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (stateProgramInovasi.findUnique.data) {
|
||||
router.push(`/admin/landing-page/profile/program-inovasi/${stateProgramInovasi.findUnique.data.id}/edit`);
|
||||
}
|
||||
}}
|
||||
disabled={!stateProgramInovasi.findUnique.data}
|
||||
color="green">
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</Flex>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Modal Hapus */}
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text="Apakah anda yakin ingin menghapus program inovasi ini?"
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default DetailProgramInovasi;
|
||||
@@ -0,0 +1,158 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Image, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import profileLandingPageState from '../../../../_state/landing-page/profile';
|
||||
|
||||
function CreateProgramInovasi() {
|
||||
const router = useRouter();
|
||||
const stateProgramInovasi = useProxy(profileLandingPageState.programInovasi)
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
stateProgramInovasi.findMany.load();
|
||||
}, []);
|
||||
|
||||
const resetForm = () => {
|
||||
stateProgramInovasi.create.form = {
|
||||
name: "",
|
||||
description: "",
|
||||
imageId: "",
|
||||
link: "",
|
||||
};
|
||||
setPreviewImage(null);
|
||||
setFile(null);
|
||||
};
|
||||
const handleSubmit = async () => {
|
||||
if (!file) {
|
||||
return toast.warn("Pilih file gambar terlebih dahulu");
|
||||
}
|
||||
|
||||
const res = await ApiFetch.api.fileStorage.create.post({
|
||||
file,
|
||||
name: file.name,
|
||||
})
|
||||
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal mengupload file");
|
||||
}
|
||||
|
||||
stateProgramInovasi.create.form.imageId = uploaded.id;
|
||||
|
||||
await stateProgramInovasi.create.create();
|
||||
|
||||
resetForm();
|
||||
router.push("/admin/landing-page/profile/program-inovasi")
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Create Program Inovasi</Title>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewImage(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
<TextInput
|
||||
value={stateProgramInovasi.create.form.name || ''}
|
||||
onChange={(val) => {
|
||||
stateProgramInovasi.create.form.name = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Program Inovasi</Text>}
|
||||
placeholder='Masukkan nama program inovasi'
|
||||
/>
|
||||
<TextInput
|
||||
value={stateProgramInovasi.create.form.description || ''}
|
||||
onChange={(val) => {
|
||||
stateProgramInovasi.create.form.description = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Deskripsi</Text>}
|
||||
placeholder='Masukkan deskripsi'
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
value={stateProgramInovasi.create.form.link || ''}
|
||||
onChange={(val) => {
|
||||
stateProgramInovasi.create.form.link = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Link</Text>}
|
||||
placeholder='Masukkan link'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateProgramInovasi;
|
||||
@@ -0,0 +1,90 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconDeviceImac, IconSearch } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import HeaderSearch from '../../../_com/header';
|
||||
import JudulList from '../../../_com/judulList';
|
||||
import profileLandingPageState from '../../../_state/landing-page/profile';
|
||||
|
||||
function ProgramInovasi() {
|
||||
const [search, setSearch] = useState("");
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='Program Inovasi'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<ListProgramInovasi search={search} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListProgramInovasi({ search }: { search: string }) {
|
||||
const stateProgramInovasi = useProxy(profileLandingPageState.programInovasi)
|
||||
const router = useRouter();
|
||||
|
||||
useShallowEffect(() => {
|
||||
stateProgramInovasi.findMany.load()
|
||||
}, [])
|
||||
|
||||
const filteredData = (stateProgramInovasi.findMany.data || []).filter(item => {
|
||||
const keyword = search.toLowerCase();
|
||||
return (
|
||||
item.name.toLowerCase().includes(keyword) ||
|
||||
item.description?.toLowerCase().includes(keyword) ||
|
||||
item.link?.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
|
||||
if (!stateProgramInovasi.findMany.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<JudulList
|
||||
title='List Program Inovasi'
|
||||
href='/admin/landing-page/profile/program-inovasi/create'
|
||||
/>
|
||||
<Table striped withTableBorder withRowBorders>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Nama Program</TableTh>
|
||||
<TableTh>Deskripsi</TableTh>
|
||||
<TableTh>Link</TableTh>
|
||||
<TableTh>Detail</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{filteredData.map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd>{item.name}</TableTd>
|
||||
<TableTd>{item.description}</TableTd>
|
||||
<TableTd>{item.link}</TableTd>
|
||||
<TableTd>
|
||||
<Button onClick={() => router.push(`/admin/landing-page/profile/program-inovasi/${item.id}`)}>
|
||||
<IconDeviceImac size={20} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProgramInovasi;
|
||||
@@ -0,0 +1,62 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Stack, Tabs, TabsList, TabsPanel, TabsTab, Title } from '@mantine/core';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
function LayoutTabs({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const tabs = [
|
||||
{
|
||||
label: "Kegiatan Desa",
|
||||
value: "kegiatanDesa",
|
||||
href: "/admin/lingkungan/gotong-royong/kegiatan-desa"
|
||||
},
|
||||
{
|
||||
label: "Kategori Kegiatan",
|
||||
value: "kategoriKegiatan",
|
||||
href: "/admin/lingkungan/gotong-royong/kategori-kegiatan"
|
||||
},
|
||||
];
|
||||
const curentTab = tabs.find(tab => tab.href === pathname)
|
||||
const [activeTab, setActiveTab] = useState<string | null>(curentTab?.value || tabs[0].value);
|
||||
|
||||
const handleTabChange = (value: string | null) => {
|
||||
const tab = tabs.find(t => t.value === value)
|
||||
if (tab) {
|
||||
router.push(tab.href)
|
||||
}
|
||||
setActiveTab(value)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const match = tabs.find(tab => tab.href === pathname)
|
||||
if (match) {
|
||||
setActiveTab(match.value)
|
||||
}
|
||||
}, [pathname])
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={3}>Gotong Royong</Title>
|
||||
<Tabs color={colors['blue-button']} variant='pills' value={activeTab} onChange={handleTabChange}>
|
||||
<TabsList p={"xs"} bg={"#BBC8E7FF"}>
|
||||
{tabs.map((e, i) => (
|
||||
<TabsTab key={i} value={e.value}>{e.label}</TabsTab>
|
||||
))}
|
||||
</TabsList>
|
||||
{tabs.map((e, i) => (
|
||||
<TabsPanel key={i} value={e.value}>
|
||||
{/* Konten dummy, bisa diganti tergantung routing */}
|
||||
<></>
|
||||
</TabsPanel>
|
||||
))}
|
||||
</Tabs>
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export default LayoutTabs;
|
||||
@@ -1,68 +0,0 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { IconArrowBack, IconImageInPicture } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import React from 'react';
|
||||
import { KeamananEditor } from '../../../keamanan/_com/keamananEditor';
|
||||
|
||||
function CreateGotongRoyong() {
|
||||
const router = useRouter()
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper bg={colors['white-1']} p="md" w={{ base: '100%', md: '50%' }}>
|
||||
<Stack gap="xs">
|
||||
<Title order={3}>Create Gotong Royong</Title>
|
||||
<TextInput
|
||||
label={<Text fz="sm" fw="bold">Judul Gotong Royong</Text>}
|
||||
placeholder="masukkan judul gotong royong"
|
||||
/>
|
||||
<TextInput
|
||||
label={<Text fz="sm" fw="bold">Kategori Gotong Royong</Text>}
|
||||
placeholder="masukkan kategori gotong royong"
|
||||
/>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"sm"}>Deskripsi Gotong Royong</Text>
|
||||
<KeamananEditor
|
||||
showSubmit={false}
|
||||
/>
|
||||
</Box>
|
||||
{/* <FileInput
|
||||
label={<Text fz="sm" fw="bold">Upload Gambar</Text>}
|
||||
value={file}
|
||||
onChange={async (e) => {
|
||||
if (!e) return;
|
||||
setFile(e);
|
||||
const base64 = await e.arrayBuffer().then((buf) =>
|
||||
'data:image/png;base64,' + Buffer.from(buf).toString('base64')
|
||||
);
|
||||
setPreviewImage(base64);
|
||||
}}
|
||||
/> */}
|
||||
{/* {previewImage ? (
|
||||
<Image alt="" src={previewImage} w={200} h={200} />
|
||||
) : (
|
||||
<Center w={200} h={200} bg="gray">
|
||||
<IconImageInPicture />
|
||||
</Center>
|
||||
)} */}
|
||||
<Box>
|
||||
<Text fz="sm" fw="bold">Gambar</Text>
|
||||
<IconImageInPicture size={25} />
|
||||
</Box>
|
||||
<Button bg={colors['blue-button']} >
|
||||
Simpan
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateGotongRoyong;
|
||||
@@ -1,66 +0,0 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Stack, Flex, Text, Image } from '@mantine/core';
|
||||
import { IconArrowBack, IconX, IconEdit } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import React from 'react';
|
||||
// import { ModalKonfirmasiHapus } from '../../../_com/modalKonfirmasiHapus';
|
||||
|
||||
function DetailGotongRoyong() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Paper w={{ base: "100%", md: "50%" }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<Text fz={"xl"} fw={"bold"}>Detail Gotong Royong</Text>
|
||||
|
||||
<Paper bg={colors['BG-trans']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Judul Gotong Royong</Text>
|
||||
<Text fz={"lg"}>Test Judul</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Kategori Gotong Royong</Text>
|
||||
<Text fz={"lg"}>Test Kategori</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Deskripsi Gotong Royong</Text>
|
||||
<Text fz={"lg"} >Test Deskripsi</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fz={"lg"} fw={"bold"}>Gambar</Text>
|
||||
<Image src={"/"} alt="gambar" />
|
||||
</Box>
|
||||
<Box>
|
||||
<Flex gap={"xs"}>
|
||||
<Button color="red">
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
<Button onClick={() => router.push('/admin/lingkungan/gotong-royong/edit')} color="green">
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</Flex>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Modal Hapus
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text="Apakah anda yakin ingin menghapus potensi ini?"
|
||||
/> */}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default DetailGotongRoyong;
|
||||
@@ -1,68 +0,0 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { IconArrowBack, IconImageInPicture } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import React from 'react';
|
||||
import { KeamananEditor } from '../../../keamanan/_com/keamananEditor';
|
||||
|
||||
function EditGotongRoyong() {
|
||||
const router = useRouter()
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper bg={colors['white-1']} p="md" w={{ base: '100%', md: '50%' }}>
|
||||
<Stack gap="xs">
|
||||
<Title order={3}>Edit Gotong Royong</Title>
|
||||
<TextInput
|
||||
label={<Text fz="sm" fw="bold">Judul Gotong Royong</Text>}
|
||||
placeholder="masukkan judul gotong royong"
|
||||
/>
|
||||
<TextInput
|
||||
label={<Text fz="sm" fw="bold">Kategori Gotong Royong</Text>}
|
||||
placeholder="masukkan kategori gotong royong"
|
||||
/>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"sm"}>Deskripsi Gotong Royong</Text>
|
||||
<KeamananEditor
|
||||
showSubmit={false}
|
||||
/>
|
||||
</Box>
|
||||
{/* <FileInput
|
||||
label={<Text fz="sm" fw="bold">Upload Gambar</Text>}
|
||||
value={file}
|
||||
onChange={async (e) => {
|
||||
if (!e) return;
|
||||
setFile(e);
|
||||
const base64 = await e.arrayBuffer().then((buf) =>
|
||||
'data:image/png;base64,' + Buffer.from(buf).toString('base64')
|
||||
);
|
||||
setPreviewImage(base64);
|
||||
}}
|
||||
/> */}
|
||||
{/* {previewImage ? (
|
||||
<Image alt="" src={previewImage} w={200} h={200} />
|
||||
) : (
|
||||
<Center w={200} h={200} bg="gray">
|
||||
<IconImageInPicture />
|
||||
</Center>
|
||||
)} */}
|
||||
<Box>
|
||||
<Text fz="sm" fw="bold">Gambar</Text>
|
||||
<IconImageInPicture size={25} />
|
||||
</Box>
|
||||
<Button bg={colors['blue-button']} >
|
||||
Simpan
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditGotongRoyong;
|
||||
@@ -0,0 +1,98 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import gotongRoyongState from '@/app/admin/(dashboard)/_state/lingkungan/gotong-royong';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { IconArrowBack } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function EditKategoriKegiatan() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const id = params?.id as string;
|
||||
const stateKategori = useProxy(gotongRoyongState.kategoriKegiatan);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
nama: "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const loadKategorikegiatan = async () => {
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
const data = await stateKategori.edit.load(id);
|
||||
|
||||
if (data) {
|
||||
// pastikan id-nya masuk ke state edit
|
||||
stateKategori.edit.id = id;
|
||||
setFormData({
|
||||
nama: data.nama || '',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading kategori kegiatan:", error);
|
||||
toast.error("Gagal memuat data kategori kegiatan");
|
||||
}
|
||||
};
|
||||
|
||||
loadKategorikegiatan();
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
if (!formData.nama.trim()) {
|
||||
toast.error('Nama kategori kegiatan tidak boleh kosong');
|
||||
return;
|
||||
}
|
||||
|
||||
stateKategori.edit.form = {
|
||||
nama: formData.nama.trim(),
|
||||
};
|
||||
|
||||
// Safety check tambahan: pastikan ID tidak kosong
|
||||
if (!stateKategori.edit.id) {
|
||||
stateKategori.edit.id = id; // fallback
|
||||
}
|
||||
|
||||
const success = await stateKategori.edit.update();
|
||||
|
||||
if (success) {
|
||||
router.push("/admin/lingkungan/gotong-royong/kategori-kegiatan");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating kategori kegiatan:", error);
|
||||
// toast akan ditampilkan dari fungsi update
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Edit Kategori kegiatan</Title>
|
||||
<TextInput
|
||||
value={formData.nama}
|
||||
onChange={(e) => setFormData({ ...formData, nama: e.target.value })}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Kategori kegiatan</Text>}
|
||||
placeholder='Masukkan nama kategori kegiatan'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditKategoriKegiatan;
|
||||
@@ -0,0 +1,61 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { IconArrowBack } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import gotongRoyongState from '../../../../_state/lingkungan/gotong-royong';
|
||||
|
||||
function CreateKategoriKegiatan() {
|
||||
const router = useRouter();
|
||||
const stateKategori = useProxy(gotongRoyongState.kategoriKegiatan)
|
||||
|
||||
useEffect(() => {
|
||||
stateKategori.findMany.load();
|
||||
}, []);
|
||||
|
||||
const resetForm = () => {
|
||||
stateKategori.create.form = {
|
||||
nama: "",
|
||||
};
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
await stateKategori.create.create();
|
||||
resetForm();
|
||||
router.push("/admin/lingkungan/gotong-royong/kategori-kegiatan")
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Create Kategori Kegiatan</Title>
|
||||
<TextInput
|
||||
value={stateKategori.create.form.nama}
|
||||
onChange={(val) => {
|
||||
stateKategori.create.form.nama = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Nama Kategori Kegiatan</Text>}
|
||||
placeholder='Masukkan nama kategori kegiatan'
|
||||
/>
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateKategoriKegiatan;
|
||||
@@ -0,0 +1,112 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconEdit, IconSearch, IconX } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import HeaderSearch from '../../../_com/header';
|
||||
import JudulList from '../../../_com/judulList';
|
||||
import { ModalKonfirmasiHapus } from '../../../_com/modalKonfirmasiHapus';
|
||||
import gotongRoyongState from '../../../_state/lingkungan/gotong-royong';
|
||||
|
||||
|
||||
function KategoriKegiatan() {
|
||||
const [search, setSearch] = useState("")
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='Kategori Kegiatan'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<ListKategoriKegiatan search={search} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListKategoriKegiatan({ search }: { search: string }) {
|
||||
const stateKategori = useProxy(gotongRoyongState.kategoriKegiatan)
|
||||
const [modalHapus, setModalHapus] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
|
||||
const handleHapus = () => {
|
||||
if (selectedId) {
|
||||
stateKategori.delete.byId(selectedId)
|
||||
setModalHapus(false)
|
||||
setSelectedId(null)
|
||||
}
|
||||
}
|
||||
|
||||
useShallowEffect(() => {
|
||||
stateKategori.findMany.load()
|
||||
}, [])
|
||||
|
||||
const filteredData = (stateKategori.findMany.data || []).filter(item => {
|
||||
const keyword = search.toLowerCase();
|
||||
return (
|
||||
item.nama.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
|
||||
if (!stateKategori.findMany.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<JudulList
|
||||
title='List Kategori Kegiatan'
|
||||
href='/admin/lingkungan/gotong-royong/kategori-kegiatan/create'
|
||||
/>
|
||||
<Table striped withTableBorder withRowBorders>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Nama Kategori</TableTh>
|
||||
<TableTh>Edit</TableTh>
|
||||
<TableTh>Delete</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{filteredData.map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd>{item.nama}</TableTd>
|
||||
<TableTd>
|
||||
<Button color="green" onClick={() => router.push(`/admin/lingkungan/gotong-royong/kategori-kegiatan/${item.id}`)}>
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
<TableTd>
|
||||
<Button color="red" onClick={() => {
|
||||
setSelectedId(item.id)
|
||||
setModalHapus(true)
|
||||
}}>
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Paper>
|
||||
{/* Modal Konfirmasi Hapus */}
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text='Apakah anda yakin ingin menghapus kategori kegiatan ini?'
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default KategoriKegiatan;
|
||||
@@ -0,0 +1,242 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import EditEditor from '@/app/admin/(dashboard)/_com/editEditor';
|
||||
import gotongRoyongState from '@/app/admin/(dashboard)/_state/lingkungan/gotong-royong';
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Image, Paper, Select, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
|
||||
interface FormKegiatanDesa {
|
||||
judul: string;
|
||||
deskripsiSingkat: string;
|
||||
deskripsiLengkap: string;
|
||||
tanggal: string;
|
||||
lokasi: string;
|
||||
partisipan: number;
|
||||
imageId: string;
|
||||
kategoriKegiatanId: string;
|
||||
}
|
||||
|
||||
function EditGotongRoyong() {
|
||||
const kegiatanDesaState = useProxy(gotongRoyongState.kegiatanDesa)
|
||||
const params = useParams()
|
||||
const router = useRouter()
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
|
||||
const [formData, setFormData] = useState<FormKegiatanDesa>({
|
||||
judul: '',
|
||||
deskripsiSingkat: '',
|
||||
deskripsiLengkap: '',
|
||||
tanggal: '',
|
||||
lokasi: '',
|
||||
partisipan: 0,
|
||||
imageId: '',
|
||||
kategoriKegiatanId: '',
|
||||
})
|
||||
|
||||
const formatDateForInput = (dateString: string) => {
|
||||
if (!dateString) return '';
|
||||
const date = new Date(dateString);
|
||||
return date.toISOString().split('T')[0];
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const loadKegiatanDesa = async () => {
|
||||
const id = params?.id as string;
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
const data = await kegiatanDesaState.edit.load(id);
|
||||
if (data) {
|
||||
setFormData({
|
||||
judul: data.judul || '',
|
||||
deskripsiSingkat: data.deskripsiSingkat || '',
|
||||
deskripsiLengkap: data.deskripsiLengkap || '',
|
||||
tanggal: data.tanggal || '',
|
||||
lokasi: data.lokasi || '',
|
||||
partisipan: data.partisipan || 0,
|
||||
imageId: data.imageId || '',
|
||||
kategoriKegiatanId: data.kategoriKegiatanId || '',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading kegiatan desa:", error);
|
||||
toast.error("Gagal memuat data kegiatan desa");
|
||||
}
|
||||
}
|
||||
gotongRoyongState.kategoriKegiatan.findMany.load()
|
||||
loadKegiatanDesa();
|
||||
}, [params?.id]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
kegiatanDesaState.edit.form = {
|
||||
...kegiatanDesaState.edit.form,
|
||||
judul: formData.judul.trim(),
|
||||
deskripsiSingkat: formData.deskripsiSingkat.trim(),
|
||||
deskripsiLengkap: formData.deskripsiLengkap.trim(),
|
||||
tanggal: new Date(formData.tanggal.trim()),
|
||||
lokasi: formData.lokasi.trim(),
|
||||
partisipan: formData.partisipan,
|
||||
imageId: formData.imageId,
|
||||
kategoriKegiatanId: formData.kategoriKegiatanId,
|
||||
}
|
||||
if (file) {
|
||||
const res = await ApiFetch.api.fileStorage.create.post({ file, name: file.name });
|
||||
const uploaded = res.data?.data;
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal upload gambar");
|
||||
}
|
||||
|
||||
// Update imageId in global state
|
||||
kegiatanDesaState.edit.form.imageId = uploaded.id;
|
||||
}
|
||||
await kegiatanDesaState.edit.update()
|
||||
router.push("/admin/lingkungan/gotong-royong/kegiatan-desa");
|
||||
} catch (error) {
|
||||
console.error("Error updating kegiatan desa:", error);
|
||||
toast.error("Terjadi kesalahan saat memperbarui kegiatan desa");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper bg={colors['white-1']} p="md" w={{ base: '100%', md: '50%' }}>
|
||||
<Stack gap="xs">
|
||||
<Title order={3}>Edit Kegiatan Desa</Title>
|
||||
<TextInput
|
||||
value={formData.judul}
|
||||
label={<Text fz="sm" fw="bold">Judul Kegiatan Desa</Text>}
|
||||
placeholder="masukkan judul kegiatan desa"
|
||||
onChange={(e) => setFormData({ ...formData, judul: e.target.value })}
|
||||
/>
|
||||
<TextInput
|
||||
value={formData.deskripsiSingkat}
|
||||
label={<Text fz="sm" fw="bold">Deskripsi Singkat Kegiatan Desa</Text>}
|
||||
placeholder="masukkan deskripsi singkat kegiatan desa"
|
||||
onChange={(e) => setFormData({ ...formData, deskripsiSingkat: e.target.value })}
|
||||
/>
|
||||
<Select
|
||||
label="Kategori Kegiatan"
|
||||
data={gotongRoyongState.kategoriKegiatan.findMany.data?.map(k => ({
|
||||
value: k.id,
|
||||
label: k.nama
|
||||
})) ?? []}
|
||||
value={formData.kategoriKegiatanId}
|
||||
onChange={(val) => setFormData({ ...formData, kategoriKegiatanId: val ?? '' })}
|
||||
/>
|
||||
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"sm"}>Deskripsi Lengkap Kegiatan Desa</Text>
|
||||
<EditEditor
|
||||
value={formData.deskripsiLengkap}
|
||||
onChange={(htmlContent) => {
|
||||
setFormData((prev) => ({ ...prev, deskripsiLengkap: htmlContent }));
|
||||
kegiatanDesaState.edit.form.deskripsiLengkap = htmlContent;
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<TextInput
|
||||
label={<Text fz="sm" fw="bold">Tanggal Kegiatan Desa</Text>}
|
||||
placeholder="masukkan tanggal kegiatan desa"
|
||||
type="date"
|
||||
value={formatDateForInput(formData.tanggal)}
|
||||
onChange={(e) => setFormData({ ...formData, tanggal: e.target.value })}
|
||||
/>
|
||||
<TextInput
|
||||
value={formData.lokasi}
|
||||
label={<Text fz="sm" fw="bold">Lokasi Kegiatan Desa</Text>}
|
||||
placeholder="masukkan lokasi kegiatan desa"
|
||||
onChange={(e) => setFormData({ ...formData, lokasi: e.target.value })}
|
||||
/>
|
||||
<TextInput
|
||||
value={formData.partisipan}
|
||||
label={<Text fz="sm" fw="bold">Partisipan Kegiatan Desa</Text>}
|
||||
placeholder="masukkan partisipan kegiatan desa"
|
||||
onChange={(e) => {
|
||||
const val = Number(e.target.value);
|
||||
if (!isNaN(val)) {
|
||||
setFormData({ ...formData, partisipan: val });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewImage(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit} >
|
||||
Simpan
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditGotongRoyong;
|
||||
@@ -0,0 +1,133 @@
|
||||
'use client'
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
import { Box, Button, Flex, Image, Paper, Skeleton, Stack, Text } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconArrowBack, IconEdit, IconX } from '@tabler/icons-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
import colors from '@/con/colors';
|
||||
|
||||
import gotongRoyongState from '@/app/admin/(dashboard)/_state/lingkungan/gotong-royong';
|
||||
import { ModalKonfirmasiHapus } from '@/app/admin/(dashboard)/_com/modalKonfirmasiHapus';
|
||||
|
||||
function DetailKegiatanDesa() {
|
||||
const kegiatanDesaState = useProxy(gotongRoyongState.kegiatanDesa)
|
||||
const [modalHapus, setModalHapus] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const params = useParams()
|
||||
const router = useRouter()
|
||||
|
||||
useShallowEffect(() => {
|
||||
kegiatanDesaState.findUnique.load(params?.id as string)
|
||||
}, [])
|
||||
|
||||
|
||||
const handleHapus = () => {
|
||||
if (selectedId) {
|
||||
kegiatanDesaState.delete.byId(selectedId)
|
||||
setModalHapus(false)
|
||||
setSelectedId(null)
|
||||
router.push("/admin/lingkungan/gotong-royong/kegiatan-desa")
|
||||
}
|
||||
}
|
||||
|
||||
if (!kegiatanDesaState.findUnique.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={40} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button variant="subtle" onClick={() => router.back()}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Paper bg={colors['white-1']} w={{ base: "100%", md: "100%", lg: "50%" }} p={'md'}>
|
||||
<Stack>
|
||||
<Text fz={"xl"} fw={"bold"}>Detail Kegiatan Desa Inovasi</Text>
|
||||
{kegiatanDesaState.findUnique.data ? (
|
||||
<Paper key={kegiatanDesaState.findUnique.data.id} bg={colors['BG-trans']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Judul Kegiatan Desa Inovasi</Text>
|
||||
<Text fz={"lg"}>{kegiatanDesaState.findUnique.data?.judul}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Tanggal</Text>
|
||||
<Text fz={"lg"}>{kegiatanDesaState.findUnique.data?.tanggal
|
||||
? new Date(kegiatanDesaState.findUnique.data.tanggal).toLocaleDateString()
|
||||
: "-"}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Deskripsi Singkat</Text>
|
||||
<Text fz={"lg"} >{kegiatanDesaState.findUnique.data?.deskripsiSingkat}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Deskripsi</Text>
|
||||
<Text fz={"lg"} dangerouslySetInnerHTML={{ __html: kegiatanDesaState.findUnique.data?.deskripsiLengkap }} />
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Kategori Kegiatan</Text>
|
||||
<Text fz={"lg"}>{kegiatanDesaState.findUnique.data?.kategoriKegiatan?.nama}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Partisipan</Text>
|
||||
<Text fz={"lg"}>{kegiatanDesaState.findUnique.data?.partisipan}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Lokasi</Text>
|
||||
<Text fz={"lg"}>{kegiatanDesaState.findUnique.data?.lokasi}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text fw={"bold"} fz={"lg"}>Gambar</Text>
|
||||
<Image w={{ base: 150, md: 150, lg: 150 }} src={kegiatanDesaState.findUnique.data?.image?.link} alt="gambar" />
|
||||
</Box>
|
||||
<Flex gap={"xs"} mt={10}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (kegiatanDesaState.findUnique.data) {
|
||||
setSelectedId(kegiatanDesaState.findUnique.data.id);
|
||||
setModalHapus(true);
|
||||
}
|
||||
}}
|
||||
disabled={kegiatanDesaState.delete.loading || !kegiatanDesaState.findUnique.data}
|
||||
color={"red"}
|
||||
>
|
||||
<IconX size={20} />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (kegiatanDesaState.findUnique.data) {
|
||||
router.push(`/admin/lingkungan/gotong-royong/kegiatan-desa/${kegiatanDesaState.findUnique.data.id}/edit`);
|
||||
}
|
||||
}}
|
||||
disabled={!kegiatanDesaState.findUnique.data}
|
||||
color={"green"}
|
||||
>
|
||||
<IconEdit size={20} />
|
||||
</Button>
|
||||
</Flex>
|
||||
</Stack>
|
||||
</Paper>
|
||||
) : null}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Modal Konfirmasi Hapus */}
|
||||
<ModalKonfirmasiHapus
|
||||
opened={modalHapus}
|
||||
onClose={() => setModalHapus(false)}
|
||||
onConfirm={handleHapus}
|
||||
text='Apakah anda yakin ingin menghapus kegiatan desa ini?'
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default DetailKegiatanDesa;
|
||||
@@ -0,0 +1,215 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import CreateEditor from '@/app/admin/(dashboard)/_com/createEditor';
|
||||
import gotongRoyongState from '@/app/admin/(dashboard)/_state/lingkungan/gotong-royong';
|
||||
import colors from '@/con/colors';
|
||||
import ApiFetch from '@/lib/api-fetch';
|
||||
import { Box, Button, Group, Image, Paper, Select, Stack, Text, TextInput, Title } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { IconArrowBack, IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
|
||||
function CreateKegiatanDesa() {
|
||||
const router = useRouter();
|
||||
const stateKegiatanDesa = useProxy(gotongRoyongState.kegiatanDesa)
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
stateKegiatanDesa.findMany.load();
|
||||
gotongRoyongState.kategoriKegiatan.findMany.load();
|
||||
}, []);
|
||||
|
||||
const resetForm = () => {
|
||||
stateKegiatanDesa.create.form = {
|
||||
judul: "",
|
||||
deskripsiSingkat: "",
|
||||
deskripsiLengkap: "",
|
||||
tanggal: new Date(),
|
||||
lokasi: "",
|
||||
partisipan: 0,
|
||||
imageId: "",
|
||||
kategoriKegiatanId: "",
|
||||
};
|
||||
setPreviewImage(null);
|
||||
setFile(null);
|
||||
};
|
||||
const handleSubmit = async () => {
|
||||
if (!file) {
|
||||
return toast.warn("Pilih file gambar terlebih dahulu");
|
||||
}
|
||||
|
||||
const res = await ApiFetch.api.fileStorage.create.post({
|
||||
file,
|
||||
name: file.name,
|
||||
})
|
||||
|
||||
const uploaded = res.data?.data;
|
||||
|
||||
if (!uploaded?.id) {
|
||||
return toast.error("Gagal mengupload file");
|
||||
}
|
||||
|
||||
stateKegiatanDesa.create.form.imageId = uploaded.id;
|
||||
|
||||
await stateKegiatanDesa.create.create();
|
||||
|
||||
resetForm();
|
||||
router.push("/admin/lingkungan/gotong-royong/kegiatan-desa")
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Box mb={10}>
|
||||
<Button onClick={() => router.back()} variant='subtle' color={'blue'}>
|
||||
<IconArrowBack color={colors['blue-button']} size={25} />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
|
||||
<Stack gap={"xs"}>
|
||||
<Title order={4}>Create Kegiatan Desa</Title>
|
||||
<Box>
|
||||
<Text fz={"md"} fw={"bold"}>Gambar</Text>
|
||||
<Box>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
const selectedFile = files[0]; // Ambil file pertama
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setPreviewImage(URL.createObjectURL(selectedFile)); // Buat preview
|
||||
}
|
||||
}}
|
||||
onReject={() => toast.error('File tidak valid.')}
|
||||
maxSize={5 * 1024 ** 2} // Maks 5MB
|
||||
accept={{ 'image/*': [] }}
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
|
||||
<Dropzone.Accept>
|
||||
<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
|
||||
</Dropzone.Accept>
|
||||
<Dropzone.Reject>
|
||||
<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
|
||||
</Dropzone.Reject>
|
||||
<Dropzone.Idle>
|
||||
<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
|
||||
</Dropzone.Idle>
|
||||
|
||||
<div>
|
||||
<Text size="xl" inline>
|
||||
Drag gambar ke sini atau klik untuk pilih file
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
Maksimal 5MB dan harus format gambar
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Dropzone>
|
||||
|
||||
{/* Tampilkan preview kalau ada */}
|
||||
{previewImage && (
|
||||
<Box mt="sm">
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '200px',
|
||||
objectFit: 'contain',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ddd',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
</Box>
|
||||
</Box>
|
||||
<TextInput
|
||||
value={stateKegiatanDesa.create.form.judul}
|
||||
onChange={(val) => {
|
||||
stateKegiatanDesa.create.form.judul = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Judul Kegiatan</Text>}
|
||||
placeholder='Masukkan judul kegiatan'
|
||||
/>
|
||||
<TextInput
|
||||
value={stateKegiatanDesa.create.form.deskripsiSingkat}
|
||||
onChange={(val) => {
|
||||
stateKegiatanDesa.create.form.deskripsiSingkat = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Deskripsi Singkat</Text>}
|
||||
placeholder='Masukkan deskripsi singkat'
|
||||
/>
|
||||
<TextInput
|
||||
type="number"
|
||||
min={0}
|
||||
max={5}
|
||||
step={0.1} // bisa pakai 0.1 biar support desimal
|
||||
value={stateKegiatanDesa.create.form.partisipan}
|
||||
onChange={(val) => {
|
||||
const value = Number(val.target.value);
|
||||
|
||||
// Validasi manual juga boleh (jaga-jaga)
|
||||
if (value >= 0 && value <= 1000) {
|
||||
stateKegiatanDesa.create.form.partisipan = value;
|
||||
}
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Partisipan</Text>}
|
||||
placeholder='Masukkan partisipan'
|
||||
/>
|
||||
<TextInput
|
||||
label={<Text fz={"sm"} fw={"bold"}>Tanggal</Text>}
|
||||
type="date"
|
||||
placeholder="Contoh: 2022-01-01"
|
||||
value={stateKegiatanDesa.create.form.tanggal ? stateKegiatanDesa.create.form.tanggal.toISOString().split('T')[0] : ''}
|
||||
onChange={(e) => {
|
||||
const dateValue = e.currentTarget.value;
|
||||
stateKegiatanDesa.create.form.tanggal = dateValue ? new Date(dateValue) : new Date();
|
||||
}}
|
||||
/>
|
||||
<TextInput
|
||||
value={stateKegiatanDesa.create.form.lokasi}
|
||||
onChange={(val) => {
|
||||
stateKegiatanDesa.create.form.lokasi = val.target.value;
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Lokasi</Text>}
|
||||
placeholder='Masukkan lokasi'
|
||||
/>
|
||||
<Box>
|
||||
<Text fz={"sm"} fw={"bold"}>Deskripsi Lengkap</Text>
|
||||
<CreateEditor
|
||||
value={stateKegiatanDesa.create.form.deskripsiLengkap}
|
||||
onChange={(val) => {
|
||||
stateKegiatanDesa.create.form.deskripsiLengkap = val;
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Select
|
||||
value={stateKegiatanDesa.create.form.kategoriKegiatanId}
|
||||
onChange={(val) => {
|
||||
stateKegiatanDesa.create.form.kategoriKegiatanId = val ?? "";
|
||||
}}
|
||||
label={<Text fw={"bold"} fz={"sm"}>Kategori Kegiatan</Text>}
|
||||
placeholder="Pilih kategori produk"
|
||||
data={
|
||||
gotongRoyongState.kategoriKegiatan.findMany.data?.map((v) => ({
|
||||
value: v.id,
|
||||
label: v.nama,
|
||||
})) || []
|
||||
}
|
||||
/>
|
||||
|
||||
<Group>
|
||||
<Button bg={colors['blue-button']} onClick={handleSubmit}>Submit</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateKegiatanDesa;
|
||||
@@ -0,0 +1,97 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Text } from '@mantine/core';
|
||||
import { IconDeviceImacCog, IconSearch } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import HeaderSearch from '../../../_com/header';
|
||||
import JudulList from '../../../_com/judulList';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import gotongRoyongState from '../../../_state/lingkungan/gotong-royong';
|
||||
|
||||
function KegiatanDesa() {
|
||||
const [search, setSearch] = useState('');
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='Kegiatan Desa'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<ListKegiatanDesa search={search} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListKegiatanDesa({ search }: { search: string }) {
|
||||
const listState = useProxy(gotongRoyongState.kegiatanDesa)
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
listState.findMany.load()
|
||||
}, [])
|
||||
|
||||
const filteredData = (listState.findMany.data || []).filter(item => {
|
||||
const keyword = search.toLowerCase();
|
||||
return (
|
||||
item.judul.toLowerCase().includes(keyword) ||
|
||||
item.lokasi.toLowerCase().includes(keyword) ||
|
||||
item.kategoriKegiatan?.nama?.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
|
||||
if (!listState.findMany.data) {
|
||||
return (
|
||||
<Stack py={10}>
|
||||
<Skeleton h={500} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<JudulList
|
||||
title='List Kegiatan Desa'
|
||||
href='/admin/lingkungan/gotong-royong/kegiatan-desa/create'
|
||||
/>
|
||||
<Box style={{ overflowX: 'auto' }}>
|
||||
<Table striped withRowBorders withTableBorder style={{ minWidth: '700px' }}>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Judul Kegiatan Desa</TableTh>
|
||||
<TableTh>Kategori Kegiatan Desa</TableTh>
|
||||
<TableTh>Lokasi Kegiatan Desa</TableTh>
|
||||
<TableTh>Detail</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{filteredData.map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd>
|
||||
<Box w={100}>
|
||||
<Text truncate="end" fz={"sm"}>{item.judul}</Text>
|
||||
</Box>
|
||||
</TableTd>
|
||||
<TableTd>{item.kategoriKegiatan?.nama}</TableTd>
|
||||
<TableTd>{item.lokasi}</TableTd>
|
||||
<TableTd>
|
||||
<Button onClick={() => router.push(`/admin/lingkungan/gotong-royong/kegiatan-desa/${item.id}`)}>
|
||||
<IconDeviceImacCog size={25} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default KegiatanDesa;
|
||||
@@ -0,0 +1,9 @@
|
||||
import LayoutTabs from "./_lib/layoutTabs";
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<LayoutTabs>
|
||||
{children}
|
||||
</LayoutTabs>
|
||||
);
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
'use client'
|
||||
import { Box, Button, Image, Paper, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Text } from '@mantine/core';
|
||||
import { IconDeviceImacCog, IconSearch } from '@tabler/icons-react';
|
||||
import HeaderSearch from '../../_com/header';
|
||||
import colors from '@/con/colors';
|
||||
import JudulList from '../../_com/judulList';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
function GotongRoyong() {
|
||||
return (
|
||||
<Box>
|
||||
<HeaderSearch
|
||||
title='Gotong Royong'
|
||||
placeholder='pencarian'
|
||||
searchIcon={<IconSearch size={20} />}
|
||||
/>
|
||||
<ListGotongRoyong/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ListGotongRoyong() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<Box py={10}>
|
||||
<Paper bg={colors['white-1']} p={'md'}>
|
||||
<Stack>
|
||||
<JudulList
|
||||
title='List Gotong Royong'
|
||||
href='/admin/lingkungan/gotong-royong/create'
|
||||
/>
|
||||
<Box style={{ overflowX: 'auto'}}>
|
||||
<Table striped withRowBorders withTableBorder style={{ minWidth: '700px'}}>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>Judul Gotong Royong</TableTh>
|
||||
<TableTh>Kategori Gotong Royong</TableTh>
|
||||
<TableTh>Image</TableTh>
|
||||
<TableTh>Deskripsi Gotong Royong</TableTh>
|
||||
<TableTh>Detail</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
<TableTr>
|
||||
<TableTd>
|
||||
<Box w={100}>
|
||||
<Text truncate="end" fz={"sm"}>Judul</Text>
|
||||
</Box>
|
||||
</TableTd>
|
||||
<TableTd>Kategori</TableTd>
|
||||
<TableTd>
|
||||
<Image w={100} src="/" alt="image" />
|
||||
</TableTd>
|
||||
<TableTd>Deskripsi</TableTd>
|
||||
<TableTd>
|
||||
<Button onClick={() => router.push('/admin/lingkungan/gotong-royong/detail')}>
|
||||
<IconDeviceImacCog size={25} />
|
||||
</Button>
|
||||
</TableTd>
|
||||
</TableTr>
|
||||
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default GotongRoyong;
|
||||
@@ -1 +1,87 @@
|
||||
'use client'
|
||||
import stateKonservasiAdatBali from '@/app/admin/(dashboard)/_state/lingkungan/konservasi-adat-bali';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Paper, Stack, Text, Title } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconArrowBack } from '@tabler/icons-react';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
const KonservasiAdatBaliTextEditor = dynamic(() => import('../../_lib/konservasiAdatBaliTextEditor').then(mod => mod.KonservasiAdatBaliTextEditor), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
function EditBentukKonservasiBerdasarkanAdat() {
|
||||
const router = useRouter()
|
||||
const bentukKonservasiState = useProxy(stateKonservasiAdatBali.stateBentukKonservasiBerdasarkanAdat)
|
||||
const [judul, setJudul] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
|
||||
useShallowEffect(() => {
|
||||
if (!bentukKonservasiState.findById.data) {
|
||||
bentukKonservasiState.findById.initialize(); // biar masuk ke `findFirst` route kamu
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (bentukKonservasiState.findById.data) {
|
||||
setJudul(bentukKonservasiState.findById.data.judul ?? '')
|
||||
setContent(bentukKonservasiState.findById.data.deskripsi ?? '')
|
||||
}
|
||||
}, [bentukKonservasiState.findById.data])
|
||||
|
||||
const submit = () => {
|
||||
if (bentukKonservasiState.findById.data) {
|
||||
bentukKonservasiState.findById.data.judul = judul;
|
||||
bentukKonservasiState.findById.data.deskripsi = content;
|
||||
bentukKonservasiState.update.save(bentukKonservasiState.findById.data)
|
||||
}
|
||||
router.push('/admin/lingkungan/konservasi-adat-bali/bentuk-konservasi-berdasarkan-adat')
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Stack gap={'xs'}>
|
||||
<Box>
|
||||
<Button
|
||||
variant={'subtle'}
|
||||
onClick={() => router.back()}
|
||||
>
|
||||
<IconArrowBack color={colors['blue-button']} size={20} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Box>
|
||||
<Paper bg={colors['white-1']} p={'md'} radius={10} w={{ base: '100%', md: '50%' }}>
|
||||
<Stack gap={'xs'}>
|
||||
<Title order={3}>Edit Bentuk Konservasi Berdasarkan Adat</Title>
|
||||
<Text fw={"bold"}>Judul</Text>
|
||||
<KonservasiAdatBaliTextEditor
|
||||
showSubmit={false}
|
||||
onChange={setJudul}
|
||||
initialContent={judul}
|
||||
/>
|
||||
<Text fw={"bold"}>Content</Text>
|
||||
<KonservasiAdatBaliTextEditor
|
||||
showSubmit={false}
|
||||
onChange={setContent}
|
||||
initialContent={content}
|
||||
/>
|
||||
<Group>
|
||||
<Button
|
||||
bg={colors['blue-button']}
|
||||
onClick={submit}
|
||||
loading={bentukKonservasiState.update.loading}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditBentukKonservasiBerdasarkanAdat;
|
||||
|
||||
@@ -1,11 +1,54 @@
|
||||
import React from 'react';
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Grid, GridCol, Paper, Skeleton, Stack, Text, Title } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconEdit } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import stateKonservasiAdatBali from '../../../_state/lingkungan/konservasi-adat-bali';
|
||||
|
||||
function Page() {
|
||||
const router = useRouter()
|
||||
const listBentukKonservasiBerdasarkanAdat = useProxy(stateKonservasiAdatBali.stateBentukKonservasiBerdasarkanAdat)
|
||||
useShallowEffect(() => {
|
||||
listBentukKonservasiBerdasarkanAdat.findById.load('edit')
|
||||
}, [])
|
||||
|
||||
if (!listBentukKonservasiBerdasarkanAdat.findById.data) {
|
||||
return (
|
||||
<Stack>
|
||||
<Skeleton radius={10} h={800} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
Page
|
||||
</div>
|
||||
);
|
||||
<Paper bg={colors['white-1']} p={'md'} radius={10}>
|
||||
<Stack gap={"22"}>
|
||||
<Grid>
|
||||
<GridCol span={{ base: 12, md: 11 }}>
|
||||
<Title order={2}>Preview Bentuk Konservasi Berdasarkan Adat</Title>
|
||||
</GridCol>
|
||||
<GridCol span={{ base: 12, md: 1 }}>
|
||||
<Button bg={colors['blue-button']} onClick={() => router.push('/admin/lingkungan/konservasi-adat-bali/bentuk-konservasi-berdasarkan-adat/edit')}>
|
||||
<IconEdit size={16} />
|
||||
</Button>
|
||||
</GridCol>
|
||||
</Grid>
|
||||
<Box>
|
||||
<Stack gap={'lg'}>
|
||||
<Paper p={"xl"} bg={colors['BG-trans']}>
|
||||
<Box px={{ base: 0, md: 30 }}>
|
||||
<Text fz={{ base: "h3", md: "h2" }} fw={"bold"} dangerouslySetInnerHTML={{ __html: listBentukKonservasiBerdasarkanAdat.findById.data.judul }} />
|
||||
</Box>
|
||||
<Box px={{ base: 0, md: 30 }}>
|
||||
<Text fz={{ base: "md", md: "h3" }} ta={"justify"} dangerouslySetInnerHTML={{ __html: listBentukKonservasiBerdasarkanAdat.findById.data.deskripsi }} />
|
||||
</Box>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page;
|
||||
|
||||
@@ -1,11 +1,87 @@
|
||||
import React from 'react';
|
||||
'use client'
|
||||
import stateKonservasiAdatBali from '@/app/admin/(dashboard)/_state/lingkungan/konservasi-adat-bali';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Group, Paper, Stack, Text, Title } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconArrowBack } from '@tabler/icons-react';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
|
||||
function Page() {
|
||||
const KonservasiAdatBaliTextEditor = dynamic(() => import('../../_lib/konservasiAdatBaliTextEditor').then(mod => mod.KonservasiAdatBaliTextEditor), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
function EditNilaiKonservasiAdat() {
|
||||
const router = useRouter()
|
||||
const nilaiKonservasiState = useProxy(stateKonservasiAdatBali.stateNilaiKonservasiAdat)
|
||||
const [judul, setJudul] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
|
||||
useShallowEffect(() => {
|
||||
if (!nilaiKonservasiState.findById.data) {
|
||||
nilaiKonservasiState.findById.initialize(); // biar masuk ke `findFirst` route kamu
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (nilaiKonservasiState.findById.data) {
|
||||
setJudul(nilaiKonservasiState.findById.data.judul ?? '')
|
||||
setContent(nilaiKonservasiState.findById.data.deskripsi ?? '')
|
||||
}
|
||||
}, [nilaiKonservasiState.findById.data])
|
||||
|
||||
const submit = () => {
|
||||
if (nilaiKonservasiState.findById.data) {
|
||||
nilaiKonservasiState.findById.data.judul = judul;
|
||||
nilaiKonservasiState.findById.data.deskripsi = content;
|
||||
nilaiKonservasiState.update.save(nilaiKonservasiState.findById.data)
|
||||
}
|
||||
router.push('/admin/lingkungan/konservasi-adat-bali/nilai-konservasi-adat')
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
Page
|
||||
</div>
|
||||
<Box>
|
||||
<Stack gap={'xs'}>
|
||||
<Box>
|
||||
<Button
|
||||
variant={'subtle'}
|
||||
onClick={() => router.back()}
|
||||
>
|
||||
<IconArrowBack color={colors['blue-button']} size={20} />
|
||||
</Button>
|
||||
</Box>
|
||||
<Box>
|
||||
<Paper bg={colors['white-1']} p={'md'} radius={10} w={{ base: '100%', md: '50%' }}>
|
||||
<Stack gap={'xs'}>
|
||||
<Title order={3}>Edit Nilai Konservasi Adat</Title>
|
||||
<Text fw={"bold"}>Judul</Text>
|
||||
<KonservasiAdatBaliTextEditor
|
||||
showSubmit={false}
|
||||
onChange={setJudul}
|
||||
initialContent={judul}
|
||||
/>
|
||||
<Text fw={"bold"}>Content</Text>
|
||||
<KonservasiAdatBaliTextEditor
|
||||
showSubmit={false}
|
||||
onChange={setContent}
|
||||
initialContent={content}
|
||||
/>
|
||||
<Group>
|
||||
<Button
|
||||
bg={colors['blue-button']}
|
||||
onClick={submit}
|
||||
loading={nilaiKonservasiState.update.loading}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default Page;
|
||||
export default EditNilaiKonservasiAdat;
|
||||
|
||||
@@ -1,11 +1,54 @@
|
||||
import React from 'react';
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Grid, GridCol, Paper, Skeleton, Stack, Text, Title } from '@mantine/core';
|
||||
import { useShallowEffect } from '@mantine/hooks';
|
||||
import { IconEdit } from '@tabler/icons-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useProxy } from 'valtio/utils';
|
||||
import stateKonservasiAdatBali from '../../../_state/lingkungan/konservasi-adat-bali';
|
||||
|
||||
function Page() {
|
||||
const router = useRouter()
|
||||
const listNilaiKonservasiAdat = useProxy(stateKonservasiAdatBali.stateNilaiKonservasiAdat)
|
||||
useShallowEffect(() => {
|
||||
listNilaiKonservasiAdat.findById.load('edit')
|
||||
}, [])
|
||||
|
||||
if (!listNilaiKonservasiAdat.findById.data) {
|
||||
return (
|
||||
<Stack>
|
||||
<Skeleton radius={10} h={800} />
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
Page
|
||||
</div>
|
||||
);
|
||||
<Paper bg={colors['white-1']} p={'md'} radius={10}>
|
||||
<Stack gap={"22"}>
|
||||
<Grid>
|
||||
<GridCol span={{ base: 12, md: 11 }}>
|
||||
<Title order={2}>Preview Nilai Konservasi Adat</Title>
|
||||
</GridCol>
|
||||
<GridCol span={{ base: 12, md: 1 }}>
|
||||
<Button bg={colors['blue-button']} onClick={() => router.push('/admin/lingkungan/konservasi-adat-bali/nilai-konservasi-adat/edit')}>
|
||||
<IconEdit size={16} />
|
||||
</Button>
|
||||
</GridCol>
|
||||
</Grid>
|
||||
<Box>
|
||||
<Stack gap={'lg'}>
|
||||
<Paper p={"xl"} bg={colors['BG-trans']}>
|
||||
<Box px={{ base: 0, md: 30 }}>
|
||||
<Text fz={{ base: "h3", md: "h2" }} fw={"bold"} dangerouslySetInnerHTML={{ __html: listNilaiKonservasiAdat.findById.data.judul }} />
|
||||
</Box>
|
||||
<Box px={{ base: 0, md: 30 }}>
|
||||
<Text fz={{ base: "md", md: "h3" }} ta={"justify"} dangerouslySetInnerHTML={{ __html: listNilaiKonservasiAdat.findById.data.deskripsi }} />
|
||||
</Box>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page;
|
||||
|
||||
@@ -7,12 +7,12 @@ export const navBar = [
|
||||
{
|
||||
id: "Landing_Page_1",
|
||||
name: "Profile",
|
||||
path: "/admin/landing-page/profile"
|
||||
path: "/admin/landing-page/profile/program-inovasi"
|
||||
},
|
||||
{
|
||||
id: "Landing_Page_2",
|
||||
name: "Desa Anti Korupsi",
|
||||
path: "/admin/landing-page/desa-anti-korupsi"
|
||||
path: "/admin/landing-page/desa-anti-korupsi/list-desa-anti-korupsi"
|
||||
},
|
||||
{
|
||||
id: "Landing_Page_3",
|
||||
@@ -323,7 +323,7 @@ export const navBar = [
|
||||
{
|
||||
id: "Lingkungan_4",
|
||||
name: "Gotong Royong",
|
||||
path: "/admin/lingkungan/gotong-royong"
|
||||
path: "/admin/lingkungan/gotong-royong/kegiatan-desa"
|
||||
},
|
||||
{
|
||||
id: "Lingkungan_5",
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
AppShellHeader,
|
||||
AppShellMain,
|
||||
AppShellNavbar,
|
||||
Box,
|
||||
Burger,
|
||||
Flex,
|
||||
Group,
|
||||
Image,
|
||||
NavLink,
|
||||
@@ -15,16 +17,16 @@ import {
|
||||
Text
|
||||
} from "@mantine/core";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import { IconChevronLeft, IconChevronRight } from "@tabler/icons-react";
|
||||
import { IconChevronLeft, IconChevronRight, IconDoorExit } from "@tabler/icons-react";
|
||||
import _ from 'lodash';
|
||||
import Link from "next/link";
|
||||
import { useSelectedLayoutSegments } from "next/navigation";
|
||||
import { useRouter, useSelectedLayoutSegments } from "next/navigation";
|
||||
import { navBar } from "./_com/list_PageAdmin";
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
const [opened, { toggle }] = useDisclosure();
|
||||
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);
|
||||
|
||||
const router = useRouter()
|
||||
// Normalisasi semua segmen jadi lowercase
|
||||
const segments = useSelectedLayoutSegments().map(s => _.lowerCase(s));
|
||||
|
||||
@@ -44,6 +46,18 @@ export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
>
|
||||
<AppShellHeader bg={colors["white-1"]}>
|
||||
<Group px={10} align="center">
|
||||
<Flex align="center" gap={'xs'}>
|
||||
<Image
|
||||
py={5}
|
||||
src={'/assets/images/darmasaba-icon.png'}
|
||||
alt=""
|
||||
width={50}
|
||||
height={50}
|
||||
/>
|
||||
<Text fw={'bold'} c={colors["blue-button"]} fz={'lg'}>
|
||||
Dashboard Admin
|
||||
</Text>
|
||||
</Flex>
|
||||
{!desktopOpened && (
|
||||
<ActionIcon variant="light" onClick={toggleDesktop}>
|
||||
<IconChevronRight />
|
||||
@@ -55,6 +69,13 @@ export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
hiddenFrom="sm"
|
||||
size={'sm'}
|
||||
/>
|
||||
<Box>
|
||||
<ActionIcon onClick={() => {
|
||||
router.push("/darmasaba")
|
||||
}} color={colors["blue-button"]} radius={'xl'}>
|
||||
<IconDoorExit size={24} />
|
||||
</ActionIcon>
|
||||
</Box>
|
||||
<ActionIcon
|
||||
w={50}
|
||||
h={50}
|
||||
@@ -62,17 +83,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
component={Link}
|
||||
href="/admin"
|
||||
>
|
||||
<Image
|
||||
py={5}
|
||||
src={'/assets/images/darmasaba-icon.png'}
|
||||
alt=""
|
||||
width={50}
|
||||
height={50}
|
||||
/>
|
||||
</ActionIcon>
|
||||
<Text fw={'bold'} c={colors["blue-button"]} fz={'lg'}>
|
||||
Dashboard Admin
|
||||
</Text>
|
||||
</Group>
|
||||
</AppShellHeader>
|
||||
|
||||
|
||||
@@ -14,27 +14,15 @@ const fileStorageCreate = async (context: Context) => {
|
||||
const file = body.file;
|
||||
const name = body.name;
|
||||
|
||||
if (!file) {
|
||||
return {
|
||||
status: 400,
|
||||
body: "No file uploaded",
|
||||
};
|
||||
}
|
||||
if (!file) return { status: 400, body: "No file uploaded" };
|
||||
if (!name) return { status: 400, body: "No name provided" };
|
||||
if (!UPLOAD_DIR) return { status: 500, body: "UPLOAD_DIR is not defined" };
|
||||
|
||||
if (!name) {
|
||||
return {
|
||||
status: 400,
|
||||
body: "No name provided",
|
||||
};
|
||||
}
|
||||
// Tentukan kategori berdasarkan mimeType
|
||||
const isImage = file.type.startsWith("image/");
|
||||
const category = isImage ? "image" : "document";
|
||||
|
||||
if (!UPLOAD_DIR) {
|
||||
return {
|
||||
status: 500,
|
||||
body: "UPLOAD_DIR is not defined",
|
||||
};
|
||||
}
|
||||
const pathName = "allFile";
|
||||
const pathName = category === "image" ? "images" : "documents";
|
||||
const rootPath = path.join(UPLOAD_DIR, pathName);
|
||||
await fs.mkdir(rootPath, { recursive: true });
|
||||
|
||||
@@ -44,9 +32,10 @@ const fileStorageCreate = async (context: Context) => {
|
||||
const data = await prisma.fileStorage.create({
|
||||
data: {
|
||||
name: newName,
|
||||
realName: file.name, // Add the original file name as realName
|
||||
realName: file.name,
|
||||
path: rootPath,
|
||||
mimeType: file.type,
|
||||
category,
|
||||
link: `/api/fileStorage/findUnique/${newName}`,
|
||||
},
|
||||
});
|
||||
@@ -56,9 +45,7 @@ const fileStorageCreate = async (context: Context) => {
|
||||
Buffer.from(await file.arrayBuffer())
|
||||
);
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
return { data };
|
||||
};
|
||||
|
||||
export default fileStorageCreate;
|
||||
export default fileStorageCreate;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export const fileStorageFindMany = async () => {
|
||||
const data = await prisma.fileStorage.findMany();
|
||||
return data;
|
||||
export const fileStorageFindMany = async (context: Context) => {
|
||||
const category = context.query?.category as string | undefined;
|
||||
|
||||
const data = await prisma.fileStorage.findMany({
|
||||
where: category ? { category } : {},
|
||||
});
|
||||
|
||||
return { data };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormCreate = {
|
||||
name: string;
|
||||
deskripsi: string;
|
||||
fileId: string;
|
||||
kategoriId: string; // minimal satu kategori
|
||||
};
|
||||
|
||||
export default async function desaAntiKorupsiCreate(context: Context) {
|
||||
const body = context.body as FormCreate;
|
||||
|
||||
if (!body.kategoriId) {
|
||||
throw new Error("kategoriId wajib diisi");
|
||||
}
|
||||
|
||||
try {
|
||||
// Create langsung data AdministrasiOnline
|
||||
const result = await prisma.desaAntiKorupsi.create({
|
||||
data: {
|
||||
name: body.name,
|
||||
deskripsi: body.deskripsi,
|
||||
fileId: body.fileId,
|
||||
kategoriId: body.kategoriId, // relasi ke JenisLayanan
|
||||
},
|
||||
include: {
|
||||
kategori: true, // Include data relasi
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil membuat desa anti korupsi",
|
||||
data: result,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating desa anti korupsi:", error);
|
||||
throw new Error(
|
||||
"Gagal membuat desa anti korupsi: " + (error as Error).message
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function desaAntiKorupsiDelete(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const deleted = await prisma.desaAntiKorupsi.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil menghapus desa anti korupsi",
|
||||
data: deleted,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// /api/berita/findManyPaginated.ts
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
async function desaAntiKorupsiFindMany(context: Context) {
|
||||
const page = Number(context.query.page) || 1;
|
||||
const limit = Number(context.query.limit) || 10;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
try {
|
||||
const [data, total] = await Promise.all([
|
||||
prisma.desaAntiKorupsi.findMany({
|
||||
where: { isActive: true },
|
||||
include: {
|
||||
kategori: true,
|
||||
file: true,
|
||||
},
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: 'desc' }, // opsional, kalau mau urut berdasarkan waktu
|
||||
}),
|
||||
prisma.desaAntiKorupsi.count({
|
||||
where: { isActive: true }
|
||||
})
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success fetch desa anti korupsi with pagination",
|
||||
data,
|
||||
page,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
total,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Find many paginated error:", e);
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed fetch desa anti korupsi with pagination",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default desaAntiKorupsiFindMany;
|
||||
@@ -0,0 +1,29 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function desaAntiKorupsiFindUnique(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const data = await prisma.desaAntiKorupsi.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
kategori: true,
|
||||
file: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
throw new Error("Desa anti korupsi tidak ditemukan");
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Data desa anti korupsi ditemukan",
|
||||
data,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import desaAntiKorupsiDelete from "./del";
|
||||
import desaAntiKorupsiFindMany from "./findMany";
|
||||
import desaAntiKorupsiFindUnique from "./findUnique";
|
||||
import desaAntiKorupsiUpdate from "./updt";
|
||||
import desaAntiKorupsiCreate from "./create";
|
||||
|
||||
const DesaAntiKorupsi = new Elysia({
|
||||
prefix: "/desaantikorupsi",
|
||||
tags: ["Landing Page/Desa Anti Korupsi"],
|
||||
})
|
||||
|
||||
// ✅ Find all
|
||||
.get("/find-many", desaAntiKorupsiFindMany)
|
||||
|
||||
// ✅ Find by ID
|
||||
.get("/:id", desaAntiKorupsiFindUnique)
|
||||
|
||||
// ✅ Create
|
||||
.post("/create", desaAntiKorupsiCreate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
deskripsi: t.String(),
|
||||
fileId: t.String(),
|
||||
kategoriId: t.String(),
|
||||
}),
|
||||
})
|
||||
|
||||
// ✅ Update
|
||||
.put("/:id", desaAntiKorupsiUpdate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
deskripsi: t.String(),
|
||||
fileId: t.String(),
|
||||
kategoriId: t.String(),
|
||||
}),
|
||||
})
|
||||
// ✅ Delete
|
||||
.delete("/del/:id", desaAntiKorupsiDelete);
|
||||
|
||||
export default DesaAntiKorupsi;
|
||||
@@ -0,0 +1,25 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
|
||||
export default async function kategoriDesaAntiKorupsiCreate(context: Context) {
|
||||
const body = context.body as {name: string};
|
||||
|
||||
if (!body.name) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Nama is required",
|
||||
};
|
||||
}
|
||||
|
||||
const kategoriDesaAntiKorupsi = await prisma.kategoriDesaAntiKorupsi.create({
|
||||
data: {
|
||||
name: body.name,
|
||||
},
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
message: "Success create kategori desa anti korupsi",
|
||||
data: kategoriDesaAntiKorupsi
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function kategoriDesaAntiKorupsiDelete(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const deleted = await prisma.kategoriDesaAntiKorupsi.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil menghapus kategori desa anti korupsi",
|
||||
data: deleted,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
|
||||
export default async function kategoriDesaAntiKorupsiFindMany() {
|
||||
const data = await prisma.kategoriDesaAntiKorupsi.findMany();
|
||||
return {
|
||||
success: true,
|
||||
data: data.map((item: any) => {
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Context } from "elysia";
|
||||
import prisma from "@/lib/prisma";
|
||||
|
||||
export default async function kategoriDesaAntiKorupsiFindUnique(context: Context) {
|
||||
const url = new URL(context.request.url);
|
||||
const pathSegments = url.pathname.split('/');
|
||||
const id = pathSegments[pathSegments.length - 1];
|
||||
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof id !== 'string') {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
}
|
||||
}
|
||||
|
||||
const data = await prisma.kategoriDesaAntiKorupsi.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Kategori desa anti korupsi tidak ditemukan",
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success find kategori desa anti korupsi",
|
||||
data,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Find by ID error:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal mengambil kategori desa anti korupsi: " + (error instanceof Error ? error.message : 'Unknown error'),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import kategoriDesaAntiKorupsiCreate from "./create";
|
||||
import kategoriDesaAntiKorupsiDelete from "./del";
|
||||
import kategoriDesaAntiKorupsiFindMany from "./findMany";
|
||||
import kategoriDesaAntiKorupsiFindUnique from "./findUnique";
|
||||
import kategoriDesaAntiKorupsiUpdate from "./updt";
|
||||
|
||||
const KategoriDesaAntiKorupsi = new Elysia({
|
||||
prefix: "/kategoridak",
|
||||
tags: ["Landing Page/Desa Anti Korupsi"],
|
||||
})
|
||||
.get("/find-many", kategoriDesaAntiKorupsiFindMany)
|
||||
.get("/:id", async (context) => {
|
||||
const response = await kategoriDesaAntiKorupsiFindUnique(context);
|
||||
return response;
|
||||
})
|
||||
.delete("/del/:id", kategoriDesaAntiKorupsiDelete)
|
||||
.post("/create", kategoriDesaAntiKorupsiCreate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
}),
|
||||
})
|
||||
.put("/:id", kategoriDesaAntiKorupsiUpdate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export default KategoriDesaAntiKorupsi;
|
||||
@@ -0,0 +1,44 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function kategoriDesaAntiKorupsiUpdate(context: Context) {
|
||||
const body = context.body as { name: string };
|
||||
const id = context.params?.id as string;
|
||||
|
||||
// Validasi ID dan nama
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
};
|
||||
}
|
||||
|
||||
if (!body.name) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Name is required",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const kategoriDesaAntiKorupsi = await prisma.kategoriDesaAntiKorupsi.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: body.name,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success update kategori desa anti korupsi",
|
||||
data: kategoriDesaAntiKorupsi,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Update error:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal update kategori desa anti korupsi",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormUpdateDesaAntiKorupsi = {
|
||||
name?: string;
|
||||
deskripsi?: string;
|
||||
fileId?: string;
|
||||
kategoriId?: string; // minimal satu kategori
|
||||
};
|
||||
|
||||
export default async function desaAntiKorupsiUpdate(context: Context) {
|
||||
const body = context.body as FormUpdateDesaAntiKorupsi;
|
||||
|
||||
const id = context.params.id;
|
||||
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID desa anti korupsi wajib diisi",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await prisma.desaAntiKorupsi.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: body.name,
|
||||
deskripsi: body.deskripsi,
|
||||
fileId: body.fileId,
|
||||
kategoriId: body.kategoriId,
|
||||
},
|
||||
include: {
|
||||
file: true,
|
||||
kategori: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Desa anti korupsi berhasil diperbarui",
|
||||
data: updated,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error("❌ Error update desa anti korupsi:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal memperbarui data desa anti korupsi",
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
19
src/app/api/[[...slugs]]/_lib/landing_page/index.ts
Normal file
19
src/app/api/[[...slugs]]/_lib/landing_page/index.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import Elysia from "elysia";
|
||||
import MediaSosial from "./profile/media-sosial";
|
||||
import ProgramInovasi from "./profile/program-inovasi";
|
||||
import PejabatDesa from "./profile/pejabat-desa";
|
||||
import KategoriDesaAntiKorupsi from "./desa-anti-korupsi/kategori-dak";
|
||||
import DesaAntiKorupsi from "./desa-anti-korupsi";
|
||||
|
||||
const LandingPage = new Elysia({
|
||||
prefix: "/api/landingpage",
|
||||
tags: ["Landing Page/Profile"]
|
||||
})
|
||||
|
||||
.use(MediaSosial)
|
||||
.use(ProgramInovasi)
|
||||
.use(PejabatDesa)
|
||||
.use(KategoriDesaAntiKorupsi)
|
||||
.use(DesaAntiKorupsi)
|
||||
|
||||
export default LandingPage
|
||||
@@ -0,0 +1,36 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormCreate = {
|
||||
name: string;
|
||||
imageId: string;
|
||||
iconUrl: string;
|
||||
};
|
||||
|
||||
export default async function mediaSosialCreate(context: Context) {
|
||||
const body = context.body as FormCreate;
|
||||
|
||||
try {
|
||||
const result = await prisma.mediaSosial.create({
|
||||
data: {
|
||||
name: body.name,
|
||||
imageId: body.imageId,
|
||||
iconUrl: body.iconUrl,
|
||||
},
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil membuat media sosial",
|
||||
data: result,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating media sosial:", error);
|
||||
throw new Error(
|
||||
"Gagal membuat media sosial: " + (error as Error).message
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function mediaSosialDelete(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const deleted = await prisma.mediaSosial.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil menghapus media sosial",
|
||||
data: deleted,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// /api/berita/findManyPaginated.ts
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
async function mediaSosialFindMany(context: Context) {
|
||||
const page = Number(context.query.page) || 1;
|
||||
const limit = Number(context.query.limit) || 10;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
try {
|
||||
const [data, total] = await Promise.all([
|
||||
prisma.mediaSosial.findMany({
|
||||
where: { isActive: true },
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" }, // opsional, kalau mau urut berdasarkan waktu
|
||||
}),
|
||||
prisma.mediaSosial.count({
|
||||
where: { isActive: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success fetch media sosial with pagination",
|
||||
data,
|
||||
page,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
total,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Find many paginated error:", e);
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed fetch media sosial with pagination",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default mediaSosialFindMany;
|
||||
@@ -0,0 +1,28 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function mediaSosialFindUnique(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const data = await prisma.mediaSosial.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
throw new Error("Media sosial tidak ditemukan");
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Data media sosial ditemukan",
|
||||
data,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import MediaSosialCreate from "./create";
|
||||
import MediaSosialDelete from "./del";
|
||||
import MediaSosialFindMany from "./findMany";
|
||||
import MediaSosialFindUnique from "./findUnique";
|
||||
import MediaSosialUpdate from "./updt";
|
||||
|
||||
const MediaSosial = new Elysia({
|
||||
prefix: "/mediasosial",
|
||||
tags: ["Landing Page/Profile/Media Sosial"],
|
||||
})
|
||||
|
||||
// ✅ Find all
|
||||
.get("/find-many", MediaSosialFindMany)
|
||||
|
||||
// ✅ Find by ID
|
||||
.get("/:id", MediaSosialFindUnique)
|
||||
|
||||
// ✅ Create
|
||||
.post("/create", MediaSosialCreate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
imageId: t.String(),
|
||||
iconUrl: t.String(),
|
||||
}),
|
||||
})
|
||||
|
||||
// ✅ Update
|
||||
.put("/:id", MediaSosialUpdate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
imageId: t.Optional(t.String()),
|
||||
iconUrl: t.Optional(t.String()),
|
||||
}),
|
||||
})
|
||||
// ✅ Delete
|
||||
.delete("/del/:id", MediaSosialDelete);
|
||||
|
||||
export default MediaSosial;
|
||||
@@ -0,0 +1,49 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormUpdateMediaSosial = {
|
||||
name?: string;
|
||||
imageId?: string;
|
||||
iconUrl?: string;
|
||||
};
|
||||
|
||||
export default async function mediaSosialUpdate(context: Context) {
|
||||
const body = context.body as FormUpdateMediaSosial;
|
||||
|
||||
const id = context.params.id;
|
||||
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID media sosial wajib diisi",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await prisma.mediaSosial.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: body.name,
|
||||
imageId: body.imageId,
|
||||
iconUrl: body.iconUrl,
|
||||
},
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Media sosial berhasil diperbarui",
|
||||
data: updated,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error("❌ Error update media sosial:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal memperbarui data media sosial",
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function pejabatDesaFindUnique(context: Context) {
|
||||
try {
|
||||
const id = context.params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "ID tidak boleh kosong",
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const existing = await prisma.pejabatDesa.findUnique({
|
||||
where: { id },
|
||||
include: { image: true },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "Data tidak ditemukan",
|
||||
}),
|
||||
{
|
||||
status: 404,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: "Data pejabat desa berhasil ditemukan",
|
||||
data: existing,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error fetching pejabat desa:", error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "Terjadi kesalahan saat mengambil data pejabat desa",
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
|
||||
import pejabatDesaFindUnique from "./findUnique";
|
||||
import pejabatDesaUpdate from "./updt";
|
||||
|
||||
const PejabatDesa = new Elysia({
|
||||
prefix: "/pejabatdesa",
|
||||
tags: ["PPID/Profile PPID"]
|
||||
})
|
||||
.get("/:id", async (context) => {
|
||||
const response = await pejabatDesaFindUnique(context)
|
||||
return response
|
||||
})
|
||||
.put("/:id", async (context) => {
|
||||
const response = await pejabatDesaUpdate(context)
|
||||
return response
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
position: t.String(),
|
||||
imageId: t.String(),
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
export default PejabatDesa;
|
||||
@@ -0,0 +1,115 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Context } from "elysia";
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
|
||||
type FormUpdate = Prisma.PejabatDesaGetPayload<{
|
||||
select: {
|
||||
id: true;
|
||||
name: true;
|
||||
position: true;
|
||||
imageId: true;
|
||||
};
|
||||
}>;
|
||||
export default async function pejabatDesaUpdate(context: Context) {
|
||||
try {
|
||||
const id = context.params?.id as string;
|
||||
const body = (await context.body) as Omit<FormUpdate, "id">;
|
||||
|
||||
const { name, position, imageId } = body;
|
||||
|
||||
if (!id) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "ID tidak boleh kosong",
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const existing = await prisma.pejabatDesa.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "Data tidak ditemukan",
|
||||
}),
|
||||
{
|
||||
status: 404,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (existing.imageId !== imageId) {
|
||||
const oldImage = existing.image;
|
||||
if (oldImage) {
|
||||
try {
|
||||
const filePath = path.join(oldImage.path, oldImage.name);
|
||||
await fs.unlink(filePath);
|
||||
await prisma.fileStorage.delete({
|
||||
where: { id: oldImage.id },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Gagal hapus gambar lama:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prisma.pejabatDesa.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data: {
|
||||
name,
|
||||
position,
|
||||
imageId,
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: "Pejabat Desa Berhasil Dibuat",
|
||||
data: updated,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error updating pejabat desa:", error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "Terjadi kesalahan saat mengupdate pejabat desa",
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormCreate = {
|
||||
name: string;
|
||||
description: string;
|
||||
imageId: string;
|
||||
link: string;
|
||||
};
|
||||
|
||||
export default async function programInovasiCreate(context: Context) {
|
||||
const body = context.body as FormCreate;
|
||||
|
||||
if (!body.name) {
|
||||
throw new Error("name wajib diisi");
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await prisma.programInovasi.create({
|
||||
data: {
|
||||
name: body.name,
|
||||
description: body.description,
|
||||
imageId: body.imageId,
|
||||
link: body.link,
|
||||
},
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil membuat program inovasi",
|
||||
data: result,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating program inovasi:", error);
|
||||
throw new Error(
|
||||
"Gagal membuat program inovasi: " + (error as Error).message
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function programInovasiDelete(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const deleted = await prisma.programInovasi.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil menghapus program inovasi",
|
||||
data: deleted,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// /api/berita/findManyPaginated.ts
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
async function programInovasiFindMany(context: Context) {
|
||||
const page = Number(context.query.page) || 1;
|
||||
const limit = Number(context.query.limit) || 10;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
try {
|
||||
const [data, total] = await Promise.all([
|
||||
prisma.programInovasi.findMany({
|
||||
where: { isActive: true },
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" }, // opsional, kalau mau urut berdasarkan waktu
|
||||
}),
|
||||
prisma.programInovasi.count({
|
||||
where: { isActive: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success fetch program inovasi with pagination",
|
||||
data,
|
||||
page,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
total,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Find many paginated error:", e);
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed fetch program inovasi with pagination",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default programInovasiFindMany;
|
||||
@@ -0,0 +1,28 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function programInovasiFindUnique(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const data = await prisma.programInovasi.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
throw new Error("Program inovasi tidak ditemukan");
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Data program inovasi ditemukan",
|
||||
data,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import ProgramInovasiCreate from "./create";
|
||||
import ProgramInovasiDelete from "./del";
|
||||
import ProgramInovasiFindMany from "./findMany";
|
||||
import ProgramInovasiFindUnique from "./findUnique";
|
||||
import ProgramInovasiUpdate from "./updt";
|
||||
|
||||
const ProgramInovasi = new Elysia({
|
||||
prefix: "/programinovasi",
|
||||
tags: ["Landing Page/Profile/Program Inovasi"],
|
||||
})
|
||||
|
||||
// ✅ Find all
|
||||
.get("/find-many", ProgramInovasiFindMany)
|
||||
|
||||
// ✅ Find by ID
|
||||
.get("/:id", ProgramInovasiFindUnique)
|
||||
|
||||
// ✅ Create
|
||||
.post("/create", ProgramInovasiCreate, {
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
description: t.String(),
|
||||
imageId: t.String(),
|
||||
link: t.String(),
|
||||
}),
|
||||
})
|
||||
|
||||
// ✅ Update
|
||||
.put("/:id", ProgramInovasiUpdate, {
|
||||
body: t.Object({
|
||||
name: t.Optional(t.String()),
|
||||
description: t.Optional(t.String()),
|
||||
imageId: t.Optional(t.String()),
|
||||
link: t.Optional(t.String()),
|
||||
}),
|
||||
})
|
||||
// ✅ Delete
|
||||
.delete("/del/:id", ProgramInovasiDelete);
|
||||
|
||||
export default ProgramInovasi;
|
||||
@@ -0,0 +1,52 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormUpdateProgramInovasi = {
|
||||
name?: string;
|
||||
description?: string;
|
||||
imageId?: string;
|
||||
link?: string;
|
||||
};
|
||||
|
||||
export default async function programInovasiUpdate(context: Context) {
|
||||
const body = context.body as FormUpdateProgramInovasi;
|
||||
|
||||
const id = context.params.id;
|
||||
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID program inovasi wajib diisi",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await prisma.programInovasi.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: body.name,
|
||||
description: body.description,
|
||||
imageId: body.imageId,
|
||||
link: body.link,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
include: {
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Program inovasi berhasil diperbarui",
|
||||
data: updated,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error("❌ Error update program inovasi:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal memperbarui data program inovasi",
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormCreate = {
|
||||
judul: string;
|
||||
deskripsiSingkat: string;
|
||||
deskripsiLengkap: string;
|
||||
tanggal: string;
|
||||
lokasi: string;
|
||||
partisipan?: number;
|
||||
imageId: string;
|
||||
kategoriKegiatanId: string; // minimal satu kategori
|
||||
};
|
||||
|
||||
export default async function kegiatanDesaCreate(context: Context) {
|
||||
const body = context.body as FormCreate;
|
||||
|
||||
if (!body.kategoriKegiatanId) {
|
||||
throw new Error("kategoriKegiatanId wajib diisi");
|
||||
}
|
||||
|
||||
try {
|
||||
// Create langsung data AdministrasiOnline
|
||||
const result = await prisma.kegiatanDesa.create({
|
||||
data: {
|
||||
judul: body.judul,
|
||||
deskripsiSingkat: body.deskripsiSingkat,
|
||||
deskripsiLengkap: body.deskripsiLengkap,
|
||||
tanggal: body.tanggal,
|
||||
lokasi: body.lokasi,
|
||||
partisipan: body.partisipan ?? 0,
|
||||
imageId: body.imageId,
|
||||
kategoriKegiatanId: body.kategoriKegiatanId, // relasi ke JenisLayanan
|
||||
},
|
||||
include: {
|
||||
kategoriKegiatan: true, // Include data relasi
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil membuat kegiatan desa",
|
||||
data: result,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating kegiatan desa:", error);
|
||||
throw new Error(
|
||||
"Gagal membuat kegiatan desa: " + (error as Error).message
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function kegiatanDesaDelete(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const deleted = await prisma.kegiatanDesa.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Berhasil menghapus kegiatan desa",
|
||||
data: deleted,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// /api/berita/findManyPaginated.ts
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
async function kegiatanDesaFindMany(context: Context) {
|
||||
const page = Number(context.query.page) || 1;
|
||||
const limit = Number(context.query.limit) || 10;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
try {
|
||||
const [data, total] = await Promise.all([
|
||||
prisma.kegiatanDesa.findMany({
|
||||
where: { isActive: true },
|
||||
include: {
|
||||
kategoriKegiatan: true,
|
||||
image: true,
|
||||
},
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: 'desc' }, // opsional, kalau mau urut berdasarkan waktu
|
||||
}),
|
||||
prisma.kegiatanDesa.count({
|
||||
where: { isActive: true }
|
||||
})
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success fetch kegiatan desa with pagination",
|
||||
data,
|
||||
page,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
total,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Find many paginated error:", e);
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed fetch kegiatan desa with pagination",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default kegiatanDesaFindMany;
|
||||
@@ -0,0 +1,29 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function kegiatanDesaFindUnique(context: Context) {
|
||||
const { params } = context;
|
||||
const id = params?.id as string;
|
||||
|
||||
if (!id) {
|
||||
throw new Error("ID tidak ditemukan dalam parameter");
|
||||
}
|
||||
|
||||
const data = await prisma.kegiatanDesa.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
kategoriKegiatan: true,
|
||||
image: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
throw new Error("Kegiatan desa tidak ditemukan");
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Data kegiatan desa ditemukan",
|
||||
data,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import KegiatanDesaCreate from "./create";
|
||||
import KegiatanDesaDelete from "./del";
|
||||
import KegiatanDesaFindMany from "./findMany";
|
||||
import KegiatanDesaFindUnique from "./findUnique";
|
||||
import KegiatanDesaUpdate from "./updt";
|
||||
|
||||
const KegiatanDesa = new Elysia({
|
||||
prefix: "/kegiatandesa",
|
||||
tags: ["Lingkungan/Gotong Royong/Kegiatan Desa"],
|
||||
})
|
||||
|
||||
// ✅ Find all
|
||||
.get("/find-many", KegiatanDesaFindMany)
|
||||
|
||||
// ✅ Find by ID
|
||||
.get("/:id", KegiatanDesaFindUnique)
|
||||
|
||||
// ✅ Create
|
||||
.post("/create", KegiatanDesaCreate, {
|
||||
body: t.Object({
|
||||
judul: t.String(),
|
||||
deskripsiSingkat: t.String(),
|
||||
deskripsiLengkap: t.String(),
|
||||
tanggal: t.String(),
|
||||
lokasi: t.String(),
|
||||
partisipan: t.Optional(t.Number()),
|
||||
imageId: t.String(),
|
||||
kategoriKegiatanId: t.String(),
|
||||
}),
|
||||
})
|
||||
|
||||
// ✅ Update
|
||||
.put("/:id", KegiatanDesaUpdate, {
|
||||
body: t.Object({
|
||||
judul: t.Optional(t.String()),
|
||||
deskripsiSingkat: t.Optional(t.String()),
|
||||
deskripsiLengkap: t.Optional(t.String()),
|
||||
tanggal: t.Optional(t.String()),
|
||||
lokasi: t.Optional(t.String()),
|
||||
partisipan: t.Optional(t.Number()),
|
||||
imageId: t.Optional(t.String()),
|
||||
kategoriKegiatanId: t.Optional(t.String()),
|
||||
}),
|
||||
})
|
||||
// ✅ Delete
|
||||
.delete("/del/:id", KegiatanDesaDelete);
|
||||
|
||||
export default KegiatanDesa;
|
||||
@@ -0,0 +1,25 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
|
||||
export default async function kategoriKegiatanCreate(context: Context) {
|
||||
const body = context.body as {nama: string};
|
||||
|
||||
if (!body.nama) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Nama is required",
|
||||
};
|
||||
}
|
||||
|
||||
const kategoriKegiatan = await prisma.kategoriKegiatan.create({
|
||||
data: {
|
||||
nama: body.nama,
|
||||
},
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
message: "Success create kategori kegiatan",
|
||||
data: kategoriKegiatan
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
const kategoriKegiatanDelete = async (context: Context) => {
|
||||
const id = context.params.id;
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
}
|
||||
}
|
||||
|
||||
const kategoriKegiatan = await prisma.kategoriKegiatan.delete({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
})
|
||||
|
||||
if(!kategoriKegiatan) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Kategori Kegiatan tidak ditemukan",
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success delete kategori produk",
|
||||
data: kategoriKegiatan,
|
||||
}
|
||||
}
|
||||
|
||||
export default kategoriKegiatanDelete
|
||||
@@ -0,0 +1,15 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
|
||||
export default async function kategoriKegiatanFindMany() {
|
||||
const data = await prisma.kategoriKegiatan.findMany();
|
||||
return {
|
||||
success: true,
|
||||
data: data.map((item: any) => {
|
||||
return {
|
||||
id: item.id,
|
||||
nama: item.nama,
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Context } from "elysia";
|
||||
import prisma from "@/lib/prisma";
|
||||
|
||||
export default async function kategoriKegiatanFindUnique(context: Context) {
|
||||
const url = new URL(context.request.url);
|
||||
const pathSegments = url.pathname.split('/');
|
||||
const id = pathSegments[pathSegments.length - 1];
|
||||
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof id !== 'string') {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
}
|
||||
}
|
||||
|
||||
const data = await prisma.kategoriKegiatan.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Kategori kegiatan tidak ditemukan",
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success find kategori kegiatan",
|
||||
data,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Find by ID error:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal mengambil kategori kegiatan: " + (error instanceof Error ? error.message : 'Unknown error'),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import kategoriKegiatanCreate from "./create";
|
||||
import kategoriKegiatanDelete from "./del";
|
||||
import kategoriKegiatanFindMany from "./findMany";
|
||||
import kategoriKegiatanFindUnique from "./findUnique";
|
||||
import kategoriKegiatanUpdate from "./updt";
|
||||
|
||||
const KategoriKegiatan = new Elysia({
|
||||
prefix: "/kategorikegiatan",
|
||||
tags: ["Lingkungan/Kategori Kegiatan"],
|
||||
})
|
||||
.get("/find-many", kategoriKegiatanFindMany)
|
||||
.get("/:id", async (context) => {
|
||||
const response = await kategoriKegiatanFindUnique(context);
|
||||
return response;
|
||||
})
|
||||
.delete("/del/:id", kategoriKegiatanDelete)
|
||||
.post("/create", kategoriKegiatanCreate, {
|
||||
body: t.Object({
|
||||
nama: t.String(),
|
||||
}),
|
||||
})
|
||||
.put("/:id", kategoriKegiatanUpdate, {
|
||||
body: t.Object({
|
||||
nama: t.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export default KategoriKegiatan;
|
||||
@@ -0,0 +1,44 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
export default async function kategoriKegiatanUpdate(context: Context) {
|
||||
const body = context.body as { nama: string };
|
||||
const id = context.params?.id as string;
|
||||
|
||||
// Validasi ID dan nama
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID is required",
|
||||
};
|
||||
}
|
||||
|
||||
if (!body.nama) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Nama is required",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const kategoriKegiatan = await prisma.kategoriKegiatan.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nama: body.nama,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Success update kategori kegiatan",
|
||||
data: kategoriKegiatan,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Update error:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal update kategori kegiatan",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
type FormUpdateKegiatanDesa = {
|
||||
judul?: string;
|
||||
deskripsiSingkat?: string;
|
||||
deskripsiLengkap?: string;
|
||||
tanggal?: string;
|
||||
lokasi?: string;
|
||||
partisipan?: number;
|
||||
imageId?: string;
|
||||
kategoriKegiatanId?: string; // minimal satu kategori
|
||||
};
|
||||
|
||||
export default async function kegiatanDesaUpdate(context: Context) {
|
||||
const body = context.body as FormUpdateKegiatanDesa;
|
||||
|
||||
const id = context.params.id;
|
||||
|
||||
if (!id) {
|
||||
return {
|
||||
success: false,
|
||||
message: "ID kegiatan desa wajib diisi",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await prisma.kegiatanDesa.update({
|
||||
where: { id },
|
||||
data: {
|
||||
judul: body.judul,
|
||||
deskripsiSingkat: body.deskripsiSingkat,
|
||||
deskripsiLengkap: body.deskripsiLengkap,
|
||||
tanggal: body.tanggal ? new Date(body.tanggal) : undefined,
|
||||
lokasi: body.lokasi,
|
||||
partisipan: body.partisipan ?? 0,
|
||||
imageId: body.imageId,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
include: {
|
||||
image: true,
|
||||
kategoriKegiatan: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Kegiatan desa berhasil diperbarui",
|
||||
data: updated,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error("❌ Error update kegiatan desa:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Gagal memperbarui data kegiatan desa",
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import ProgramPenghijauan from "./program-penghijauan";
|
||||
import DataLingkunganDesa from "./data-lingkungan-desa";
|
||||
import EdukasiLingkungan from "./edukasi-lingkungan";
|
||||
import KonservasiAdatBali from "./konservasi-adat-bali";
|
||||
import KegiatanDesa from "./gotong-royong";
|
||||
import KategoriKegiatan from "./gotong-royong/kategori-kegiatan";
|
||||
|
||||
const Lingkungan = new Elysia({
|
||||
prefix: "/api/lingkungan",
|
||||
@@ -15,6 +17,8 @@ const Lingkungan = new Elysia({
|
||||
.use(DataLingkunganDesa)
|
||||
.use(EdukasiLingkungan)
|
||||
.use(KonservasiAdatBali)
|
||||
.use(KegiatanDesa)
|
||||
.use(KategoriKegiatan)
|
||||
|
||||
|
||||
export default Lingkungan;
|
||||
|
||||
@@ -21,6 +21,7 @@ import Keamanan from "./_lib/keamanan";
|
||||
import Ekonomi from "./_lib/ekonomi";
|
||||
import Inovasi from "./_lib/inovasi";
|
||||
import Lingkungan from "./_lib/lingkungan";
|
||||
import LandingPage from "./_lib/landing_page";
|
||||
|
||||
|
||||
const ROOT = process.cwd();
|
||||
@@ -85,6 +86,7 @@ const ApiServer = new Elysia()
|
||||
.use(Ekonomi)
|
||||
.use(Inovasi)
|
||||
.use(Lingkungan)
|
||||
.use(LandingPage)
|
||||
.onError(({ code }) => {
|
||||
if (code === "NOT_FOUND") {
|
||||
return {
|
||||
|
||||
@@ -26,6 +26,7 @@ export function Navbar() {
|
||||
}}
|
||||
>
|
||||
<NavbarMainMenu listNavbar={navbarListMenu} />
|
||||
|
||||
<Stack hiddenFrom="sm" bg={colors.grey[2]}>
|
||||
<Group justify="space-between">
|
||||
<ActionIcon variant="transparent" onClick={() => {
|
||||
@@ -50,6 +51,7 @@ export function Navbar() {
|
||||
<NavbarMobile listNavbar={navbarListMenu} />
|
||||
</motion.div>}
|
||||
</Stack>
|
||||
|
||||
</Box>
|
||||
{(item || isSearch) && <Box className="glass" />}
|
||||
</Box>
|
||||
|
||||
@@ -4,18 +4,20 @@ import colors from "@/con/colors"
|
||||
import stateNav from "@/state/state-nav"
|
||||
import { ActionIcon, Button, Container, Flex, Image, Stack } from "@mantine/core"
|
||||
import { useHover } from "@mantine/hooks"
|
||||
import { IconSearch, IconUser } from "@tabler/icons-react"
|
||||
import { useTransitionRouter } from 'next-view-transitions'
|
||||
import { useSnapshot } from "valtio"
|
||||
import { MenuItem } from "../../../../types/menu-item"
|
||||
import { NavbarSearch } from "./NavBarSearch"
|
||||
import { NavbarSubMenu } from "./NavbarSubMenu"
|
||||
import { IconSearch } from "@tabler/icons-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
export function NavbarMainMenu({ listNavbar }: {
|
||||
listNavbar: MenuItem[]
|
||||
}) {
|
||||
const { item, isSearch } = useSnapshot(stateNav)
|
||||
const router = useTransitionRouter()
|
||||
const next = useRouter()
|
||||
return <Stack gap={0} visibleFrom="sm" bg={colors["white-trans-1"]}>
|
||||
<Container pos={"relative"} w={{
|
||||
base: '100%',
|
||||
@@ -28,7 +30,7 @@ export function NavbarMainMenu({ listNavbar }: {
|
||||
<ActionIcon radius={"100"} variant="transparent" onClick={() => {
|
||||
router.push("/darmasaba")
|
||||
stateNav.clear()
|
||||
|
||||
|
||||
}} >
|
||||
<Image radius={"100"} src={"/assets/images/darmasaba-icon.png"} alt="icon" w={24} h={24} loading="lazy" />
|
||||
</ActionIcon>
|
||||
@@ -44,6 +46,11 @@ export function NavbarMainMenu({ listNavbar }: {
|
||||
{/* TODO: add icon search */}
|
||||
<IconSearch size={"1.5rem"} />
|
||||
</ActionIcon>
|
||||
<ActionIcon onClick={() => {
|
||||
next.push("/admin/landing-page/profile/program-inovasi")
|
||||
}} color={colors["blue-button"]} radius={'xl'}>
|
||||
<IconUser size={24} />
|
||||
</ActionIcon>
|
||||
</Flex>
|
||||
</Container>
|
||||
{item && <NavbarSubMenu item={item as MenuItem[]} />}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user