Compare commits

...

24 Commits

Author SHA1 Message Date
Daeng Deni Mardaeni
d8767174ca feat(location): perbaiki middleware auth dan optimalkan metode controllers
- **Middleware Auth**:
  - Mengganti penanganan middleware auth menggunakan `this->middleware('auth')` pada semua controller.
  - Menambahkan middleware closure untuk menginisialisasi properti user dengan `Auth::user()` setelah auth diverifikasi.

- **Controller Updates**:
  - **CitiesController**:
    - Menambahkan variabel `$provinces` untuk mendapatkan semua data provinsi.
    - Menambahkan data `$provinces` ke dalam view `location::cities.index`.
  - **DistrictsController**:
    - Menambahkan variabel `$provinces` untuk mendukung akses data provinsi dalam view.
    - Menyertakan data provinsi ke dalam view `location::districts.index`.
  - **ProvincesController** dan **VillagesController**:
    - Penyesuaian middleware auth sama seperti controller lainnya. Tidak ada perubahan pada struktur utama lainnya.

- **Seeder Optimization**:
  - Menghapus metode `crudActions` dalam `PermissionSeeder` yang sebelumnya menghasilkan daftar tindakan CRUD.
  - Mengurangi redundansi kode seeding dengan langsung membuat grup permission tanpa tindakan tambahan.
  - Membersihkan logika tambahan terkait CRUD actions yang tidak dipakai.
2025-06-22 20:51:20 +07:00
Daeng Deni Mardaeni
53a2c3a38e feat(auth): tambah validasi peran pengguna untuk modul lokasi
- **Autentikasi dan Otorisasi**:
  - Menambah validasi akses berdasarkan peran pengguna menggunakan `Auth::guard('web')->user()`.
  - Menentukan izin seperti `location.read`, `location.create`, `location.update`, `location.delete`, dan `location.export` untuk setiap metode di controller.
  - Menambahkan pesan error khusus untuk user yang tidak memiliki izin akses tertentu.

- **Peningkatan Controller**:
  - Mengubah properti `user` dari publik menjadi `protected`.
  - Menambahkan validasi peran pengguna pada metode di controller berikut:
    - `ProvincesController`: Pembatasan akses untuk operasi CRUD dan export.
    - `CitiesController`: Restriksi yang sama seperti pada `ProvincesController`.
    - `DistrictsController`: Menambahkan pengecekan otorisasi berdasarkan peran.
    - `VillagesController`: Validasi akses CRUD, export, dan data villager.

- **Seeder**:
  - Menambahkan `PermissionSeeder` untuk menghasilkan izin CRUD dengan grup `location`.
  - Memastikan setiap action CRUD (`read`, `create`, `update`, dll.) terdaftar dalam basis data.

- **Perbaikan API Response**:
  - Mengganti penggunaan `echo json_encode` dengan metode `response()->json()`.
  - Penanganan response untuk berbagai metode seperti `destroy`, dan validasi akses lainnya.

Signed-off-by: Daeng Deni Mardaeni <ddeni05@gmail.com>
2025-06-22 19:16:11 +07:00
Daeng Deni Mardaeni
cd10e17259 fix(models): ganti penggunaan trait Userstamps
- Mengubah penggunaan trait dari `Wildside\Userstamps\Userstamps` menjadi `Mattiverse\Userstamps\Traits\Userstamps`.
- Penyesuaian ini dilakukan untuk mendukung versi terbaru dari dependensi yang digunakan.
- Memastikan kompatibilitas dengan implementasi terkini pada model.
- Tidak ada perubahan pada logika utama aplikasi, hanya penggantian trait.
2025-06-05 16:55:06 +07:00
Daeng Deni Mardaeni
80e592c639 fix(cities): perbaiki pemetaan kolom untuk tabel kota
- Menambahkan indeks pada kolom 'code' untuk meningkatkan performa pencarian.
- Menghapus indeks yang tidak diperlukan untuk kolom 'province_code'.
2025-04-27 16:40:13 +07:00
Daeng Deni Mardaeni
4cf14d46b4 fix(cities): perbaiki pemetaan indeks untuk tabel kota
- Memisahkan indeks untuk kolom 'code' dan 'province_code' pada tabel kota.
- Meningkatkan performa pencarian dengan menambahkan indeks terpisah.
2025-04-27 16:34:29 +07:00
Daeng Deni Mardaeni
817eb3360b fix(cities): perbaiki pemetaan nama provinsi untuk kota
- Memperbarui pemetaan nama provinsi berdasarkan kode kota tertentu.
- Menambahkan logika untuk menetapkan nama provinsi jika kode kota termasuk dalam daftar tertentu.
- Mengubah referensi dari `$row->province->name` menjadi `$row->province_name` untuk konsistensi.

fix(districts): perbaiki pemetaan nama provinsi untuk distrik

- Memperbarui pemetaan nama provinsi berdasarkan kode kota dalam distrik.
- Menambahkan logika untuk menetapkan nama provinsi jika kode kota termasuk dalam daftar tertentu.
- Mengubah referensi dari `$row->city->province->name` menjadi `$row->province_name` untuk konsistensi.

fix(villages): perbaiki pemetaan nama provinsi untuk desa

