fix dashboard pbg, add soft delete users, fix js create pbg task

This commit is contained in:
arifal
2025-03-19 14:06:10 +07:00
parent e940b8d6c7
commit 5e1c9f3a2e
10 changed files with 237 additions and 297 deletions

View File

@@ -85,4 +85,17 @@ class UsersController extends Controller
return response()->json(['message' => $e->getMessage()],500); return response()->json(['message' => $e->getMessage()],500);
} }
} }
public function destroy($id){
try{
$user = User::findOrFail($id);
DB::beginTransaction();
$user->delete();
DB::commit();
return response()->json(['message' => 'Successfully deleted'], 200);
}catch(\Exception $e){
Log::error('Failed to delete user: '. $e->getMessage());
return response()->json(['message' => 'Failed to delete user'],500);
}
}
} }

View File

@@ -4,6 +4,7 @@ namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail; // use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\HasApiTokens;
@@ -11,7 +12,7 @@ use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable class User extends Authenticatable
{ {
/** @use HasFactory<\Database\Factories\UserFactory> */ /** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable, HasApiTokens; use HasFactory, Notifiable, HasApiTokens, SoftDeletes;
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
@@ -27,6 +28,8 @@ class User extends Authenticatable
'position' 'position'
]; ];
protected $dates = ['deleted_at'];
/** /**
* The attributes that should be hidden for serialization. * The attributes that should be hidden for serialization.
* *
@@ -50,6 +53,12 @@ class User extends Authenticatable
]; ];
} }
public function delete(){
$this->email = $this->email . '_deleted_'. now()->timestamp;
$this->save();
return parent::delete();
}
public function roles(){ public function roles(){
return $this->belongsToMany(Role::class, 'user_role')->withTimestamps(); return $this->belongsToMany(Role::class, 'user_role')->withTimestamps();
} }

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
};

View File

@@ -3,107 +3,99 @@ import GlobalConfig, { addThousandSeparators } from "../global-config.js";
import ApexCharts from "apexcharts"; import ApexCharts from "apexcharts";
import "gridjs/dist/gridjs.umd.js"; import "gridjs/dist/gridjs.umd.js";
import GeneralTable from "../table-generator.js"; import GeneralTable from "../table-generator.js";
import InitDatePicker from "../utils/InitDatePicker.js";
var chart; var chart;
document.addEventListener("DOMContentLoaded", async function () {
await initChart();
const yearPicker = document.getElementById("yearPicker");
async function updateDataByYear(selectedYear) { class DashboardPBG {
// Target PAD Element async init() {
try {
new InitDatePicker(
"#datepicker-dashboard-pbg",
this.handleChangedDate.bind(this)
).init();
// Load initial data
this.updateData("latest");
} catch (error) {
console.error("Error initializing data:", error);
}
}
handleChangedDate(filterDate) {
if (!filterDate) return;
this.updateData(filterDate);
}
async updateData(filterDate) {
let resumeData = await this.getResume(filterDate);
if (!resumeData) return;
let targetPAD = resumeData.target_pad.sum;
const targetPadElement = document.getElementById("target-pad"); const targetPadElement = document.getElementById("target-pad");
if (!targetPadElement) return; targetPadElement.textContent = formatCurrency(targetPAD);
const targetPadValue = await getDataSettings("TARGET_PAD");
targetPadElement.textContent = formatCurrency(targetPadValue);
// Total Potensi Berkas
const totalPotensiBerkas = document.getElementById( const totalPotensiBerkas = document.getElementById(
"total-potensi-berkas" "total-potensi-berkas"
); );
if (!totalPotensiBerkas) return;
const totalPotensiBerkasValue = await getDataTotalPotensi(selectedYear);
totalPotensiBerkas.textContent = formatCurrency( totalPotensiBerkas.textContent = formatCurrency(
totalPotensiBerkasValue.totalData resumeData.total_potensi.sum
); );
// Total Berkas Terverifikasi
const totalBerkasTerverifikasi = document.getElementById( const totalBerkasTerverifikasi = document.getElementById(
"total-berkas-terverifikasi" "total-berkas-terverifikasi"
); );
if (!totalBerkasTerverifikasi) return;
const totalBerkasTerverifikasiValue = await getDataVerification(
selectedYear
);
totalBerkasTerverifikasi.textContent = formatCurrency( totalBerkasTerverifikasi.textContent = formatCurrency(
totalBerkasTerverifikasiValue.totalData resumeData.verified_document.sum
); );
// Total Kekurangan potensi
const totalKekuranganPotensi = document.getElementById( const totalKekuranganPotensi = document.getElementById(
"total-kekurangan-potensi" "total-kekurangan-potensi"
); );
if (!totalKekuranganPotensi) return;
const totalKekuranganPotensiValue =
new Big(targetPadValue) -
new Big(totalPotensiBerkasValue.totalData);
totalKekuranganPotensi.textContent = formatCurrency( totalKekuranganPotensi.textContent = formatCurrency(
totalKekuranganPotensiValue resumeData.kekurangan_potensi.sum
); );
// Total Potensi PBG dari tata ruang
const totalPotensiPBGTataRuang = document.getElementById( const totalPotensiPBGTataRuang = document.getElementById(
"total-potensi-pbd-tata-ruang" "total-potensi-pbd-tata-ruang"
); );
if (!totalPotensiPBGTataRuang) return; totalPotensiPBGTataRuang.textContent = "Rp.-";
const totalPotensiPBGTataRuangValue = await getDataSettings(
"TATA_RUANG"
);
totalPotensiPBGTataRuang.textContent = formatCurrency(
totalPotensiPBGTataRuangValue
);
// Total Berkas Belum terverifikasi
const totalBerkasBelumTerverifikasi = document.getElementById( const totalBerkasBelumTerverifikasi = document.getElementById(
"total-berkas-belum-terverifikasi" "total-berkas-belum-terverifikasi"
); );
if (!totalBerkasBelumTerverifikasi) return;
const totalBerkasBelumTerverifikasiValue = await getDataNonVerification(
selectedYear
);
const totalBerkasBelumTerverifikasiCount =
totalBerkasBelumTerverifikasiValue.countData;
totalBerkasBelumTerverifikasi.textContent = formatCurrency( totalBerkasBelumTerverifikasi.textContent = formatCurrency(
totalBerkasBelumTerverifikasiValue.totalData resumeData.non_verified_document.sum
); );
const totalRealisasiTerbitPBG = document.getElementById(
"realisasi-terbit-pbg"
);
totalRealisasiTerbitPBG.textContent = formatCurrency(
resumeData.realisasi_terbit.sum
);
const totalProsesDinasTeknis = document.getElementById(
"processing-technical-services"
);
totalProsesDinasTeknis.textContent = formatCurrency(
resumeData.proses_dinas_teknis.sum
);
await this.initPieChart(resumeData);
}
async initPieChart(data) {
// Total Berkas Usaha // Total Berkas Usaha
const totalBerkasUsahaValue = await getDataBusiness(selectedYear); const totalBerkasUsahaTotalData = data.verified_document.sum;
const totalBerkasUsahaCount = totalBerkasUsahaValue.countData;
const totalBerkasUsahaTotalData = totalBerkasUsahaValue.totalData;
// Total Berkas Non Usaha // Total Berkas Non Usaha
const totalBerkasNonUsahaValue = await getDataNonBusiness(selectedYear); const totalBerkasNonUsahaTotalData = data.non_verified_document.sum;
const totalBerkasNonUsahaCount = totalBerkasNonUsahaValue.countData;
const totalBerkasNonUsahaTotalData = totalBerkasNonUsahaValue.totalData;
// Pie Chart Section // Pie Chart Section
let persenUsaha = let persenUsaha = data.verified_document.percentage;
totalBerkasBelumTerverifikasiCount > 0
? (
(totalBerkasUsahaCount /
totalBerkasBelumTerverifikasiCount) *
100
).toFixed(2)
: "0";
let persenNonUsaha = let persenNonUsaha = data.non_verified_document.percentage;
totalBerkasBelumTerverifikasiCount > 0
? (
(totalBerkasNonUsahaCount /
totalBerkasBelumTerverifikasiCount) *
100
).toFixed(2)
: "0";
const dataSeriesPieChart = [ const dataSeriesPieChart = [
Number(persenUsaha), Number(persenUsaha),
@@ -123,7 +115,41 @@ document.addEventListener("DOMContentLoaded", async function () {
).textContent = persenUsaha + "%"; ).textContent = persenUsaha + "%";
updatePieChart(dataSeriesPieChart, labelsPieChart); updatePieChart(dataSeriesPieChart, labelsPieChart);
}
async getResume(filterByDate) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/bigdata-resume?filterByDate=${filterByDate}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']")
.content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching chart data:", error);
return null;
}
}
}
document.addEventListener("DOMContentLoaded", async function (e) {
await new DashboardPBG().init();
await initChart();
async function updateDataByYear() {
// Load all Tourism location // Load all Tourism location
const allLocation = await getAllLocation(); const allLocation = await getAllLocation();
console.log(allLocation); console.log(allLocation);
@@ -159,42 +185,6 @@ document.addEventListener("DOMContentLoaded", async function () {
.bindTooltip(loc.name, { permanent: false, direction: "top" }); // Tooltip saat di-hover .bindTooltip(loc.name, { permanent: false, direction: "top" }); // Tooltip saat di-hover
}); });
// Realisasi terbit PBG
const totalRealisasiTerbitPBG = document.getElementById(
"realisasi-terbit-pbg"
);
if (!totalRealisasiTerbitPBG) return;
const totalRealisasiTerbitPBGValue = await getDataSettings(
"REALISASI_TERBIT_PBG_SUM"
);
totalRealisasiTerbitPBG.textContent = formatCurrency(
totalRealisasiTerbitPBGValue
);
// Menunggu Klik DPMPTSP
const totalMenungguKlikDpmptsp = document.getElementById(
"waiting-click-dpmptsp"
);
if (!totalMenungguKlikDpmptsp) return;
const totalMenungguKlikDpmptspValue = await getDataSettings(
"MENUNGGU_KLIK_DPMPTSP_SUM"
);
totalMenungguKlikDpmptsp.textContent = formatCurrency(
totalMenungguKlikDpmptspValue
);
// Proses Dinas Teknis
const totalProsesDinasTeknis = document.getElementById(
"processing-technical-services"
);
if (!totalProsesDinasTeknis) return;
const totalProsesDinasTeknisValue = await getDataSettings(
"PROSES_DINAS_TEKNIS_SUM"
);
totalProsesDinasTeknis.textContent = formatCurrency(
totalProsesDinasTeknisValue
);
// Load Tabel Baru di Update // Load Tabel Baru di Update
const tableLastUpdated = new GeneralTable( const tableLastUpdated = new GeneralTable(
"pbg-filter-by-updated-at", "pbg-filter-by-updated-at",
@@ -255,188 +245,9 @@ document.addEventListener("DOMContentLoaded", async function () {
).hidden = true; ).hidden = true;
} }
await updateDataByYear(yearPicker.value); await updateDataByYear();
yearPicker.addEventListener("change", async function () {
console.log("event change dropdown");
await updateDataByYear(yearPicker.value);
});
}); });
async function getDataSettings(string_key) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/data-settings?search=${string_key}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']").content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return data.data?.[0]?.value ?? 0; // Pastikan tidak error jika data kosong
} catch (error) {
console.error("Error fetching data:", error);
return 0;
}
}
async function getDataTotalPotensi(year) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/all-task-documents?year=${year}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']").content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return {
totalData: data.data.total,
};
} catch (error) {
console.error("Error fetching chart data:", error);
return null;
}
}
async function getDataVerification(year) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/verification-documents?year=${year}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']").content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return {
totalData: data.data.total,
};
} catch (error) {
console.error("Error fetching chart data:", error);
return 0;
}
}
async function getDataNonVerification(year) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/non-verification-documents?year=${year}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']").content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return {
countData: data.data.count,
totalData: data.data.total,
};
} catch (error) {
console.error("Error fetching chart data:", error);
return 0;
}
}
async function getDataBusiness(year) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/business-documents?year=${year}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']").content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return {
countData: data.data.count,
totalData: data.data.total,
};
} catch (error) {
console.error("Error fetching chart data:", error);
return 0;
}
}
async function getDataNonBusiness(year) {
try {
const response = await fetch(
`${GlobalConfig.apiHost}/api/non-business-documents?year=${year}`,
{
credentials: "include",
headers: {
Authorization: `Bearer ${
document.querySelector("meta[name='api-token']").content
}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.error("Network response was not ok", response);
}
const data = await response.json();
return {
countData: data.data.count,
totalData: data.data.total,
};
} catch (error) {
console.error("Error fetching chart data:", error);
return 0;
}
}
async function getAllLocation() { async function getAllLocation() {
try { try {
const response = await fetch( const response = await fetch(

View File

@@ -2,10 +2,25 @@ import { Grid } from "gridjs/dist/gridjs.umd.js";
import gridjs from "gridjs/dist/gridjs.umd.js"; import gridjs from "gridjs/dist/gridjs.umd.js";
import "gridjs/dist/gridjs.umd.js"; import "gridjs/dist/gridjs.umd.js";
import GlobalConfig from "../../global-config"; import GlobalConfig from "../../global-config";
import Swal from "sweetalert2";
class UsersTable { class UsersTable {
init() { constructor() {
this.toastMessage = document.getElementById("toast-message");
this.toastElement = document.getElementById("toastNotification");
this.toast = new bootstrap.Toast(this.toastElement);
this.table = null;
this.initTableUsers(); this.initTableUsers();
this.initEvents();
}
initEvents() {
document.body.addEventListener("click", async (event) => {
const deleteButton = event.target.closest(".btn-delete-users");
if (deleteButton) {
event.preventDefault();
await this.handleDelete(deleteButton);
}
});
} }
initTableUsers() { initTableUsers() {
@@ -14,7 +29,8 @@ class UsersTable {
tableContainer.innerHTML = ""; tableContainer.innerHTML = "";
let canUpdate = tableContainer.getAttribute("data-updater") === "1"; let canUpdate = tableContainer.getAttribute("data-updater") === "1";
new Grid({ let canDestroy = tableContainer.getAttribute("data-destroyer") === "1";
this.table = new Grid({
columns: [ columns: [
"ID", "ID",
"Name", "Name",
@@ -26,18 +42,28 @@ class UsersTable {
{ {
name: "Action", name: "Action",
formatter: (cell) => { formatter: (cell) => {
if (!canUpdate) { if (!canUpdate && !canDestroy) {
return gridjs.html( return gridjs.html(
`<span class="text-muted">No Privilege</span>` `<span class="text-muted">No Privilege</span>`
); );
} }
return gridjs.html(`
<div class="d-flex justify-content-center"> let buttons = `<div class="d-flex justify-content-center align-items-center gap-2">`;
buttons += `
<a href="/master/users/${cell}/edit?menu_id=${menuId}" class="btn btn-yellow btn-sm d-inline-flex align-items-center justify-content-center"> <a href="/master/users/${cell}/edit?menu_id=${menuId}" class="btn btn-yellow btn-sm d-inline-flex align-items-center justify-content-center">
<i class='bx bx-edit'></i> <i class='bx bx-edit'></i>
</a> </a>
</div> `;
`); buttons += `
<button data-id="${cell}" class="btn btn-sm btn-red btn-delete-users d-inline-flex align-items-center justify-content-center">
<i class='bx bxs-trash'></i>
</button>
`;
buttons += `</div>`;
return gridjs.html(buttons);
}, },
}, },
], ],
@@ -67,7 +93,6 @@ class UsersTable {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
then: (data) => { then: (data) => {
console.log(data.data);
return data.data.map((item) => [ return data.data.map((item) => [
item.id, item.id,
item.name, item.name,
@@ -83,8 +108,62 @@ class UsersTable {
}, },
}).render(document.getElementById("table-users")); }).render(document.getElementById("table-users"));
} }
async handleDelete(button) {
const id = button.getAttribute("data-id");
const result = await Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
});
if (result.isConfirmed) {
try {
let response = await fetch(
`${GlobalConfig.apiHost}/api/users/${id}`,
{
method: "DELETE",
credentials: "include",
headers: {
Authorization: `Bearer ${document
.querySelector('meta[name="api-token"]')
.getAttribute("content")}`,
"Content-Type": "application/json",
},
}
);
if (response.ok) {
let result = await response.json();
this.toastMessage.innerText =
result.message || "Deleted successfully!";
this.toast.show();
// Refresh Grid.js table
if (typeof this.table !== "undefined") {
this.table.updateConfig({}).forceRender();
}
} else {
let error = await response.json();
console.error("Delete failed:", error);
this.toastMessage.innerText =
error.message || "Delete failed!";
this.toast.show();
}
} catch (error) {
console.error("Error deleting item:", error);
this.toastMessage.innerText = "An error occurred!";
this.toast.show();
}
}
}
} }
document.addEventListener("DOMContentLoaded", function (e) { document.addEventListener("DOMContentLoaded", function (e) {
new UsersTable().init(); new UsersTable();
}); });

View File

@@ -56,7 +56,7 @@ class Roles {
if (canDelete) { if (canDelete) {
buttons += ` buttons += `
<button data-id="${cell}" class="btn btn-sm btn-red btn-delete-role d-inline-flex align-items-center justify-content-center"> <button data-id="${cell}" class="btn btn-sm btn-red btn-delete-role d-none d-inline-flex align-items-center justify-content-center">
<i class='bx bxs-trash'></i> <i class='bx bxs-trash'></i>
</button> </button>
`; `;

View File

@@ -12,11 +12,7 @@
<div class="card mb-3 mb-xl-0"> <div class="card mb-3 mb-xl-0">
<div class="card-title mt-3"> <div class="card-title mt-3">
<div class="d-flex flex-sm-nowrap flex-wrap justify-content-end gap-2 me-3"> <div class="d-flex flex-sm-nowrap flex-wrap justify-content-end gap-2 me-3">
<select class="form-select w-25 w-sm-auto" id="yearPicker" name="year" style="min-width: 100px;"> <input type="text" class="form-control mt-2" style="max-width: 125px;" id="datepicker-dashboard-pbg" placeholder="Filter Date" />
@for ($i = date('Y'); $i > date('Y') - 5; $i--)
<option value="{{ $i }}" {{ $i == date('Y') ? 'selected' : '' }}>{{ $i }}</option>
@endfor
</select>
</div> </div>
</div> </div>
@@ -218,7 +214,7 @@
<div class="row"> <div class="row">
<!-- Card 1 --> <!-- Card 1 -->
<div class="col-md-12 col-lg-12 col-xl-4"> <div class="col-md-12 col-lg-12 col-xl-6">
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<div class="row"> <div class="row">
@@ -240,7 +236,7 @@
</div> </div>
<!-- Card 2 --> <!-- Card 2 -->
<div class="col-md-12 col-lg-12 col-xl-4"> <div class="col-md-12 col-lg-12 col-xl-4 d-none">
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<div class="row"> <div class="row">
@@ -262,7 +258,7 @@
</div> </div>
<!-- Card 3 --> <!-- Card 3 -->
<div class="col-md-12 col-lg-12 col-xl-4"> <div class="col-md-12 col-lg-12 col-xl-6">
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<div class="row"> <div class="row">

View File

@@ -8,6 +8,8 @@
@include('layouts.partials/page-title', ['title' => 'Master', 'subtitle' => 'Users']) @include('layouts.partials/page-title', ['title' => 'Master', 'subtitle' => 'Users'])
<x-toast-notification />
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<div class="card w-100"> <div class="card w-100">

View File

@@ -35,6 +35,7 @@ Route::group(['middleware' => 'auth:sanctum'], function (){
Route::get('/users', 'index')->name('api.users'); Route::get('/users', 'index')->name('api.users');
Route::post('/users', 'store')->name('api.users.store'); Route::post('/users', 'store')->name('api.users.store');
Route::put('/users/{id}', 'update')->name('api.users.update'); Route::put('/users/{id}', 'update')->name('api.users.update');
Route::delete('/users/{id}','destroy')->name('api.users.destroy');
Route::post('/logout','logout')->name('api.users.logout'); Route::post('/logout','logout')->name('api.users.logout');
}); });

View File

@@ -106,6 +106,7 @@ export default defineConfig({
//pbg-task //pbg-task
"resources/js/pbg-task/index.js", "resources/js/pbg-task/index.js",
"resources/js/pbg-task/show.js", "resources/js/pbg-task/show.js",
"resources/js/pbg-task/create.js",
// google-sheets // google-sheets
"resources/js/data/google-sheet/index.js", "resources/js/data/google-sheet/index.js",
// dummy // dummy