Fix UI & API Admin Menu Kesehatan, Submenu Data Kesehatan Warga Bagian ChartBar

This commit is contained in:
2025-08-14 20:47:07 +08:00
parent 5e137ba658
commit d7a592c635
34 changed files with 2285 additions and 445 deletions

View File

@@ -911,15 +911,42 @@ model PendaftaranJadwalKegiatan {
// ========================================= PERSENTASE KELAHIRAN & KEMATIAN ========================================= //
model DataKematian_Kelahiran {
id String @id @default(cuid())
tahun String
kematianKasar String
kematianBayi String
kelahiranKasar String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime @default(now())
isActive Boolean @default(true)
id String @id @default(cuid())
kematian Kematian @relation(fields: [kematianId], references: [id])
kematianId String
kelahiran Kelahiran @relation(fields: [kelahiranId], references: [id])
kelahiranId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime @default(now())
isActive Boolean @default(true)
}
model Kelahiran {
id String @id @default(cuid())
nama String
tanggal DateTime
jenisKelamin String
alamat String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime @default(now())
isActive Boolean @default(true)
DataKematian_Kelahiran DataKematian_Kelahiran[]
}
model Kematian {
id String @id @default(cuid())
nama String
tanggal DateTime
jenisKelamin String
alamat String
penyebab String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime @default(now())
isActive Boolean @default(true)
DataKematian_Kelahiran DataKematian_Kelahiran[]
}
// ========================================= GRAFIK KEPUASAN ========================================= //

View File

@@ -1,10 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
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 templatePersentase = z.object({
//persentase kelahiran kematian
const templatePersentaseKelahiran = z.object({
tahun: z.string().min(4, "Tahun harus diisi"),
kematianKasar: z.string().min(1, "Kematian kasar harus diisi"),
kelahiranKasar: z.string().min(1, "Kelahiran kasar harus diisi"),
@@ -13,18 +16,14 @@ const templatePersentase = z.object({
type Persentase = Prisma.DataKematian_KelahiranGetPayload<{
select: {
tahun: true;
kematianKasar: true;
kelahiranKasar: true;
kematianBayi: true;
kematianId: true;
kelahiranId: true;
};
}>;
const defaultForm: Persentase = {
tahun: "",
kematianKasar: "",
kelahiranKasar: "",
kematianBayi: "",
kematianId: "",
kelahiranId: "",
};
const persentasekelahiran = proxy({
@@ -32,7 +31,9 @@ const persentasekelahiran = proxy({
form: defaultForm,
loading: false,
async create() {
const cek = templatePersentase.safeParse(persentasekelahiran.create.form);
const cek = templatePersentaseKelahiran.safeParse(
persentasekelahiran.create.form
);
if (!cek.success) {
const err = `[${cek.error.issues
.map((v) => `${v.path.join(".")}`)
@@ -47,7 +48,7 @@ const persentasekelahiran = proxy({
].post(persentasekelahiran.create.form);
if (res.status === 200) {
const id = res.data?.data?.id;
const id = res.data?.data;
if (id) {
toast.success("Success create");
persentasekelahiran.create.form = { ...defaultForm };
@@ -69,21 +70,51 @@ const persentasekelahiran = proxy({
findMany: {
data: null as
| Prisma.DataKematian_KelahiranGetPayload<{
omit: { isActive: true };
include: {
kematian: true;
kelahiran: true;
};
}>[]
| null,
async load() {
const res = await ApiFetch.api.kesehatan.persentasekelahiran[
"find-many"
].get();
if (res.status === 200) {
persentasekelahiran.findMany.data = res.data?.data ?? [];
page: 1,
totalPages: 1,
loading: false,
search: "",
load: async (page = 1, limit = 10, search = "") => {
persentasekelahiran.findMany.loading = true; // ✅ Akses langsung via nama path
persentasekelahiran.findMany.page = page;
persentasekelahiran.findMany.search = search;
try {
const query: any = { page, limit };
if (search) query.search = search;
const res = await ApiFetch.api.kesehatan.persentasekelahiran[
"find-many"
].get({ query });
if (res.status === 200 && res.data?.success) {
persentasekelahiran.findMany.data = res.data.data ?? [];
persentasekelahiran.findMany.totalPages = res.data.totalPages ?? 1;
} else {
persentasekelahiran.findMany.data = [];
persentasekelahiran.findMany.totalPages = 1;
}
} catch (err) {
console.error("Gagal fetch berita paginated:", err);
persentasekelahiran.findMany.data = [];
persentasekelahiran.findMany.totalPages = 1;
} finally {
persentasekelahiran.findMany.loading = false;
}
},
},
findUnique: {
data: null as Prisma.DataKematian_KelahiranGetPayload<{
omit: { isActive: true };
include: {
kematian: true;
kelahiran: true;
};
}> | null,
async load(id: string) {
try {
@@ -114,13 +145,11 @@ const persentasekelahiran = proxy({
}
const formData = {
tahun: this.form.tahun,
kematianKasar: this.form.kematianKasar,
kelahiranKasar: this.form.kelahiranKasar,
kematianBayi: this.form.kematianBayi,
kematianId: this.form.kematianId,
kelahiranId: this.form.kelahiranId,
};
const cek = templatePersentase.safeParse(formData);
const cek = templatePersentaseKelahiran.safeParse(formData);
if (!cek.success) {
const err = `[${cek.error.issues
.map((v) => `${v.path.join(".")}`)
@@ -197,4 +226,521 @@ const persentasekelahiran = proxy({
},
});
export default persentasekelahiran;
// data kelahiran
const templateKelahiran = z.object({
nama: z.string().min(1, "Nama harus diisi"),
tanggal: z.string().min(4, "Tahun harus diisi"),
jenisKelamin: z.string().min(1, "Jenis kelamin harus diisi"),
alamat: z.string().min(1, "Alamat harus diisi"),
});
const defaultKelahiran = {
nama: "",
tanggal: "",
jenisKelamin: "",
alamat: "",
};
const kelahiran = proxy({
create: {
form: { ...defaultKelahiran }, // ✅ ini kunci fix-nya
loading: false,
async create() {
const cek = templateKelahiran.safeParse(kelahiran.create.form);
if (!cek.success) {
const err = `[${cek.error.issues
.map((v) => `${v.path.join(".")}`)
.join("\n")}] required`;
return toast.error(err);
}
try {
kelahiran.create.loading = true;
const res = await ApiFetch.api.kesehatan.kelahiran["create"].post(
kelahiran.create.form
);
if (res.status === 200) {
kelahiran.findMany.load();
return toast.success("Kelahiran berhasil disimpan!");
}
return toast.error("Gagal menyimpan kelahiran");
} catch (error) {
console.log((error as Error).message);
} finally {
kelahiran.create.loading = false;
}
},
resetForm() {
kelahiran.create.form = { ...defaultKelahiran };
},
},
findMany: {
data: null as
| Prisma.KelahiranGetPayload<{
omit: {
isActive: true;
};
}>[]
| null,
page: 1,
totalPages: 1,
loading: false,
search: "",
load: async (page = 1, limit = 10, search = "") => {
kelahiran.findMany.loading = true; // ✅ Akses langsung via nama path
kelahiran.findMany.page = page;
kelahiran.findMany.search = search;
try {
const query: any = { page, limit };
if (search) query.search = search;
const res = await ApiFetch.api.kesehatan.kelahiran["findMany"].get({
query,
});
if (res.status === 200 && res.data?.success) {
kelahiran.findMany.data = res.data.data ?? [];
kelahiran.findMany.totalPages = res.data.totalPages ?? 1;
} else {
kelahiran.findMany.data = [];
kelahiran.findMany.totalPages = 1;
}
} catch (err) {
console.error("Gagal fetch kelahiran paginated:", err);
kelahiran.findMany.data = [];
kelahiran.findMany.totalPages = 1;
} finally {
kelahiran.findMany.loading = false;
}
},
},
findUnique: {
data: null as Prisma.KelahiranGetPayload<{
omit: {
isActive: true;
};
}> | null,
async load(id: string) {
try {
const res = await fetch(`/api/kesehatan/kelahiran/${id}`);
if (res.ok) {
const data = await res.json();
kelahiran.findUnique.data = data.data ?? null;
} else {
console.error("Failed to fetch kelahiran:", res.statusText);
kelahiran.findUnique.data = null;
}
} catch (error) {
console.error("Error fetching kelahiran:", error);
kelahiran.findUnique.data = null;
}
},
},
delete: {
loading: false,
async byId(id: string) {
if (!id) return toast.warn("ID tidak valid");
try {
kelahiran.delete.loading = true;
const response = await fetch(`/api/kesehatan/kelahiran/del/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
const result = await response.json();
if (response.ok && result?.success) {
toast.success(result.message || "Kelahiran berhasil dihapus");
await kelahiran.findMany.load(); // refresh list
} else {
toast.error(result?.message || "Gagal menghapus kelahiran");
}
} catch (error) {
console.error("Gagal delete:", error);
toast.error("Terjadi kesalahan saat menghapus kelahiran");
} finally {
kelahiran.delete.loading = false;
}
},
},
edit: {
id: "",
form: { ...defaultKelahiran },
loading: false,
async load(id: string) {
if (!id) {
toast.warn("ID tidak valid");
return null;
}
try {
const response = await fetch(`/api/kesehatan/kelahiran/${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,
tanggal: data.tanggal,
jenisKelamin: data.jenisKelamin,
alamat: data.alamat,
};
return data; // Return the loaded data
} else {
throw new Error(result?.message || "Gagal memuat data");
}
} catch (error) {
console.error("Error loading data kelahiran:", error);
toast.error(
error instanceof Error ? error.message : "Gagal memuat data"
);
return null;
}
},
async update() {
const cek = templateKelahiran.safeParse(kelahiran.edit.form);
if (!cek.success) {
const err = `[${cek.error.issues
.map((v) => `${v.path.join(".")}`)
.join("\n")}] required`;
toast.error(err);
return false;
}
try {
kelahiran.edit.loading = true;
const response = await fetch(`/api/kesehatan/kelahiran/${this.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
nama: this.form.nama,
tanggal: this.form.tanggal,
jenisKelamin: this.form.jenisKelamin,
alamat: this.form.alamat,
}),
});
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 data kelahiran");
await kelahiran.findMany.load(); // refresh list
return true;
} else {
throw new Error(result.message || "Gagal update data kelahiran");
}
} catch (error) {
console.error("Error updating data kelahiran:", error);
toast.error(
error instanceof Error
? error.message
: "Terjadi kesalahan saat update data kelahiran"
);
return false;
} finally {
kelahiran.edit.loading = false;
}
},
reset() {
kelahiran.edit.id = "";
kelahiran.edit.form = { ...defaultKelahiran };
},
},
});
// data kematian
const templateKematian = z.object({
nama: z.string().min(1, "Nama harus diisi"),
tanggal: z.string().min(4, "Tahun harus diisi"),
jenisKelamin: z.string().min(1, "Jenis kelamin harus diisi"),
alamat: z.string().min(1, "Alamat harus diisi"),
penyebab: z.string().min(1, "Penyebab harus diisi"),
});
const defaultKematian = {
nama: "",
tanggal: "",
jenisKelamin: "",
alamat: "",
penyebab: "",
};
const kematian = proxy({
create: {
form: { ...defaultKematian }, // ✅ ini kunci fix-nya
loading: false,
async create() {
const cek = templateKematian.safeParse(kematian.create.form);
if (!cek.success) {
const err = `[${cek.error.issues
.map((v) => `${v.path.join(".")}`)
.join("\n")}] required`;
return toast.error(err);
}
try {
kematian.create.loading = true;
const res = await ApiFetch.api.kesehatan.kematian["create"].post(
kematian.create.form
);
if (res.status === 200) {
kematian.findMany.load();
return toast.success("Kematian berhasil disimpan!");
}
return toast.error("Gagal menyimpan kematian");
} catch (error) {
console.log((error as Error).message);
} finally {
kematian.create.loading = false;
}
},
resetForm() {
kematian.create.form = { ...defaultKematian };
},
},
findMany: {
data: null as
| Prisma.KematianGetPayload<{
omit: {
isActive: true;
};
}>[]
| null,
page: 1,
totalPages: 1,
loading: false,
search: "",
load: async (page = 1, limit = 10, search = "") => {
kematian.findMany.loading = true; // ✅ Akses langsung via nama path
kematian.findMany.page = page;
kematian.findMany.search = search;
try {
const query: any = { page, limit };
if (search) query.search = search;
const res = await ApiFetch.api.kesehatan.kematian["findMany"].get({
query,
});
if (res.status === 200 && res.data?.success) {
kematian.findMany.data = res.data.data ?? [];
kematian.findMany.totalPages = res.data.totalPages ?? 1;
} else {
kematian.findMany.data = [];
kematian.findMany.totalPages = 1;
}
} catch (err) {
console.error("Gagal fetch kematian paginated:", err);
kematian.findMany.data = [];
kematian.findMany.totalPages = 1;
} finally {
kematian.findMany.loading = false;
}
},
},
findUnique: {
data: null as Prisma.KematianGetPayload<{
omit: {
isActive: true;
};
}> | null,
async load(id: string) {
try {
const res = await fetch(`/api/kesehatan/kematian/${id}`);
if (res.ok) {
const data = await res.json();
kematian.findUnique.data = data.data ?? null;
} else {
console.error("Failed to fetch kematian:", res.statusText);
kematian.findUnique.data = null;
}
} catch (error) {
console.error("Error fetching kematian:", error);
kematian.findUnique.data = null;
}
},
},
delete: {
loading: false,
async byId(id: string) {
if (!id) return toast.warn("ID tidak valid");
try {
kematian.delete.loading = true;
const response = await fetch(`/api/kesehatan/kematian/del/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
const result = await response.json();
if (response.ok && result?.success) {
toast.success(result.message || "Kematian berhasil dihapus");
await kematian.findMany.load(); // refresh list
} else {
toast.error(result?.message || "Gagal menghapus kematian");
}
} catch (error) {
console.error("Gagal delete:", error);
toast.error("Terjadi kesalahan saat menghapus kematian");
} finally {
kematian.delete.loading = false;
}
},
},
edit: {
id: "",
form: { ...defaultKematian },
loading: false,
async load(id: string) {
if (!id) {
toast.warn("ID tidak valid");
return null;
}
try {
const response = await fetch(`/api/kesehatan/kematian/${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,
tanggal: data.tanggal,
jenisKelamin: data.jenisKelamin,
alamat: data.alamat,
penyebab: data.penyebab,
};
return data; // Return the loaded data
} else {
throw new Error(result?.message || "Gagal memuat data");
}
} catch (error) {
console.error("Error loading data kematian:", error);
toast.error(
error instanceof Error ? error.message : "Gagal memuat data"
);
return null;
}
},
async update() {
const cek = templateKematian.safeParse(kematian.edit.form);
if (!cek.success) {
const err = `[${cek.error.issues
.map((v) => `${v.path.join(".")}`)
.join("\n")}] required`;
toast.error(err);
return false;
}
try {
kematian.edit.loading = true;
const response = await fetch(`/api/kesehatan/kematian/${this.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
nama: this.form.nama,
tanggal: this.form.tanggal,
jenisKelamin: this.form.jenisKelamin,
alamat: this.form.alamat,
penyebab: this.form.penyebab,
}),
});
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 data kematian");
await kematian.findMany.load(); // refresh list
return true;
} else {
throw new Error(result.message || "Gagal update data kematian");
}
} catch (error) {
console.error("Error updating data kematian:", error);
toast.error(
error instanceof Error
? error.message
: "Terjadi kesalahan saat update data kematian"
);
return false;
} finally {
kematian.edit.loading = false;
}
},
reset() {
kematian.edit.id = "";
kematian.edit.form = { ...defaultKematian };
},
},
});
const persentaseKelahiranKematian = proxy({
persentasekelahiran,
kelahiran,
kematian
});
export default persentaseKelahiranKematian;

View File

@@ -1,113 +0,0 @@
/* eslint-disable react-hooks/exhaustive-deps */
'use client'
import persentasekelahiran from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, Paper, Stack, TextInput, Title } from '@mantine/core';
import { IconArrowBack } from '@tabler/icons-react';
import { useParams, useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { toast } from 'react-toastify';
import { useProxy } from 'valtio/utils';
function EditPersentaseDataKelahiranKematian() {
const router = useRouter()
const params = useParams() as { id: string }
const statePresentase = useProxy(persentasekelahiran)
const id = params.id
// Load data saat komponen mount
// Di file page.tsx, ubah useEffect-nya menjadi:
useEffect(() => {
if (!id) return;
statePresentase.update.id = id;
statePresentase.findUnique.load(id)
.then(() => {
const data = statePresentase.findUnique.data;
if (data) {
statePresentase.update.form = {
tahun: String(data.tahun || ''),
kematianKasar: String(data.kematianKasar || ''),
kelahiranKasar: String(data.kelahiranKasar || ''),
kematianBayi: String(data.kematianBayi || '')
};
}
})
.catch(error => {
console.error('Error loading data:', error);
toast.error('Gagal memuat data');
});
}, [id]);
// Di handleSubmit, ubah menjadi:
const handleSubmit = async () => {
try {
statePresentase.update.id = id;
await statePresentase.update.submit();
toast.success('Data berhasil diperbarui');
router.push('/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian');
} catch (error) {
console.error('Error updating data:', error);
toast.error('Gagal memperbarui data');
}
};
return (
<Box>
<Box mb={10}>
<Button variant="subtle" onClick={() => router.back()}>
<IconArrowBack size={20} />
</Button>
</Box>
<Paper bg={colors['white-1']} w={{ base: '100%', md: '50%' }} p={'md'}>
<Stack>
<Title order={3}>Edit Persentase Data Kelahiran & Kematian</Title>
<TextInput
label="Tahun"
placeholder="masukkan tahun"
value={statePresentase.update.form.tahun}
onChange={(val) => {
statePresentase.update.form.tahun = val.currentTarget.value;
}}
/>
<TextInput
label="Kematian Kasar"
type="number"
placeholder="masukkan kematian kasar"
value={statePresentase.update.form.kematianKasar}
onChange={(val) => {
statePresentase.update.form.kematianKasar = val.currentTarget.value;
}}
/>
<TextInput
label="Kematian Bayi"
type="number"
placeholder="masukkan kematian bayi"
value={statePresentase.update.form.kematianBayi}
onChange={(val) => {
statePresentase.update.form.kematianBayi = val.currentTarget.value;
}}
/>
<TextInput
label="Kelahiran Kasar"
type="number"
placeholder="masukkan kelahiran kasar"
value={statePresentase.update.form.kelahiranKasar}
onChange={(val) => {
statePresentase.update.form.kelahiranKasar = val.currentTarget.value;
}}
/>
<Button
mt={10}
bg={colors['blue-button']}
onClick={handleSubmit}
>
Simpan Perubahan
</Button>
</Stack>
</Paper>
</Box>
)
}
export default EditPersentaseDataKelahiranKematian;

View File

@@ -1,101 +0,0 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client'
import persentasekelahiran from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, Group, Paper, Stack, TextInput, Title } from '@mantine/core';
import { IconArrowBack } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useProxy } from 'valtio/utils';
function CreatePersentaseDataKelahiranKematian() {
const statePersentase = useProxy(persentasekelahiran);
const [chartData, setChartData] = useState<any[]>([]);
const router = useRouter()
const resetForm = () => {
statePersentase.create.form = {
tahun: "",
kematianBayi: "",
kematianKasar: "",
kelahiranKasar: "",
}
}
const handleSubmit = async () => {
const id = await statePersentase.create.create();
if (id) {
const idStr = String(id);
await statePersentase.findUnique.load(idStr);
if (statePersentase.findUnique.data) {
setChartData([statePersentase.findUnique.data]);
}
}
resetForm();
router.push("/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian");
}
return (
<Box>
<Box mb={10}>
<Button variant="subtle" onClick={() => router.back()}>
<IconArrowBack size={20} />
</Button>
</Box>
<Box>
<Paper w={{ base: '100%', md: '50%' }} bg={colors['white-1']} p={'md'}>
<Title order={4}>Tambah Persentase Data Kelahiran & Kematian</Title>
<Stack gap={"xs"}>
<TextInput
label="Tahun"
type="number"
value={statePersentase.create.form.tahun}
placeholder="Masukkan tahun"
onChange={(val) => {
statePersentase.create.form.tahun = val.currentTarget.value;
}}
/>
<TextInput
label="Kematian Kasar"
type="number"
value={statePersentase.create.form.kematianKasar}
placeholder="Masukkan kematian kasar"
onChange={(val) => {
statePersentase.create.form.kematianKasar = val.currentTarget.value;
}}
/>
<TextInput
label="Kematian Bayi"
type="number"
value={statePersentase.create.form.kematianBayi}
placeholder="Masukkan kematian bayi"
onChange={(val) => {
statePersentase.create.form.kematianBayi = val.currentTarget.value;
}}
/>
<TextInput
label="Kelahiran Kasar"
type="number"
value={statePersentase.create.form.kelahiranKasar}
placeholder="Masukkan kelahiran kasar"
onChange={(val) => {
statePersentase.create.form.kelahiranKasar = val.currentTarget.value;
}}
/>
<Group>
<Button
bg={colors['blue-button']}
mt={10}
onClick={handleSubmit}
>
Submit
</Button>
</Group>
</Stack>
</Paper>
</Box>
</Box>
);
}
export default CreatePersentaseDataKelahiranKematian;

View File

@@ -0,0 +1,107 @@
/* eslint-disable react-hooks/exhaustive-deps */
'use client'
import persentaseKelahiranKematian from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, 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 EditKelahiran() {
const editState = useProxy(persentaseKelahiranKematian.kelahiran)
const router = useRouter();
const params = useParams();
const [formData, setFormData] = useState({
nama: editState.edit.form.nama || '',
tanggal: editState.edit.form.tanggal || '',
jenisKelamin: editState.edit.form.jenisKelamin || '',
alamat: editState.edit.form.alamat || '',
});
useEffect(() => {
const loadKelahiran = async () => {
const id = params?.id as string;
if (!id) return;
try {
const data = await editState.edit.load(id); // akses langsung, bukan dari proxy
if (data) {
setFormData({
nama: data.nama || '',
tanggal: data.tanggal || '',
jenisKelamin: data.jenisKelamin || '',
alamat: data.alamat || '',
});
}
} catch (error) {
console.error("Error loading data kelahiran:", error);
toast.error("Gagal memuat data data kelahiran");
}
};
loadKelahiran();
}, [params?.id]);
const handleSubmit = async () => {
try {
editState.edit.form = {
...editState.edit.form,
nama: formData.nama,
tanggal: formData.tanggal,
jenisKelamin: formData.jenisKelamin,
alamat: formData.alamat,
};
await editState.edit.update();
toast.success('data kelahiran berhasil diperbarui!');
router.push('/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran');
} catch (error) {
console.error('Error updating data kelahiran:', error);
toast.error('Terjadi kesalahan saat memperbarui data kelahiran');
}
};
return (
<Box>
<Box mb={10}>
<Button variant="subtle" onClick={() => router.back()}>
<IconArrowBack color={colors["blue-button"]} size={30} />
</Button>
</Box>
<Paper bg={"white"} p={"md"} w={{ base: "100%", md: "50%" }}>
<Stack gap={"xs"}>
<Title order={3}>Edit data kelahiran</Title>
<TextInput
value={formData.nama}
onChange={(e) => setFormData({ ...formData, nama: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Nama</Text>}
placeholder="masukkan nama"
/>
<TextInput
type='date'
value={formData.tanggal}
onChange={(e) => setFormData({ ...formData, tanggal: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Tanggal</Text>}
placeholder="masukkan tanggal"
/>
<TextInput
value={formData.jenisKelamin}
onChange={(e) => setFormData({ ...formData, jenisKelamin: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Jenis Kelamin</Text>}
placeholder="masukkan jenis kelamin"
/>
<TextInput
value={formData.alamat}
onChange={(e) => setFormData({ ...formData, alamat: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Alamat</Text>}
placeholder="masukkan alamat"
/>
<Button onClick={handleSubmit}>Simpan</Button>
</Stack>
</Paper>
</Box>
);
}
export default EditKelahiran;

View File

@@ -0,0 +1,121 @@
'use client'
import { useProxy } from 'valtio/utils';
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 { ModalKonfirmasiHapus } from '@/app/admin/(dashboard)/_com/modalKonfirmasiHapus';
import persentaseKelahiranKematian from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
function DetailKelahiran() {
const state = useProxy(persentaseKelahiranKematian.kelahiran)
const [modalHapus, setModalHapus] = useState(false)
const [selectedId, setSelectedId] = useState<string | null>(null)
const params = useParams()
const router = useRouter()
useShallowEffect(() => {
state.findUnique.load(params?.id as string)
}, [])
const handleHapus = () => {
if (selectedId) {
state.delete.byId(selectedId)
setModalHapus(false)
setSelectedId(null)
router.push("/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran")
}
}
if (!state.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 Data Kelahiran</Text>
{state.findUnique.data ? (
<Paper key={state.findUnique.data.id} bg={colors['BG-trans']} p={'md'}>
<Stack gap={"xs"}>
<Box>
<Text fw={"bold"} fz={"lg"}>Nama</Text>
<Text fz={"lg"}>{state.findUnique.data?.nama}</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Tanggal</Text>
<Text fz={"lg"}>
{new Date(state.findUnique.data?.tanggal).toLocaleDateString('id-ID', {
day: '2-digit',
month: 'long',
year: 'numeric'
})}
</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Jenis Kelamin</Text>
<Text fz={"lg"} >{state.findUnique.data?.jenisKelamin}</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Alamat</Text>
<Text fz={"lg"} >{state.findUnique.data?.alamat}</Text>
</Box>
<Flex gap={"xs"} mt={10}>
<Button
onClick={() => {
if (state.findUnique.data) {
setSelectedId(state.findUnique.data.id);
setModalHapus(true);
}
}}
disabled={state.delete.loading || !state.findUnique.data}
color={"red"}
>
<IconX size={20} />
</Button>
<Button
onClick={() => {
if (state.findUnique.data) {
router.push(`/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran/${state.findUnique.data.id}/edit`);
}
}}
disabled={!state.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 data ini?'
/>
</Box>
);
}
export default DetailKelahiran;

View File

@@ -0,0 +1,83 @@
'use client'
import persentaseKelahiranKematian from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
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 { useProxy } from 'valtio/utils';
function CreateKelahiran() {
const createState = useProxy(persentaseKelahiranKematian.kelahiran)
const router = useRouter();
const resetForm = () => {
createState.create.form = {
nama: "",
tanggal: "",
jenisKelamin: "",
alamat: "",
};
};
const handleSubmit = async () => {
await createState.create.create();
resetForm();
router.push("/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran")
};
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 Kelahiran</Title>
<TextInput
label={<Text fw={"bold"} fz={"sm"}>Nama</Text>}
placeholder='Masukkan nama'
value={createState.create.form.nama}
onChange={(val) => {
createState.create.form.nama = val.target.value;
}}
/>
<TextInput
type='date'
label={<Text fw={"bold"} fz={"sm"}>Tanggal</Text>}
placeholder='Masukkan tanggal'
value={createState.create.form.tanggal}
onChange={(val) => {
createState.create.form.tanggal = val.target.value;
}}
/>
<TextInput
label={<Text fw={"bold"} fz={"sm"}>Jenis Kelamin</Text>}
placeholder='Masukkan jenis kelamin'
value={createState.create.form.jenisKelamin}
onChange={(val) => {
createState.create.form.jenisKelamin = val.target.value;
}}
/>
<TextInput
label={<Text fw={"bold"} fz={"sm"}>Alamat</Text>}
placeholder='Masukkan alamat'
value={createState.create.form.alamat}
onChange={(val) => {
createState.create.form.alamat = val.target.value;
}}
/>
<Group>
<Button onClick={handleSubmit} bg={colors['blue-button']}>Submit</Button>
</Group>
</Stack>
</Paper>
</Box>
);
}
export default CreateKelahiran;

View File

@@ -0,0 +1,118 @@
'use client'
import HeaderSearch from '@/app/admin/(dashboard)/_com/header';
import JudulList from '@/app/admin/(dashboard)/_com/judulList';
import persentasekelahiran from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, Center, Pagination, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { IconArrowBack, IconEdit, IconSearch } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useProxy } from 'valtio/utils';
function Kelahiran() {
const router = useRouter();
const [search, setSearch] = useState("");
return (
<Box>
<Box mb={10}>
<Button variant="subtle" onClick={() => router.back()}>
<IconArrowBack color={colors["blue-button"]} size={30} />
</Button>
</Box>
<HeaderSearch
title='Data Kelahiran'
placeholder='pencarian'
searchIcon={<IconSearch size={20} />}
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
/>
<ListKelahiran search={search} />
</Box>
);
}
function ListKelahiran({ search }: { search: string }) {
const statePersentase = useProxy(persentasekelahiran.kelahiran);
const router = useRouter();
const {
data,
page,
totalPages,
loading,
load
} = statePersentase.findMany;
useShallowEffect(() => {
load(page, 10, search)
}, [search])
const filteredData = data || []
if (loading || !data) {
return (
<Stack>
<Skeleton h={500} />
</Stack>
)
}
return (
<Box>
<Stack gap={"xs"}>
{/* Form Input */}
<Paper bg={colors['white-1']} p={'md'}>
<JudulList
title='List Data Kelahiran'
href='/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran/create'
/>
<Table striped withTableBorder withRowBorders>
<TableThead>
<TableTr>
<TableTh>Nama</TableTh>
<TableTh>Tanggal</TableTh>
<TableTh>Jenis Kelamin</TableTh>
<TableTh>Alamat</TableTh>
<TableTh>Detail</TableTh>
</TableTr>
</TableThead>
<TableTbody>
{filteredData.map((item) => (
<TableTr key={item.id}>
<TableTd>{item.nama}</TableTd>
<TableTd>
{new Date(item.tanggal).toLocaleDateString('id-ID', {
day: '2-digit',
month: 'long',
year: 'numeric'
})}
</TableTd>
<TableTd>{item.jenisKelamin}</TableTd>
<TableTd>{item.alamat}</TableTd>
<TableTd>
<Button color='green' onClick={() => router.push(`/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran/${item.id}`)}>
<IconEdit size={20} />
</Button>
</TableTd>
</TableTr>
))}
</TableTbody>
</Table>
</Paper>
</Stack>
<Center>
<Pagination
value={page}
onChange={(newPage) => load(newPage)} // ini penting!
total={totalPages}
mt="md"
mb="md"
/>
</Center>
</Box>
);
}
export default Kelahiran;

View File

@@ -0,0 +1,121 @@
/* eslint-disable react-hooks/exhaustive-deps */
'use client'
import EditEditor from '@/app/admin/(dashboard)/_com/editEditor';
import persentaseKelahiranKematian from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, 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 EditKematian() {
const editState = useProxy(persentaseKelahiranKematian.kematian)
const router = useRouter();
const params = useParams();
const [formData, setFormData] = useState({
nama: editState.edit.form.nama || '',
tanggal: editState.edit.form.tanggal || '',
jenisKelamin: editState.edit.form.jenisKelamin || '',
alamat: editState.edit.form.alamat || '',
penyebab: editState.edit.form.penyebab || '',
});
useEffect(() => {
const loadKelahiran = async () => {
const id = params?.id as string;
if (!id) return;
try {
const data = await editState.edit.load(id); // akses langsung, bukan dari proxy
if (data) {
setFormData({
nama: data.nama || '',
tanggal: data.tanggal || '',
jenisKelamin: data.jenisKelamin || '',
alamat: data.alamat || '',
penyebab: data.penyebab || '',
});
}
} catch (error) {
console.error("Error loading data kelahiran:", error);
toast.error("Gagal memuat data data kelahiran");
}
};
loadKelahiran();
}, [params?.id]);
const handleSubmit = async () => {
try {
editState.edit.form = {
...editState.edit.form,
nama: formData.nama,
tanggal: formData.tanggal,
jenisKelamin: formData.jenisKelamin,
alamat: formData.alamat,
penyebab: formData.penyebab,
};
await editState.edit.update();
toast.success('data kelahiran berhasil diperbarui!');
router.push('/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran');
} catch (error) {
console.error('Error updating data kelahiran:', error);
toast.error('Terjadi kesalahan saat memperbarui data kelahiran');
}
};
return (
<Box>
<Box mb={10}>
<Button variant="subtle" onClick={() => router.back()}>
<IconArrowBack color={colors["blue-button"]} size={30} />
</Button>
</Box>
<Paper bg={"white"} p={"md"} w={{ base: "100%", md: "50%" }}>
<Stack gap={"xs"}>
<Title order={3}>Edit data kelahiran</Title>
<TextInput
value={formData.nama}
onChange={(e) => setFormData({ ...formData, nama: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Nama</Text>}
placeholder="masukkan nama"
/>
<TextInput
type='date'
value={formData.tanggal}
onChange={(e) => setFormData({ ...formData, tanggal: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Tanggal</Text>}
placeholder="masukkan tanggal"
/>
<TextInput
value={formData.jenisKelamin}
onChange={(e) => setFormData({ ...formData, jenisKelamin: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Jenis Kelamin</Text>}
placeholder="masukkan jenis kelamin"
/>
<TextInput
value={formData.alamat}
onChange={(e) => setFormData({ ...formData, alamat: e.target.value })}
label={<Text fz={"sm"} fw={"bold"}>Alamat</Text>}
placeholder="masukkan alamat"
/>
<Box>
<Text fz={"sm"} fw={"bold"}>Penyebab</Text>
<EditEditor
value={formData.penyebab}
onChange={(htmlContent) => {
setFormData((prev) => ({ ...prev, penyebab: htmlContent }));
editState.edit.form.penyebab = htmlContent;
}}
/>
</Box>
<Button onClick={handleSubmit}>Simpan</Button>
</Stack>
</Paper>
</Box>
);
}
export default EditKematian;

View File

@@ -0,0 +1,126 @@
'use client'
import { useProxy } from 'valtio/utils';
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 { ModalKonfirmasiHapus } from '@/app/admin/(dashboard)/_com/modalKonfirmasiHapus';
import persentaseKelahiranKematian from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
function DetailKematian() {
const state = useProxy(persentaseKelahiranKematian.kematian)
const [modalHapus, setModalHapus] = useState(false)
const [selectedId, setSelectedId] = useState<string | null>(null)
const params = useParams()
const router = useRouter()
useShallowEffect(() => {
state.findUnique.load(params?.id as string)
}, [])
const handleHapus = () => {
if (selectedId) {
state.delete.byId(selectedId)
setModalHapus(false)
setSelectedId(null)
router.push("/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran")
}
}
if (!state.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 Data Kematian</Text>
{state.findUnique.data ? (
<Paper key={state.findUnique.data.id} bg={colors['BG-trans']} p={'md'}>
<Stack gap={"xs"}>
<Box>
<Text fw={"bold"} fz={"lg"}>Nama</Text>
<Text fz={"lg"}>{state.findUnique.data?.nama}</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Tanggal</Text>
<Text fz={"lg"}>
{state.findUnique.data?.tanggal instanceof Date
? state.findUnique.data.tanggal.toLocaleDateString('id-ID', {
day: '2-digit',
month: 'long',
year: 'numeric'
})
: state.findUnique.data?.tanggal}
</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Jenis Kelamin</Text>
<Text fz={"lg"} >{state.findUnique.data?.jenisKelamin}</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Alamat</Text>
<Text fz={"lg"} >{state.findUnique.data?.alamat}</Text>
</Box>
<Box>
<Text fw={"bold"} fz={"lg"}>Penyebab</Text>
<Text fz={"lg"} dangerouslySetInnerHTML={{ __html: state.findUnique.data?.penyebab || '' }} />
</Box>
<Flex gap={"xs"} mt={10}>
<Button
onClick={() => {
if (state.findUnique.data) {
setSelectedId(state.findUnique.data.id);
setModalHapus(true);
}
}}
disabled={state.delete.loading || !state.findUnique.data}
color={"red"}
>
<IconX size={20} />
</Button>
<Button
onClick={() => {
if (state.findUnique.data) {
router.push(`/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran/${state.findUnique.data.id}/edit`);
}
}}
disabled={!state.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 data ini?'
/>
</Box>
);
}
export default DetailKematian;

View File

@@ -0,0 +1,94 @@
'use client'
import CreateEditor from '@/app/admin/(dashboard)/_com/createEditor';
import persentaseKelahiranKematian from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
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 { useProxy } from 'valtio/utils';
function CreateKematian() {
const createState = useProxy(persentaseKelahiranKematian.kematian)
const router = useRouter();
const resetForm = () => {
createState.create.form = {
nama: "",
tanggal: "",
jenisKelamin: "",
alamat: "",
penyebab: "",
};
};
const handleSubmit = async () => {
await createState.create.create();
resetForm();
router.push("/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kematian")
};
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 Kematian</Title>
<TextInput
label={<Text fw={"bold"} fz={"sm"}>Nama</Text>}
placeholder='Masukkan nama'
value={createState.create.form.nama}
onChange={(val) => {
createState.create.form.nama = val.target.value;
}}
/>
<TextInput
type='date'
label={<Text fw={"bold"} fz={"sm"}>Tanggal</Text>}
placeholder='Masukkan tanggal'
value={createState.create.form.tanggal}
onChange={(val) => {
createState.create.form.tanggal = val.target.value;
}}
/>
<TextInput
label={<Text fw={"bold"} fz={"sm"}>Jenis Kelamin</Text>}
placeholder='Masukkan jenis kelamin'
value={createState.create.form.jenisKelamin}
onChange={(val) => {
createState.create.form.jenisKelamin = val.target.value;
}}
/>
<TextInput
label={<Text fw={"bold"} fz={"sm"}>Alamat</Text>}
placeholder='Masukkan alamat'
value={createState.create.form.alamat}
onChange={(val) => {
createState.create.form.alamat = val.target.value;
}}
/>
<Box>
<Text fw={"bold"} fz={"sm"}>Penyebab</Text>
<CreateEditor
value={createState.create.form.penyebab}
onChange={(htmlContent) => {
createState.create.form.penyebab = htmlContent;
}}
/>
</Box>
<Group>
<Button onClick={handleSubmit} bg={colors['blue-button']}>Submit</Button>
</Group>
</Stack>
</Paper>
</Box>
);
}
export default CreateKematian;

View File

@@ -0,0 +1,118 @@
'use client'
import HeaderSearch from '@/app/admin/(dashboard)/_com/header';
import JudulList from '@/app/admin/(dashboard)/_com/judulList';
import persentasekelahiran from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, Center, Pagination, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { IconArrowBack, IconEdit, IconSearch } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useProxy } from 'valtio/utils';
function Kematian() {
const [search, setSearch] = useState("");
const router = useRouter();
return (
<Box>
<Box mb={10}>
<Button variant="subtle" onClick={() => router.back()}>
<IconArrowBack color={colors["blue-button"]} size={30} />
</Button>
</Box>
<HeaderSearch
title='Data Kematian'
placeholder='pencarian'
searchIcon={<IconSearch size={20} />}
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
/>
<ListKematian search={search} />
</Box >
);
}
function ListKematian({ search }: { search: string }) {
const statePersentase = useProxy(persentasekelahiran.kematian);
const router = useRouter();
const {
data,
page,
totalPages,
loading,
load
} = statePersentase.findMany;
useShallowEffect(() => {
load(page, 10, search)
}, [search])
const filteredData = data || []
if (loading || !data) {
return (
<Stack>
<Skeleton h={500} />
</Stack>
)
}
return (
<Box>
<Stack gap={"xs"}>
{/* Form Input */}
<Paper bg={colors['white-1']} p={'md'}>
<JudulList
title='List Data Kematian'
href='/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kematian/create'
/>
<Table striped withTableBorder withRowBorders>
<TableThead>
<TableTr>
<TableTh>Nama</TableTh>
<TableTh>Tanggal</TableTh>
<TableTh>Jenis Kelamin</TableTh>
<TableTh>Alamat</TableTh>
<TableTh>Detail</TableTh>
</TableTr>
</TableThead>
<TableTbody>
{filteredData.map((item) => (
<TableTr key={item.id}>
<TableTd>{item.nama}</TableTd>
<TableTd>
{new Date(item.tanggal).toLocaleDateString('id-ID', {
day: '2-digit',
month: 'long',
year: 'numeric'
})}
</TableTd>
<TableTd>{item.jenisKelamin}</TableTd>
<TableTd>{item.alamat}</TableTd>
<TableTd>
<Button color='green' onClick={() => router.push(`/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran/${item.id}`)}>
<IconEdit size={20} />
</Button>
</TableTd>
</TableTr>
))}
</TableTbody>
</Table>
</Paper>
</Stack>
<Center>
<Pagination
value={page}
onChange={(newPage) => load(newPage)} // ini penting!
total={totalPages}
mt="md"
mb="md"
/>
</Center>
</Box>
);
}
export default Kematian;

View File

@@ -1,183 +1,229 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client'
import persentasekelahiran from '@/app/admin/(dashboard)/_state/kesehatan/data_kesehatan_warga/persentaseKelahiran';
import colors from '@/con/colors';
import { Box, Button, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Text, Title } from '@mantine/core';
import { ActionIcon, Box, Button, Center, Flex, Paper, Skeleton, Stack, Table, Text, Title } from '@mantine/core';
import { useMediaQuery, useShallowEffect } from '@mantine/hooks';
import { IconEdit, IconSearch, IconTrash } from '@tabler/icons-react';
import { IconBabyCarriage, IconGrave2 } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { Bar, BarChart, Legend, Tooltip, XAxis, YAxis } from 'recharts';
import { Bar, BarChart, Legend, Tooltip, TooltipProps, XAxis, YAxis } from 'recharts';
import { useProxy } from 'valtio/utils';
import JudulListTab from '../../../_com/judulListTab';
import { ModalKonfirmasiHapus } from '../../../_com/modalKonfirmasiHapus';
import HeaderSearch from '../../../_com/header';
type TooltipPayload = {
name: string;
value: number;
payload: any;
color: string;
dataKey: string;
};
type CustomTooltipProps = TooltipProps<number, string> & {
active?: boolean;
payload?: TooltipPayload[];
label?: string;
};
function PersentaseDataKelahiranKematian() {
const [search, setSearch] = useState("");
return (
<Box>
<HeaderSearch
title='Persentase Data Kelahiran & Kematian'
placeholder='pencarian'
searchIcon={<IconSearch size={20} />}
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
/>
<ListPersentaseDataKelahiranKematian search={search} />
</Box>
<Stack gap={"xs"}>
<GrafikPersentaseKelahiranKematian />
</Stack>
);
}
function ListPersentaseDataKelahiranKematian({ search }: { search: string }) {
type PDKMGrafik = {
id: string;
tahun: string;
kematianKasar: number;
kematianBayi: number;
kelahiranKasar: number;
}
const statePersentase = useProxy(persentasekelahiran);
const [chartData, setChartData] = useState<PDKMGrafik[]>([]);
const [mounted, setMounted] = useState(false); // untuk memastikan DOM sudah ready
const isTablet = useMediaQuery('(max-width: 1024px)')
const isMobile = useMediaQuery('(max-width: 768px)')
const [modalHapus, setModalHapus] = useState(false)
const [selectedId, setSelectedId] = useState<string | null>(null)
function GrafikPersentaseKelahiranKematian() {
const router = useRouter();
type DataTahunan = {
tahun: string;
totalKelahiran: number;
totalKematian: number;
data: Array<{
id: string;
bulan: string;
kelahiran: number;
kematian: number;
}>;
};
const handleDelete = () => {
if (selectedId) {
statePersentase.delete.byId(selectedId)
setModalHapus(false)
setSelectedId(null)
// Count occurrences per year
const countByYear = (data: any[], dateField: string) => {
const counts: Record<string, number> = {};
data?.forEach(item => {
const year = new Date(item[dateField]).getFullYear().toString();
counts[year] = (counts[year] || 0) + 1;
});
return counts;
};
statePersentase.findMany.load()
const statePersentase = useProxy(persentasekelahiran);
const [chartData, setChartData] = useState<DataTahunan[]>([]);
const isTablet = useMediaQuery('(max-width: 1024px)');
const isMobile = useMediaQuery('(max-width: 768px)');
const [selectedYear, setSelectedYear] = useState<string | null>(null);
// Format number to Indonesian locale
const formatNumber = (num: number) => {
return new Intl.NumberFormat('id-ID').format(num);
};
// Format tooltip
const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
if (active && payload && payload.length) {
return (
<Paper p="md" shadow="md" withBorder>
<Text size="sm" fw={500} mb={5}>Tahun {label}</Text>
<Text size="sm" c="blue">Kelahiran: {formatNumber(payload[0].value)}</Text>
<Text size="sm" c="red">Kematian: {formatNumber(payload[1].value)}</Text>
</Paper>
);
}
}
return null;
};
useShallowEffect(() => {
setMounted(true)
statePersentase.findMany.load()
}, [])
statePersentase.kelahiran.findMany.load(1, 1000); // Load all kelahiran data
statePersentase.kematian.findMany.load(1, 1000); // Load all kematian data
}, []);
useEffect(() => {
setMounted(true);
if (statePersentase.findMany.data) {
setChartData(statePersentase.findMany.data.map((item) => ({
id: item.id,
tahun: item.tahun,
kematianKasar: Number(item.kematianKasar),
kematianBayi: Number(item.kematianBayi),
kelahiranKasar: Number(item.kelahiranKasar),
})));
if (statePersentase.kelahiran.findMany.data && statePersentase.kematian.findMany.data) {
// Count kelahiran and kematian by year
const kelahiranByYear = countByYear(statePersentase.kelahiran.findMany.data, 'tanggal');
const kematianByYear = countByYear(statePersentase.kematian.findMany.data, 'tanggal');
// Get all unique years
const allYears = new Set([
...Object.keys(kelahiranByYear),
...Object.keys(kematianByYear)
]);
// Create data structure for the chart
const dataByYear = Array.from(allYears).reduce<Record<string, DataTahunan>>((acc, year) => {
acc[year] = {
tahun: year,
totalKelahiran: kelahiranByYear[year] || 0,
totalKematian: kematianByYear[year] || 0,
data: []
};
return acc;
}, {});
const sortedData = Object.values(dataByYear).sort((a, b) =>
parseInt(a.tahun) - parseInt(b.tahun)
);
setChartData(sortedData);
setSelectedYear(sortedData[0]?.tahun || '');
}
}, [statePersentase.findMany.data]);
}, [
statePersentase.kelahiran.findMany.data,
statePersentase.kematian.findMany.data,
]);
const filteredData = (statePersentase.findMany.data || []).filter(item => {
const keyword = search.toLowerCase();
return (
item.tahun.toLowerCase().includes(keyword) ||
item.kematianKasar.toString().toLowerCase().includes(keyword) ||
item.kematianBayi.toString().toLowerCase().includes(keyword) ||
item.kelahiranKasar.toString().toLowerCase().includes(keyword)
);
});
if (!statePersentase.findMany.data) {
if (!statePersentase.kelahiran.findMany.data || !statePersentase.kematian.findMany.data) {
return (
<Stack>
<Skeleton h={500} />
</Stack>
)
);
}
const selectedYearData = chartData.find(d => d.tahun === selectedYear);
return (
<Box>
<Paper bg={colors['white-1']} p="md">
<Stack gap={"xs"}>
{/* Form Input */}
<Paper bg={colors['white-1']} p={'md'}>
<JudulListTab
title='List Persentase Data Kelahiran & Kematian'
href='/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/create'
placeholder='pencarian'
searchIcon={<IconSearch size={16} />}
/>
<Table striped withTableBorder withRowBorders>
<TableThead>
<TableTr>
<TableTh>Tahun</TableTh>
<TableTh>Kematian Kasar</TableTh>
<TableTh>Kematian Bayi</TableTh>
<TableTh>kelahiran Kasar</TableTh>
<TableTh>Edit</TableTh>
<TableTh>Delete</TableTh>
</TableTr>
</TableThead>
<TableTbody>
{filteredData.map((item) => (
<TableTr key={item.id}>
<TableTd>{item.tahun}</TableTd>
<TableTd>{item.kematianKasar}</TableTd>
<TableTd>{item.kematianBayi}</TableTd>
<TableTd>{item.kelahiranKasar}</TableTd>
<TableTd>
<Button color='green' onClick={() => router.push(`/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/${item.id}`)}>
<IconEdit size={20} />
</Button>
</TableTd>
<TableTd>
<Button
color='red'
disabled={statePersentase.delete.loading}
onClick={() => {
setSelectedId(item.id)
setModalHapus(true)
}}>
<IconTrash size={20} />
</Button>
</TableTd>
</TableTr>
))}
</TableTbody>
</Table>
</Paper>
{/* Chart */}
{!mounted && !chartData ? (
<Box style={{ width: '100%', minWidth: 300, height: 400, minHeight: 300 }}>
<Paper bg={colors['white-1']} p={'md'}>
<Title pb={10} order={3}>Data Kelahiran & Kematian</Title>
<Text c='dimmed'>Belum ada data untuk ditampilkan dalam grafik</Text>
</Paper>
</Box>
) : (
<Box style={{ width: '100%', minWidth: 300, height: 400, minHeight: 300 }}>
<Paper bg={colors['white-1']} p={'md'}>
<Title pb={10} order={4}>Data Kelahiran & Kematian</Title>
{mounted && chartData.length > 0 && (
<BarChart width={isMobile ? 450 : isTablet ? 500 : 550} height={350} data={chartData} >
<XAxis dataKey="tahun" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="kematianKasar" fill="#f03e3e" name="Kematian Kasar" />
<Bar dataKey="kematianBayi" fill="#ff922b" name="Kematian Bayi" />
<Bar dataKey="kelahiranKasar" fill="#4dabf7" name="Kelahiran Kasar" />
</BarChart>
)}
</Paper>
</Box>
)}
<Title order={3} mb="md">Statistik Kelahiran & Kematian</Title>
<Box>
<Flex gap={"xs"}>
<Box>
<ActionIcon size={30} color={colors['blue-button']} onClick={() => router.push('/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kelahiran')}>
<IconBabyCarriage size={30} color={colors['white-1']} />
</ActionIcon>
</Box>
<Box>
<ActionIcon size={30} color={colors['blue-button']} onClick={() => router.push('/admin/kesehatan/data-kesehatan-warga/persentase_data_kelahiran_kematian/kematian')} >
<IconGrave2 size={30} color={colors['white-1']} />
</ActionIcon>
</Box>
</Flex>
</Box>
</Stack>
{/* Modal Konfirmasi Hapus */}
<ModalKonfirmasiHapus
opened={modalHapus}
onClose={() => setModalHapus(false)}
onConfirm={handleDelete}
text='Apakah anda yakin ingin menghapus persentase data kelahiran & kematian ini?'
/>
</Box>
{chartData.length === 0 ? (
<Text c="dimmed" ta="center" py="xl">
Belum ada data yang tersedia untuk ditampilkan
</Text>
) : (
<>
{/* Year Selector */}
<Box mb="md">
<Text mb="xs" fw={500}>Pilih Tahun:</Text>
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
{chartData.map(({ tahun }) => (
<Button
key={tahun}
variant={selectedYear === tahun ? 'filled' : 'outline'}
onClick={() => setSelectedYear(tahun)}
size="xs"
>
{tahun}
</Button>
))}
</div>
</Box>
{/* Main Chart */}
<Center>
<Box h={400}>
<BarChart
width={isMobile ? window.innerWidth * 0.9 : isTablet ? 700 : 800}
height={350}
data={chartData}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<XAxis dataKey="tahun" />
<YAxis />
<Tooltip content={<CustomTooltip />} />
<Legend />
<Bar dataKey="totalKelahiran" name="Total Kelahiran" fill="#4dabf7" />
<Bar dataKey="totalKematian" name="Total Kematian" fill="#f03e3e" />
</BarChart>
</Box>
</Center>
{/* Yearly Breakdown */}
{selectedYearData && (
<Box mt="xl">
<Title order={4} mb="md">Rincian Tahun {selectedYear}</Title>
<Table striped withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>Bulan</Table.Th>
<Table.Th ta="right">Kelahiran</Table.Th>
<Table.Th ta="right">Kematian</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{selectedYearData.data.map((item) => (
<Table.Tr key={item.id}>
<Table.Td>{item.bulan}</Table.Td>
<Table.Td ta="right">{formatNumber(item.kelahiran)}</Table.Td>
<Table.Td ta="right">{formatNumber(item.kematian)}</Table.Td>
</Table.Tr>
))}
<Table.Tr style={{ fontWeight: 'bold' }}>
<Table.Td>Total</Table.Td>
<Table.Td ta="right">{formatNumber(selectedYearData.totalKelahiran)}</Table.Td>
<Table.Td ta="right">{formatNumber(selectedYearData.totalKematian)}</Table.Td>
</Table.Tr>
</Table.Tbody>
</Table>
</Box>
)}
</>
)}
</Paper>
);
}

View File

@@ -1,32 +1,22 @@
import prisma from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { Context } from "elysia";
type FormCreate = Prisma.DataKematian_KelahiranGetPayload<{
select: {
tahun: true;
kematianKasar: true;
kematianBayi: true;
kelahiranKasar: true;
};
}>;
type FormCreate = {
kematianId: string;
kelahiranId: string;
};
export default async function persentaseKelahiranKematianCreate(context: Context) {
const body = context.body as FormCreate
const created = await prisma.dataKematian_Kelahiran.create({
data: {
tahun: body.tahun,
kematianKasar: body.kematianKasar,
kematianBayi: body.kematianBayi,
kelahiranKasar: body.kelahiranKasar,
kematianId: body.kematianId,
kelahiranId: body.kelahiranId,
},
select: {
id: true,
tahun: true,
kematianKasar: true,
kematianBayi: true,
kelahiranKasar: true,
kematianId: true,
kelahiranId: true,
}
})
return{

View File

@@ -1,9 +1,58 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// /api/berita/findManyPaginated.ts
import prisma from "@/lib/prisma";
import { Context } from "elysia";
async function persentaseKelahiranKematianFindMany(context: Context) {
// Ambil parameter dari query
const page = Number(context.query.page) || 1;
const limit = Number(context.query.limit) || 10;
const search = (context.query.search as string) || '';
const skip = (page - 1) * limit;
// Buat where clause
const where: any = { isActive: true };
// Tambahkan pencarian (jika ada)
if (search) {
where.OR = [
{ kematian: { nama: { contains: search, mode: 'insensitive' } } },
{ kelahiran: { nama: { contains: search, mode: 'insensitive' } } },
];
}
try {
// Ambil data dan total count secara paralel
const [data, total] = await Promise.all([
prisma.dataKematian_Kelahiran.findMany({
where,
include: {
kematian: true,
kelahiran: true,
},
skip,
take: limit,
orderBy: { createdAt: 'desc' },
}),
prisma.dataKematian_Kelahiran.count({ where }),
]);
export default async function persentaseKelahiranKematianFindMany() {
const res = await prisma.dataKematian_Kelahiran.findMany();
return {
data: res
}
success: true,
message: "Berhasil ambil data persentase kelahiran kematian dengan pagination",
data,
page,
limit,
total,
totalPages: Math.ceil(total / limit),
};
} catch (e) {
console.error("Error di findMany paginated:", e);
return {
success: false,
message: "Gagal mengambil data persentase kelahiran kematian",
};
}
}
export default persentaseKelahiranKematianFindMany;

View File

@@ -22,6 +22,10 @@ export default async function persentaseKelahiranKematianFindUnique(request: Req
const data = await prisma.dataKematian_Kelahiran.findUnique({
where: { id },
include: {
kematian: true,
kelahiran: true,
},
});
if (!data) {

View File

@@ -16,10 +16,8 @@ const PersentaseKelahiranKematian = new Elysia({
.get("/find-many", persentaseKelahiranKematianFindMany)
.post("/create", persentaseKelahiranKematianCreate, {
body: t.Object({
tahun: t.String(),
kematianKasar: t.String(),
kematianBayi: t.String(),
kelahiranKasar: t.String(),
kematianId: t.String(),
kelahiranId: t.String(),
}),
})
.put("/:id", persentaseKelahiranKematianUpdate, {
@@ -27,10 +25,8 @@ const PersentaseKelahiranKematian = new Elysia({
id: t.String(),
}),
body: t.Object({
tahun: t.String(),
kematianKasar: t.String(),
kematianBayi: t.String(),
kelahiranKasar: t.String(),
kematianId: t.String(),
kelahiranId: t.String(),
}),
})
.delete("/del/:id", persentaseKelahiranKematianDelete, {

View File

@@ -0,0 +1,34 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
type FormCreate = {
nama: string;
tanggal: string;
jenisKelamin: string;
alamat: string;
}
export default async function kelahiranCreate(context: Context) {
const body = context.body as FormCreate;
const created = await prisma.kelahiran.create({
data: {
nama: body.nama,
tanggal: new Date(body.tanggal),
jenisKelamin: body.jenisKelamin,
alamat: body.alamat,
},
select: {
nama: true,
tanggal: true,
jenisKelamin: true,
alamat: true,
},
});
return {
success: true,
message: "Success create kelahiran",
data: created,
};
}

View File

@@ -0,0 +1,36 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
export default async function kelahiranDelete(context: Context) {
const id = context.params?.id;
if (!id) {
return {
success: false,
message: "ID tidak ditemukan",
}
}
const existing = await prisma.kelahiran.findUnique({
where: {
id: id,
},
})
if (!existing) {
return {
success: false,
message: "Data tidak ditemukan",
}
}
const deleted = await prisma.kelahiran.delete({
where: { id },
})
return {
success: true,
message: "Data berhasil dihapus",
data: deleted,
}
}

View File

@@ -0,0 +1,54 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// /api/berita/findManyPaginated.ts
import prisma from "@/lib/prisma";
import { Context } from "elysia";
async function kelahiranFindMany(context: Context) {
// Ambil parameter dari query
const page = Number(context.query.page) || 1;
const limit = Number(context.query.limit) || 10;
const search = (context.query.search as string) || '';
const skip = (page - 1) * limit;
// Buat where clause
const where: any = { isActive: true };
// Tambahkan pencarian (jika ada)
if (search) {
where.OR = [
{ nama: { contains: search, mode: 'insensitive' } },
{ alamat: { contains: search, mode: 'insensitive' } },
];
}
try {
// Ambil data dan total count secara paralel
const [data, total] = await Promise.all([
prisma.kelahiran.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
}),
prisma.kelahiran.count({ where }),
]);
return {
success: true,
message: "Berhasil ambil data kelahiran dengan pagination",
data,
page,
limit,
total,
totalPages: Math.ceil(total / limit),
};
} catch (e) {
console.error("Error di findMany paginated:", e);
return {
success: false,
message: "Gagal mengambil data kelahiran",
};
}
}
export default kelahiranFindMany;

View File

@@ -0,0 +1,46 @@
import prisma from "@/lib/prisma";
export default async function kelahiranFindUnique(request: Request) {
const url = new URL(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.kelahiran.findUnique({
where: { id },
});
if (!data) {
return {
success: false,
message: "Data not found",
}
}
return {
success: true,
message: "Success get data kelahiran",
data,
}
} catch (error) {
console.error("Find by ID error:", error);
return {
success: false,
message: "Gagal mengambil data: " + (error instanceof Error ? error.message : 'Unknown error'),
}
}
}

View File

@@ -0,0 +1,39 @@
import Elysia, { t } from "elysia";
import kelahiranCreate from "./create";
import kelahiranDelete from "./del";
import kelahiranFindMany from "./findMany";
import kelahiranFindUnique from "./findUnique";
import kelahiranUpdate from "./updt";
const Kelahiran = new Elysia({
prefix: "/kelahiran",
tags: ["Kesehatan / Data Kesehatan Warga / Persentase Kelahiran Kematian / Kelahiran"],
})
.post("/create", kelahiranCreate, {
body: t.Object({
nama: t.String(),
tanggal: t.String(),
jenisKelamin: t.String(),
alamat: t.String(),
}),
})
.get("/findMany", kelahiranFindMany)
.get("/:id", async (context) => {
const response = await kelahiranFindUnique(
new Request(context.request)
);
return response;
})
.put("/:id", kelahiranUpdate, {
body: t.Object({
nama: t.String(),
tanggal: t.String(),
jenisKelamin: t.String(),
alamat: t.String(),
}),
})
.delete("/del/:id", kelahiranDelete);
export default Kelahiran;

View File

@@ -0,0 +1,34 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
type FormUpdate = {
nama: string;
tanggal: string;
jenisKelamin: string;
alamat: string;
}
export default async function kelahiranUpdate(context: Context) {
const body = (await context.body) as FormUpdate;
const id = context.params.id as string;
try {
const result = await prisma.kelahiran.update({
where: { id },
data: {
nama: body.nama,
tanggal: new Date(body.tanggal),
jenisKelamin: body.jenisKelamin,
alamat: body.alamat,
},
});
return {
success: true,
message: "Berhasil mengupdate data kelahiran",
data: result,
};
} catch (error) {
console.error("Error updating data kelahiran:", error);
throw new Error("Gagal mengupdate data kelahiran: " + (error as Error).message);
}
}

View File

@@ -0,0 +1,36 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
type FormCreate = {
nama: string;
tanggal: string;
jenisKelamin: string;
alamat: string;
penyebab: string;
};
export default async function kematianCreate(context: Context) {
const body = context.body as FormCreate;
const created = await prisma.kematian.create({
data: {
nama: body.nama,
tanggal: new Date(body.tanggal),
jenisKelamin: body.jenisKelamin,
alamat: body.alamat,
penyebab: body.penyebab,
},
select: {
nama: true,
tanggal: true,
jenisKelamin: true,
alamat: true,
penyebab: true,
},
});
return {
success: true,
message: "Success create kematian",
data: created,
};
}

View File

@@ -0,0 +1,36 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
export default async function kematianDelete(context: Context) {
const id = context.params?.id;
if (!id) {
return {
success: false,
message: "ID tidak ditemukan",
}
}
const existing = await prisma.kematian.findUnique({
where: {
id: id,
},
})
if (!existing) {
return {
success: false,
message: "Data tidak ditemukan",
}
}
const deleted = await prisma.kematian.delete({
where: { id },
})
return {
success: true,
message: "Data berhasil dihapus",
data: deleted,
}
}

View File

@@ -0,0 +1,54 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// /api/berita/findManyPaginated.ts
import prisma from "@/lib/prisma";
import { Context } from "elysia";
async function kematianFindMany(context: Context) {
// Ambil parameter dari query
const page = Number(context.query.page) || 1;
const limit = Number(context.query.limit) || 10;
const search = (context.query.search as string) || '';
const skip = (page - 1) * limit;
// Buat where clause
const where: any = { isActive: true };
// Tambahkan pencarian (jika ada)
if (search) {
where.OR = [
{ nama: { contains: search, mode: 'insensitive' } },
{ alamat: { contains: search, mode: 'insensitive' } },
];
}
try {
// Ambil data dan total count secara paralel
const [data, total] = await Promise.all([
prisma.kematian.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
}),
prisma.kematian.count({ where }),
]);
return {
success: true,
message: "Berhasil ambil data kematian dengan pagination",
data,
page,
limit,
total,
totalPages: Math.ceil(total / limit),
};
} catch (e) {
console.error("Error di findMany paginated:", e);
return {
success: false,
message: "Gagal mengambil data kematian",
};
}
}
export default kematianFindMany;

View File

@@ -0,0 +1,46 @@
import prisma from "@/lib/prisma";
export default async function kematianFindUnique(request: Request) {
const url = new URL(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.kematian.findUnique({
where: { id },
});
if (!data) {
return {
success: false,
message: "Data not found",
}
}
return {
success: true,
message: "Success get data kematian",
data,
}
} catch (error) {
console.error("Find by ID error:", error);
return {
success: false,
message: "Gagal mengambil data: " + (error instanceof Error ? error.message : 'Unknown error'),
}
}
}

View File

@@ -0,0 +1,41 @@
import Elysia, { t } from "elysia";
import kematianCreate from "./create";
import kematianDelete from "./del";
import kematianFindMany from "./findMany";
import kematianFindUnique from "./findUnique";
import kematianUpdate from "./updt";
const Kematian = new Elysia({
prefix: "/kematian",
tags: ["Kesehatan / Data Kesehatan Warga / Persentase Kelahiran Kematian / Kematian"],
})
.post("/create", kematianCreate, {
body: t.Object({
nama: t.String(),
tanggal: t.String(),
jenisKelamin: t.String(),
alamat: t.String(),
penyebab: t.String(),
}),
})
.get("/findMany", kematianFindMany)
.get("/:id", async (context) => {
const response = await kematianFindUnique(
new Request(context.request)
);
return response;
})
.put("/:id", kematianUpdate, {
body: t.Object({
nama: t.String(),
tanggal: t.String(),
jenisKelamin: t.String(),
alamat: t.String(),
penyebab: t.String(),
}),
})
.delete("/del/:id", kematianDelete);
export default Kematian;

View File

@@ -0,0 +1,36 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
type FormUpdate = {
nama: string;
tanggal: string;
jenisKelamin: string;
alamat: string;
penyebab: string;
}
export default async function kematianUpdate(context: Context) {
const body = (await context.body) as FormUpdate;
const id = context.params.id as string;
try {
const result = await prisma.kematian.update({
where: { id },
data: {
nama: body.nama,
tanggal: new Date(body.tanggal),
jenisKelamin: body.jenisKelamin,
alamat: body.alamat,
penyebab: body.penyebab,
},
});
return {
success: true,
message: "Berhasil mengupdate data kematian",
data: result,
};
} catch (error) {
console.error("Error updating data kematian:", error);
throw new Error("Gagal mengupdate data kematian: " + (error as Error).message);
}
}

View File

@@ -11,11 +11,9 @@ export default async function persentaseKelahiranKematianUpdate(context: Context
}
}
const {tahun, kematianKasar, kematianBayi, kelahiranKasar} = context.body as {
tahun: string;
kematianKasar: string;
kematianBayi: string;
kelahiranKasar: string;
const {kematianId, kelahiranId} = context.body as {
kematianId: string;
kelahiranId: string;
}
const existing = await prisma.dataKematian_Kelahiran.findUnique({
@@ -34,10 +32,8 @@ export default async function persentaseKelahiranKematianUpdate(context: Context
const updated = await prisma.dataKematian_Kelahiran.update({
where: { id },
data: {
tahun,
kematianKasar,
kematianBayi,
kelahiranKasar,
kematianId,
kelahiranId,
},
})

View File

@@ -16,6 +16,8 @@ import Puskesmas from "./puskesmas";
import FasilitasKesehatan from "./data_kesehatan_warga/fasilitas_kesehatan";
import JadwalKegiatan from "./data_kesehatan_warga/jadwal_kegiatan";
import ArtikelKesehatan from "./data_kesehatan_warga/artikel_kesehatan";
import Kelahiran from "./data_kesehatan_warga/persentase_kelahiran_kematian/kelahiran";
import Kematian from "./data_kesehatan_warga/persentase_kelahiran_kematian/kematian";
const Kesehatan = new Elysia({
@@ -38,5 +40,7 @@ const Kesehatan = new Elysia({
.use(InfoWabahPenyakit)
.use(FasilitasKesehatan)
.use(JadwalKegiatan)
.use(ArtikelKesehatan);
.use(ArtikelKesehatan)
.use(Kelahiran)
.use(Kematian)
export default Kesehatan;

View File

@@ -1,5 +1,5 @@
import profileLandingPageState from "@/app/admin/(dashboard)/_state/landing-page/profile";
import { Center, Image, Paper, SimpleGrid } from "@mantine/core";
import { Center, Image, Paper, SimpleGrid, Text } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { motion } from 'framer-motion';
import { useTransitionRouter } from 'next-view-transitions';
@@ -25,15 +25,21 @@ function ModuleItem({ data }: { data: ProgramInovasiItem }) {
<motion.div
whileHover={{ scale: 1.05 }}
>
<Image src={data.image?.link || ""} alt="icon"
fit="contain"
sizes="100%"
loading="lazy"
{data.image?.link ? (
<Image src={data.image.link} alt="icon"
fit="contain"
sizes="100%"
loading="lazy"
style={{
objectFit: "contain",
objectPosition: "center"
}}
/>
) : (
<Text>
-
</Text>
)}
</motion.div>
</Center>
</Paper>

View File

@@ -23,13 +23,17 @@ function ProfileView({ data }: ProfileViewProps) {
}}
px="xl"
>
{data.image?.link && (
{data.image?.link ? (
<Image
src={data.image.link}
alt={data.name || "Profile image"}
sizes="100%"
fit="contain"
/>
): (
<Text>
-
</Text>
)}
<Box
pos="absolute"

View File

@@ -1,4 +1,4 @@
import { ActionIcon, Flex, Image } from "@mantine/core";
import { ActionIcon, Flex, Image, Text } from "@mantine/core";
import { Prisma } from "@prisma/client";
import { useTransitionRouter } from "next-view-transitions";
@@ -20,7 +20,13 @@ function SosmedView({data} : {data : Prisma.MediaSosialGetPayload<{ include: { i
router.push(item.iconUrl || "");
}}
>
<Image src={item.image?.link || ""} alt="icon" loading="lazy" />
{item.image?.link ? (
<Image src={item.image.link} alt="icon" loading="lazy" />
) : (
<Text>
none
</Text>
)}
</ActionIcon>
);
})}