add edit and delete data tax

This commit is contained in:
arifal hidayat
2025-08-06 00:36:56 +07:00
parent c2cb1b99f2
commit 0abf278aa3
12 changed files with 318 additions and 7 deletions

View File

@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Api;
use App\Exports\TaxationsExport; use App\Exports\TaxationsExport;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Http\Requests\ExcelUploadRequest; use App\Http\Requests\ExcelUploadRequest;
use App\Http\Requests\TaxationsRequest;
use App\Http\Resources\TaxationsResource; use App\Http\Resources\TaxationsResource;
use App\Imports\TaxationsImport; use App\Imports\TaxationsImport;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -60,4 +61,38 @@ class TaxationsController extends Controller
{ {
return Excel::download(new TaxationsExport, 'pajak_per_kecamatan.xlsx'); return Excel::download(new TaxationsExport, 'pajak_per_kecamatan.xlsx');
} }
public function delete(Request $request)
{
try{
$tax = Tax::find($request->id);
$tax->delete();
return response()->json(['message' => 'Data deleted successfully'], 200);
}catch(\Exception $e){
Log::info($e->getMessage());
return response()->json([
'error' => 'Failed to delete data',
'message' => $e->getMessage()
], 500);
}
}
public function update(TaxationsRequest $request, string $id)
{
try{
$tax = Tax::find($id);
if($tax){
$tax->update($request->validated());
return response()->json(['message' => 'Successfully updated', new TaxationsResource($tax)]);
} else {
return response()->json(['message' => 'Tax not found'], 404);
}
}catch(\Exception $e){
Log::info($e->getMessage());
return response()->json([
'error' => 'Failed to update tax',
'message' => $e->getMessage()
], 500);
}
}
} }

View File