- Memperbarui pemetaan nama provinsi berdasarkan kode kota dalam desa.
- Menambahkan logika untuk menetapkan nama provinsi jika kode kota termasuk dalam daftar tertentu.
- Mengubah referensi dari `$row->district->city->province->name` menjadi `$row->province_name` untuk konsistensi.
2025-04-27 16:00:19 +07:00
Daeng Deni Mardaeni
d92b66185c fix(villages): perbaiki pencarian dan pemetaan provinsi untuk desa
- Tambahkan penanganan khusus untuk kode kota di provinsi Papua.
- Perbarui aturan validasi untuk kode desa agar mendukung panjang maksimum 13 karakter.
- Perbaiki tampilan nama provinsi pada tabel desa dengan menggunakan nama yang sesuai.
2025-04-27 12:14:50 +07:00
Daeng Deni Mardaeni
094f9fa6d6 fix(districts): perbaiki pencarian dan pemetaan provinsi untuk distrik
- Tambahkan penanganan khusus untuk kode kota Papua.
- Perbarui aturan validasi untuk kolom kode distrik.
- Perbaiki tampilan nama provinsi pada tabel distrik.
2025-04-27 12:14:40 +07:00
Daeng Deni Mardaeni
bf288013f4 fix(cities): perbaiki pencarian dan pemetaan provinsi untuk kota
- Tambahkan logika untuk menangani kode kota khusus di provinsi Papua.
- Perbarui pemetaan nama provinsi berdasarkan kode kota.
- Sesuaikan tampilan data kota di tabel dengan nama provinsi yang benar.
2025-04-27 12:14:22 +07:00
Daeng Deni Mardaeni
1a7703a6cc fix(provinces): perbarui tampilan dan fungsionalitas tabel provinsi
- Hapus dropdown filter yang tidak diperlukan.
- Tambahkan garis batas untuk pemisahan elemen.
- Modifikasi render kolom kode untuk menampilkan dua karakter pertama.
2025-04-27 12:14:07 +07:00
Daeng Deni Mardaeni
dc931dbb4b fix(villages): perbaiki nama desa Cikampek Utara
- Mengubah nama desa dari 'Cilkampek Utara' menjadi 'Cikampek Utara'
- Memastikan konsistensi penamaan dalam database
2025-04-27 12:13:48 +07:00
Daeng Deni Mardaeni
d74dbb37a7 fix(migration): tambahkan index pada tabel villages
- Menambahkan index pada kolom province_code, city_code, district_code, dan code.
- Meningkatkan performa query yang melibatkan kolom-kolom tersebut.
2025-04-27 12:13:20 +07:00
Daeng Deni Mardaeni
00356f2366 fix(migration): tambahkan index pada tabel districts
- Menambahkan index pada kolom 'province_code', 'city_code', dan 'code' di tabel districts.
- Meningkatkan performa query yang melibatkan kolom-kolom tersebut.
2025-04-27 12:13:15 +07:00
Daeng Deni Mardaeni
0be26178ff fix(migration): tambahkan index pada tabel cities
- Menambahkan index pada kolom 'province_code' dan 'code' untuk meningkatkan performa query.
2025-04-27 12:13:07 +07:00
Daeng Deni Mardaeni
4502f9a298 Merge remote-tracking branch 'origin/master' 2025-03-13 08:57:58 +07:00
Daeng Deni Mardaeni
934d293d2e feat(locations): perbarui pengelolaan pemilihan lokasi
- Menambahkan fungsi reset untuk membersihkan pilihan kota, distrik, dan desa.
- Mengoptimalkan inisialisasi TomSelect untuk menghindari penghancuran yang tidak perlu.
- Memperbaiki pengambilan data untuk kota, distrik, dan desa berdasarkan pilihan pengguna.
- Menangani kesalahan saat mengambil data dengan menambahkan log kesalahan.
2025-03-13 08:55:53 +07:00
majid
2c610987e6 fix(city): seeder to format city names to lowercase format 2025-02-13 11:01:30 +07:00
Daeng Deni Mardaeni
0b58db9d16 fix(seeder): handle exceptions in VillageSeeder
- Menambahkan penanganan kesalahan saat menjalankan seeder untuk menghindari kegagalan tanpa informasi.
- Menggunakan Log untuk mencatat kesalahan yang terjadi saat memuat data dari file villages.sql.
2025-01-15 09:44:03 +07:00
Daeng Deni Mardaeni
6f899fa131 Perbarui atribut ikon pada menu Locations
- Menambahkan kelas `text-primary` pada atribut ikon di menu `Locations` dalam file `module.json`.
- Perubahan ini bertujuan untuk meningkatkan styling visual dengan warna ikon yang lebih menonjol (`text-primary`).
- Tidak ada logika atau fungsi lain yang terdampak oleh perubahan ini.
2024-12-22 16:17:28 +07:00
Daeng Deni Mardaeni
f12b63871b update roles 2024-10-03 11:52:36 +07:00
Daeng Deni Mardaeni
4987002a9d Feature #6 : Update
- Add Get Village by District Code
- Add Get Postal Code by Village Code
- Update Filter on Villages, District, and City, add dropdown to select province, city, district before filter for faster filter
2024-08-13 10:42:03 +07:00
Daeng Deni Mardaeni
b75db02f27 Fix Delete Modal 2024-08-10 21:07:22 +07:00
Daeng Deni Mardaeni
ae1a6c6513 Feature #5 : Activate Filter Button on Table on Each Module Location 2024-08-10 20:13:04 +07:00
Daeng Deni Mardaeni
d73a006ce0 Feature #4 : Villages 2024-08-10 20:12:04 +07:00
31 changed files with 85095 additions and 368 deletions

View File

