Feature #1 : Provinces

This commit is contained in:
Daeng Deni Mardaeni 2024-08-08 22:42:10 +07:00
parent 6a1a039eca
commit aa3289bd56
16 changed files with 659 additions and 51 deletions

View File

@ -0,0 +1,41 @@
<?php
namespace Modules\Location\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Modules\Location\Models\Province;
use Modules\Usermanagement\Models\Role;
class ProvincesExport implements WithColumnFormatting, WithHeadings, FromCollection, withMapping
{
public function collection(){
return Province::all();
}
public function map($row): array{
return [
$row->id,
$row->code,
$row->name,
$row->created_at
];
}
public function headings(): array{
return [
'ID',
'Code',
'Name',
'Created At'
];
}
public function columnFormats(): array{
return [
'A' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER,
'C' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME
];
}
}

View File

@ -0,0 +1,133 @@
<?php
namespace Modules\Location\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Exports\ProvincesExport;
use Modules\Location\Http\Requests\ProvinceRequest;
use Modules\Location\Models\Province;
class ProvincesController extends Controller
{
public $user;
public function index(){
return view('location::provinces.index');
}
public function create(){
return view('location::provinces.create');
}
public function store(ProvinceRequest $request){
$validate = $request->validated();
if($validate){
try{
// Save to database
$province = Province::create($validate);
return redirect()->route('locations.provinces.index')->with('success', 'Province created successfully');
} catch (\Exception $e){
return redirect()->route('locations.provinces.create')->with('error', 'Failed to create province');
}
}
}
public function edit($id){
$province = Province::find($id);
return view('location::provinces.create', compact('province'));
}
public function update(ProvinceRequest $request, $id){
$validate = $request->validated();
if($validate){
try{
// Update in database
$province = Province::find($id);
$province->update($validate);
return redirect()->route('locations.provinces.index')->with('success', 'Province updated successfully');
} catch (\Exception $e){
return redirect()->route('locations.provinces.edit', $id)->with('error', 'Failed to update province');
}
}
}
public function destroy($id){
try{
// Delete from database
$province = Province::find($id);
$province->delete();
echo json_encode(['success' => true, 'message' => 'Province deleted successfully']);
} catch (\Exception $e){
echo json_encode(['success' => false, 'message' => 'Failed to delete province']);
}
}
public function dataForDatatables(Request $request){
if (is_null($this->user) || !$this->user->can('provinces.view')) {
//abort(403, 'Sorry! You are not allowed to view users.');
}
// Retrieve data from the database
$query = Province::query();
// Apply search filter if provided
if ($request->has('search') && !empty($request->get('search'))) {
$search = $request->get('search');
$query->where(function ($q) use ($search) {
$q->where('name', 'LIKE', "%$search%");
});
}
// Apply sorting if provided
if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
$order = $request->get('sortOrder');
$column = $request->get('sortField');
$query->orderBy($column, $order);
}
// Get the total count of records
$totalRecords = $query->count();
// Apply pagination if provided
if ($request->has('page') && $request->has('size')) {
$page = $request->get('page');
$size = $request->get('size');
$offset = ($page - 1) * $size; // Calculate the offset
$query->skip($offset)->take($size);
}
// Get the filtered count of records
$filteredRecords = $query->count();
// Get the data for the current page
$roles = $query->get();
// Calculate the page count
$pageCount = ceil($totalRecords/$request->get('size'));
// Calculate the current page number
$currentPage = 0 + 1;
// Return the response data as a JSON object
return response()->json([
'draw' => $request->get('draw'),
'recordsTotal' => $totalRecords,
'recordsFiltered' => $filteredRecords,
'pageCount' => $pageCount,
'page' => $currentPage,
'totalCount' => $totalRecords,
'data' => $roles,
]);
}
public function export()
{
return Excel::download(new ProvincesExport, 'provinces.xlsx');
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace Modules\Location\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ProvinceRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
if ($this->method() === 'PUT') {
$rules['code'] = 'required|string|max:4|unique:provinces,code,' . $this->id;
$rules['name'] = 'required|string|max:2554|unique:provinces,name,' . $this->id;
} else {
$rules['code'] = 'required|string|max:4|unique:provinces,code';
$rules['name'] = 'required|string|max:2554|unique:provinces,name';
}
return $rules;
}
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
}