@@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Tax;
use Illuminate\Http\Request; use Illuminate\Http\Request;
class TaxationController extends Controller class TaxationController extends Controller
@@ -52,9 +53,11 @@ class TaxationController extends Controller
/** /**
* Show the form for editing the specified resource. * Show the form for editing the specified resource.
*/ */
public function edit(string $id) public function edit(Request $request, string $id)
{ {
// $menuId = $request->query('menu_id') ?? $request->input('menu_id');
$data = Tax::find($id);
return view('taxation.edit', compact('menuId', 'data'));
} }
/** /**

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class TaxationsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'tax_no' => ['required', 'string', Rule::unique('taxs')->ignore($this->id)],
'tax_code' => ['required', 'string'],
'wp_name' => ['required', 'string'],
'business_name' => ['required', 'string'],
'address' => ['required', 'string'],
'start_validity' => ['required', 'date_format:Y-m-d'],
'end_validity' => ['required', 'date_format:Y-m-d'],
'tax_value' => ['required', 'numeric', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
'subdistrict' => ['required', 'string'],
'village' => ['required', 'string'],
];
}
}

BIN
build.zip

Binary file not shown.

View File

@@ -0,0 +1,66 @@
class UpdateTax {
constructor() {
this.initUpdateCustomer();
}
initUpdateCustomer() {
const toastNotification = document.getElementById("toastNotification");
const toast = new bootstrap.Toast(toastNotification);
let menuId = document.getElementById("menuId").value;
document
.getElementById("btnUpdateTax")
.addEventListener("click", async function () {
let submitButton = this;
let spinner = document.getElementById("spinner");
let form = document.getElementById("formUpdateTax");
if (!form) {
console.error("Form element not found!");
return;
}
// Get form data
let formData = new FormData(form);
// Disable button and show spinner
submitButton.disabled = true;
spinner.classList.remove("d-none");
try {
let response = await fetch(form.action, {
method: "POST",
headers: {
Authorization: `Bearer ${document
.querySelector('meta[name="api-token"]')
.getAttribute("content")}`,
},
body: formData,
});
if (response.ok) {
let result = await response.json();
document.getElementById("toast-message").innerText =
result.message;
toast.show();
setTimeout(() => {
window.location.href = `/tax?menu_id=${menuId}`;
}, 2000);
} else {
let error = await response.json();
document.getElementById("toast-message").innerText =
error.message;
toast.show();
console.error("Error:", error);
}
} catch (error) {
console.error("Request failed:", error);
document.getElementById("toast-message").innerText =
error.message;
toast.show();
}
});
}
}
document.addEventListener("DOMContentLoaded", function (e) {
new UpdateTax();
});

View File

@@ -1,7 +1,9 @@
import { Grid } from "gridjs/dist/gridjs.umd.js"; import { Grid } 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 { addThousandSeparators } from "../global-config"; import { addThousandSeparators } from "../global-config";
import Swal from "sweetalert2";
class Taxation { class Taxation {
constructor() { constructor() {
@@ -11,7 +13,7 @@ class Taxation {
this.table = null; this.table = null;
this.initTableTaxation(); this.initTableTaxation();
// this.initEvents(); this.initEvents();
this.handleExportToExcel(); this.handleExportToExcel();
} }
@@ -66,11 +68,64 @@ class Taxation {
} }
initEvents() { initEvents() {
document.body.addEventListener("click", async (event) => { document.body.addEventListener("click", (event) => {
const deleteButton = event.target.closest(".btn-delete-taxation"); const deleteButton = event.target.closest(".btn-delete-taxation");
if (deleteButton) { if (deleteButton) {
event.preventDefault(); event.preventDefault();
await this.handleDelete(deleteButton); this.handleDelete(deleteButton);
}
});
}
handleDelete(deleteButton) {
const id = deleteButton.getAttribute("data-id");
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!",
}).then((result) => {
if (result.isConfirmed) {
fetch(`${GlobalConfig.apiHost}/api/taxs/${id}`, {
method: "DELETE",
credentials: "include",
headers: {
Authorization: `Bearer ${document
.querySelector('meta[name="api-token"]')
.getAttribute("content")}`,
"Content-Type": "application/json",
},
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
return response.json().then((error) => {
throw new Error(
error.message || "Delete failed!"
);
});
}
})
.then((result) => {
this.toastMessage.innerText =
result.message || "Data deleted successfully!";
this.toast.show();
if (typeof this.table !== "undefined") {
this.table.updateConfig({}).forceRender();
}
})
.catch((error) => {
console.error("Error deleting item:", error);
this.toastMessage.innerText =
error.message || "An error occurred!";
this.toast.show();
});
} }
}); });
} }
@@ -86,6 +141,10 @@ class Taxation {
// Clear previous table content // Clear previous table content
tableContainer.innerHTML = ""; tableContainer.innerHTML = "";
let canUpdate = tableContainer.getAttribute("data-updater") === "1";
let canDelete = tableContainer.getAttribute("data-destroyer") === "1";
let menuId = tableContainer.getAttribute("data-menuId");
this.table = new Grid({ this.table = new Grid({
columns: [ columns: [
"ID", "ID",
@@ -99,6 +158,33 @@ class Taxation {
{ name: "Tax Value" }, { name: "Tax Value" },
{ name: "Subdistrict" }, { name: "Subdistrict" },
{ name: "Village" }, { name: "Village" },
{
name: "Action",
formatter: (cell) => {
let buttons = "";
if (canUpdate) {
buttons += `
<a href="/tax/${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>
</a>
`;
}
if (canDelete) {
buttons += `
<button data-id="${cell}" class="btn btn-sm btn-red btn-delete-taxation d-inline-flex align-items-center justify-content-center">
<i class='bx bxs-trash'></i>
</button>
`;
}
if (!canUpdate && !canDelete) {
buttons = `<span class="text-muted">No Privilege</span>`;
}
return gridjs.html(
`<div class="d-flex justify-content-center gap-2">${buttons}</div>`
);
},
},
], ],
pagination: { pagination: {
limit: 50, limit: 50,
@@ -148,6 +234,7 @@ class Taxation {
addThousandSeparators(item.tax_value), addThousandSeparators(item.tax_value),
item.subdistrict, item.subdistrict,
item.village, item.village,
item.id,
]; ];
}); });
}, },

View File

@@ -0,0 +1,34 @@
@extends('layouts.vertical', ['subtitle' => 'Data'])
@section('content')
@include('layouts.partials/page-title', ['title' => 'Data', 'subtitle' => 'PDAM'])
<x-toast-notification />
<input type="hidden" id="menuId" value="{{ $menuId ?? 0 }}">
<div class="row d-flex justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header d-flex justify-content-end">
<a href="{{ route('taxation', ['menu_id' => $menuId]) }}" class="btn btn-sm btn-secondary">Back</a>
</div>
<div class="card-body">
<form id="formUpdateTax" action="{{ route('api.taxs.update', $data->id) }}" method="post">
@csrf
@method('put')
@include('taxation.form')
<button type="button" class="btn btn-primary" id="btnUpdateTax">
<span id="spinner" class="spinner-border spinner-border-sm me-1 d-none" role="status" aria-hidden="true"></span>
Update
</button>
</form>
</div>
</div>
</div>
</div>
@endsection
@section('scripts')
@vite(['resources/js/taxation/edit.js'])
@endsection

View File

@@ -0,0 +1,40 @@
<div class="mb-3">
<label class="form-label" for="tax_no">Tax No</label>
<input type="text" id="tax_no" name="tax_no" class="form-control" placeholder="Enter tax_no" value="{{ old('tax_no', $data->tax_no ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="tax_code">Tax Code</label>
<input type="text" id="tax_code" name="tax_code" class="form-control" placeholder="Enter tax_code" value="{{ old('tax_code', $data->tax_code ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="wp_name">WP Name</label>
<input type="text" id="wp_name" name="wp_name" class="form-control" placeholder="Enter wp_name" value="{{ old('wp_name', $data->wp_name ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="business_name">Business Name</label>
<input type="text" id="business_name" name="business_name" class="form-control" placeholder="Enter business_name" value="{{ old('business_name', $data->business_name ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="5" required>{{ old('address', $data->address ?? '') }}</textarea>
</div>
<div class="mb-3">
<label class="form-label" for="start_validity">Start Validity</label>
<input type="date" id="start_validity" name="start_validity" class="form-control" placeholder="Enter start_validity" value="{{ old('start_validity', $data->start_validity ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="end_validity">End Validity</label>
<input type="date" id="end_validity" name="end_validity" class="form-control" placeholder="Enter end_validity" value="{{ old('end_validity', $data->end_validity ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="tax_value">Tax Value</label>
<input type="number" id="tax_value" name="tax_value" class="form-control" placeholder="Enter tax_value" value="{{ old('tax_value', $data->tax_value ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="subdistrict">Subdistrict</label>
<input type="text" id="subdistrict" name="subdistrict" class="form-control" placeholder="Enter subdistrict" value="{{ old('subdistrict', $data->subdistrict ?? '') }}" required>
</div>
<div class="mb-3">
<label class="form-label" for="village">Village</label>
<input type="text" id="village" name="village" class="form-control" placeholder="Enter village" value="{{ old('village', $data->village ?? '') }}" required>
</div>

View File

@@ -21,10 +21,14 @@
</div> </div>
<div class="card-body"> <div class="card-body">
<div class="d-flex flex-wrap justify-content-end align-items-center mb-2"> <div class="d-flex flex-wrap justify-content-end align-items-center mb-2">
@if ($creator)
<a href="{{ route('taxation.upload', ['menu_id' => $menuId]) }}" class="btn btn-primary btn-sm d-block d-sm-inline w-auto">Upload</a> <a href="{{ route('taxation.upload', ['menu_id' => $menuId]) }}" class="btn btn-primary btn-sm d-block d-sm-inline w-auto">Upload</a>
@endif
</div> </div>
<div> <div>
<div id="table-taxation"></div> <div id="table-taxation" data-updater="{{ $updater }}"
data-destroyer="{{ $destroyer }}"
data-menuId="{{ $menuId }}"></div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -198,6 +198,8 @@ Route::group(['middleware' => 'auth:sanctum'], function (){
Route::get('/taxs', 'index')->name('api.taxs'); Route::get('/taxs', 'index')->name('api.taxs');
Route::post('/taxs/upload', 'upload')->name('api.taxs.upload'); Route::post('/taxs/upload', 'upload')->name('api.taxs.upload');
Route::get('/taxs/export', 'export')->name('api.taxs.export'); Route::get('/taxs/export', 'export')->name('api.taxs.export');
Route::delete('/taxs/{id}', 'delete')->name('api.taxs.delete');
Route::put('/taxs/{id}', 'update')->name('api.taxs.update');
}); });
// TODO: Implement new retribution calculation API endpoints using the new schema // TODO: Implement new retribution calculation API endpoints using the new schema

View File

@@ -192,5 +192,6 @@ Route::group(['middleware' => 'auth'], function(){
Route::group(['prefix' => '/tax'], function (){ Route::group(['prefix' => '/tax'], function (){
Route::get('/', [TaxationController::class, 'index'])->name('taxation'); Route::get('/', [TaxationController::class, 'index'])->name('taxation');
Route::get('/upload', [TaxationController::class, 'upload'])->name('taxation.upload'); Route::get('/upload', [TaxationController::class, 'upload'])->name('taxation.upload');
Route::get('/{id}/edit', [TaxationController::class, 'edit'])->name('taxation.edit');
}); });
}); });

View File

@@ -151,6 +151,7 @@ export default defineConfig({
// taxation // taxation
"resources/js/taxation/index.js", "resources/js/taxation/index.js",
"resources/js/taxation/upload.js", "resources/js/taxation/upload.js",
"resources/js/taxation/edit.js",
], ],
refresh: true, refresh: true,
}), }),