@@ -11,7 +11,18 @@ use Modules\Location\Models\City;
class CitiesExport implements WithColumnFormatting, WithHeadings, FromCollection, withMapping
{
public function collection(){
return City::with('province')->get();
$data = City::with('province')->get();
$data = $data->map(function ($item) {
if (in_array($item->code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->province->name;
}
return $item;
});
return $data;
}
public function map($row): array{
@@ -19,7 +30,7 @@ class CitiesExport implements WithColumnFormatting, WithHeadings, FromCollection
$row->id,
$row->code,
$row->name,
$row->province->name,
$row->province_name,
$row->created_at
];
}

View File

@@ -7,11 +7,21 @@ use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Modules\Location\Models\District;
use Modules\Location\Models\Province;
class DistrictsExport implements WithColumnFormatting, WithHeadings, FromCollection, withMapping
{
public function collection(){
return District::with('city.province')->get();
$data = District::with('city.province')->get();
$data = $data->map(function ($item) {
if (in_array($item->city_code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->city->province->name;
}
return $item;
});
}
public function map($row): array{
@@ -20,7 +30,7 @@ class DistrictsExport implements WithColumnFormatting, WithHeadings, FromCollect
$row->code,
$row->name,
$row->city->name,
$row->city->province->name,
$row->province_name,
$row->created_at
];
}

View File

@@ -0,0 +1,59 @@
<?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\Location\Models\Village;
class VillagesExport implements WithColumnFormatting, WithHeadings, FromCollection, withMapping
{
public function collection(){
$data = Village::with('district.city.province')->get();
$data = $data->map(function ($item) {
if (in_array($item->city_code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->district->city->province->name;
}
return $item;
});
}
public function map($row): array{
return [
$row->id,
$row->code,
$row->name,
$row->postal_code,
$row->district->name,
$row->district->city->name,
$row->province_name,
$row->created_at
];
}
public function headings(): array{
return [
'ID',
'Code',
'Name',
'Postal Code',
'District',
'City',
'Province',
'Created At'
];
}
public function columnFormats(): array{
return [
'A' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER,
'D' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER,
'H' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME
];
}
}

View File

@@ -3,29 +3,55 @@
namespace Modules\Location\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Exports\CitiesExport;
use Modules\Location\Http\Requests\CityRequest;
use Modules\Location\Models\City;
use Modules\Location\Models\Province;
class CitiesController extends Controller
{
public $user;
protected $user;
public function __construct()
{
// Mengatur middleware auth
$this->middleware('auth');
// Mengatur user setelah middleware auth dijalankan
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
public function index(){
return view('location::cities.index');
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to view cities.');
}
$provinces = Province::all();
return view('location::cities.index', compact('provinces'));
}
public function create(){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create cities.');
}
$provinces = Province::all();
return view('location::cities.create',compact('provinces'));
}
public function store(CityRequest $request){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create cities.');
}
$validate = $request->validated();
if($validate){
@@ -39,12 +65,20 @@ class CitiesController extends Controller
}
public function edit($id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update cities.');
}
$city = City::find($id);
$provinces = Province::all();
return view('location::cities.create', compact('city', 'provinces'));
}
public function update(CityRequest $request, $id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update cities.');
}
$validate = $request->validated();
if($validate){
@@ -59,17 +93,21 @@ class CitiesController extends Controller
}
public function destroy($id){
if (is_null($this->user) || !$this->user->can('provinces.delete')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to delete cities.']);
}
try {
City::destroy($id);
echo json_encode(['message' => 'City deleted successfully', 'success' => true]);
return response()->json(['message' => 'City deleted successfully', 'success' => true]);
} catch (\Exception $e) {
echo json_encode(['message' => 'Failed to delete city', 'success' => false]);
return response()->json(['message' => 'Failed to delete city', 'success' => false]);
}
}
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.');
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view cities.'], 403);
}
// Retrieve data from the database
@@ -78,10 +116,27 @@ class CitiesController extends Controller
// Apply search filter if provided
if ($request->has('search') && !empty($request->get('search'))) {
$search = $request->get('search');
$search = explode('|', $search);
if(isset($search[0]) && !empty($search[0])){
// Define special city codes once
$specialCityCodes = ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'];
// Handle Papua province special cases
if($search[0] == '92'){
$query->where('province_code', '92')
->whereNotIn('code', $specialCityCodes);
} else if($search[0] == '92.1'){
$query->where('province_code', '92')
->whereIn('code', $specialCityCodes);
} else {
// For all other provinces
$query->where('province_code', $search[0]);
}
}
$query->where(function ($q) use ($search) {
$q->where('code', 'LIKE', "%$search%");
$q->orWhere('name', 'LIKE', "%$search%");
$q->orWhereRelation('province','name', 'LIKE', "%$search%");
$q->where('code', 'LIKE', "%$search[1]%");
$q->orWhere('name', 'LIKE', "%$search[1]%");
$q->orWhereRelation('province','name', 'LIKE', "%$search[1]%");
});
}
@@ -108,7 +163,7 @@ class CitiesController extends Controller
$filteredRecords = $query->count();
// Get the data for the current page
$cities = $query->with('province')->get();
$data = $query->with('province')->get();
// Calculate the page count
$pageCount = ceil($totalRecords/$request->get('size'));
@@ -116,6 +171,19 @@ class CitiesController extends Controller
// Calculate the current page number
$currentPage = 0 + 1;
//maping data for datatables,
//jika city code adalah '92.01', '92.04', '92.05', '92.09', '92.10', '92.71' maka province code yang dipilih adalah 92.1
$data = $data->map(function ($item) {
if (in_array($item->code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->province->name;
}
return $item;
});
// Apply the search filter again if there is a search filter
// Return the response data as a JSON object
return response()->json([
'draw' => $request->get('draw'),
@@ -124,16 +192,36 @@ class CitiesController extends Controller
'pageCount' => $pageCount,
'page' => $currentPage,
'totalCount' => $totalRecords,
'data' => $cities,
'data' => $data,
]);
}
public function export()
{
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to export cities.');
}
return Excel::download(new CitiesExport, 'cities.xlsx');
}
public function getCitiesByProvinceId($id){
return response()->json(City::where('province_code', $id)->get());
public function getCitiesByProvinceId($id)
{
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view cities.'], 403);
}
$query = City::query();
$provinceCode = substr($id, 0, 2);
$query->where('province_code', $provinceCode);
if ($id == '92.1') {
$query->whereIn('code', ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71']);
} elseif ($id == '92') {
$query->whereNotIn('code', ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71']);
}
return response()->json($query->get());
}
}

View File

@@ -10,26 +10,52 @@ use Modules\Location\Http\Requests\DistrictRequest;
use Modules\Location\Models\City;
use Modules\Location\Models\District;
use Modules\Location\Models\Province;
use Illuminate\Support\Facades\Auth;
class DistrictsController extends Controller
{
public $user;
protected $user;
public function __construct()
{
// Mengatur middleware auth
$this->middleware('auth');
// Mengatur user setelah middleware auth dijalankan
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
public function index(){
return view('location::districts.index');
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to view districts.');
}
$provinces = Province::all();
return view('location::districts.index', compact('provinces'));
}
public function create(){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create districts.');
}
$provinces = Province::all();
return view('location::districts.create', compact('provinces'));
}
public function store(DistrictRequest $request){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create districts.');
}
$validate = $request->validated();
if($validate){
try{
$district = District::create($validate);
District::create($validate);
return redirect()->route('locations.districts.index')->with('success', 'District created successfully');
} catch(\Exception $e){
return redirect()->back()->with('error', 'Failed to create district. '.$e->getMessage());
@@ -38,6 +64,10 @@ class DistrictsController extends Controller
}
public function edit($id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to edit districts.');
}
$district = District::find($id);
$provinces = Province::all();
$cities = City::where('province_code', $district->province_code)->get();
@@ -45,6 +75,10 @@ class DistrictsController extends Controller
}
public function update(DistrictRequest $request, $id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update districts.');
}
$validate = $request->validated();
if($validate){
@@ -59,17 +93,22 @@ class DistrictsController extends Controller
}
public function destroy($id){
if (is_null($this->user) || !$this->user->can('location.delete')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to delete districts.'], 403);
}
try{
District::destroy($id);
echo json_encode(['message' => 'District deleted successfully','success'=>true ]);
return response()->json(['message' => 'District deleted successfully', 'success' => true]);
} catch(\Exception $e){
echo json_encode(['message' => 'Failed to delete District', 'success' => false]);
return response()->json(['message' => 'Failed to delete District', 'success' => false]);
}
}
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.');
// Check if the authenticated user has the required permission to view audit logs
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view districts.'], 403);
}
// Retrieve data from the database
@@ -78,11 +117,30 @@ class DistrictsController extends Controller
// Apply search filter if provided
if ($request->has('search') && !empty($request->get('search'))) {
$search = $request->get('search');
$search = explode('|', $search);
if(isset($search[0]) && !empty($search[0])){
// Define special city codes once
$specialCityCodes = ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'];
// Handle Papua province special cases
if($search[0] == '92'){
$query->where('province_code', '92')
->whereNotIn('city_code', $specialCityCodes);
} else if($search[0] == '92.1'){
$query->where('province_code', '92')
->whereIn('city_code', $specialCityCodes);
} else {
// For all other provinces
$query->where('province_code', $search[0]);
}
}
if(isset($search[1]) &&!empty($search[1])){
$query->where('city_code',$search[1]);
}
$query->where(function ($q) use ($search) {
$q->where('code', 'LIKE', "%$search%");
$q->orWhere('name', 'LIKE', "%$search%");
$q->orWhereRelation('city','name', 'LIKE', "%$search%");
$q->orWhereRelation('city.province','name', 'LIKE', "%$search%");
$q->where('code', 'LIKE', "%$search[2]%");
$q->orWhere('name', 'LIKE', "%$search[2]%");
});
}
@@ -109,7 +167,7 @@ class DistrictsController extends Controller
$filteredRecords = $query->count();
// Get the data for the current page
$cities = $query->with('city.province')->get();
$data = $query->with('city.province')->get();
// Calculate the page count
$pageCount = ceil($totalRecords/$request->get('size'));
@@ -117,6 +175,15 @@ class DistrictsController extends Controller
// Calculate the current page number
$currentPage = 0 + 1;
$data = $data->map(function ($item) {
if (in_array($item->city_code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->city->province->name;
}
return $item;
});
// Return the response data as a JSON object
return response()->json([
'draw' => $request->get('draw'),
@@ -125,11 +192,23 @@ class DistrictsController extends Controller
'pageCount' => $pageCount,
'page' => $currentPage,
'totalCount' => $totalRecords,
'data' => $cities,
'data' => $data,
]);
}
public function export(Request $request){
if (is_null($this->user) || !$this->user->can('location.export')) {
abort(403, 'Sorry! You are not allowed to export districts.');
}
return Excel::download(new DistrictsExport, 'districts.xlsx');
}
public function getDistrictsByCityId($id){
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view districts.'], 403);
}
return response()->json(District::where('city_code', $id)->get());
}
}