50
app/Models/Base.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace Modules\Location\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Wildside\Userstamps\Userstamps;
/**
*
*/
class Base extends Model
{
use LogsActivity, SoftDeletes, Userstamps;
protected $connection;
/**
* Constructs a new instance of the class.
*
* @param array $attributes Optional attributes to initialize the object with.
*
* @return void
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// Retrieve the module configuration from the module.json file
$modulePath = dirname(__FILE__, 3) . '/module.json';
$module = file_get_contents($modulePath);
$module = json_decode($module);
// Set the connection property to the database connection specified in the module configuration
$this->connection = $module->database;
}
/**
* Retrieves the activity log options for the User Management.
*
* @return LogOptions The activity log options.
*/
public function getActivitylogOptions()
: LogOptions
{
return LogOptions::defaults()->logAll()->useLogName('Locations : ');
}
}

22
app/Models/Province.php Normal file
View File

@ -0,0 +1,22 @@
<?php
namespace Modules\Location\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Location\Models\City;
use Modules\Location\Models\District;
use Modules\Location\Models\Village;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Permission\Models\Role as SpatieRole;
class Province extends Base
{
protected $fillable = ['code','name'];
public function cities(){
return $this->hasMany(City::class, 'province_code', 'code');
}
}

View File

@ -22,6 +22,10 @@ class LocationServiceProvider extends ServiceProvider
$this->registerConfig();
$this->registerViews();
$this->loadMigrationsFrom(module_path($this->moduleName, 'database/migrations'));
if (class_exists('Breadcrumbs')) {
require __DIR__ . '/../../routes/breadcrumbs.php';
}
}
/**

View File

@ -0,0 +1,33 @@
<?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::create('provinces', function (Blueprint $table) {
$table->id();
$table->string('code');
$table->string('name');
$table->timestamps();
$table->softDeletes();
$table->uuid('created_by')->nullable();
$table->uuid('updated_by')->nullable();
$table->uuid('deleted_by')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('provinces');
}
};

View File

@ -11,6 +11,8 @@ class LocationDatabaseSeeder extends Seeder
*/
public function run(): void
{
// $this->call([]);
$this->call([
ProvinceSeeder::class
]);
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace Modules\Location\Database\Seeders;
use Illuminate\Database\Seeder;
use Modules\Location\Models\Province;
class ProvinceSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$provinces = [
['code' => '11', 'name' => 'Aceh'],
['code' => '12', 'name' => 'Sumatera Utara'],
['code' => '13', 'name' => 'Sumatera Barat'],
['code' => '14', 'name' => 'Riau'],
['code' => '15', 'name' => 'Jambi'],
['code' => '16', 'name' => 'Sumatera Selatan'],
['code' => '17', 'name' => 'Bengkulu'],
['code' => '18', 'name' => 'Lampung'],
['code' => '19', 'name' => 'Kepulauan Bangka Belitung'],
['code' => '21', 'name' => 'Kepulauan Riau'],
['code' => '31', 'name' => 'Jakarta'],
['code' => '32', 'name' => 'Jawa Barat'],
['code' => '33', 'name' => 'Jawa Tengah'],
['code' => '34', 'name' => 'Yogyakarta'],
['code' => '35', 'name' => 'Jawa Timur'],
['code' => '36', 'name' => 'Banten'],
['code' => '51', 'name' => 'Bali'],
['code' => '52', 'name' => 'Nusa Tenggara Barat'],
['code' => '53', 'name' => 'Nusa Tenggara Timur'],
['code' => '61', 'name' => 'Kalimantan Barat'],
['code' => '62', 'name' => 'Kalimantan Tengah'],
['code' => '63', 'name' => 'Kalimantan Selatan'],
['code' => '64', 'name' => 'Kalimantan Timur'],
['code' => '65', 'name' => 'Kalimantan Utara'],
['code' => '71', 'name' => 'Sulawesi Utara'],
['code' => '72', 'name' => 'Sulawesi Tengah'],
['code' => '73', 'name' => 'Sulawesi Selatan'],
['code' => '74', 'name' => 'Sulawesi Tenggara'],
['code' => '75', 'name' => 'Gorontalo'],
['code' => '76', 'name' => 'Sulawesi Barat'],
['code' => '81', 'name' => 'Maluku'],
['code' => '82', 'name' => 'Maluku Utara'],
['code' => '91', 'name' => 'Papua'],
['code' => '92', 'name' => 'Papua Barat'],
['code' => '92.1', 'name' => 'Papua Barat Daya'],
['code' => '93', 'name' => 'Papua Tengah'],
['code' => '94', 'name' => 'Papua Selatan'],
['code' => '95', 'name' => 'Papua Pegunungan'],
];
foreach ($provinces as $province) {
Province::create($province);
}
}
}

