add spatial plannings retribution calculations
This commit is contained in:
288
app/Console/Commands/CalculateRetributionProposalsCommand.php
Normal file
288
app/Console/Commands/CalculateRetributionProposalsCommand.php
Normal file
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\Models\SpatialPlanning;
|
||||
use App\Models\RetributionProposal;
|
||||
use App\Services\RetributionProposalService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Exception;
|
||||
|
||||
class CalculateRetributionProposalsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'retribution:calculate-proposals
|
||||
{--force : Force recalculate existing proposals}
|
||||
{--limit= : Limit number of spatial plannings to process}
|
||||
{--skip-existing : Skip spatial plannings that already have proposals}
|
||||
{--dry-run : Show what would be processed without actually creating proposals}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Calculate retribution proposals for all spatial plannings';
|
||||
|
||||
protected RetributionProposalService $proposalService;
|
||||
|
||||
public function __construct(RetributionProposalService $proposalService)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->proposalService = $proposalService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->info('🧮 Starting Retribution Proposal Calculation...');
|
||||
$this->newLine();
|
||||
|
||||
try {
|
||||
// Get processing options
|
||||
$force = $this->option('force');
|
||||
$limit = $this->option('limit') ? (int) $this->option('limit') : null;
|
||||
$skipExisting = $this->option('skip-existing');
|
||||
$dryRun = $this->option('dry-run');
|
||||
|
||||
// Build query for spatial plannings
|
||||
$query = SpatialPlanning::query();
|
||||
|
||||
if ($skipExisting && !$force) {
|
||||
$query->whereDoesntHave('retributionProposals');
|
||||
}
|
||||
|
||||
if ($limit) {
|
||||
$query->limit($limit);
|
||||
}
|
||||
|
||||
$spatialPlannings = $query->get();
|
||||
$totalCount = $spatialPlannings->count();
|
||||
|
||||
if ($totalCount === 0) {
|
||||
$this->warn('No spatial plannings found to process.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Show processing summary
|
||||
$this->info("📊 PROCESSING SUMMARY:");
|
||||
$this->info(" Total Spatial Plannings: {$totalCount}");
|
||||
$this->info(" Force Recalculate: " . ($force ? 'Yes' : 'No'));
|
||||
$this->info(" Skip Existing: " . ($skipExisting ? 'Yes' : 'No'));
|
||||
$this->info(" Dry Run: " . ($dryRun ? 'Yes' : 'No'));
|
||||
$this->newLine();
|
||||
|
||||
if ($dryRun) {
|
||||
$this->showDryRunPreview($spatialPlannings);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Confirm processing
|
||||
if (!$this->confirm("Process {$totalCount} spatial plannings?")) {
|
||||
$this->info('Operation cancelled.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Process spatial plannings
|
||||
$this->processRetributionCalculations($spatialPlannings, $force);
|
||||
|
||||
return 0;
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->error('Error during retribution calculation: ' . $e->getMessage());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show dry run preview
|
||||
*/
|
||||
private function showDryRunPreview($spatialPlannings)
|
||||
{
|
||||
$this->info('🔍 DRY RUN PREVIEW:');
|
||||
$this->newLine();
|
||||
|
||||
$processable = 0;
|
||||
$withProposals = 0;
|
||||
$withoutFunction = 0;
|
||||
$withoutArea = 0;
|
||||
|
||||
foreach ($spatialPlannings as $spatial) {
|
||||
$hasProposals = $spatial->retributionProposals()->exists();
|
||||
$buildingFunction = $this->proposalService->detectBuildingFunction($spatial->getBuildingFunctionText());
|
||||
$area = $spatial->getCalculationArea();
|
||||
|
||||
if ($hasProposals) {
|
||||
$withProposals++;
|
||||
}
|
||||
|
||||
if (!$buildingFunction) {
|
||||
$withoutFunction++;
|
||||
}
|
||||
|
||||
if ($area <= 0) {
|
||||
$withoutArea++;
|
||||
}
|
||||
|
||||
if ($buildingFunction && $area > 0) {
|
||||
$processable++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->table(
|
||||
['Status', 'Count', 'Description'],
|
||||
[
|
||||
['✅ Processable', $processable, 'Can create retribution proposals'],
|
||||
['🔄 With Existing Proposals', $withProposals, 'Already have proposals (will skip unless --force)'],
|
||||
['❌ Missing Building Function', $withoutFunction, 'Cannot detect building function'],
|
||||
['❌ Missing Area', $withoutArea, 'Area is zero or missing'],
|
||||
]
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
$this->info("💡 To process: php artisan retribution:calculate-proposals");
|
||||
$this->info("💡 To force recalculate: php artisan retribution:calculate-proposals --force");
|
||||
}
|
||||
|
||||
/**
|
||||
* Process retribution calculations
|
||||
*/
|
||||
private function processRetributionCalculations($spatialPlannings, $force)
|
||||
{
|
||||
$progressBar = $this->output->createProgressBar($spatialPlannings->count());
|
||||
$progressBar->start();
|
||||
|
||||
$stats = [
|
||||
'processed' => 0,
|
||||
'skipped' => 0,
|
||||
'errors' => 0,
|
||||
'created_proposals' => 0
|
||||
];
|
||||
|
||||
foreach ($spatialPlannings as $spatial) {
|
||||
try {
|
||||
$result = $this->processSingleSpatialPlanning($spatial, $force);
|
||||
|
||||
if ($result['status'] === 'processed') {
|
||||
$stats['processed']++;
|
||||
$stats['created_proposals'] += $result['proposals_created'];
|
||||
} elseif ($result['status'] === 'skipped') {
|
||||
$stats['skipped']++;
|
||||
} else {
|
||||
$stats['errors']++;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
$stats['errors']++;
|
||||
$this->newLine();
|
||||
$this->error("Error processing spatial planning ID {$spatial->id}: " . $e->getMessage());
|
||||
}
|
||||
|
||||
$progressBar->advance();
|
||||
}
|
||||
|
||||
$progressBar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
// Show final statistics
|
||||
$this->showFinalStatistics($stats);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process single spatial planning
|
||||
*/
|
||||
private function processSingleSpatialPlanning(SpatialPlanning $spatial, $force)
|
||||
{
|
||||
// Check if already has proposals
|
||||
if (!$force && $spatial->retributionProposals()->exists()) {
|
||||
return ['status' => 'skipped', 'reason' => 'already_has_proposals'];
|
||||
}
|
||||
|
||||
// Detect building function
|
||||
$buildingFunction = $this->proposalService->detectBuildingFunction($spatial->getBuildingFunctionText());
|
||||
if (!$buildingFunction) {
|
||||
return ['status' => 'error', 'reason' => 'no_building_function'];
|
||||
}
|
||||
|
||||
// Get area
|
||||
$totalArea = $spatial->getCalculationArea();
|
||||
if ($totalArea <= 0) {
|
||||
return ['status' => 'error', 'reason' => 'no_area'];
|
||||
}
|
||||
|
||||
// Get number of floors
|
||||
$numberOfFloors = max(1, $spatial->number_of_floors ?? 1);
|
||||
|
||||
// Delete existing proposals if force mode
|
||||
if ($force) {
|
||||
$spatial->retributionProposals()->delete();
|
||||
}
|
||||
|
||||
$proposalsCreated = 0;
|
||||
|
||||
// Create proposals for each floor
|
||||
for ($floor = 1; $floor <= $numberOfFloors; $floor++) {
|
||||
// Calculate floor area (distribute total area across floors)
|
||||
$floorArea = $totalArea / $numberOfFloors;
|
||||
|
||||
// Create retribution proposal
|
||||
$proposal = $this->proposalService->createProposalForSpatialPlanning(
|
||||
$spatial,
|
||||
$buildingFunction->id,
|
||||
$floor,
|
||||
$floorArea,
|
||||
$totalArea,
|
||||
"Auto-generated from spatial planning calculation"
|
||||
);
|
||||
|
||||
if ($proposal) {
|
||||
$proposalsCreated++;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'processed',
|
||||
'proposals_created' => $proposalsCreated
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Show final statistics
|
||||
*/
|
||||
private function showFinalStatistics($stats)
|
||||
{
|
||||
$this->info('✅ CALCULATION COMPLETED!');
|
||||
$this->newLine();
|
||||
|
||||
$this->table(
|
||||
['Metric', 'Count'],
|
||||
[
|
||||
['Processed Successfully', $stats['processed']],
|
||||
['Skipped (Already Exists)', $stats['skipped']],
|
||||
['Errors', $stats['errors']],
|
||||
['Total Proposals Created', $stats['created_proposals']],
|
||||
]
|
||||
);
|
||||
|
||||
if ($stats['errors'] > 0) {
|
||||
$this->newLine();
|
||||
$this->warn("⚠️ {$stats['errors']} spatial plannings had errors:");
|
||||
$this->warn(" • Missing building function detection");
|
||||
$this->warn(" • Missing or zero area");
|
||||
$this->warn(" • Other calculation errors");
|
||||
}
|
||||
|
||||
if ($stats['processed'] > 0) {
|
||||
$this->newLine();
|
||||
$this->info("🎉 Successfully created {$stats['created_proposals']} retribution proposals!");
|
||||
$this->info("💡 You can view them using: php artisan retribution:list-proposals");
|
||||
}
|
||||
}
|
||||
}
|
||||
101
app/Console/Commands/CheckSpatialPlanningConstraints.php
Normal file
101
app/Console/Commands/CheckSpatialPlanningConstraints.php
Normal file
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Models\SpatialPlanning;
|
||||
use App\Models\RetributionProposal;
|
||||
|
||||
class CheckSpatialPlanningConstraints extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'spatial:check-constraints';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Check spatial planning foreign key constraints and show statistics';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->info('Checking Spatial Planning Constraints...');
|
||||
$this->newLine();
|
||||
|
||||
try {
|
||||
// Get total spatial plannings
|
||||
$totalSpatialPlannings = SpatialPlanning::count();
|
||||
|
||||
// Get spatial plannings with retribution proposals
|
||||
$withProposals = SpatialPlanning::whereHas('retributionProposals')->count();
|
||||
|
||||
// Get spatial plannings without retribution proposals
|
||||
$withoutProposals = SpatialPlanning::whereDoesntHave('retributionProposals')->count();
|
||||
|
||||
// Get total retribution proposals
|
||||
$totalProposals = RetributionProposal::count();
|
||||
|
||||
// Get retribution proposals linked to spatial plannings
|
||||
$linkedProposals = RetributionProposal::whereNotNull('spatial_planning_id')->count();
|
||||
|
||||
// Get standalone retribution proposals
|
||||
$standaloneProposals = RetributionProposal::whereNull('spatial_planning_id')->count();
|
||||
|
||||
// Display statistics
|
||||
$this->table(
|
||||
['Metric', 'Count'],
|
||||
[
|
||||
['Total Spatial Plannings', $totalSpatialPlannings],
|
||||
['├─ With Retribution Proposals', $withProposals],
|
||||
['└─ Without Retribution Proposals', $withoutProposals],
|
||||
['', ''],
|
||||
['Total Retribution Proposals', $totalProposals],
|
||||
['├─ Linked to Spatial Planning', $linkedProposals],
|
||||
['└─ Standalone Proposals', $standaloneProposals],
|
||||
]
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// Show constraint implications
|
||||
if ($withProposals > 0) {
|
||||
$this->warn("⚠️ CONSTRAINT WARNING:");
|
||||
$this->warn(" {$withProposals} spatial plannings have retribution proposals linked to them.");
|
||||
$this->warn(" These cannot be deleted directly due to foreign key constraints.");
|
||||
$this->newLine();
|
||||
|
||||
$this->info("💡 TRUNCATE OPTIONS:");
|
||||
$this->info(" • Use --truncate to delete ALL data (spatial plannings + linked proposals)");
|
||||
$this->info(" • Use --safe-truncate to delete only spatial plannings without proposals");
|
||||
$this->info(" • Manual cleanup: Delete proposals first, then spatial plannings");
|
||||
} else {
|
||||
$this->info("✅ No foreign key constraints found.");
|
||||
$this->info(" All spatial plannings can be safely truncated.");
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// Show example commands
|
||||
$this->info("📋 EXAMPLE COMMANDS:");
|
||||
$this->info(" php artisan spatial:init --truncate # Delete all data (smart method)");
|
||||
$this->info(" php artisan spatial:init --safe-truncate # Delete safe data only");
|
||||
$this->info(" php artisan spatial:init --force-truncate # Force truncate (disable FK checks)");
|
||||
$this->info(" php artisan spatial:init file.csv --truncate # Import with truncate");
|
||||
|
||||
return 0;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->error('Error checking constraints: ' . $e->getMessage());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ class InitSpatialPlanningDatas extends Command
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'spatial:init {file? : Path to the CSV/Excel file} {--truncate : Clear existing data before import}';
|
||||
protected $signature = 'spatial:init {file? : Path to the CSV/Excel file} {--truncate : Clear existing data before import} {--safe-truncate : Clear only spatial plannings without retribution proposals} {--force-truncate : Force truncate by disabling foreign key checks}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
@@ -40,12 +40,133 @@ class InitSpatialPlanningDatas extends Command
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Handle truncate options
|
||||
if (($this->option('truncate') && $this->option('safe-truncate')) ||
|
||||
($this->option('truncate') && $this->option('force-truncate')) ||
|
||||
($this->option('safe-truncate') && $this->option('force-truncate'))) {
|
||||
$this->error('Cannot use multiple truncate options together. Choose only one.');
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Confirm truncate if requested
|
||||
if ($this->option('truncate')) {
|
||||
if ($this->confirm('This will delete all existing spatial planning data. Continue?')) {
|
||||
$this->info('Truncating spatial_plannings table...');
|
||||
DB::table('spatial_plannings')->truncate();
|
||||
$this->info('Table truncated successfully.');
|
||||
if ($this->confirm('This will delete all existing spatial planning data and related retribution proposals. Continue?')) {
|
||||
$this->info('Truncating tables...');
|
||||
|
||||
try {
|
||||
// First delete retribution proposals that reference spatial plannings
|
||||
$deletedProposals = DB::table('retribution_proposals')
|
||||
->whereNotNull('spatial_planning_id')
|
||||
->count();
|
||||
|
||||
if ($deletedProposals > 0) {
|
||||
DB::table('retribution_proposals')
|
||||
->whereNotNull('spatial_planning_id')
|
||||
->delete();
|
||||
$this->info("Deleted {$deletedProposals} retribution proposals linked to spatial plannings.");
|
||||
}
|
||||
|
||||
// Method 1: Try truncate with disabled foreign key checks
|
||||
try {
|
||||
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
|
||||
DB::table('spatial_plannings')->truncate();
|
||||
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
|
||||
$this->info('Spatial plannings table truncated successfully.');
|
||||
} catch (\Exception $truncateError) {
|
||||
// Method 2: Fallback to delete if truncate fails
|
||||
$this->warn('Truncate failed, using delete method...');
|
||||
$deletedSpatial = DB::table('spatial_plannings')->delete();
|
||||
$this->info("Deleted {$deletedSpatial} spatial planning records.");
|
||||
|
||||
// Reset auto increment
|
||||
DB::statement('ALTER TABLE spatial_plannings AUTO_INCREMENT = 1');
|
||||
}
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->error('Failed to truncate tables: ' . $e->getMessage());
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
$this->info('Operation cancelled.');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Force truncate - disable foreign key checks and truncate everything
|
||||
if ($this->option('force-truncate')) {
|
||||
if ($this->confirm('This will FORCE truncate ALL spatial planning data by disabling foreign key checks. This is risky! Continue?')) {
|
||||
$this->info('Force truncating with disabled foreign key checks...');
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
// Disable foreign key checks
|
||||
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
|
||||
|
||||
// Truncate both tables
|
||||
DB::table('retribution_proposals')->truncate();
|
||||
DB::table('spatial_plannings')->truncate();
|
||||
|
||||
// Re-enable foreign key checks
|
||||
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
|
||||
|
||||
$this->info('Force truncate completed successfully.');
|
||||
|
||||
DB::commit();
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
// Make sure to re-enable foreign key checks even on error
|
||||
try {
|
||||
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
|
||||
} catch (\Exception $fkError) {
|
||||
$this->error('Failed to re-enable foreign key checks: ' . $fkError->getMessage());
|
||||
}
|
||||
$this->error('Failed to force truncate: ' . $e->getMessage());
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
$this->info('Operation cancelled.');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Safe truncate - only delete spatial plannings without retribution proposals
|
||||
if ($this->option('safe-truncate')) {
|
||||
if ($this->confirm('This will delete only spatial planning data that have no retribution proposals. Continue?')) {
|
||||
$this->info('Safe truncating spatial plannings...');
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
// Count spatial plannings with retribution proposals
|
||||
$withProposals = DB::table('spatial_plannings')
|
||||
->whereExists(function ($query) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('retribution_proposals')
|
||||
->whereColumn('retribution_proposals.spatial_planning_id', 'spatial_plannings.id');
|
||||
})
|
||||
->count();
|
||||
|
||||
// Delete spatial plannings without retribution proposals
|
||||
$deletedCount = DB::table('spatial_plannings')
|
||||
->whereNotExists(function ($query) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('retribution_proposals')
|
||||
->whereColumn('retribution_proposals.spatial_planning_id', 'spatial_plannings.id');
|
||||
})
|
||||
->delete();
|
||||
|
||||
$this->info("Deleted {$deletedCount} spatial plannings without retribution proposals.");
|
||||
$this->info("Kept {$withProposals} spatial plannings that have retribution proposals.");
|
||||
|
||||
DB::commit();
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
$this->error('Failed to safe truncate: ' . $e->getMessage());
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
$this->info('Operation cancelled.');
|
||||
return 0;
|
||||
@@ -171,18 +292,25 @@ class InitSpatialPlanningDatas extends Command
|
||||
{
|
||||
$templatesPath = storage_path('app/public/templates');
|
||||
if (is_dir($templatesPath)) {
|
||||
$files = glob($templatesPath . '/*.{csv,xlsx,xls}', GLOB_BRACE);
|
||||
foreach ($files as $file) {
|
||||
$this->line(' - ' . basename($file));
|
||||
$this->info("Files in storage/app/public/templates:");
|
||||
$extensions = ['csv', 'xlsx', 'xls'];
|
||||
foreach ($extensions as $ext) {
|
||||
$files = glob($templatesPath . '/*.' . $ext);
|
||||
foreach ($files as $file) {
|
||||
$this->line(' - ' . basename($file));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$publicTemplatesPath = public_path('templates');
|
||||
if (is_dir($publicTemplatesPath)) {
|
||||
$this->info("Files in public/templates:");
|
||||
$files = glob($publicTemplatesPath . '/*.{csv,xlsx,xls}', GLOB_BRACE);
|
||||
foreach ($files as $file) {
|
||||
$this->line(' - ' . basename($file));
|
||||
$extensions = ['csv', 'xlsx', 'xls'];
|
||||
foreach ($extensions as $ext) {
|
||||
$files = glob($publicTemplatesPath . '/*.' . $ext);
|
||||
foreach ($files as $file) {
|
||||
$this->line(' - ' . basename($file));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\Models\SpatialPlanning;
|
||||
use App\Models\RetributionProposal;
|
||||
use App\Services\RetributionProposalService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Exception;
|
||||
|
||||
class ProcessSpatialPlanningRetributionCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'spatial:process-retribution
|
||||
{--all : Process all spatial plannings}
|
||||
{--new-only : Process only spatial plannings without retribution proposals}
|
||||
{--force : Force recalculate existing retribution proposals}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Process and save retribution calculations for spatial plannings';
|
||||
|
||||
protected RetributionProposalService $proposalService;
|
||||
|
||||
public function __construct(RetributionProposalService $proposalService)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->proposalService = $proposalService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->info('🏗️ Processing Spatial Planning Retribution Calculations...');
|
||||
$this->newLine();
|
||||
|
||||
try {
|
||||
// Get options
|
||||
$processAll = $this->option('all');
|
||||
$newOnly = $this->option('new-only');
|
||||
$force = $this->option('force');
|
||||
|
||||
// Build query
|
||||
$query = SpatialPlanning::query();
|
||||
|
||||
if ($newOnly || (!$processAll && !$force)) {
|
||||
$query->whereDoesntHave('retributionProposals');
|
||||
$this->info('📋 Mode: Processing only spatial plannings WITHOUT retribution proposals');
|
||||
} elseif ($processAll) {
|
||||
$this->info('📋 Mode: Processing ALL spatial plannings');
|
||||
}
|
||||
|
||||
$spatialPlannings = $query->get();
|
||||
$totalCount = $spatialPlannings->count();
|
||||
|
||||
if ($totalCount === 0) {
|
||||
$this->warn('❌ No spatial plannings found to process.');
|
||||
$this->info('💡 Try running: php artisan spatial:init first');
|
||||
return 0;
|
||||
}
|
||||
|
||||
$this->info("📊 Found {$totalCount} spatial plannings to process");
|
||||
$this->newLine();
|
||||
|
||||
// Show preview of what will be processed
|
||||
$this->showProcessingPreview($spatialPlannings);
|
||||
|
||||
// Confirm processing
|
||||
if (!$this->confirm("Process {$totalCount} spatial plannings and create retribution proposals?")) {
|
||||
$this->info('Operation cancelled.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Process all spatial plannings
|
||||
$this->processAllSpatialPlannings($spatialPlannings, $force);
|
||||
|
||||
return 0;
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->error('❌ Error during processing: ' . $e->getMessage());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show processing preview
|
||||
*/
|
||||
private function showProcessingPreview($spatialPlannings)
|
||||
{
|
||||
$this->info('🔍 PREVIEW:');
|
||||
|
||||
$canProcess = 0;
|
||||
$cannotProcess = 0;
|
||||
$hasExisting = 0;
|
||||
|
||||
$sampleData = [];
|
||||
$errorReasons = [];
|
||||
|
||||
foreach ($spatialPlannings->take(5) as $spatial) {
|
||||
$buildingFunction = $this->proposalService->detectBuildingFunction($spatial->getBuildingFunctionText());
|
||||
$area = $spatial->getCalculationArea();
|
||||
$floors = max(1, $spatial->number_of_floors ?? 1);
|
||||
$hasProposals = $spatial->retributionProposals()->exists();
|
||||
|
||||
if ($hasProposals) {
|
||||
$hasExisting++;
|
||||
}
|
||||
|
||||
if ($buildingFunction && $area > 0) {
|
||||
$canProcess++;
|
||||
$sampleData[] = [
|
||||
'ID' => $spatial->id,
|
||||
'Name' => substr($spatial->name ?? 'N/A', 0, 30),
|
||||
'Function' => $buildingFunction->name ?? 'N/A',
|
||||
'Area' => number_format($area, 2),
|
||||
'Floors' => $floors,
|
||||
'Status' => $hasProposals ? '🔄 Has Proposals' : '✅ Ready'
|
||||
];
|
||||
} else {
|
||||
$cannotProcess++;
|
||||
if (!$buildingFunction) {
|
||||
$errorReasons[] = 'Missing building function';
|
||||
}
|
||||
if ($area <= 0) {
|
||||
$errorReasons[] = 'Missing/zero area';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show sample data table
|
||||
if (!empty($sampleData)) {
|
||||
$this->table(
|
||||
['ID', 'Name', 'Function', 'Area (m²)', 'Floors', 'Status'],
|
||||
$sampleData
|
||||
);
|
||||
}
|
||||
|
||||
// Show summary
|
||||
$this->newLine();
|
||||
$this->info("📈 SUMMARY:");
|
||||
$this->info(" ✅ Can Process: {$canProcess}");
|
||||
$this->info(" ❌ Cannot Process: {$cannotProcess}");
|
||||
$this->info(" 🔄 Has Existing Proposals: {$hasExisting}");
|
||||
|
||||
if ($cannotProcess > 0) {
|
||||
$this->warn(" ⚠️ Common Issues: " . implode(', ', array_unique($errorReasons)));
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process all spatial plannings
|
||||
*/
|
||||
private function processAllSpatialPlannings($spatialPlannings, $force)
|
||||
{
|
||||
$this->info('🚀 Starting processing...');
|
||||
$this->newLine();
|
||||
|
||||
$progressBar = $this->output->createProgressBar($spatialPlannings->count());
|
||||
$progressBar->start();
|
||||
|
||||
$stats = [
|
||||
'processed' => 0,
|
||||
'skipped' => 0,
|
||||
'errors' => 0,
|
||||
'total_proposals' => 0,
|
||||
'total_amount' => 0
|
||||
];
|
||||
|
||||
$errors = [];
|
||||
|
||||
foreach ($spatialPlannings as $spatial) {
|
||||
try {
|
||||
$result = $this->processSingleSpatialPlanning($spatial, $force);
|
||||
|
||||
if ($result['success']) {
|
||||
$stats['processed']++;
|
||||
$stats['total_proposals'] += $result['proposals_count'];
|
||||
$stats['total_amount'] += $result['total_amount'];
|
||||
} elseif ($result['skipped']) {
|
||||
$stats['skipped']++;
|
||||
} else {
|
||||
$stats['errors']++;
|
||||
$errors[] = "ID {$spatial->id}: " . $result['error'];
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
$stats['errors']++;
|
||||
$errors[] = "ID {$spatial->id}: " . $e->getMessage();
|
||||
}
|
||||
|
||||
$progressBar->advance();
|
||||
}
|
||||
|
||||
$progressBar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
// Show final results
|
||||
$this->showFinalResults($stats, $errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process single spatial planning
|
||||
*/
|
||||
private function processSingleSpatialPlanning(SpatialPlanning $spatial, $force)
|
||||
{
|
||||
// Check if already has proposals
|
||||
if (!$force && $spatial->retributionProposals()->exists()) {
|
||||
return ['success' => false, 'skipped' => true];
|
||||
}
|
||||
|
||||
// Detect building function
|
||||
$buildingFunction = $this->proposalService->detectBuildingFunction($spatial->getBuildingFunctionText());
|
||||
if (!$buildingFunction) {
|
||||
return ['success' => false, 'skipped' => false, 'error' => 'Cannot detect building function from: ' . $spatial->getBuildingFunctionText()];
|
||||
}
|
||||
|
||||
// Get area
|
||||
$totalArea = $spatial->getCalculationArea();
|
||||
if ($totalArea <= 0) {
|
||||
return ['success' => false, 'skipped' => false, 'error' => 'Area is zero or missing'];
|
||||
}
|
||||
|
||||
// Get number of floors
|
||||
$numberOfFloors = max(1, $spatial->number_of_floors ?? 1);
|
||||
|
||||
// Delete existing proposals if force mode
|
||||
if ($force) {
|
||||
$spatial->retributionProposals()->delete();
|
||||
}
|
||||
|
||||
$proposalsCount = 0;
|
||||
$totalAmount = 0;
|
||||
|
||||
// Create single proposal for the spatial planning (not per floor to prevent duplicates)
|
||||
// Use the highest floor for IP ketinggian calculation (worst case scenario)
|
||||
$highestFloor = $numberOfFloors;
|
||||
|
||||
$proposal = $this->proposalService->createProposalForSpatialPlanning(
|
||||
$spatial,
|
||||
$buildingFunction->id,
|
||||
$highestFloor, // Use highest floor for calculation
|
||||
$totalArea, // Use total area, not divided by floors
|
||||
$totalArea,
|
||||
"Auto-calculated from spatial planning data (floors: {$numberOfFloors})"
|
||||
);
|
||||
|
||||
if ($proposal) {
|
||||
$proposalsCount = 1;
|
||||
$totalAmount = $proposal->total_retribution_amount;
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'skipped' => false,
|
||||
'proposals_count' => $proposalsCount,
|
||||
'total_amount' => $totalAmount
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Show final results
|
||||
*/
|
||||
private function showFinalResults($stats, $errors)
|
||||
{
|
||||
$this->info('🎉 PROCESSING COMPLETED!');
|
||||
$this->newLine();
|
||||
|
||||
// Main statistics table
|
||||
$this->table(
|
||||
['Metric', 'Count'],
|
||||
[
|
||||
['✅ Successfully Processed', $stats['processed']],
|
||||
['⏭️ Skipped (Already Has Proposals)', $stats['skipped']],
|
||||
['❌ Errors', $stats['errors']],
|
||||
['📄 Total Proposals Created', $stats['total_proposals']],
|
||||
['💰 Total Retribution Amount', 'Rp ' . number_format($stats['total_amount'], 2)],
|
||||
]
|
||||
);
|
||||
|
||||
// Show success message
|
||||
if ($stats['processed'] > 0) {
|
||||
$this->newLine();
|
||||
$this->info("🎊 SUCCESS!");
|
||||
$this->info(" 📊 Created {$stats['total_proposals']} retribution proposals");
|
||||
$this->info(" 💵 Total calculated amount: Rp " . number_format($stats['total_amount'], 2));
|
||||
$this->info(" 📋 Processed {$stats['processed']} spatial plannings");
|
||||
}
|
||||
|
||||
// Show errors if any
|
||||
if ($stats['errors'] > 0) {
|
||||
$this->newLine();
|
||||
$this->warn("⚠️ ERRORS ENCOUNTERED:");
|
||||
foreach (array_slice($errors, 0, 10) as $error) {
|
||||
$this->warn(" • {$error}");
|
||||
}
|
||||
|
||||
if (count($errors) > 10) {
|
||||
$this->warn(" ... and " . (count($errors) - 10) . " more errors");
|
||||
}
|
||||
}
|
||||
|
||||
// Show next steps
|
||||
$this->newLine();
|
||||
$this->info("📋 NEXT STEPS:");
|
||||
$this->info(" • View proposals: php artisan spatial:check-constraints");
|
||||
$this->info(" • Check database: SELECT COUNT(*) FROM retribution_proposals;");
|
||||
$this->info(" • Access via API: GET /api/retribution-proposals");
|
||||
}
|
||||
}
|
||||
209
app/Console/Commands/TestExcelFormulaCommand.php
Normal file
209
app/Console/Commands/TestExcelFormulaCommand.php
Normal file
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\BuildingFunction;
|
||||
use App\Models\FloorHeightIndex;
|
||||
use App\Models\RetributionProposal;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class TestExcelFormulaCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'test:excel-formula {--building-function=10} {--floor-area=100} {--floor-number=2}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Test Excel formula calculation with sample data';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->info('🧮 Testing Excel Formula Calculation');
|
||||
$this->newLine();
|
||||
|
||||
// Get parameters
|
||||
$buildingFunctionId = $this->option('building-function');
|
||||
$floorArea = (float) $this->option('floor-area');
|
||||
$floorNumber = (int) $this->option('floor-number');
|
||||
|
||||
// Get building function and parameters
|
||||
$buildingFunction = BuildingFunction::with('parameter')->find($buildingFunctionId);
|
||||
if (!$buildingFunction || !$buildingFunction->parameter) {
|
||||
$this->error("Building function with ID {$buildingFunctionId} not found or has no parameters.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Get IP ketinggian for floor
|
||||
$floorHeightIndex = FloorHeightIndex::where('floor_number', $floorNumber)->first();
|
||||
$ipKetinggian = $floorHeightIndex ? $floorHeightIndex->ip_ketinggian : 1.0;
|
||||
|
||||
// Get parameters
|
||||
$parameters = $buildingFunction->parameter->getParametersArray();
|
||||
|
||||
$this->info("Test Parameters:");
|
||||
$this->table(
|
||||
['Parameter', 'Excel Cell', 'Value'],
|
||||
[
|
||||
['Building Function', 'Building Function', $buildingFunction->name],
|
||||
['Floor Area (D13)', 'D13', $floorArea . ' m²'],
|
||||
['Fungsi Bangunan (E13)', 'E13', $parameters['fungsi_bangunan']],
|
||||
['IP Permanen (F13)', 'F13', $parameters['ip_permanen']],
|
||||
['IP Kompleksitas (G13)', 'G13', $parameters['ip_kompleksitas']],
|
||||
['IP Ketinggian (H$3)', 'H$3', $ipKetinggian],
|
||||
['Indeks Lokalitas (N13)', 'N13', $parameters['indeks_lokalitas']],
|
||||
['Base Value', '70350', '70,350'],
|
||||
['Additional Factor ($O$3)', '$O$3', '0.5 (50%)']
|
||||
]
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// Calculate manually using the Excel formula
|
||||
$fungsi_bangunan = $parameters['fungsi_bangunan'];
|
||||
$ip_permanen = $parameters['ip_permanen'];
|
||||
$ip_kompleksitas = $parameters['ip_kompleksitas'];
|
||||
$indeks_lokalitas = $parameters['indeks_lokalitas'];
|
||||
$base_value = 70350;
|
||||
$additional_factor = 0.5;
|
||||
|
||||
// Step 1: Calculate H13 (floor coefficient)
|
||||
$h13 = $fungsi_bangunan * ($ip_permanen + $ip_kompleksitas + (0.5 * $ipKetinggian));
|
||||
|
||||
// Step 2: Main calculation
|
||||
$main_calculation = 1 * $floorArea * ($indeks_lokalitas * $base_value * $h13 * 1);
|
||||
|
||||
// Step 3: Additional (50%)
|
||||
$additional_calculation = $additional_factor * $main_calculation;
|
||||
|
||||
// Step 4: Total
|
||||
$total_retribution = $main_calculation + $additional_calculation;
|
||||
|
||||
// Create breakdown array
|
||||
$breakdown = [
|
||||
'calculation_steps' => [
|
||||
'step_1_h13' => [
|
||||
'formula' => 'fungsi_bangunan * (ip_permanen + ip_kompleksitas + (0.5 * ip_ketinggian))',
|
||||
'calculation' => "{$fungsi_bangunan} * ({$ip_permanen} + {$ip_kompleksitas} + (0.5 * {$ipKetinggian}))",
|
||||
'result' => $h13
|
||||
],
|
||||
'step_2_main' => [
|
||||
'formula' => '(1*D13*(N13*70350*H13*1))',
|
||||
'calculation' => "1 * {$floorArea} * ({$indeks_lokalitas} * {$base_value} * {$h13} * 1)",
|
||||
'result' => $main_calculation
|
||||
],
|
||||
'step_3_additional' => [
|
||||
'formula' => '($O$3*(1*D13*(N13*70350*H13*1)))',
|
||||
'calculation' => "{$additional_factor} * {$main_calculation}",
|
||||
'result' => $additional_calculation
|
||||
],
|
||||
'step_4_total' => [
|
||||
'formula' => 'main + additional',
|
||||
'calculation' => "{$main_calculation} + {$additional_calculation}",
|
||||
'result' => $total_retribution
|
||||
]
|
||||
],
|
||||
'formatted_results' => [
|
||||
'H13' => number_format($h13, 6),
|
||||
'main_calculation' => 'Rp ' . number_format($main_calculation, 2),
|
||||
'additional_calculation' => 'Rp ' . number_format($additional_calculation, 2),
|
||||
'total_result' => 'Rp ' . number_format($total_retribution, 2)
|
||||
]
|
||||
];
|
||||
|
||||
$this->info("📊 Calculation Breakdown:");
|
||||
$this->newLine();
|
||||
|
||||
// Show each step
|
||||
foreach ($breakdown['calculation_steps'] as $stepName => $step) {
|
||||
$this->info("🔸 " . strtoupper(str_replace('_', ' ', $stepName)));
|
||||
$this->line(" Formula: " . $step['formula']);
|
||||
$this->line(" Calculation: " . $step['calculation']);
|
||||
$this->line(" Result: " . (is_numeric($step['result']) ? number_format($step['result'], 6) : $step['result']));
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
$this->info("💰 Final Results:");
|
||||
$this->table(
|
||||
['Component', 'Value'],
|
||||
[
|
||||
['H13 (Floor Coefficient)', $breakdown['formatted_results']['H13']],
|
||||
['Main Calculation', $breakdown['formatted_results']['main_calculation']],
|
||||
['Additional (50%)', $breakdown['formatted_results']['additional_calculation']],
|
||||
['Total Retribution', $breakdown['formatted_results']['total_result']]
|
||||
]
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
$this->info("🔍 Excel Formula Verification:");
|
||||
$this->line("Main Formula: =(1*D13*(N13*70350*H13*1))+(\$O\$3*(1*D13*(N13*70350*H13*1)))");
|
||||
$this->line("H13 Formula: =(\$E13*(\$F13+\$G13+(0.5*H\$3)))");
|
||||
|
||||
// Test with different floor numbers
|
||||
if ($this->confirm('Test with different floor numbers?')) {
|
||||
$this->testMultipleFloors($buildingFunction, $floorArea, $parameters);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test calculation with multiple floor numbers
|
||||
*/
|
||||
protected function testMultipleFloors(BuildingFunction $buildingFunction, float $floorArea, array $parameters)
|
||||
{
|
||||
$this->newLine();
|
||||
$this->info("🏢 Testing Multiple Floors:");
|
||||
|
||||
$tableData = [];
|
||||
$totalRetribution = 0;
|
||||
|
||||
for ($floor = 1; $floor <= 5; $floor++) {
|
||||
$floorHeightIndex = FloorHeightIndex::where('floor_number', $floor)->first();
|
||||
$ipKetinggian = $floorHeightIndex ? $floorHeightIndex->ip_ketinggian : 1.0;
|
||||
|
||||
// Calculate using Excel formula
|
||||
$fungsi_bangunan = $parameters['fungsi_bangunan'];
|
||||
$ip_permanen = $parameters['ip_permanen'];
|
||||
$ip_kompleksitas = $parameters['ip_kompleksitas'];
|
||||
$indeks_lokalitas = $parameters['indeks_lokalitas'];
|
||||
$base_value = 70350;
|
||||
$additional_factor = 0.5;
|
||||
|
||||
// Calculate H13 and result
|
||||
$H13 = $fungsi_bangunan * ($ip_permanen + $ip_kompleksitas + (0.5 * $ipKetinggian));
|
||||
$main_calc = 1 * $floorArea * ($indeks_lokalitas * $base_value * $H13 * 1);
|
||||
$additional_calc = $additional_factor * $main_calc;
|
||||
$result = $main_calc + $additional_calc;
|
||||
|
||||
$totalRetribution += $result;
|
||||
|
||||
$tableData[] = [
|
||||
"L{$floor}",
|
||||
$ipKetinggian,
|
||||
number_format($H13, 6),
|
||||
'Rp ' . number_format($result, 2)
|
||||
];
|
||||
}
|
||||
|
||||
$this->table(
|
||||
['Floor', 'IP Ketinggian', 'H13 Value', 'Retribution Amount'],
|
||||
$tableData
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
$this->info("🏗️ Total Building Retribution (5 floors): Rp " . number_format($totalRetribution, 2));
|
||||
$this->info("📏 Total Building Area: " . number_format($floorArea * 5, 2) . " m²");
|
||||
$this->info("💡 Average per m²: Rp " . number_format($totalRetribution / ($floorArea * 5), 2));
|
||||
}
|
||||
}
|
||||
@@ -25,12 +25,13 @@ class BigDataResumeController extends Controller
|
||||
$filterDate = $request->get("filterByDate");
|
||||
|
||||
if (!$filterDate || $filterDate === "latest") {
|
||||
$big_data_resume = BigdataResume::where('year', now()->year)->latest()->first();
|
||||
$big_data_resume = BigdataResume::where('year', 'leader')->latest()->first();
|
||||
if (!$big_data_resume) {
|
||||
return $this->response_empty_resume();
|
||||
}
|
||||
} else {
|
||||
$big_data_resume = BigdataResume::whereDate('created_at', $filterDate)
|
||||
$big_data_resume = BigdataResume::where('year', 'leader')
|
||||
->whereDate('created_at', $filterDate)
|
||||
->orderBy('id', 'desc')
|
||||
->first();
|
||||
|
||||
|
||||
295
app/Http/Controllers/RetributionProposalController.php
Normal file
295
app/Http/Controllers/RetributionProposalController.php
Normal file
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\RetributionProposal;
|
||||
use App\Models\SpatialPlanning;
|
||||
use App\Models\BuildingFunction;
|
||||
use App\Services\RetributionProposalService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class RetributionProposalController extends Controller
|
||||
{
|
||||
protected RetributionProposalService $proposalService;
|
||||
|
||||
public function __construct(RetributionProposalService $proposalService)
|
||||
{
|
||||
$this->proposalService = $proposalService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of retribution proposals
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$query = RetributionProposal::with(['spatialPlanning', 'buildingFunction', 'retributionFormula']);
|
||||
|
||||
// Filtering
|
||||
if ($request->has('building_function_id')) {
|
||||
$query->where('building_function_id', $request->building_function_id);
|
||||
}
|
||||
|
||||
if ($request->has('spatial_planning_id')) {
|
||||
$query->where('spatial_planning_id', $request->spatial_planning_id);
|
||||
}
|
||||
|
||||
if ($request->has('floor_number')) {
|
||||
$query->where('floor_number', $request->floor_number);
|
||||
}
|
||||
|
||||
if ($request->has('has_spatial_planning')) {
|
||||
if ($request->boolean('has_spatial_planning')) {
|
||||
$query->whereNotNull('spatial_planning_id');
|
||||
} else {
|
||||
$query->whereNull('spatial_planning_id');
|
||||
}
|
||||
}
|
||||
|
||||
// Search
|
||||
if ($request->has('search')) {
|
||||
$search = $request->search;
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('proposal_number', 'like', "%{$search}%")
|
||||
->orWhere('notes', 'like', "%{$search}%")
|
||||
->orWhereHas('spatialPlanning', function ($sq) use ($search) {
|
||||
$sq->where('name', 'like', "%{$search}%");
|
||||
})
|
||||
->orWhereHas('buildingFunction', function ($bq) use ($search) {
|
||||
$bq->where('name', 'like', "%{$search}%");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Sorting
|
||||
$sortBy = $request->get('sort_by', 'created_at');
|
||||
$sortOrder = $request->get('sort_order', 'desc');
|
||||
$query->orderBy($sortBy, $sortOrder);
|
||||
|
||||
// Pagination
|
||||
$perPage = $request->get('per_page', 15);
|
||||
$proposals = $query->paginate($perPage);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $proposals,
|
||||
'meta' => [
|
||||
'total_amount' => RetributionProposal::sum('total_retribution_amount'),
|
||||
'total_proposals' => RetributionProposal::count(),
|
||||
'formatted_total_amount' => 'Rp ' . number_format(RetributionProposal::sum('total_retribution_amount'), 0, ',', '.')
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a new retribution proposal
|
||||
*/
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'spatial_planning_id' => 'nullable|exists:spatial_plannings,id',
|
||||
'building_function_id' => 'required|exists:building_functions,id',
|
||||
'floor_number' => 'required|integer|min:1|max:10',
|
||||
'floor_area' => 'required|numeric|min:0.01',
|
||||
'total_building_area' => 'nullable|numeric|min:0.01',
|
||||
'notes' => 'nullable|string|max:1000'
|
||||
]);
|
||||
|
||||
try {
|
||||
if ($request->spatial_planning_id) {
|
||||
$spatialPlanning = SpatialPlanning::findOrFail($request->spatial_planning_id);
|
||||
$proposal = $this->proposalService->createProposalForSpatialPlanning(
|
||||
$spatialPlanning,
|
||||
$request->building_function_id,
|
||||
$request->floor_number,
|
||||
$request->floor_area,
|
||||
$request->total_building_area,
|
||||
$request->notes
|
||||
);
|
||||
} else {
|
||||
$proposal = $this->proposalService->createStandaloneProposal(
|
||||
$request->building_function_id,
|
||||
$request->floor_number,
|
||||
$request->floor_area,
|
||||
$request->total_building_area,
|
||||
$request->notes
|
||||
);
|
||||
}
|
||||
|
||||
$proposal->load(['spatialPlanning', 'buildingFunction', 'retributionFormula']);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Retribution proposal created successfully',
|
||||
'data' => $proposal
|
||||
], 201);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to create retribution proposal',
|
||||
'error' => $e->getMessage()
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified retribution proposal
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
$proposal = RetributionProposal::with(['spatialPlanning', 'buildingFunction', 'retributionFormula'])
|
||||
->findOrFail($id);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $proposal
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified retribution proposal
|
||||
*/
|
||||
public function update(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$proposal = RetributionProposal::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'notes' => 'nullable|string|max:1000'
|
||||
]);
|
||||
|
||||
$proposal->update($request->only(['notes']));
|
||||
|
||||
$proposal->load(['spatialPlanning', 'buildingFunction', 'retributionFormula']);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Retribution proposal updated successfully',
|
||||
'data' => $proposal
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified retribution proposal
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
$proposal = RetributionProposal::findOrFail($id);
|
||||
$proposal->delete();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Retribution proposal deleted successfully'
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get retribution proposal statistics
|
||||
*/
|
||||
public function statistics(): JsonResponse
|
||||
{
|
||||
$stats = $this->proposalService->getStatistics();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $stats
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total sum of all retribution proposals
|
||||
*/
|
||||
public function totalSum(): JsonResponse
|
||||
{
|
||||
$totalAmount = RetributionProposal::sum('total_retribution_amount');
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'total_amount' => $totalAmount,
|
||||
'formatted_total_amount' => 'Rp ' . number_format($totalAmount, 0, ',', '.'),
|
||||
'total_proposals' => RetributionProposal::count()
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get building functions list
|
||||
*/
|
||||
public function buildingFunctions(): JsonResponse
|
||||
{
|
||||
$buildingFunctions = BuildingFunction::whereNotNull('parent_id')
|
||||
->with(['parameter'])
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $buildingFunctions
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-detect building function and create proposal
|
||||
*/
|
||||
public function autoCreateProposal(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'spatial_planning_id' => 'nullable|exists:spatial_plannings,id',
|
||||
'building_function_text' => 'required|string',
|
||||
'floor_number' => 'required|integer|min:1|max:10',
|
||||
'floor_area' => 'required|numeric|min:0.01',
|
||||
'total_building_area' => 'nullable|numeric|min:0.01',
|
||||
'notes' => 'nullable|string|max:1000'
|
||||
]);
|
||||
|
||||
try {
|
||||
// Auto-detect building function
|
||||
$buildingFunction = $this->proposalService->detectBuildingFunction($request->building_function_text);
|
||||
|
||||
if (!$buildingFunction) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Could not detect building function from text',
|
||||
'suggestion' => 'Please specify building function manually'
|
||||
], 400);
|
||||
}
|
||||
|
||||
if ($request->spatial_planning_id) {
|
||||
$spatialPlanning = SpatialPlanning::findOrFail($request->spatial_planning_id);
|
||||
$proposal = $this->proposalService->createProposalForSpatialPlanning(
|
||||
$spatialPlanning,
|
||||
$buildingFunction->id,
|
||||
$request->floor_number,
|
||||
$request->floor_area,
|
||||
$request->total_building_area,
|
||||
$request->notes
|
||||
);
|
||||
} else {
|
||||
$proposal = $this->proposalService->createStandaloneProposal(
|
||||
$buildingFunction->id,
|
||||
$request->floor_number,
|
||||
$request->floor_area,
|
||||
$request->total_building_area,
|
||||
$request->notes
|
||||
);
|
||||
}
|
||||
|
||||
$proposal->load(['spatialPlanning', 'buildingFunction', 'retributionFormula']);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Retribution proposal created successfully with auto-detected building function',
|
||||
'data' => $proposal,
|
||||
'detected_building_function' => $buildingFunction->name
|
||||
], 201);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to create retribution proposal',
|
||||
'error' => $e->getMessage()
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,21 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
class BuildingFunction extends Model
|
||||
{
|
||||
protected $table = 'building_functions';
|
||||
protected $fillable = ['code', 'name', 'description', 'parent_id', 'is_active', 'level', 'sort_order'];
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'name',
|
||||
'description',
|
||||
'parent_id',
|
||||
'level',
|
||||
'sort_order',
|
||||
'base_tariff'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
'level' => 'integer',
|
||||
'sort_order' => 'integer'
|
||||
'sort_order' => 'integer',
|
||||
'base_tariff' => 'decimal:2'
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -32,48 +41,41 @@ class BuildingFunction extends Model
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(BuildingFunction::class, 'parent_id')
|
||||
->where('is_active', true)
|
||||
->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters relationship (1:1)
|
||||
*/
|
||||
public function parameters(): HasOne
|
||||
public function parameter(): HasOne
|
||||
{
|
||||
return $this->hasOne(BuildingFunctionParameter::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formula relationship (1:1)
|
||||
* Formulas relationship (1:n) - multiple formulas for different floor numbers
|
||||
*/
|
||||
public function formula(): HasOne
|
||||
public function formulas(): HasMany
|
||||
{
|
||||
return $this->hasOne(RetributionFormula::class);
|
||||
return $this->hasMany(RetributionFormula::class)->orderBy('floor_number');
|
||||
}
|
||||
|
||||
/**
|
||||
* Spatial plannings relationship (1:n) - via detected building function
|
||||
* Get appropriate formula based on floor number
|
||||
*/
|
||||
public function spatialPlannings(): HasMany
|
||||
public function getFormulaForFloor(int $floorNumber): ?RetributionFormula
|
||||
{
|
||||
return $this->hasMany(SpatialPlanning::class, 'building_function_id');
|
||||
return $this->formulas()
|
||||
->where('floor_number', $floorNumber)
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retribution calculations relationship (1:n) - via detected building function
|
||||
* Retribution proposals relationship (1:n)
|
||||
*/
|
||||
public function retributionCalculations(): HasMany
|
||||
public function retributionProposals(): HasMany
|
||||
{
|
||||
return $this->hasMany(RetributionCalculation::class, 'detected_building_function_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Active building functions only
|
||||
*/
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
return $this->hasMany(RetributionProposal::class, 'building_function_id');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,11 +95,19 @@ class BuildingFunction extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if building function has complete setup (parameters + formula)
|
||||
* Scope: By level
|
||||
*/
|
||||
public function scopeByLevel($query, int $level)
|
||||
{
|
||||
return $query->where('level', $level);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if building function has complete setup (parameters + at least one formula)
|
||||
*/
|
||||
public function hasCompleteSetup(): bool
|
||||
{
|
||||
return $this->parameters()->exists() && $this->formula()->exists();
|
||||
return $this->parameter()->exists() && $this->formulas()->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,13 +120,48 @@ class BuildingFunction extends Model
|
||||
'code' => $this->code,
|
||||
'name' => $this->name,
|
||||
'description' => $this->description,
|
||||
'parameters' => $this->parameters?->getParametersArray(),
|
||||
'formula' => [
|
||||
'name' => $this->formula?->name,
|
||||
'expression' => $this->formula?->formula_expression,
|
||||
'description' => $this->formula?->description
|
||||
],
|
||||
'level' => $this->level,
|
||||
'sort_order' => $this->sort_order,
|
||||
'base_tariff' => $this->base_tariff,
|
||||
'parameters' => $this->parameter?->getParametersArray(),
|
||||
'formulas' => $this->formulas->map(function ($formula) {
|
||||
return [
|
||||
'id' => $formula->id,
|
||||
'name' => $formula->name,
|
||||
'expression' => $formula->formula_expression,
|
||||
'floor_number' => $formula->floor_number,
|
||||
'floor_description' => $this->getFloorDescription($formula->floor_number)
|
||||
];
|
||||
})->toArray(),
|
||||
'has_complete_setup' => $this->hasCompleteSetup()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get floor description
|
||||
*/
|
||||
public function getFloorDescription(?int $floorNumber): string
|
||||
{
|
||||
if ($floorNumber === null || $floorNumber === 0) {
|
||||
return 'Semua lantai';
|
||||
}
|
||||
|
||||
return "Lantai {$floorNumber}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a parent function
|
||||
*/
|
||||
public function isParent(): bool
|
||||
{
|
||||
return $this->parent_id === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a child function
|
||||
*/
|
||||
public function isChild(): bool
|
||||
{
|
||||
return $this->parent_id !== null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,19 +12,23 @@ class BuildingFunctionParameter extends Model
|
||||
'fungsi_bangunan',
|
||||
'ip_permanen',
|
||||
'ip_kompleksitas',
|
||||
'ip_ketinggian',
|
||||
'indeks_lokalitas',
|
||||
'is_active',
|
||||
'notes'
|
||||
'asumsi_prasarana',
|
||||
'koefisien_dasar',
|
||||
'faktor_penyesuaian',
|
||||
'custom_parameters',
|
||||
'parameter_notes'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'fungsi_bangunan' => 'decimal:6',
|
||||
'ip_permanen' => 'decimal:6',
|
||||
'ip_kompleksitas' => 'decimal:6',
|
||||
'ip_ketinggian' => 'decimal:6',
|
||||
'indeks_lokalitas' => 'decimal:6',
|
||||
'is_active' => 'boolean'
|
||||
'asumsi_prasarana' => 'decimal:6',
|
||||
'koefisien_dasar' => 'decimal:6',
|
||||
'faktor_penyesuaian' => 'decimal:6',
|
||||
'custom_parameters' => 'array'
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -52,8 +56,11 @@ class BuildingFunctionParameter extends Model
|
||||
'fungsi_bangunan' => $this->fungsi_bangunan,
|
||||
'ip_permanen' => $this->ip_permanen,
|
||||
'ip_kompleksitas' => $this->ip_kompleksitas,
|
||||
'ip_ketinggian' => $this->ip_ketinggian,
|
||||
'indeks_lokalitas' => $this->indeks_lokalitas
|
||||
'indeks_lokalitas' => $this->indeks_lokalitas,
|
||||
'asumsi_prasarana' => $this->asumsi_prasarana,
|
||||
'koefisien_dasar' => $this->koefisien_dasar,
|
||||
'faktor_penyesuaian' => $this->faktor_penyesuaian,
|
||||
'custom_parameters' => $this->custom_parameters
|
||||
];
|
||||
}
|
||||
|
||||
@@ -66,8 +73,62 @@ class BuildingFunctionParameter extends Model
|
||||
'Fungsi Bangunan' => $this->fungsi_bangunan,
|
||||
'IP Permanen' => $this->ip_permanen,
|
||||
'IP Kompleksitas' => $this->ip_kompleksitas,
|
||||
'IP Ketinggian' => $this->ip_ketinggian,
|
||||
'Indeks Lokalitas' => $this->indeks_lokalitas . '%'
|
||||
'Indeks Lokalitas' => $this->indeks_lokalitas,
|
||||
'Asumsi Prasarana' => $this->asumsi_prasarana,
|
||||
'Koefisien Dasar' => $this->koefisien_dasar,
|
||||
'Faktor Penyesuaian' => $this->faktor_penyesuaian
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate floor result using the main formula
|
||||
*/
|
||||
public function calculateFloorResult(float $ipKetinggian): float
|
||||
{
|
||||
return $this->fungsi_bangunan * (
|
||||
$this->ip_permanen +
|
||||
$this->ip_kompleksitas +
|
||||
(0.5 * $ipKetinggian)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate full retribution for given building area and floor result
|
||||
*/
|
||||
public function calculateRetribution(float $luasBangunan, float $floorResult): float
|
||||
{
|
||||
$baseValue = 70350; // Base retribution value
|
||||
$mainCalculation = 1 * $luasBangunan * ($this->indeks_lokalitas * $baseValue * $floorResult * 1);
|
||||
$additionalCalculation = 0.5 * $mainCalculation;
|
||||
|
||||
return $mainCalculation + $additionalCalculation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply custom parameters if available
|
||||
*/
|
||||
public function getParameterValue(string $key, $default = null)
|
||||
{
|
||||
// First check if it's a standard parameter
|
||||
if (property_exists($this, $key) && $this->$key !== null) {
|
||||
return $this->$key;
|
||||
}
|
||||
|
||||
// Then check custom parameters
|
||||
if ($this->custom_parameters && is_array($this->custom_parameters)) {
|
||||
return $this->custom_parameters[$key] ?? $default;
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set custom parameter
|
||||
*/
|
||||
public function setCustomParameter(string $key, $value): void
|
||||
{
|
||||
$customParams = $this->custom_parameters ?? [];
|
||||
$customParams[$key] = $value;
|
||||
$this->custom_parameters = $customParams;
|
||||
}
|
||||
}
|
||||
|
||||
56
app/Models/FloorHeightIndex.php
Normal file
56
app/Models/FloorHeightIndex.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class FloorHeightIndex extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'floor_number',
|
||||
'ip_ketinggian',
|
||||
'description'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'floor_number' => 'integer',
|
||||
'ip_ketinggian' => 'decimal:6'
|
||||
];
|
||||
|
||||
/**
|
||||
* Get IP ketinggian by floor number
|
||||
*/
|
||||
public static function getIpKetinggianByFloor(int $floorNumber): float
|
||||
{
|
||||
$index = self::where('floor_number', $floorNumber)->first();
|
||||
return $index ? (float) $index->ip_ketinggian : 1.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all IP ketinggian mapping as array
|
||||
*/
|
||||
public static function getAllMapping(): array
|
||||
{
|
||||
return self::orderBy('floor_number')
|
||||
->pluck('ip_ketinggian', 'floor_number')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available floor numbers
|
||||
*/
|
||||
public static function getAvailableFloors(): array
|
||||
{
|
||||
return self::orderBy('floor_number')
|
||||
->pluck('floor_number')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: By floor number
|
||||
*/
|
||||
public function scopeByFloor($query, int $floorNumber)
|
||||
{
|
||||
return $query->where('floor_number', $floorNumber);
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class RetributionCalculation extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'spatial_planning_id',
|
||||
'retribution_formula_id',
|
||||
'detected_building_function_id',
|
||||
'luas_bangunan',
|
||||
'used_parameters',
|
||||
'used_formula',
|
||||
'calculation_result',
|
||||
'calculation_date',
|
||||
'calculated_by',
|
||||
'notes'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'luas_bangunan' => 'decimal:6',
|
||||
'calculation_result' => 'decimal:6',
|
||||
'used_parameters' => 'array',
|
||||
'calculation_date' => 'datetime'
|
||||
];
|
||||
|
||||
/**
|
||||
* Spatial planning relationship (1:1)
|
||||
*/
|
||||
public function spatialPlanning(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SpatialPlanning::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retribution formula relationship
|
||||
*/
|
||||
public function retributionFormula(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(RetributionFormula::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detected building function relationship
|
||||
*/
|
||||
public function detectedBuildingFunction(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(BuildingFunction::class, 'detected_building_function_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* User who calculated relationship
|
||||
*/
|
||||
public function calculatedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'calculated_by');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Recent calculations
|
||||
*/
|
||||
public function scopeRecent($query, int $days = 30)
|
||||
{
|
||||
return $query->where('calculation_date', '>=', now()->subDays($days));
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: By building function
|
||||
*/
|
||||
public function scopeByBuildingFunction($query, int $buildingFunctionId)
|
||||
{
|
||||
return $query->where('detected_building_function_id', $buildingFunctionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted calculation result
|
||||
*/
|
||||
public function getFormattedResultAttribute(): string
|
||||
{
|
||||
return number_format($this->calculation_result, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get calculation summary
|
||||
*/
|
||||
public function getCalculationSummary(): array
|
||||
{
|
||||
return [
|
||||
'spatial_planning' => $this->spatialPlanning->name ?? 'N/A',
|
||||
'building_function' => $this->detectedBuildingFunction->name ?? 'N/A',
|
||||
'luas_bangunan' => $this->luas_bangunan,
|
||||
'formula_used' => $this->used_formula,
|
||||
'parameters_used' => $this->used_parameters,
|
||||
'result' => $this->calculation_result,
|
||||
'calculated_date' => $this->calculation_date?->format('Y-m-d H:i:s'),
|
||||
'calculated_by' => $this->calculatedBy->name ?? 'System'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if calculation is recent (within last 24 hours)
|
||||
*/
|
||||
public function isRecent(): bool
|
||||
{
|
||||
return $this->calculation_date && $this->calculation_date->isAfter(now()->subDay());
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculate retribution
|
||||
*/
|
||||
public function recalculate(): bool
|
||||
{
|
||||
if (!$this->spatialPlanning || !$this->retributionFormula) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$service = app(\App\Services\RetributionCalculationService::class);
|
||||
$service->calculateRetribution($this->spatialPlanning);
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
\Log::error('Recalculation failed: ' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,16 @@ class RetributionFormula extends Model
|
||||
protected $fillable = [
|
||||
'building_function_id',
|
||||
'name',
|
||||
'formula_expression',
|
||||
'description',
|
||||
'is_active'
|
||||
'floor_number',
|
||||
'formula_expression'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean'
|
||||
'floor_number' => 'integer'
|
||||
];
|
||||
|
||||
/**
|
||||
* Building function relationship (1:1)
|
||||
* Building function relationship (n:1)
|
||||
*/
|
||||
public function buildingFunction(): BelongsTo
|
||||
{
|
||||
@@ -29,45 +28,47 @@ class RetributionFormula extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Retribution calculations relationship (1:n)
|
||||
* Retribution proposals relationship (1:n)
|
||||
*/
|
||||
public function retributionCalculations(): HasMany
|
||||
public function retributionProposals(): HasMany
|
||||
{
|
||||
return $this->hasMany(RetributionCalculation::class);
|
||||
return $this->hasMany(RetributionProposal::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Active formulas only
|
||||
* Scope: By floor number
|
||||
*/
|
||||
public function scopeActive($query)
|
||||
public function scopeByFloor($query, int $floorNumber)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
return $query->where('floor_number', $floorNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute formula calculation
|
||||
* Execute formula calculation with parameters and IP ketinggian
|
||||
*/
|
||||
public function calculate(float $luasBangunan, array $parameters): float
|
||||
public function calculate(float $luasBangunan, array $parameters, float $ipKetinggian): float
|
||||
{
|
||||
// Replace placeholders in formula with actual values
|
||||
$formula = $this->formula_expression;
|
||||
// Extract parameters
|
||||
$fungsi_bangunan = $parameters['fungsi_bangunan'] ?? 0;
|
||||
$ip_permanen = $parameters['ip_permanen'] ?? 0;
|
||||
$ip_kompleksitas = $parameters['ip_kompleksitas'] ?? 0;
|
||||
$indeks_lokalitas = $parameters['indeks_lokalitas'] ?? 0;
|
||||
|
||||
// Calculate H13 (floor coefficient) using Excel formula
|
||||
$h13 = $fungsi_bangunan * ($ip_permanen + $ip_kompleksitas + (0.5 * $ipKetinggian));
|
||||
|
||||
// Calculate full retribution using Excel formula
|
||||
$baseValue = 70350;
|
||||
$additionalFactor = 0.5;
|
||||
|
||||
// Replace luas_bangunan
|
||||
$formula = str_replace('luas_bangunan', $luasBangunan, $formula);
|
||||
// Main calculation: (1*D13*(N13*70350*H13*1))
|
||||
$mainCalculation = 1 * $luasBangunan * ($indeks_lokalitas * $baseValue * $h13 * 1);
|
||||
|
||||
// Replace parameter values
|
||||
foreach ($parameters as $key => $value) {
|
||||
$formula = str_replace($key, $value, $formula);
|
||||
}
|
||||
// Additional calculation: ($O$3*(1*D13*(N13*70350*H13*1)))
|
||||
$additionalCalculation = $additionalFactor * $mainCalculation;
|
||||
|
||||
// Evaluate the mathematical expression
|
||||
// Note: In production, use a safer math expression evaluator
|
||||
try {
|
||||
$result = eval("return $formula;");
|
||||
return (float) $result;
|
||||
} catch (Exception $e) {
|
||||
throw new \Exception("Error calculating formula: " . $e->getMessage());
|
||||
}
|
||||
// Total: main + additional
|
||||
return $mainCalculation + $additionalCalculation;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,19 +88,140 @@ class RetributionFormula extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate formula expression
|
||||
* Check if this formula applies to given floor number
|
||||
*/
|
||||
public function appliesTo(int $floorNumber): bool
|
||||
{
|
||||
// If floor_number is 0, formula applies to all floors
|
||||
if ($this->floor_number === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise, exact match required
|
||||
return $this->floor_number == $floorNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get human readable floor description
|
||||
*/
|
||||
public function getFloorDescription(): string
|
||||
{
|
||||
if ($this->floor_number === 0) {
|
||||
return 'Semua lantai';
|
||||
}
|
||||
|
||||
return "Lantai {$this->floor_number}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default formula expression
|
||||
*/
|
||||
public static function getDefaultFormula(): string
|
||||
{
|
||||
return '(fungsi_bangunan * (ip_permanen + ip_kompleksitas + (0.5 * ip_ketinggian)))';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate formula expression syntax
|
||||
*/
|
||||
public function validateFormula(): bool
|
||||
{
|
||||
// Basic validation - check if formula contains required elements
|
||||
$requiredElements = ['luas_bangunan'];
|
||||
// Basic validation - check if formula contains required variables
|
||||
$requiredVariables = ['fungsi_bangunan', 'ip_permanen', 'ip_kompleksitas', 'ip_ketinggian'];
|
||||
|
||||
foreach ($requiredElements as $element) {
|
||||
if (strpos($this->formula_expression, $element) === false) {
|
||||
foreach ($requiredVariables as $variable) {
|
||||
if (strpos($this->formula_expression, $variable) === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get calculation breakdown for debugging
|
||||
*/
|
||||
public function getCalculationBreakdown(float $luasBangunan, array $parameters, float $ipKetinggian): array
|
||||
{
|
||||
// Extract parameters
|
||||
$fungsi_bangunan = $parameters['fungsi_bangunan'] ?? 0;
|
||||
$ip_permanen = $parameters['ip_permanen'] ?? 0;
|
||||
$ip_kompleksitas = $parameters['ip_kompleksitas'] ?? 0;
|
||||
$indeks_lokalitas = $parameters['indeks_lokalitas'] ?? 0;
|
||||
|
||||
// Calculate H13 (floor coefficient)
|
||||
$h13 = $fungsi_bangunan * ($ip_permanen + $ip_kompleksitas + (0.5 * $ipKetinggian));
|
||||
|
||||
// Calculate components
|
||||
$baseValue = 70350;
|
||||
$additionalFactor = 0.5;
|
||||
$mainCalculation = 1 * $luasBangunan * ($indeks_lokalitas * $baseValue * $h13 * 1);
|
||||
$additionalCalculation = $additionalFactor * $mainCalculation;
|
||||
$totalCalculation = $mainCalculation + $additionalCalculation;
|
||||
|
||||
return [
|
||||
'input_parameters' => [
|
||||
'luas_bangunan' => $luasBangunan,
|
||||
'fungsi_bangunan' => $fungsi_bangunan,
|
||||
'ip_permanen' => $ip_permanen,
|
||||
'ip_kompleksitas' => $ip_kompleksitas,
|
||||
'ip_ketinggian' => $ipKetinggian,
|
||||
'indeks_lokalitas' => $indeks_lokalitas,
|
||||
'base_value' => $baseValue,
|
||||
'additional_factor' => $additionalFactor
|
||||
],
|
||||
'calculation_steps' => [
|
||||
'h13_calculation' => [
|
||||
'formula' => 'fungsi_bangunan * (ip_permanen + ip_kompleksitas + (0.5 * ip_ketinggian))',
|
||||
'calculation' => "{$fungsi_bangunan} * ({$ip_permanen} + {$ip_kompleksitas} + (0.5 * {$ipKetinggian}))",
|
||||
'result' => $h13
|
||||
],
|
||||
'main_calculation' => [
|
||||
'formula' => '1 * luas_bangunan * (indeks_lokalitas * base_value * h13 * 1)',
|
||||
'calculation' => "1 * {$luasBangunan} * ({$indeks_lokalitas} * {$baseValue} * {$h13} * 1)",
|
||||
'result' => $mainCalculation
|
||||
],
|
||||
'additional_calculation' => [
|
||||
'formula' => 'additional_factor * main_calculation',
|
||||
'calculation' => "{$additionalFactor} * {$mainCalculation}",
|
||||
'result' => $additionalCalculation
|
||||
],
|
||||
'total_calculation' => [
|
||||
'formula' => 'main_calculation + additional_calculation',
|
||||
'calculation' => "{$mainCalculation} + {$additionalCalculation}",
|
||||
'result' => $totalCalculation
|
||||
]
|
||||
],
|
||||
'formatted_results' => [
|
||||
'h13' => number_format($h13, 6),
|
||||
'main_calculation' => 'Rp ' . number_format($mainCalculation, 2),
|
||||
'additional_calculation' => 'Rp ' . number_format($additionalCalculation, 2),
|
||||
'total_calculation' => 'Rp ' . number_format($totalCalculation, 2)
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this formula has been used in any proposals
|
||||
*/
|
||||
public function hasProposals(): bool
|
||||
{
|
||||
return $this->retributionProposals()->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total amount calculated using this formula
|
||||
*/
|
||||
public function getTotalCalculatedAmount(): float
|
||||
{
|
||||
return $this->retributionProposals()->sum('total_retribution_amount');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get count of proposals using this formula
|
||||
*/
|
||||
public function getProposalCount(): int
|
||||
{
|
||||
return $this->retributionProposals()->count();
|
||||
}
|
||||
}
|
||||
|
||||
187
app/Models/RetributionProposal.php
Normal file
187
app/Models/RetributionProposal.php
Normal file
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class RetributionProposal extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'spatial_planning_id',
|
||||
'building_function_id',
|
||||
'retribution_formula_id',
|
||||
'proposal_number',
|
||||
'floor_number',
|
||||
'floor_area',
|
||||
'total_building_area',
|
||||
'ip_ketinggian',
|
||||
'floor_retribution_amount',
|
||||
'total_retribution_amount',
|
||||
'calculation_parameters',
|
||||
'calculation_breakdown',
|
||||
'notes',
|
||||
'calculated_at'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'floor_area' => 'decimal:6',
|
||||
'total_building_area' => 'decimal:6',
|
||||
'ip_ketinggian' => 'decimal:6',
|
||||
'floor_retribution_amount' => 'decimal:2',
|
||||
'total_retribution_amount' => 'decimal:2',
|
||||
'calculation_parameters' => 'array',
|
||||
'calculation_breakdown' => 'array',
|
||||
'calculated_at' => 'datetime'
|
||||
];
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Relationship with SpatialPlanning
|
||||
*/
|
||||
public function spatialPlanning(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SpatialPlanning::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Relationship with BuildingFunction
|
||||
*/
|
||||
public function buildingFunction(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(BuildingFunction::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Relationship with RetributionFormula
|
||||
*/
|
||||
public function retributionFormula(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(RetributionFormula::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate proposal number
|
||||
*/
|
||||
public static function generateProposalNumber(): string
|
||||
{
|
||||
$year = now()->format('Y');
|
||||
$month = now()->format('m');
|
||||
|
||||
// Use max ID + 1 to avoid duplicates when records are deleted
|
||||
$maxId = static::whereYear('created_at', now()->year)
|
||||
->whereMonth('created_at', now()->month)
|
||||
->max('id') ?? 0;
|
||||
$nextNumber = $maxId + 1;
|
||||
|
||||
// Fallback: if still duplicate, use timestamp
|
||||
$proposalNumber = sprintf('RP-%s%s-%04d', $year, $month, $nextNumber);
|
||||
|
||||
// Check if exists and increment until unique
|
||||
$counter = $nextNumber;
|
||||
while (static::where('proposal_number', $proposalNumber)->exists()) {
|
||||
$counter++;
|
||||
$proposalNumber = sprintf('RP-%s%s-%04d', $year, $month, $counter);
|
||||
}
|
||||
|
||||
return $proposalNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted floor retribution amount
|
||||
*/
|
||||
public function getFormattedFloorAmountAttribute(): string
|
||||
{
|
||||
return 'Rp ' . number_format($this->floor_retribution_amount, 0, ',', '.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted total retribution amount
|
||||
*/
|
||||
public function getFormattedTotalAmountAttribute(): string
|
||||
{
|
||||
return 'Rp ' . number_format($this->total_retribution_amount, 0, ',', '.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get calculation breakdown for specific parameter
|
||||
*/
|
||||
public function getCalculationBreakdownFor(string $parameter)
|
||||
{
|
||||
return $this->calculation_breakdown[$parameter] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get parameter value
|
||||
*/
|
||||
public function getParameterValue(string $parameter)
|
||||
{
|
||||
return $this->calculation_parameters[$parameter] ?? null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Scope for filtering by building function
|
||||
*/
|
||||
public function scopeByBuildingFunction($query, int $buildingFunctionId)
|
||||
{
|
||||
return $query->where('building_function_id', $buildingFunctionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope for filtering by spatial planning
|
||||
*/
|
||||
public function scopeBySpatialPlanning($query, int $spatialPlanningId)
|
||||
{
|
||||
return $query->where('spatial_planning_id', $spatialPlanningId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total retribution amount for multiple proposals
|
||||
*/
|
||||
public static function getTotalAmount($proposals = null): float
|
||||
{
|
||||
if ($proposals) {
|
||||
return $proposals->sum('total_retribution_amount');
|
||||
}
|
||||
|
||||
return static::sum('total_retribution_amount');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get basic statistics
|
||||
*/
|
||||
public static function getBasicStats(): array
|
||||
{
|
||||
return [
|
||||
'total_count' => static::count(),
|
||||
'total_amount' => static::sum('total_retribution_amount'),
|
||||
'average_amount' => static::avg('total_retribution_amount'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Boot method to generate proposal number
|
||||
*/
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($model) {
|
||||
if (empty($model->proposal_number)) {
|
||||
$model->proposal_number = static::generateProposalNumber();
|
||||
}
|
||||
|
||||
if (empty($model->calculated_at)) {
|
||||
$model->calculated_at = now();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
@@ -44,11 +45,11 @@ class SpatialPlanning extends Model
|
||||
];
|
||||
|
||||
/**
|
||||
* Retribution calculation relationship (1:1)
|
||||
* Retribution proposals relationship (1:many)
|
||||
*/
|
||||
public function retributionCalculation(): HasOne
|
||||
public function retributionProposals(): HasMany
|
||||
{
|
||||
return $this->hasOne(RetributionCalculation::class);
|
||||
return $this->hasMany(RetributionProposal::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,11 +61,27 @@ class SpatialPlanning extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if spatial planning has retribution calculation
|
||||
* Check if spatial planning has retribution proposals
|
||||
*/
|
||||
public function hasRetributionCalculation(): bool
|
||||
public function hasRetributionProposals(): bool
|
||||
{
|
||||
return $this->retributionCalculation()->exists();
|
||||
return $this->retributionProposals()->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest retribution proposal
|
||||
*/
|
||||
public function getLatestRetributionProposal()
|
||||
{
|
||||
return $this->retributionProposals()->latest()->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all retribution proposals
|
||||
*/
|
||||
public function getAllRetributionProposals()
|
||||
{
|
||||
return $this->retributionProposals()->get();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,18 +101,20 @@ class SpatialPlanning extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Without retribution calculation
|
||||
* Scope: Without retribution proposals
|
||||
*/
|
||||
public function scopeWithoutRetributionCalculation($query)
|
||||
public function scopeWithoutRetributionProposals($query)
|
||||
{
|
||||
return $query->whereDoesntHave('retributionCalculation');
|
||||
return $query->whereDoesntHave('retributionProposals');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: With retribution calculation
|
||||
* Scope: With retribution proposals
|
||||
*/
|
||||
public function scopeWithRetributionCalculation($query)
|
||||
public function scopeWithRetributionProposals($query)
|
||||
{
|
||||
return $query->whereHas('retributionCalculation');
|
||||
return $query->whereHas('retributionProposals');
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
294
app/Services/RetributionProposalService.php
Normal file
294
app/Services/RetributionProposalService.php
Normal file
@@ -0,0 +1,294 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SpatialPlanning;
|
||||
use App\Models\BuildingFunction;
|
||||
use App\Models\RetributionProposal;
|
||||
use App\Models\RetributionFormula;
|
||||
use App\Models\FloorHeightIndex;
|
||||
use App\Models\BuildingFunctionParameter;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class RetributionProposalService
|
||||
{
|
||||
/**
|
||||
* Create retribution proposal for spatial planning
|
||||
*/
|
||||
public function createProposalForSpatialPlanning(
|
||||
SpatialPlanning $spatialPlanning,
|
||||
int $buildingFunctionId,
|
||||
int $floorNumber,
|
||||
float $floorArea,
|
||||
float $totalBuildingArea = null,
|
||||
string $notes = null
|
||||
): RetributionProposal {
|
||||
// Get building function and its parameters
|
||||
$buildingFunction = BuildingFunction::with('parameter')->findOrFail($buildingFunctionId);
|
||||
$parameters = $buildingFunction->parameter;
|
||||
|
||||
if (!$parameters) {
|
||||
throw new \Exception("Building function parameters not found for ID: {$buildingFunctionId}");
|
||||
}
|
||||
|
||||
// Get floor height index
|
||||
$floorHeightIndex = FloorHeightIndex::where('floor_number', $floorNumber)->first();
|
||||
if (!$floorHeightIndex) {
|
||||
throw new \Exception("Floor height index not found for floor: {$floorNumber}");
|
||||
}
|
||||
|
||||
// Get retribution formula
|
||||
$retributionFormula = RetributionFormula::where('building_function_id', $buildingFunctionId)
|
||||
->where('floor_number', $floorNumber)
|
||||
->first();
|
||||
|
||||
if (!$retributionFormula) {
|
||||
throw new \Exception("Retribution formula not found for building function ID: {$buildingFunctionId}, floor: {$floorNumber}");
|
||||
}
|
||||
|
||||
// Calculate retribution using Excel formula
|
||||
$calculationResult = $this->calculateRetribution(
|
||||
$floorArea,
|
||||
$parameters,
|
||||
$floorHeightIndex->ip_ketinggian
|
||||
);
|
||||
|
||||
// Create retribution proposal
|
||||
return RetributionProposal::create([
|
||||
'spatial_planning_id' => $spatialPlanning->id,
|
||||
'building_function_id' => $buildingFunctionId,
|
||||
'retribution_formula_id' => $retributionFormula->id,
|
||||
'floor_number' => $floorNumber,
|
||||
'floor_area' => $floorArea,
|
||||
'total_building_area' => $totalBuildingArea ?? $floorArea,
|
||||
'ip_ketinggian' => $floorHeightIndex->ip_ketinggian,
|
||||
'floor_retribution_amount' => $calculationResult['total_retribution'],
|
||||
'total_retribution_amount' => $calculationResult['total_retribution'],
|
||||
'calculation_parameters' => $calculationResult['parameters'],
|
||||
'calculation_breakdown' => $calculationResult['breakdown'],
|
||||
'notes' => $notes,
|
||||
'calculated_at' => Carbon::now()
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create proposal without spatial planning
|
||||
*/
|
||||
public function createStandaloneProposal(
|
||||
int $buildingFunctionId,
|
||||
int $floorNumber,
|
||||
float $floorArea,
|
||||
float $totalBuildingArea = null,
|
||||
string $notes = null
|
||||
): RetributionProposal {
|
||||
// Get building function and its parameters
|
||||
$buildingFunction = BuildingFunction::with('parameter')->findOrFail($buildingFunctionId);
|
||||
$parameters = $buildingFunction->parameter;
|
||||
|
||||
if (!$parameters) {
|
||||
throw new \Exception("Building function parameters not found for ID: {$buildingFunctionId}");
|
||||
}
|
||||
|
||||
// Get floor height index
|
||||
$floorHeightIndex = FloorHeightIndex::where('floor_number', $floorNumber)->first();
|
||||
if (!$floorHeightIndex) {
|
||||
throw new \Exception("Floor height index not found for floor: {$floorNumber}");
|
||||
}
|
||||
|
||||
// Get retribution formula
|
||||
$retributionFormula = RetributionFormula::where('building_function_id', $buildingFunctionId)
|
||||
->where('floor_number', $floorNumber)
|
||||
->first();
|
||||
|
||||
if (!$retributionFormula) {
|
||||
throw new \Exception("Retribution formula not found for building function ID: {$buildingFunctionId}, floor: {$floorNumber}");
|
||||
}
|
||||
|
||||
// Calculate retribution using Excel formula
|
||||
$calculationResult = $this->calculateRetribution(
|
||||
$floorArea,
|
||||
$parameters,
|
||||
$floorHeightIndex->ip_ketinggian
|
||||
);
|
||||
|
||||
// Create retribution proposal
|
||||
return RetributionProposal::create([
|
||||
'spatial_planning_id' => null,
|
||||
'building_function_id' => $buildingFunctionId,
|
||||
'retribution_formula_id' => $retributionFormula->id,
|
||||
'floor_number' => $floorNumber,
|
||||
'floor_area' => $floorArea,
|
||||
'total_building_area' => $totalBuildingArea ?? $floorArea,
|
||||
'ip_ketinggian' => $floorHeightIndex->ip_ketinggian,
|
||||
'floor_retribution_amount' => $calculationResult['total_retribution'],
|
||||
'total_retribution_amount' => $calculationResult['total_retribution'],
|
||||
'calculation_parameters' => $calculationResult['parameters'],
|
||||
'calculation_breakdown' => $calculationResult['breakdown'],
|
||||
'notes' => $notes,
|
||||
'calculated_at' => Carbon::now()
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate retribution using Excel formula
|
||||
*/
|
||||
protected function calculateRetribution(
|
||||
float $floorArea,
|
||||
BuildingFunctionParameter $parameters,
|
||||
float $ipKetinggian
|
||||
): array {
|
||||
// Excel formula parameters
|
||||
$fungsi_bangunan = $parameters->fungsi_bangunan;
|
||||
$ip_permanen = $parameters->ip_permanen;
|
||||
$ip_kompleksitas = $parameters->ip_kompleksitas;
|
||||
$indeks_lokalitas = $parameters->indeks_lokalitas;
|
||||
$base_value = 70350;
|
||||
$additional_factor = 0.5;
|
||||
|
||||
// Step 1: Calculate H13 (floor coefficient)
|
||||
$h13 = $fungsi_bangunan * ($ip_permanen + $ip_kompleksitas + (0.5 * $ipKetinggian));
|
||||
|
||||
// Step 2: Main calculation
|
||||
$main_calculation = 1 * $floorArea * ($indeks_lokalitas * $base_value * $h13 * 1);
|
||||
|
||||
// Step 3: Additional (50%)
|
||||
$additional_calculation = $additional_factor * $main_calculation;
|
||||
|
||||
// Step 4: Total
|
||||
$total_retribution = $main_calculation + $additional_calculation;
|
||||
|
||||
return [
|
||||
'total_retribution' => $total_retribution,
|
||||
'parameters' => [
|
||||
'fungsi_bangunan' => $fungsi_bangunan,
|
||||
'ip_permanen' => $ip_permanen,
|
||||
'ip_kompleksitas' => $ip_kompleksitas,
|
||||
'ip_ketinggian' => $ipKetinggian,
|
||||
'indeks_lokalitas' => $indeks_lokalitas,
|
||||
'base_value' => $base_value,
|
||||
'additional_factor' => $additional_factor,
|
||||
'floor_area' => $floorArea
|
||||
],
|
||||
'breakdown' => [
|
||||
'h13_calculation' => [
|
||||
'formula' => 'fungsi_bangunan * (ip_permanen + ip_kompleksitas + (0.5 * ip_ketinggian))',
|
||||
'calculation' => "{$fungsi_bangunan} * ({$ip_permanen} + {$ip_kompleksitas} + (0.5 * {$ipKetinggian}))",
|
||||
'result' => $h13
|
||||
],
|
||||
'main_calculation' => [
|
||||
'formula' => '1 * floor_area * (indeks_lokalitas * base_value * h13 * 1)',
|
||||
'calculation' => "1 * {$floorArea} * ({$indeks_lokalitas} * {$base_value} * {$h13} * 1)",
|
||||
'result' => $main_calculation
|
||||
],
|
||||
'additional_calculation' => [
|
||||
'formula' => 'additional_factor * main_calculation',
|
||||
'calculation' => "{$additional_factor} * {$main_calculation}",
|
||||
'result' => $additional_calculation
|
||||
],
|
||||
'total_calculation' => [
|
||||
'formula' => 'main_calculation + additional_calculation',
|
||||
'calculation' => "{$main_calculation} + {$additional_calculation}",
|
||||
'result' => $total_retribution
|
||||
]
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get proposal statistics
|
||||
*/
|
||||
public function getStatistics(): array
|
||||
{
|
||||
return [
|
||||
'total_proposals' => RetributionProposal::count(),
|
||||
'total_amount' => RetributionProposal::sum('total_retribution_amount'),
|
||||
'average_amount' => RetributionProposal::avg('total_retribution_amount'),
|
||||
'proposals_with_spatial_planning' => RetributionProposal::whereNotNull('spatial_planning_id')->count(),
|
||||
'proposals_without_spatial_planning' => RetributionProposal::whereNull('spatial_planning_id')->count(),
|
||||
'by_building_function' => RetributionProposal::with('buildingFunction')
|
||||
->selectRaw('building_function_id, COUNT(*) as count, SUM(total_retribution_amount) as total_amount')
|
||||
->groupBy('building_function_id')
|
||||
->orderBy('total_amount', 'desc')
|
||||
->get()
|
||||
->map(function ($item) {
|
||||
return [
|
||||
'building_function_id' => $item->building_function_id,
|
||||
'building_function_name' => $item->buildingFunction->name ?? 'Unknown',
|
||||
'count' => $item->count,
|
||||
'total_amount' => $item->total_amount,
|
||||
'formatted_amount' => 'Rp ' . number_format($item->total_amount, 0, ',', '.')
|
||||
];
|
||||
})->toArray()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect building function from text
|
||||
*/
|
||||
public function detectBuildingFunction(string $text): ?BuildingFunction
|
||||
{
|
||||
$text = strtolower($text);
|
||||
|
||||
// Detection patterns - order matters (more specific first)
|
||||
$patterns = [
|
||||
'HUNIAN_TIDAK_SEDERHANA' => [
|
||||
'hunian mewah', 'villa', 'apartemen', 'kondominium', 'townhouse'
|
||||
],
|
||||
'HUNIAN_SEDERHANA' => [
|
||||
'hunian sederhana', 'hunian', 'rumah', 'perumahan', 'residential', 'fungsi hunian'
|
||||
],
|
||||
'USAHA_BESAR' => [
|
||||
'usaha besar', 'pabrik', 'industri', 'mall', 'hotel', 'restoran', 'supermarket',
|
||||
'plaza', 'gedung perkantoran', 'non-mikro', 'non mikro'
|
||||
],
|
||||
'USAHA_KECIL' => [
|
||||
'usaha kecil', 'umkm', 'warung', 'toko', 'mikro', 'kios'
|
||||
],
|
||||
'CAMPURAN_BESAR' => [
|
||||
'campuran besar', 'mixed use besar'
|
||||
],
|
||||
'CAMPURAN_KECIL' => [
|
||||
'campuran kecil', 'ruko', 'mixed use', 'campuran'
|
||||
],
|
||||
'SOSIAL_BUDAYA' => [
|
||||
'sekolah', 'rumah sakit', 'masjid', 'gereja', 'puskesmas', 'klinik',
|
||||
'universitas', 'perpustakaan', 'museum'
|
||||
],
|
||||
'AGAMA' => [
|
||||
'tempat ibadah', 'masjid', 'mushola', 'gereja', 'pura', 'vihara', 'klenteng'
|
||||
]
|
||||
];
|
||||
|
||||
// Try to find exact matches first
|
||||
foreach ($patterns as $functionCode => $keywords) {
|
||||
foreach ($keywords as $keyword) {
|
||||
if (strpos($text, $keyword) !== false) {
|
||||
$buildingFunction = BuildingFunction::where('code', $functionCode)->first();
|
||||
if ($buildingFunction) {
|
||||
return $buildingFunction;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Debug: Log what we're trying to match
|
||||
\Illuminate\Support\Facades\Log::info("Building function detection failed for text: '{$text}'");
|
||||
|
||||
// If no exact match, try to find by name similarity
|
||||
$allFunctions = BuildingFunction::whereNotNull('parent_id')->get(); // Only child functions
|
||||
|
||||
foreach ($allFunctions as $function) {
|
||||
$functionName = strtolower($function->name);
|
||||
|
||||
// Check if any word from the function name appears in the text
|
||||
$words = explode(' ', $functionName);
|
||||
foreach ($words as $word) {
|
||||
if (strlen($word) > 3 && strpos($text, $word) !== false) {
|
||||
return $function;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Models\BigdataResume;
|
||||
use App\Models\DataSetting;
|
||||
use App\Models\ImportDatasource;
|
||||
use App\Models\PbgTaskGoogleSheet;
|
||||
use App\Models\RetributionProposal;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Google\Client as Google_Client;
|
||||
@@ -249,7 +250,7 @@ class ServiceGoogleSheet
|
||||
|
||||
BigdataResume::create([
|
||||
'import_datasource_id' => $import_datasource->id,
|
||||
'year' => now()->year,
|
||||
'year' => 'leader',
|
||||
// USAHA
|
||||
'business_count' => $this->convertToInteger($result['USAHA']['total'] ?? null) ?? 0,
|
||||
'business_sum' => $this->convertToDecimal($result['USAHA']['nominal'] ?? null) ?? 0,
|
||||
@@ -273,7 +274,10 @@ class ServiceGoogleSheet
|
||||
'waiting_click_dpmptsp_sum' => $this->convertToDecimal($result['WAITING_KLIK_DPMPTSP']['nominal'] ?? null) ?? 0,
|
||||
// PROSES DINAS TEKNIS
|
||||
'process_in_technical_office_count' => $this->convertToInteger($result['PROSES_DINAS_TEKNIS']['total'] ?? null) ?? 0,
|
||||
'process_in_technical_office_sum' => $this->convertToDecimal($result['PROSES_DINAS_TEKNIS']['nominal'] ?? null) ?? 0
|
||||
'process_in_technical_office_sum' => $this->convertToDecimal($result['PROSES_DINAS_TEKNIS']['nominal'] ?? null) ?? 0,
|
||||
// TATA RUANG
|
||||
'spatial_count' => RetributionProposal::count(),
|
||||
'spatial_sum' => RetributionProposal::sum('total_retribution_amount'),
|
||||
]);
|
||||
|
||||
// Save data settings
|
||||
|
||||
Reference in New Issue
Block a user