View File

@@ -1,67 +0,0 @@
<?php
namespace Modules\Location\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class LocationController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return view('location::index');
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('location::create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): RedirectResponse
{
//
}
/**
* Show the specified resource.
*/
public function show($id)
{
return view('location::show');
}
/**
* Show the form for editing the specified resource.
*/
public function edit($id)
{
return view('location::edit');
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id): RedirectResponse
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
//
}
}

View File

@@ -2,32 +2,57 @@
namespace Modules\Location\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Models\Province;
use Modules\Location\Exports\ProvincesExport;
use Modules\Location\Http\Requests\ProvinceRequest;
use Modules\Location\Models\Province;
class ProvincesController extends Controller
{
public $user;
protected $user;
public function __construct()
{
// Mengatur middleware auth
$this->middleware('auth');
// Mengatur user setelah middleware auth dijalankan
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
public function index(){
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to view provinces.');
}
return view('location::provinces.index');
}
public function create(){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create provinces.');
}
return view('location::provinces.create');
}
public function store(ProvinceRequest $request){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create provinces.');
}
$validate = $request->validated();
if($validate){
try{
// Save to database
$province = Province::create($validate);
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');
@@ -36,11 +61,19 @@ class ProvincesController extends Controller
}
public function edit($id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update provinces.');
}
$province = Province::find($id);
return view('location::provinces.create', compact('province'));
}
public function update(ProvinceRequest $request, $id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update provinces.');
}
$validate = $request->validated();
if($validate){
@@ -56,20 +89,24 @@ class ProvincesController extends Controller
}
public function destroy($id){
if (is_null($this->user) || !$this->user->can('location.delete')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to delete provinces.']);
}
try{
// Delete from database
$province = Province::find($id);
$province->delete();
echo json_encode(['success' => true, 'message' => 'Province deleted successfully']);
return response()->json(['success' => true, 'message' => 'Province deleted successfully']);
} catch (\Exception $e){
echo json_encode(['success' => false, 'message' => 'Failed to delete province']);
return response()->json(['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.');
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view provinces.']);
}
// Retrieve data from the database
@@ -107,7 +144,7 @@ class ProvincesController extends Controller
$filteredRecords = $query->count();
// Get the data for the current page
$provinces = $query->get();
$data = $query->get();
// Calculate the page count
$pageCount = ceil($totalRecords/$request->get('size'));
@@ -123,12 +160,16 @@ class ProvincesController extends Controller
'pageCount' => $pageCount,
'page' => $currentPage,
'totalCount' => $totalRecords,
'data' => $provinces,
'data' => $data,
]);
}
public function export()
{
if (is_null($this->user) || !$this->user->can('location.export')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to export provinces.']);
}
return Excel::download(new ProvincesExport, 'provinces.xlsx');
}
}

View File

@@ -0,0 +1,243 @@
<?php
namespace Modules\Location\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Exports\VillagesExport;
use Modules\Location\Http\Requests\VillageRequest;
use Modules\Location\Models\City;
use Modules\Location\Models\District;
use Modules\Location\Models\Province;
use Modules\Location\Models\Village;
use Exception;
class VillagesController extends Controller
{
protected $user;
public function __construct()
{
// Mengatur middleware auth
$this->middleware('auth');
// Mengatur user setelah middleware auth dijalankan
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
/**
* Display a listing of the resource.
*/
public function index()
{
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to view villages.');
}
$provinces = Province::all();
return view('location::villages.index',compact('provinces'));
}
public function store(VillageRequest $request)
{
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create villages.');
}
$validate = $request->validated();
if ($validate) {
try {
Village::create($validate);
return redirect()
->route('locations.villages.index')
->with('success', 'Village created successfully');
} catch (Exception $e) {
return redirect()->back()->with('error', 'Failed to create village. ' . $e->getMessage());
}
}
}
public function create()
{
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create villages.');
}
$provinces = Province::all();
return view('location::villages.create', compact('provinces'));
}
public function edit($id)
{
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update villages.');
}
$village = Village::find($id);
$provinces = Province::all();
$cities = City::where('province_code', $village->province_code)->get();
$districts = District::where('city_code', $village->city_code)->get();
return view('location::villages.create', compact('village', 'provinces', 'cities', 'districts'));
}
public function update(VillageRequest $request, $id)
{
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update villages.');
}
$validate = $request->validated();
if ($validate) {
try {
$village = Village::find($id);
$village->update($validate);
return redirect()
->route('locations.villages.index')
->with('success', 'Village updated successfully');
} catch (Exception $e) {
return redirect()->back()->with('error', 'Failed to update village. ' . $e->getMessage());
}
}
}
public function destroy($id)
{
if (is_null($this->user) || !$this->user->can('location.delete')) {
return response()->json(['success' => false,'message' => 'Sorry! You are not allowed to delete villages.'], 403);
}
try {
Village::destroy($id);
return json_encode(['message' => 'Village deleted successfully', 'success' => true]);
} catch (Exception $e) {
return json_encode(['message' => 'Failed to delete Village', 'success' => false]);
}
}
public function export(Request $request)
{
if (is_null($this->user) || !$this->user->can('location.export')) {
abort(403, 'Sorry! You are not allowed to export villages.');
}
return Excel::download(new VillagesExport, 'villages.xlsx');
}
public function dataForDatatables(Request $request)
{
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false,'message' => 'Sorry! You are not allowed to view villages.'], 403);
}
// Retrieve data from the database
$query = Village::query();
// Apply search filter if provided
if ($request->has('search') && !empty($request->get('search'))) {
$search = $request->get('search');
$search = explode('|', $search);
if(isset($search[0]) && !empty($search[0])){
// Define special city codes once
$specialCityCodes = ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'];
// Handle Papua province special cases
if($search[0] == '92'){
$query->where('province_code', '92')
->whereNotIn('city_code', $specialCityCodes);
} else if($search[0] == '92.1'){
$query->where('province_code', '92')
->whereIn('city_code', $specialCityCodes);
} else {
// For all other provinces
$query->where('province_code', $search[0]);
}
}
if(isset($search[1]) &&!empty($search[1])){
$query->where('city_code',$search[1]);
}
if(isset($search[2]) &&!empty($search[2])){
$query->where('district_code',$search[2]);
}
$query->where(function ($q) use ($search) {
$q->where('code', 'LIKE', "%$search[3]%");
$q->orWhere('name', 'LIKE', "%$search[3]%");
});
}
// 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
$data = $query->with('district.city.province')->get();
// Calculate the page count
$pageCount = ceil($totalRecords / $request->get('size'));
// Calculate the current page number
$currentPage = 0 + 1;
$data = $data->map(function ($item) {
if (in_array($item->city_code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->district->city->province->name;
}
return $item;
});
// 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' => $data,
]);
}
public function getVillagesByDistrictId($id){
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false,'message' => 'Sorry! You are not allowed to view villages.'], 403);
}
return response()->json(Village::where('district_code', $id)->get());
}
public function getPostalCodesByVillageId($id){
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false,'message' => 'Sorry! You are not allowed to view villages.'], 403);
}
return response()->json(Village::where('code', $id)->first());
}
}