View File

@ -23,7 +23,7 @@
"sub": [
{
"title": "Provinces",
"path": "",
"path": "locations.provinces",
"classes": "",
"attributes": [],
"permission": "",

View File

@ -1,7 +0,0 @@
@extends('location::layouts.master')
@section('content')
<h1>Hello World</h1>
<p>Module: {!! config('location.name') !!}</p>
@endsection

View File

@ -1,29 +0,0 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Location Module - {{ config('app.name', 'Laravel') }}</title>
<meta name="description" content="{{ $description ?? '' }}">
<meta name="keywords" content="{{ $keywords ?? '' }}">
<meta name="author" content="{{ $author ?? '' }}">
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
{{-- Vite CSS --}}
{{-- {{ module_vite('build-location', 'resources/assets/sass/app.scss') }} --}}
</head>
<body>
@yield('content')
{{-- Vite JS --}}
{{-- {{ module_vite('build-location', 'resources/assets/js/app.js') }} --}}
</body>

View File

@ -0,0 +1,58 @@
@extends('layouts.main')
@section('breadcrumbs')
{{ Breadcrumbs::render(request()->route()->getName()) }}
@endsection
@section('content')
<div class="w-full grid gap-5 lg:gap-7.5 mx-auto">
@if(isset($province->id))
<form action="{{ route('locations.provinces.update', $province->id) }}" method="POST">
<input type="hidden" name="id" value="{{ $province->id }}">
@method('PUT')
@else
<form method="POST" action="{{ route('locations.provinces.store') }}">
@endif
@csrf
<div class="card pb-2.5">
<div class="card-header" id="basic_settings">
<h3 class="card-title">
{{ isset($province->id) ? 'Edit' : 'Add' }} Province
</h3>
<div class="flex items-center gap-2">
<a href="{{ route('locations.provinces.index') }}" class="btn btn-xs btn-info">Back</a>
</div>
</div>
<div class="card-body grid gap-5">
<div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label class="form-label max-w-56">
Code
</label>
<div class="flex flex-wrap items-baseline w-full">
<input class="input @error('code') border-danger @enderror" type="text" name="code" value="{{ $province->code ?? '' }}">
@error('code')
<em class="alert text-danger text-sm">{{ $message }}</em>
@enderror
</div>
</div>
<div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label class="form-label max-w-56">
Name
</label>
<div class="flex flex-wrap items-baseline w-full">
<input class="input @error('name') border-danger @enderror" type="text" name="name" value="{{ $province->name ?? '' }}">
@error('name')
<em class="alert text-danger text-sm">{{ $message }}</em>
@enderror
</div>
</div>
<div class="flex justify-end">
<button type="submit" class="btn btn-primary">
Save
</button>
</div>
</div>
</div>
</form>
</div>
@endsection

View File

@ -0,0 +1,172 @@
@extends('layouts.main')
@section('breadcrumbs')
{{ Breadcrumbs::render('locations.provinces') }}
@endsection
@section('content')
<div class="container-fluid">
<div class="grid">
<div class="card card-grid min-w-full" data-datatable="false" data-datatable-page-size="5" data-datatable-state-save="true" id="provinces-table" data-api-url="{{ route('locations.provinces.datatables') }}">
<div class="card-header py-5 flex-wrap">
<h3 class="card-title">
List of Provinces
</h3>
<div class="flex flex-wrap gap-2 lg:gap-5">
<div class="flex">
<label class="input input-sm"> <i class="ki-filled ki-magnifier"> </i>
<input placeholder="Search provinces" id="search" type="text" value="">
</label>
</div>
<div class="flex flex-wrap gap-2.5">
<select class="select select-sm w-28">
<option value="1">
Active
</option>
<option value="2">
Disabled
</option>
<option value="2">
Pending
</option>
</select>
<select class="select select-sm w-28">
<option value="desc">
Latest
</option>
<option value="asc">
Oldest
</option>
</select>
<button class="btn btn-sm btn-outline btn-primary">
<i class="ki-filled ki-setting-4"> </i> <Filters></Filters>
</button>
<div class="h-[24px] border border-r-gray-200"> </div>
<a class="btn btn-sm btn-light" href="{{ route('locations.provinces.export') }}"> Export to Excel </a>
<a class="btn btn-sm btn-primary" href="{{ route('locations.provinces.create') }}"> Add Province </a>
</div>
</div>
</div>
<div class="card-body">
<div class="scrollable-x-auto">
<table class="table table-auto table-border align-middle text-gray-700 font-medium text-sm" data-datatable-table="true">
<thead>
<tr>
<th class="w-14">
<input class="checkbox checkbox-sm" data-datatable-check="true" type="checkbox"/>
</th>
<th class="min-w-[250px]" data-datatable-column="code">
<span class="sort"> <span class="sort-label"> Code </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="name">
<span class="sort"> <span class="sort-label"> Province </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[50px] text-center" data-datatable-column="actions">Action</th>
</tr>
</thead>
</table>
</div>
<div class="card-footer justify-center md:justify-between flex-col md:flex-row gap-3 text-gray-600 text-2sm font-medium">
<div class="flex items-center gap-2">
Show
<select class="select select-sm w-16" data-datatable-size="true" name="perpage"> </select> per page
</div>
<div class="flex items-center gap-4">
<span data-datatable-info="true"> </span>
<div class="pagination" data-datatable-pagination="true">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script type="text/javascript">
function deleteData(data) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!" + data,
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
$.ajax(`locations/provinces/${data}`, {
type: 'DELETE'
}).then((response) => {
swal.fire('Deleted!', 'User has been deleted.','success').then(() => {
window.location.reload();
});
}).catch((error) => {
console.error('Error:', error);
Swal.fire('Error!', 'An error occurred while deleting the file.', 'error');
});
}
})
}
</script>
<script type="module">
const element = document.querySelector('#provinces-table');
const searchInput = document.getElementById('search');
const apiUrl = element.getAttribute('data-api-url');
const dataTableOptions = {
apiEndpoint: apiUrl,
pageSize: 5,
columns: {
select: {
render: (item, data, context) => {
const checkbox = document.createElement('input');
checkbox.className = 'checkbox checkbox-sm';
checkbox.type = 'checkbox';
checkbox.value = data.id.toString();
checkbox.setAttribute('data-datatable-row-check', 'true');
return checkbox.outerHTML.trim();
},
},
code: {
title: 'Code',
},
name: {
title: 'Province',
},
actions: {
title: 'Status',
render: (item, data) => {
return `<div class="flex flex-nowrap justify-center">
<a class="btn btn-sm btn-icon btn-clear btn-info" href="locations/provinces/${data.id}/edit">
<i class="ki-outline ki-notepad-edit"></i>
</a>
<a onclick="deleteData(${data.id})" class="delete btn btn-sm btn-icon btn-clear btn-danger">
<i class="ki-outline ki-trash"></i>
</a>
</div>`;
},
}
},
};
let dataTable = new KTDataTable(element, dataTableOptions);
// Custom search functionality
searchInput.addEventListener('input', function () {
const searchValue = this.value.trim();
dataTable.search(searchValue, true);
});
</script>
@endpush

