Nico 20 Nov 25

Dibagian layout admin sudah disesuaikan dengan rolenya : supadmin, admin desa, admin kesehatan, admin pendidikan
Fix API User & Role Admin
This commit is contained in:
2025-11-20 16:42:36 +08:00
parent 78b8aa74cd
commit 0dff8f3254
19 changed files with 835 additions and 209 deletions

View File

@@ -90,27 +90,35 @@ const userState = proxy({
}
},
},
updateActive: {
update: {
loading: false,
async submit(id: string, isActive: boolean) {
async submit(payload: { id: string; isActive?: boolean; roleId?: string }) {
this.loading = true;
try {
const res = await fetch(`/api/user/updt`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, isActive }),
body: JSON.stringify(payload),
});
const data = await res.json();
if (res.status === 200 && data.success) {
toast.success(data.message);
userState.findMany.load(userState.findMany.page, 10, userState.findMany.search);
// refresh list
userState.findMany.load(
userState.findMany.page,
10,
userState.findMany.search
);
} else {
toast.error(data.message || "Gagal update status user");
toast.error(data.message || "Gagal update user");
}
} catch (e) {
console.error(e);
toast.error("Gagal update status user");
toast.error("Gagal update user");
} finally {
this.loading = false;
}
@@ -120,12 +128,10 @@ const userState = proxy({
const templateRole = z.object({
name: z.string().min(1, "Nama harus diisi"),
permissions: z.array(z.string()).min(1, "Permission harus diisi"),
});
const defaultRole = {
name: "",
permissions: [] as string[],
};
const roleState = proxy({
@@ -237,7 +243,7 @@ const roleState = proxy({
toast.warn("ID tidak valid");
return null;
}
try {
const response = await fetch(`/api/role/${id}`, {
method: "GET",
@@ -245,31 +251,25 @@ const roleState = proxy({
"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 = {
// langsung set melalui root state, bukan this
roleState.update.id = data.id;
roleState.update.form = {
name: data.name,
permissions: data.permissions,
};
return data; // Return the loaded data
} else {
throw new Error(result?.message || "Gagal memuat data");
return data;
}
} catch (error) {
console.error("Error loading role:", error);
toast.error(
error instanceof Error ? error.message : "Gagal memuat data"
);
return null;
toast.error("Gagal memuat data");
}
},
},
async update() {
const cek = templateRole.safeParse(roleState.update.form);
if (!cek.success) {
@@ -290,7 +290,6 @@ const roleState = proxy({
},
body: JSON.stringify({
name: this.form.name,
permissions: this.form.permissions,
}),
});

View File

@@ -7,6 +7,7 @@ import { Box, Button, Loader, Paper, PinInput, Stack, Text, Title } from '@manti
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { authStore } from '@/store/authStore';
export default function Validasi() {
const router = useRouter();
@@ -53,10 +54,17 @@ export default function Validasi() {
setLoading(true);
const verifyResult = await apiFetchVerifyOtp({ nomor, otp, kodeId });
if (verifyResult.success) {
if (verifyResult.success && verifyResult.user) {
// ✅ SET USER KE STORE
authStore.setUser({
id: verifyResult.user.id,
name: verifyResult.user.name,
roleId: Number(verifyResult.user.roleId),
});
cleanupStorage();
router.push('/admin/landing-page/profil/program-inovasi');
return; // ✅ HENTIKAN eksekusi di sini
return;
}
// Hanya coba registrasi jika akun tidak ditemukan

View File

@@ -1,7 +1,8 @@
/* eslint-disable react-hooks/exhaustive-deps */
'use client'
import colors from '@/con/colors';
import { Box, Button, Loader, Group, MultiSelect, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
import { Box, Button, Group, Loader, Paper, Stack, Text, TextInput, Title } from '@mantine/core';
import { IconArrowBack } from '@tabler/icons-react';
import { useParams, useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
@@ -9,6 +10,7 @@ import { toast } from 'react-toastify';
import { useProxy } from 'valtio/utils';
import user from '../../../_state/user/user-state';
function EditRole() {
const stateRole = useProxy(user.roleState);
const router = useRouter();
@@ -17,46 +19,37 @@ function EditRole() {
// Controlled local state
const [formData, setFormData] = useState({
name: '',
permissions: [] as string[],
});
const [originalData, setOriginalData] = useState({
name: '',
permissions: [] as string[],
});
const [isSubmitting, setIsSubmitting] = useState(false);
// Load role data
const loadRole = useCallback(async (id: string) => {
try {
const data = await stateRole.update.load(id);
if (data) {
setFormData({
name: data.name || '',
permissions: data.permissions || [],
});
setOriginalData({
name: data.name || '',
permissions: data.permissions || [],
});
}
} catch (error) {
console.error('Error loading role:', error);
toast.error(error instanceof Error ? error.message : 'Gagal mengambil data role');
const data = await stateRole.update.load(id);
if (data) {
setFormData({
name: data.name ?? '',
});
setOriginalData({
name: data.name ?? '',
});
}
}, [stateRole.update]);
}, []);
useEffect(() => {
stateRole.findMany.load(); // Load permissions/options
const id = params?.id as string;
if (id) loadRole(id);
}, [params?.id, loadRole, stateRole.findMany]);
stateRole.findMany.load(); // load permission
if (params?.id) loadRole(params.id as string);
}, [params?.id]);
const handleResetForm = () => {
setFormData({
name: originalData.name,
permissions: originalData.permissions,
});
toast.info("Form dikembalikan ke data awal");
};
@@ -66,10 +59,6 @@ function EditRole() {
toast.error('Nama role tidak boleh kosong');
return;
}
if (!formData.permissions.length) {
toast.error('Pilih minimal satu permission');
return;
}
try {
setIsSubmitting(true);
@@ -77,7 +66,6 @@ function EditRole() {
stateRole.update.form = {
...stateRole.update.form,
name: formData.name,
permissions: formData.permissions,
};
await stateRole.update.update();
toast.success('Role berhasil diperbarui!');
@@ -116,24 +104,7 @@ function EditRole() {
label={<Text fw="bold" fz="sm">Nama Role</Text>}
placeholder="Masukkan nama role"
/>
<MultiSelect
value={formData.permissions}
onChange={(val) => setFormData({ ...formData, permissions: val })}
label={<Text fw="bold" fz="sm">Permission</Text>}
placeholder="Pilih permission"
data={
stateRole.findMany.data?.map((v) => ({
value: v.id,
label: v.name,
})) || []
}
clearable
searchable
required
error={!formData.permissions.length ? 'Pilih minimal satu permission' : undefined}
/>
<Group justify="right">
<Group justify="right">
{/* Tombol Batal */}
<Button
variant="outline"

View File

@@ -5,9 +5,8 @@ import {
Box,
Button,
Group,
MultiSelect,
Paper,
Loader,
Paper,
Stack,
TextInput,
Title
@@ -15,9 +14,9 @@ import {
import { IconArrowBack } 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 user from '../../../_state/user/user-state';
import { toast } from 'react-toastify';
export default function CreateRole() {
@@ -31,8 +30,7 @@ export default function CreateRole() {
const resetForm = () => {
stateRole.create.form = {
name: '',
permissions: [],
name: ''
};
};
@@ -80,28 +78,6 @@ export default function CreateRole() {
required
/>
</Box>
<Box>
<MultiSelect
label="Permission"
placeholder="Pilih permission"
data={
Array.from(
new Set(
stateRole.findMany.data
?.map((item) => item.permissions)
.flat()
)
)
.filter((p): p is string => typeof p === 'string')
.map((p) => ({ label: p, value: p }))
}
value={stateRole.create.form.permissions}
onChange={(value) => (stateRole.create.form.permissions = value)}
required
/>
</Box>
<Group justify="right">
<Button

View File

@@ -1,6 +1,6 @@
'use client'
import colors from '@/con/colors';
import { Box, Button, Center, Group, Pagination, Paper, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Text, Title, Tooltip } from '@mantine/core';
import { Box, Button, Center, Group, Pagination, Paper, Select, Skeleton, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Text, Title, Tooltip } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { IconCheck, IconSearch, IconX } from '@tabler/icons-react';
import { useState } from 'react';
@@ -28,6 +28,7 @@ function User() {
function ListUser({ search }: { search: string }) {
const stateUser = useProxy(user.userState)
const stateRole = useProxy(user.roleState)
const [modalHapus, setModalHapus] = useState(false)
const [selectedId, setSelectedId] = useState<string | null>(null)
@@ -51,6 +52,7 @@ function ListUser({ search }: { search: string }) {
useShallowEffect(() => {
stateRole.findMany.load()
load(page, 10, search)
}, [page, search])
@@ -92,11 +94,31 @@ function ListUser({ search }: { search: string }) {
{item.nomor}
</Text>
</TableTd>
<TableTd style={{ width: '20%', }}>
<Text truncate fz="sm" c="dimmed">
{item.role.name}
</Text>
<TableTd style={{ width: '20%' }}>
<Select
placeholder="Pilih role"
data={stateRole.findMany.data.map((r) => ({
label: r.name,
value: r.id,
}))}
value={item.roleId} // ⬅ role milik user ini
onChange={async (val) => {
if (!val) return;
await stateUser.update.submit({
id: item.id,
roleId: val, // ⬅ kirim roleId
});
// reload data supaya UI up-to-date
stateUser.findMany.load(page, 10, search);
}}
searchable
clearable={false} // role harus ada
nothingFoundMessage="Role tidak ditemukan"
/>
</TableTd>
<TableTd style={{ width: '15%' }}>
<Tooltip
label={item.isActive ? "Nonaktifkan user" : "Aktifkan user"}
@@ -106,8 +128,12 @@ function ListUser({ search }: { search: string }) {
variant="light"
color={item.isActive ? "green" : "red"}
onClick={async () => {
await stateUser.updateActive.submit(item.id, !item.isActive)
stateUser.findMany.load(page, 10, search)
await stateUser.update.submit({
id: item.id,
isActive: !item.isActive, // toggle
});
stateUser.findMany.load(page, 10, search);
}}
>
{item.isActive ? <IconCheck size={20} /> : <IconX size={20} />}