View File

@@ -18,10 +18,10 @@
];
if ($this->method() === 'PUT') {
$rules['code'] = 'required|string|max:6|unique:districts,code,' . $this->id;
$rules['code'] = 'required|string|max:9|unique:districts,code,' . $this->id;
$rules['name'] = 'required|string|max:2554|unique:districts,name,' . $this->id;
} else {
$rules['code'] = 'required|string|max:6|unique:districts,code';
$rules['code'] = 'required|string|max:9|unique:districts,code';
$rules['name'] = 'required|string|max:2554|unique:districts,name';
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Modules\Location\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class VillageRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*/
public function rules()
: array
{
$rules = [
'province_code' => 'required|exists:provinces,code',
'city_code' => 'required|exists:cities,code',
'district_code' => 'required|exists:districts,code',
'postal_code' => 'required|string|max:5',
'alt_name' => 'nullable|string|max:255',
];
if ($this->method() === 'PUT') {
$rules['code'] = 'required|string|max:13|unique:villages,code,' . $this->id;
$rules['name'] = 'required|string|max:2554|unique:villages,name,' . $this->id;
} else {
$rules['code'] = 'required|string|max:13|unique:villages,code';
$rules['name'] = 'required|string|max:2554|unique:villages,name';
}
return $rules;
}
/**
* Determine if the user is authorized to make this request.
*/
public function authorize()
: bool
{
return true;
}
}

View File