27
routes/breadcrumbs.php Normal file
View File

@ -0,0 +1,27 @@
<?php
use Diglactic\Breadcrumbs\Breadcrumbs;
use Diglactic\Breadcrumbs\Generator as BreadcrumbTrail;
// Home
Breadcrumbs::for('locations', function (BreadcrumbTrail $trail) {
$trail->push('Locations');
});
// Provinces
Breadcrumbs::for('locations.provinces', function (BreadcrumbTrail $trail) {
$trail->parent('locations');
$trail->push('Provinces', route('locations.provinces.index'));
});
Breadcrumbs::for('locations.provinces.create', function (BreadcrumbTrail $trail) {
$trail->parent('locations.provinces');
$trail->push('Create Province', route('locations.provinces.create'));
});
Breadcrumbs::for('locations.provinces.edit', function (BreadcrumbTrail $trail) {
$trail->parent('locations.provinces');
$trail->push('Edit Province');
});
// Districts

View File

@ -2,18 +2,27 @@
use Illuminate\Support\Facades\Route;
use Modules\Location\Http\Controllers\LocationController;
use Modules\Location\Http\Controllers\ProvincesController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group([], function () {
Route::resource('location', LocationController::class)->names('location');
});
Route::middleware(['auth'])->group(function () {
Route::name('locations.')->prefix('locations')->group(function () {
Route::name('provinces.')->prefix('roles')->group(function () {
Route::get('restore/{id}', [ProvincesController::class, 'restore'])->name('restore');
Route::get('datatables', [ProvincesController::class, 'dataForDatatables'])->name('datatables');
Route::get('export', [ProvincesController ::class, 'export'])->name('export');
});
Route::resource('provinces', ProvincesController::class);
});
});