@@ -5,7 +5,7 @@
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Wildside\Userstamps\Userstamps;
use Mattiverse\Userstamps\Traits\Userstamps;
/**

17
app/Models/Village.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
namespace Modules\Location\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Modules\Location\Database\Factories\VillageFactory;
class Village extends Base
{
protected $fillable = ['province_code','city_code','district_code', 'code', 'name','alt_name','postal_code'];
public function district(){
return $this->belongsTo(District::class, 'district_code', 'code');
}
}

View File

@@ -14,7 +14,7 @@ return new class extends Migration
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->string('province_code')->index();
$table->string('code');
$table->string('code')->index();
$table->string('name');
$table->timestamps();
$table->softDeletes();

View File

@@ -15,7 +15,7 @@ return new class extends Migration
$table->id();
$table->string('province_code')->index();
$table->string('city_code')->index();
$table->string('code');
$table->string('code')->index();
$table->string('name');
$table->timestamps();
$table->softDeletes();

View File

@@ -0,0 +1,38 @@
<?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('villages', function (Blueprint $table) {
$table->id();
$table->string('province_code')->index();
$table->string('city_code')->index();
$table->string('district_code')->index();
$table->string('code')->index();
$table->string('name');
$table->string('alt_name')->nullable();
$table->string('postal_code', 5)->nullable();
$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('villages');
}
};

View File

@@ -23,7 +23,9 @@
public function data()
{
return [
// return = [
$originalData = [
['province_code' => 11, 'code' => '11.01', 'name' => 'KAB. ACEH SELATAN'],
['province_code' => 11, 'code' => '11.02', 'name' => 'KAB. ACEH TENGGARA'],
['province_code' => 11, 'code' => '11.03', 'name' => 'KAB. ACEH TIMUR'],
@@ -540,5 +542,15 @@
['province_code' => 92, 'code' => '92.71', 'name' => 'KOTA SORONG'],
];
$formattedData = array_map(function ($item) {
$item['name'] = ucwords(strtolower($item['name']));
return $item;
}, $originalData);
return $formattedData;
}
}

View File

@@ -13,9 +13,11 @@ class LocationDatabaseSeeder extends Seeder
public function run(): void
{
$this->call([
PermissionSeeder::class,
ProvinceSeeder::class,
CitySeeder::class,
DistrictSeeder::class,
VillageSeeder::class,
]);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Modules\Location\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Modules\Usermanagement\Models\PermissionGroup;
class PermissionSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run()
{
$data = $this->data();
foreach ($data as $value) {
PermissionGroup::updateOrCreate([
'name' => $value['name'],
'slug' => Str::slug($value['name'])
]);
}
}
public function data()
{
return [
['name' => 'location']
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Modules\Location\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class VillageSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
try {
DB::unprepared(file_get_contents(__DIR__ . '/villages.sql'));
} catch (\Exception $e) {
Log::error('Seeder Error: ' . $e->getMessage());
throw $e;
}
}
}

83467
database/seeders/villages.sql Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -15,11 +15,13 @@
{
"title": "Locations",
"path": "locations",
"icon": "ki-filled ki-map text-lg",
"icon": "ki-filled ki-map text-lg text-primary",
"classes": "",
"attributes": [],
"permission": "",
"roles": [],
"roles": [
"administrator"
],
"sub": [
{
"title": "Provinces",
@@ -27,7 +29,9 @@
"classes": "",
"attributes": [],
"permission": "",
"roles": []
"roles": [
"administrator"
]
},
{
"title": "Cities",
@@ -35,7 +39,9 @@
"classes": "",
"attributes": [],
"permission": "",
"roles": []
"roles": [
"administrator"
]
},
{
"title": "Districts",
@@ -43,15 +49,19 @@
"classes": "",
"attributes": [],
"permission": "",
"roles": []
"roles": [
"administrator"
]
},
{
"title": "Villages",
"path": "",
"path": "locations.villages",
"classes": "",
"attributes": [],
"permission": "",
"roles": []
"roles": [
"administrator"
]
}
]
}

View File

@@ -2,29 +2,32 @@ import TomSelect from "tom-select";
let settings = {
plugins: ['dropdown_input'],
create: true,
create: false,
createOnBlur: true
};
const provinceSelect = document.querySelector('#province_code');
const citySelect = document.querySelector('#city_code');
const districtSelect = document.querySelector('#district_code');
const villageSelect = document.querySelector('#village_code');
const postalCode = document.querySelector('#postal_code');
if (provinceSelect && !citySelect) {
new TomSelect('#province_code', settings);
}
if (citySelect) {
var tomcities = new TomSelect('#city_code', settings);
var tomprovince = new TomSelect('#province_code', {
if (citySelect && !districtSelect) {
let tomcities = new TomSelect('#city_code', settings);
let tomprovince = new TomSelect('#province_code', {
...settings, // Spread existing settings
onChange: function (value) {
console.log('Province selected 1:', value);
// Destroy only if necessary (prevents unnecessary re-initialization)
if (tomcities) {
tomcities.destroy();
}
var url = 'locations/cities/province/' + value;
let url = 'locations/cities/province/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
@@ -44,3 +47,208 @@ if (citySelect) {
}
});
}
if (districtSelect && !villageSelect) {
let tomdistrict = new TomSelect('#district_code', settings);
let tomcities = new TomSelect('#city_code', {
...settings,
onChange: function (value) {
console.log('City selected:', value);
// Destroy only if necessary (prevents unnecessary re-initialization)
if (tomdistrict) {
tomdistrict.destroy();
}
let url = 'locations/districts/city/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
const options = data.map(item => ({
value: item.code,
text: item.name
}));
tomdistrict = new TomSelect('#district_code', {
...settings, // Spread existing settings (including createOnBlur: false)
options: options
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
});
let tomprovince = new TomSelect('#province_code', {
...settings, // Spread existing settings
onChange: function (value) {
console.log('Province selected:', value);
// Destroy only if necessary (prevents unnecessary re-initialization)
if (tomcities) {
tomcities.destroy();
}
let url = 'locations/cities/province/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
const options = data.map(item => ({
value: item.code,
text: item.name
}));
tomcities = new TomSelect('#city_code', {
...settings, // Spread existing settings (including createOnBlur: false)
options: options,
onChange: function (value) {
console.log('City selected:', value);
// Destroy only if necessary (prevents unnecessary re-initialization)
if (tomdistrict) {
tomdistrict.destroy();
}
let url = 'locations/districts/city/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
const options = data.map(item => ({
value: item.code,
text: item.name
}));
tomdistrict = new TomSelect('#district_code', {
...settings, // Spread existing settings (including createOnBlur: false)
options: options
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
});
}
if (villageSelect) {
let tomvillage, tomdistrict, tomcities, tomprovince;
const resetFields = (fromLevel) => {
if (fromLevel <= 1) {
citySelect.value = "";
if (tomcities) tomcities.clear();
}
if (fromLevel <= 2) {
districtSelect.value = "";
if (tomdistrict) tomdistrict.clear();
}
if (fromLevel <= 3) {
villageSelect.value = "";
if (tomvillage) tomvillage.clear();
}
if (postalCode) postalCode.value = "";
};
tomvillage = new TomSelect('#village_code', settings);
tomdistrict = new TomSelect('#district_code', {
...settings,
onChange: function (value) {
resetFields(3);
if (value) {
let url = 'locations/villages/district/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
const options = data.map(item => ({
value: item.code,
text: item.name
}));
tomvillage.clear();
tomvillage.clearOptions();
tomvillage.addOptions(options);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
});
tomcities = new TomSelect('#city_code', {
...settings,
onChange: function (value) {
resetFields(2);
if (value) {
let url = 'locations/districts/city/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
const options = data.map(item => ({
value: item.code,
text: item.name
}));
tomdistrict.clear();
tomdistrict.clearOptions();
tomdistrict.addOptions(options);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
});
tomprovince = new TomSelect('#province_code', {
...settings,
onChange: function (value) {
resetFields(1);
if (value) {
let url = 'locations/cities/province/' + value;
fetch(url)
.then(response => response.json())
.then(data => {
const options = data.map(item => ({
value: item.code,
text: item.name
}));
tomcities.clear();
tomcities.clearOptions();
tomcities.addOptions(options);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
});
if (postalCode) {
villageSelect.addEventListener('change', function (event) {
if (event.target.value) {
fetch('locations/villages/postal-code/' + event.target.value)
.then(response => response.json())
.then(data => {
postalCode.value = data.postal_code;
})
.catch(error => {
console.error('Error fetching postal code:', error);
});
} else {
postalCode.value = "";
}
});
}
}

View File

@@ -4,84 +4,80 @@
{{ Breadcrumbs::render('locations.cities') }}
@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="cities-table" data-api-url="{{ route('locations.cities.datatables') }}">
<div class="card-header py-5 flex-wrap">
<h3 class="card-title">
List of Cities
</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 cities" id="search" type="text" value="">
@push('styles')
<style>
.ts-dropdown,
.ts-control,
.ts-control input {
| font-size: 12 px;
line-height: 14px !important;
}
</style
@endpush
</label>
</div>
<div class="flex flex-wrap gap-2.5">
<select class="select select-sm w-28">
<option value="1">
Active
@section('content')
<div class="grid">
<div class="card card-grid min-w-full" data-datatable="false" data-datatable-page-size="5" data-datatable-state-save="false" id="cities-table" data-api-url="{{ route('locations.cities.datatables') }}">
<div class="card-header py-5 flex-wrap">
<h3 class="card-title">
List of Cities
</h3>
<div class="flex flex-wrap gap-2 lg:gap-5">
<div class="flex flex-wrap gap-2.5">
<select id="province_code" name="province_code" class="select select-sm w-[150px]">
<option value="">Select Province</option>
@foreach($provinces as $province)
<option value="{{ $province->code }}">
{{ $province->name }}
</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.cities.export') }}"> Export to Excel </a>
<a class="btn btn-sm btn-primary" href="{{ route('locations.cities.create') }}"> Add City </a>
</div>
@endforeach
</select>
<label class="input input-sm w-[150px]"> <i class="ki-filled ki-magnifier"> </i>
<input placeholder="Search Cities" id="search" type="text" value="">
</label>
<button class="search btn btn-sm btn-outline btn-primary">
<i class="ki-filled ki-setting-4"> </i>
</button>
<div class="border border-r-gray-200"></div>
<a class="btn btn-sm btn-light" href="{{ route('locations.cities.export') }}"> Export to Excel </a>
<a class="btn btn-sm btn-primary" href="{{ route('locations.cities.create') }}"> Add City </a>
</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"> City </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="province">
<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-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"> City </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="province">
<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="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 class="flex items-center gap-4">
<span data-datatable-info="true"> </span>
<div class="pagination" data-datatable-pagination="true">
</div>
</div>
</div>
@@ -96,7 +92,7 @@
function deleteData(data) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!" + data,
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
@@ -113,7 +109,7 @@
$.ajax(`locations/cities/${data}`, {
type: 'DELETE'
}).then((response) => {
swal.fire('Deleted!', 'User has been deleted.','success').then(() => {
swal.fire('Deleted!', 'User has been deleted.', 'success').then(() => {
window.location.reload();
});
}).catch((error) => {
@@ -127,6 +123,7 @@
<script type="module">
const element = document.querySelector('#cities-table');
const searchInput = document.getElementById('search');
const searchButton = document.querySelector('.search');
const apiUrl = element.getAttribute('data-api-url');
const dataTableOptions = {
@@ -152,7 +149,7 @@
province: {
title: 'Province',
render: (item, data) => {
return data.province.name;
return data.province_name;
}
},
actions: {
@@ -173,9 +170,16 @@
let dataTable = new KTDataTable(element, dataTableOptions);
// Custom search functionality
searchInput.addEventListener('input', function () {
const searchValue = this.value.trim();
dataTable.search(searchValue, true);
searchInput.addEventListener('keyup', function () {
const _province = document.getElementById('province_code').value;
const _search = searchInput.value.trim();
dataTable.search(`${_province}|${_search}`, true);
});
searchButton.addEventListener('click', function () {
const _province = document.getElementById('province_code').value;
const _search = searchInput.value.trim();
dataTable.search(`${_province}|${_search}`, true);
});
</script>
@endpush

View File

@@ -17,7 +17,7 @@
<div class="card pb-2.5">
<div class="card-header" id="basic_settings">
<h3 class="card-title">
{{ isset($district->id) ? 'Edit' : 'Add' }} City
{{ isset($district->id) ? 'Edit' : 'Add' }} District
</h3>
<div class="flex items-center gap-2">
<a href="{{ route('locations.districts.index') }}" class="btn btn-xs btn-info">Back</a>

View File

@@ -4,88 +4,88 @@
{{ Breadcrumbs::render('locations.districts') }}
@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="districts-table" data-api-url="{{ route('locations.districts.datatables') }}">
<div class="card-header py-5 flex-wrap">
<h3 class="card-title">
List of Districts
</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 districts" id="search" type="text" value="">
@push('styles')
<style>
.ts-dropdown,
.ts-control,
.ts-control input {
| font-size: 12 px;
line-height: 14px !important;
}
</style
@endpush
</label>
</div>
<div class="flex flex-wrap gap-2.5">
<select class="select select-sm w-28">
<option value="1">
Active
@section('content')
<div class="grid">
<div class="card card-grid min-w-full" data-datatable="false" data-datatable-page-size="5" data-datatable-state-save="false" id="districts-table" data-api-url="{{ route('locations.districts.datatables') }}">
<div class="card-header py-5 flex-wrap">
<h3 class="card-title">
List of Districts
</h3>
<div class="flex flex-wrap gap-2 lg:gap-5">
<div class="flex flex-wrap gap-2.5">
<select id="province_code" name="province_code" class="select select-sm w-[150px]">
<option value="">Select Province</option>
@foreach($provinces as $province)
<option value="{{ $province->code }}">
{{ $province->name }}
</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.districts.export') }}"> Export to Excel </a>
<a class="btn btn-sm btn-primary" href="{{ route('locations.districts.create') }}"> Add District </a>
</div>
@endforeach
</select>
<select id="city_code" name="city_code" class="select select-sm w-[250px]">
<option value="">Select City</option>
</select>
<label class="input input-sm w-[150px]"> <i class="ki-filled ki-magnifier"> </i>
<input placeholder="Search Districts" id="search" type="text" value="">
</label>
<button class="search btn btn-sm btn-outline btn-primary">
<i class="ki-filled ki-setting-4"> </i>
</button>
<div class="border border-r-gray-200"></div>
<a class="btn btn-sm btn-light" href="{{ route('locations.districts.export') }}"> Export to Excel </a>
<a class="btn btn-sm btn-primary" href="{{ route('locations.districts.create') }}"> Add District </a>
</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"> District </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="city">
<span class="sort"> <span class="sort-label"> City </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="province">
<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-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"> District </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="city">
<span class="sort"> <span class="sort-label"> City </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="province">
<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="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 class="flex items-center gap-4">
<span data-datatable-info="true"> </span>
<div class="pagination" data-datatable-pagination="true">
</div>
</div>
</div>
@@ -100,7 +100,7 @@
function deleteData(data) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!" + data,
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
@@ -117,7 +117,7 @@
$.ajax(`locations/districts/${data}`, {
type: 'DELETE'
}).then((response) => {
swal.fire('Deleted!', 'User has been deleted.','success').then(() => {
swal.fire('Deleted!', 'User has been deleted.', 'success').then(() => {
window.location.reload();
});
}).catch((error) => {
@@ -131,11 +131,13 @@
<script type="module">
const element = document.querySelector('#districts-table');
const searchInput = document.getElementById('search');
const searchButton = document.querySelector('.search');
const apiUrl = element.getAttribute('data-api-url');
const dataTableOptions = {
apiEndpoint: apiUrl,
pageSize: 5,
responsive: true,
columns: {
select: {
render: (item, data, context) => {
@@ -162,7 +164,7 @@
province: {
title: 'Province',
render: (item, data) => {
return data.city.province.name;
return data.province_name;
}
},
actions: {
@@ -183,9 +185,18 @@
let dataTable = new KTDataTable(element, dataTableOptions);
// Custom search functionality
searchInput.addEventListener('input', function () {
const searchValue = this.value.trim();
dataTable.search(searchValue, true);
searchInput.addEventListener('keyup', function () {
const _province = document.getElementById('province_code').value;
const _city = document.getElementById('city_code').value;
const _search = searchInput.value.trim();
dataTable.search(`${_province}|${_city}|${_search}`, true);
});
searchButton.addEventListener('click', function () {
const _province = document.getElementById('province_code').value;
const _city = document.getElementById('city_code').value;
const _search = searchInput.value.trim();
dataTable.search(`${_province}|${_city}|${_search}`, true);
});
</script>
@endpush

View File

@@ -5,79 +5,54 @@
@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 class="grid">
<div class="card card-grid min-w-full" data-datatable="false" data-datatable-page-size="5" data-datatable-state-save="false" 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="border border-r-gray-200"></div>
<div class="flex flex-wrap gap-2.5">
<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 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-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="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 class="flex items-center gap-4">
<span data-datatable-info="true"> </span>
<div class="pagination" data-datatable-pagination="true">
</div>
</div>
</div>
@@ -92,7 +67,7 @@
function deleteData(data) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!" + data,
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
@@ -109,7 +84,7 @@
$.ajax(`locations/provinces/${data}`, {
type: 'DELETE'
}).then((response) => {
swal.fire('Deleted!', 'User has been deleted.','success').then(() => {
swal.fire('Deleted!', 'User has been deleted.', 'success').then(() => {
window.location.reload();
});
}).catch((error) => {
@@ -141,6 +116,9 @@
},
code: {
title: 'Code',
render: (item, data) => {
return `${data.code.substring(0, 2)}`;
},
},
name: {
title: 'Province',
@@ -165,7 +143,9 @@
// Custom search functionality
searchInput.addEventListener('input', function () {
const searchValue = this.value.trim();
dataTable.search(searchValue, true);
if (searchValue.length > 3) {
dataTable.search(searchValue, true);
}
});
</script>
@endpush

View File

@@ -0,0 +1,161 @@
@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($village->id))
<form action="{{ route('locations.villages.update', $village->id) }}" method="POST">
<input type="hidden" name="id" value="{{ $village->id }}">
@method('PUT')
@else
<form method="POST" action="{{ route('locations.villages.store') }}">
@endif
@csrf
<div class="card pb-2.5">
<div class="card-header" id="basic_settings">
<h3 class="card-title">
{{ isset($village->id) ? 'Edit' : 'Add' }} Village
</h3>
<div class="flex items-center gap-2">
<a href="{{ route('locations.villages.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">
Province
</label>
<div class="flex flex-wrap items-baseline w-full">
<select id="province_code" name="province_code" class="select w-full @error('province_code') border-danger @enderror">
<option value="">Select Province</option>
@foreach($provinces as $province)
@if(isset($village))
<option value="{{ $province->code }}" {{ isset($village->province_code) && $village->province_code == $province->code?'selected' : '' }}>
{{ $province->name }}
</option>
@else
<option value="{{ $province->code }}">
{{ $province->name }}
</option>
@endif
@endforeach
</select>
@error('province_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">
City
</label>
<div class="flex flex-wrap items-baseline w-full">
<select id="city_code" name="city_code" class="select w-full @error('city_code') border-danger @enderror">
<option value="">Select City</option>
@if(isset($cities))
@foreach($cities as $city)
@if(isset($village))
<option value="{{ $city->code }}" {{ isset($village->city_code) && $village->city_code == $city->code?'selected' : '' }}>
{{ $city->name }}
</option>
@else
<option value="{{ $city->code }}">
{{ $city->name }}
</option>
@endif
@endforeach
@endif
</select>
@error('city_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">
District
</label>
<div class="flex flex-wrap items-baseline w-full">
<select id="district_code" name="district_code" class="select w-full @error('district_code') border-danger @enderror">
<option value="">Select District</option>
@if(isset($districts))
@foreach($districts as $district)
@if(isset($village))
<option value="{{ $district->code }}" {{ isset($village->district_code) && $village->district_code == $district->code?'selected' : '' }}>
{{ $district->name }}
</option>
@else
<option value="{{ $district->code }}">
{{ $district->name }}
</option>
@endif
@endforeach
@endif
</select>
@error('district_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">
Code
</label>
<div class="flex flex-wrap items-baseline w-full">
<input class="input @error('code') border-danger @enderror" type="text" name="code" value="{{ $village->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="{{ $village->name ?? '' }}">
@error('name')
<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">
Alternative Name
</label>
<div class="flex flex-wrap items-baseline w-full">
<input class="input @error('alt_name') border-danger @enderror" type="text" name="alt_name" value="{{ $village->alt_name ?? '' }}">
@error('alt_name')
<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">
Postal Code
</label>
<div class="flex flex-wrap items-baseline w-full">
<input class="input @error('postal_code') border-danger @enderror" type="number" name="postal_code" value="{{ $village->postal_code ?? '' }}">
@error('postal_code')
<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
@push('scripts')
@endpush

View File

@@ -0,0 +1,233 @@
@extends('layouts.main')
@section('breadcrumbs')
{{ Breadcrumbs::render('locations.villages') }}
@endsection
@push('styles')
<style>
.ts-dropdown,
.ts-control,
.ts-control input {
| font-size: 12 px;
line-height: 14px !important;
}
</style
@endpush
@section('content')
<div class="grid">
<div class="card card-grid min-w-full" data-datatable="false" data-datatable-page-size="5" data-datatable-state-save="false" id="villages-table" data-api-url="{{ route('locations.villages.datatables') }}">
<div class="card-header py-5 flex-wrap">
<h3 class="card-title">
List of Vilalges
</h3>
<div class="flex flex-wrap gap-2">
<div class="flex flex-wrap gap-1.5">
<select id="province_code" name="province_code" class="select select-sm w-[150px]">
<option value="">Select Province</option>
@foreach($provinces as $province)
<option value="{{ $province->code }}">
{{ $province->name }}
</option>
@endforeach
</select>
<select id="city_code" name="city_code" class="select select-sm w-[250px]">
<option value="">Select City</option>
</select>
<select id="district_code" name="district_code" class="select select-sm w-[150px]">
<option value="">Select District</option>
</select>
<label class="input input-sm w-[150px]"> <i class="ki-filled ki-magnifier"> </i>
<input placeholder="Search villages" id="search" type="text" value="">
</label>
<button class="search btn btn-sm btn-outline btn-primary">
<i class="ki-filled ki-setting-4"> </i>
</button>
<div class="border border-r-gray-200"></div>
<a class="btn btn-sm btn-light" href="{{ route('locations.villages.export') }}"> Export to Excel </a>
<a class="btn btn-sm btn-primary" href="{{ route('locations.villages.create') }}"> Add District </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-[100px]" 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"> Village </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="alt_name">
<span class="sort"> <span class="sort-label"> Alternative Name </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[50px]" data-datatable-column="postal_code">
<span class="sort"> <span class="sort-label"> Postal Code </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="district">
<span class="sort"> <span class="sort-label"> District </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="city">
<span class="sort"> <span class="sort-label"> City </span>
<span class="sort-icon"> </span> </span>
</th>
<th class="min-w-[250px]" data-datatable-column="province">
<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>
@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!",
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/villages/${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('#villages-table');
const searchInput = document.getElementById('search');
const searchButton = document.querySelector('.search');
const apiUrl = element.getAttribute('data-api-url');
const dataTableOptions = {
apiEndpoint: apiUrl,
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: 'Village',
},
alt_name: {
title: 'Alternative Name',
},
postal_code: {
title: 'Postal Code',
},
district: {
title: 'District',
render: (item, data) => {
return data.district.name;
}
},
city: {
title: 'City',
render: (item, data) => {
return data.district.city.name;
}
},
province: {
title: 'Province',
render: (item, data) => {
return data.province_name;
}
},
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/villages/${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);
dataTable.showSpinner();
// Custom search functionality
searchInput.addEventListener('keyup', function () {
const _province = document.getElementById('province_code').value;
const _city = document.getElementById('city_code').value;
const _district = document.getElementById('district_code').value;
const _search = searchInput.value.trim();
dataTable.search(`${_province}|${_city}|${_district}|${_search}`, true);
});
searchButton.addEventListener('click', function () {
const _province = document.getElementById('province_code').value;
const _city = document.getElementById('city_code').value;
const _district = document.getElementById('district_code').value;
const _search = searchInput.value.trim();
dataTable.search(`${_province}|${_city}|${_district}|${_search}`, true);
});
</script>
@endpush

View File

@@ -13,7 +13,3 @@ use Modules\Location\Http\Controllers\LocationController;
* is assigned the "api" middleware group. Enjoy building your API!
*
*/
Route::middleware(['auth:sanctum'])->prefix('v1')->group(function () {
Route::apiResource('location', LocationController::class)->names('location');
});

View File

@@ -57,3 +57,19 @@
$trail->parent('locations.districts');
$trail->push('Edit District');
});
//Villages
Breadcrumbs::for('locations.villages', function (BreadcrumbTrail $trail) {
$trail->parent('locations');
$trail->push('Villages', route('locations.villages.index'));
});
Breadcrumbs::for('locations.villages.create', function (BreadcrumbTrail $trail) {
$trail->parent('locations.villages');
$trail->push('Create Village', route('locations.villages.create'));
});
Breadcrumbs::for('locations.villages.edit', function (BreadcrumbTrail $trail) {
$trail->parent('locations.villages');
$trail->push('Edit Village');
});

View File

@@ -5,6 +5,7 @@ use Illuminate\Support\Facades\Route;
use Modules\Location\Http\Controllers\DistrictsController;
use Modules\Location\Http\Controllers\LocationController;
use Modules\Location\Http\Controllers\ProvincesController;
use Modules\Location\Http\Controllers\VillagesController;
/*
|--------------------------------------------------------------------------
@@ -41,5 +42,14 @@ use Illuminate\Support\Facades\Route;
Route::get('city/{city_code}', [DistrictsController::class, 'getDistrictsByCityId'])->name('city');
});
Route::resource('districts', DistrictsController::class);
Route::name('villages.')->prefix('villages')->group(function () {
Route::get('restore/{id}', [VillagesController::class, 'restore'])->name('restore');
Route::get('datatables', [VillagesController::class, 'dataForDatatables'])->name('datatables');
Route::get('export', [VillagesController ::class, 'export'])->name('export');
Route::get('district/{district_code}', [VillagesController::class, 'getVillagesByDistrictId'])->name('district');
Route::get('postal-code/{village_code}', [VillagesController::class, 'getPostalCodesByVillageId'])->name('postalcode');
});
Route::resource('villages', VillagesController::class);
});
});