done restructure calculation retribution

This commit is contained in:
arifal
2025-06-19 13:48:35 +07:00
parent 4c3443c2d6
commit 285e89d5d0
27 changed files with 791 additions and 3161 deletions

View File

@@ -0,0 +1,467 @@
<?php
namespace App\Console\Commands;
use App\Models\SpatialPlanning;
use App\Models\RetributionCalculation;
use App\Models\BuildingType;
use App\Services\RetributionCalculatorService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AssignSpatialPlanningsToCalculation extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'spatial-planning:assign-calculations
{--force : Force assign even if already has calculation}
{--recalculate : Recalculate existing calculations with new values}
{--chunk=100 : Process in chunks}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Assign retribution calculations to spatial plannings (supports recalculate for existing calculations)';
protected $calculatorService;
public function __construct(RetributionCalculatorService $calculatorService)
{
parent::__construct();
$this->calculatorService = $calculatorService;
}
/**
* Execute the console command.
*/
public function handle()
{
$this->info('🏗️ Starting spatial planning calculation assignment...');
// Get processing options
$force = $this->option('force');
$recalculate = $this->option('recalculate');
$chunkSize = (int) $this->option('chunk');
// Get spatial plannings query
$query = SpatialPlanning::query();
if ($recalculate) {
// Recalculate mode: only process those WITH active calculations
$query->whereHas('retributionCalculations', function ($q) {
$q->where('is_active', true);
});
$this->info('🔄 Recalculate mode: Processing spatial plannings with existing calculations');
} elseif (!$force) {
// Normal mode: only process those without active calculations
$query->whereDoesntHave('retributionCalculations', function ($q) {
$q->where('is_active', true);
});
$this->info(' Normal mode: Processing spatial plannings without calculations');
} else {
// Force mode: process all
$this->info('🔥 Force mode: Processing ALL spatial plannings');
}
$totalRecords = $query->count();
if ($totalRecords === 0) {
$this->warn('No spatial plannings found to process.');
return 0;
}
$this->info("Found {$totalRecords} spatial planning(s) to process");
if (!$this->confirm('Do you want to continue?')) {
$this->info('Operation cancelled.');
return 0;
}
// Process in chunks
$processed = 0;
$errors = 0;
$reused = 0;
$created = 0;
$buildingTypeStats = [];
$progressBar = $this->output->createProgressBar($totalRecords);
$progressBar->start();
$recalculated = 0;
$query->chunk($chunkSize, function ($spatialPlannings) use (&$processed, &$errors, &$reused, &$created, &$recalculated, &$buildingTypeStats, $progressBar, $recalculate) {
foreach ($spatialPlannings as $spatialPlanning) {
try {
$result = $this->assignCalculationToSpatialPlanning($spatialPlanning, $recalculate);
if ($result['reused']) {
$reused++;
} elseif (isset($result['recalculated']) && $result['recalculated']) {
$recalculated++;
} else {
$created++;
}
// Track building type statistics
$buildingTypeName = $result['building_type_name'] ?? 'Unknown';
if (!isset($buildingTypeStats[$buildingTypeName])) {
$buildingTypeStats[$buildingTypeName] = 0;
}
$buildingTypeStats[$buildingTypeName]++;
$processed++;
} catch (\Exception $e) {
$errors++;
$this->error("Error processing ID {$spatialPlanning->id}: " . $e->getMessage());
}
$progressBar->advance();
}
});
$progressBar->finish();
// Show summary
$this->newLine(2);
$this->info('✅ Assignment completed!');
if ($recalculate) {
$this->table(
['Metric', 'Count'],
[
['Total Processed', $processed],
['Recalculated (Changed)', $recalculated],
['Unchanged', $reused],
['Errors', $errors],
]
);
} else {
$this->table(
['Metric', 'Count'],
[
['Total Processed', $processed],
['Calculations Created', $created],
['Calculations Reused', $reused],
['Errors', $errors],
]
);
}
// Show building type statistics
if (!empty($buildingTypeStats)) {
$this->newLine();
$this->info('📊 Building Type Distribution:');
$statsRows = [];
arsort($buildingTypeStats); // Sort by count descending
foreach ($buildingTypeStats as $typeName => $count) {
$percentage = round(($count / $processed) * 100, 1);
$statsRows[] = [$typeName, $count, $percentage . '%'];
}
$this->table(['Building Type', 'Count', 'Percentage'], $statsRows);
}
return 0;
}
/**
* Assign calculation to a spatial planning
*/
private function assignCalculationToSpatialPlanning(SpatialPlanning $spatialPlanning, bool $recalculate = false): array
{
// 1. Detect building type
$buildingType = $this->detectBuildingType($spatialPlanning->building_function);
// 2. Get calculation parameters (round to 2 decimal places)
$floorNumber = $spatialPlanning->number_of_floors ?: 1;
$buildingArea = round($spatialPlanning->getCalculationArea(), 2);
if ($buildingArea <= 0) {
throw new \Exception("Invalid building area: {$buildingArea}");
}
$reused = false;
$isRecalculated = false;
if ($recalculate) {
// Recalculate mode: Always create new calculation
$calculationResult = $this->performCalculation($spatialPlanning, $buildingType);
// Check if spatial planning has existing active calculation
$currentActiveCalculation = $spatialPlanning->activeRetributionCalculation;
if ($currentActiveCalculation) {
$oldAmount = $currentActiveCalculation->retributionCalculation->retribution_amount;
$oldArea = $currentActiveCalculation->retributionCalculation->building_area;
$newAmount = $calculationResult['amount'];
// Check if there's a significant difference (more than 1 rupiah)
if (abs($oldAmount - $newAmount) > 1) {
// Create new calculation
$calculation = RetributionCalculation::create([
'building_type_id' => $buildingType->id,
'floor_number' => $floorNumber,
'building_area' => $buildingArea,
'retribution_amount' => $calculationResult['amount'],
'calculation_detail' => $calculationResult['detail'],
]);
// Assign new calculation
$spatialPlanning->assignRetributionCalculation(
$calculation,
"Recalculated: Area {$oldArea}{$buildingArea}, Amount {$oldAmount}{$newAmount}"
);
$isRecalculated = true;
} else {
// No significant difference, keep existing
$calculation = $currentActiveCalculation->retributionCalculation;
$reused = true;
}
} else {
// No existing calculation, create new
$calculation = RetributionCalculation::create([
'building_type_id' => $buildingType->id,
'floor_number' => $floorNumber,
'building_area' => $buildingArea,
'retribution_amount' => $calculationResult['amount'],
'calculation_detail' => $calculationResult['detail'],
]);
$spatialPlanning->assignRetributionCalculation(
$calculation,
'Recalculated (new calculation)'
);
}
} else {
// Normal mode: Check if calculation already exists with same parameters
$existingCalculation = RetributionCalculation::where([
'building_type_id' => $buildingType->id,
'floor_number' => $floorNumber,
])
->whereBetween('building_area', [
$buildingArea * 0.99, // 1% tolerance
$buildingArea * 1.01
])
->first();
if ($existingCalculation) {
// Reuse existing calculation
$calculation = $existingCalculation;
$reused = true;
} else {
// Create new calculation
$calculationResult = $this->performCalculation($spatialPlanning, $buildingType);
$calculation = RetributionCalculation::create([
'building_type_id' => $buildingType->id,
'floor_number' => $floorNumber,
'building_area' => $buildingArea,
'retribution_amount' => $calculationResult['amount'],
'calculation_detail' => $calculationResult['detail'],
]);
}
// Assign to spatial planning
$spatialPlanning->assignRetributionCalculation(
$calculation,
$reused ? 'Auto-assigned (reused calculation)' : 'Auto-assigned (new calculation)'
);
}
return [
'calculation' => $calculation,
'reused' => $reused,
'recalculated' => $isRecalculated,
'building_type_name' => $buildingType->name,
'building_type_code' => $buildingType->code,
];
}
/**
* Detect building type based on building function using database
*/
private function detectBuildingType(string $buildingFunction = null): BuildingType
{
$function = strtolower($buildingFunction ?? '');
// Mapping building functions to building type codes from database
$mappings = [
// Religious
'masjid' => 'KEAGAMAAN',
'gereja' => 'KEAGAMAAN',
'vihara' => 'KEAGAMAAN',
'pura' => 'KEAGAMAAN',
'keagamaan' => 'KEAGAMAAN',
'religious' => 'KEAGAMAAN',
// Residential/Housing
'rumah' => 'HUN_SEDH', // Default to simple housing
'perumahan' => 'HUN_SEDH',
'hunian' => 'HUN_SEDH',
'residential' => 'HUN_SEDH',
'tinggal' => 'HUN_SEDH',
'mbr' => 'MBR', // Specifically for MBR
'masyarakat berpenghasilan rendah' => 'MBR',
// Commercial/Business - default to UMKM
'toko' => 'UMKM',
'warung' => 'UMKM',
'perdagangan' => 'UMKM',
'dagang' => 'UMKM',
'usaha' => 'UMKM',
'komersial' => 'UMKM',
'commercial' => 'UMKM',
'pasar' => 'UMKM',
'kios' => 'UMKM',
// Large commercial
'mall' => 'USH_BESAR',
'plaza' => 'USH_BESAR',
'supermarket' => 'USH_BESAR',
'department' => 'USH_BESAR',
'hotel' => 'USH_BESAR',
'resort' => 'USH_BESAR',
// Office
'kantor' => 'UMKM', // Can be UMKM or USH_BESAR depending on size
'perkantoran' => 'UMKM',
'office' => 'UMKM',
// Industry (usually big business)
'industri' => 'USH_BESAR',
'pabrik' => 'USH_BESAR',
'gudang' => 'USH_BESAR',
'warehouse' => 'USH_BESAR',
'manufacturing' => 'USH_BESAR',
// Social/Cultural
'sekolah' => 'SOSBUDAYA',
'pendidikan' => 'SOSBUDAYA',
'universitas' => 'SOSBUDAYA',
'kampus' => 'SOSBUDAYA',
'rumah sakit' => 'SOSBUDAYA',
'klinik' => 'SOSBUDAYA',
'kesehatan' => 'SOSBUDAYA',
'puskesmas' => 'SOSBUDAYA',
'museum' => 'SOSBUDAYA',
'perpustakaan' => 'SOSBUDAYA',
'gedung olahraga' => 'SOSBUDAYA',
// Mixed use
'campuran' => 'CAMP_KECIL', // Default to small mixed
'mixed' => 'CAMP_KECIL',
];
// Try to match building function
$detectedCode = null;
foreach ($mappings as $keyword => $code) {
if (str_contains($function, $keyword)) {
$detectedCode = $code;
break;
}
}
// Find building type in database by code
if ($detectedCode) {
$buildingType = BuildingType::where('code', $detectedCode)
->whereHas('indices') // Only types with indices
->first();
if ($buildingType) {
return $buildingType;
}
}
// Default to "UMKM" type if not detected (most common business type)
$defaultType = BuildingType::where('code', 'UMKM')
->whereHas('indices')
->first();
if ($defaultType) {
return $defaultType;
}
// Fallback to any available type with indices
$fallbackType = BuildingType::whereHas('indices')
->where('is_active', true)
->first();
if (!$fallbackType) {
throw new \Exception('No building types with indices found in database. Please run: php artisan db:seed --class=RetributionDataSeeder');
}
return $fallbackType;
}
/**
* Perform calculation using RetributionCalculatorService
*/
private function performCalculation(SpatialPlanning $spatialPlanning, BuildingType $buildingType): array
{
// Round area to 2 decimal places to match database storage format
$buildingArea = round($spatialPlanning->getCalculationArea(), 2);
$floorNumber = $spatialPlanning->number_of_floors ?: 1;
try {
// Use the same calculation service as TestRetributionCalculation
$result = $this->calculatorService->calculate(
$buildingType->id,
$floorNumber,
$buildingArea,
false // Don't save to database, we'll handle that separately
);
return [
'amount' => $result['total_retribution'],
'detail' => [
'building_type_id' => $buildingType->id,
'building_type_name' => $buildingType->name,
'building_type_code' => $buildingType->code,
'coefficient' => $result['indices']['coefficient'],
'ip_permanent' => $result['indices']['ip_permanent'],
'ip_complexity' => $result['indices']['ip_complexity'],
'locality_index' => $result['indices']['locality_index'],
'height_index' => $result['input_parameters']['height_index'],
'infrastructure_factor' => $result['indices']['infrastructure_factor'],
'building_area' => $buildingArea,
'floor_number' => $floorNumber,
'building_function' => $spatialPlanning->building_function,
'calculation_steps' => $result['calculation_detail'],
'base_value' => $result['input_parameters']['base_value'],
'is_free' => $buildingType->is_free,
'calculation_date' => now()->toDateTimeString(),
'total' => $result['total_retribution'],
]
];
} catch (\Exception $e) {
// Fallback to basic calculation if service fails
$this->warn("Calculation service failed for {$spatialPlanning->name}: {$e->getMessage()}. Using fallback calculation.");
// Basic fallback calculation
$totalAmount = $buildingType->is_free ? 0 : ($buildingArea * 50000);
return [
'amount' => $totalAmount,
'detail' => [
'building_type_id' => $buildingType->id,
'building_type_name' => $buildingType->name,
'building_type_code' => $buildingType->code,
'building_area' => $buildingArea,
'floor_number' => $floorNumber,
'building_function' => $spatialPlanning->building_function,
'calculation_method' => 'fallback',
'error_message' => $e->getMessage(),
'is_free' => $buildingType->is_free,
'calculation_date' => now()->toDateTimeString(),
'total' => $totalAmount,
]
];
}
}
}

View File

@@ -1,288 +0,0 @@
<?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");
}
}
}

View File

@@ -1,321 +0,0 @@
<?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");
}
}

View File

@@ -1,209 +0,0 @@
<?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) . "");
$this->info("💡 Average per m²: Rp " . number_format($totalRetribution / ($floorArea * 5), 2));
}
}

View File

@@ -150,9 +150,11 @@ class TestRetributionCalculation extends Command
protected function performCalculation($buildingTypeId, $floor, $area)
{
try {
$result = $this->calculatorService->calculate($buildingTypeId, $floor, $area, false);
// Round area to 2 decimal places to match database storage format
$roundedArea = round($area, 2);
$result = $this->calculatorService->calculate($buildingTypeId, $floor, $roundedArea, false);
$this->displayResults($result, $area, $floor);
$this->displayResults($result, $roundedArea, $floor);
} catch (\Exception $e) {
$this->error('❌ Error: ' . $e->getMessage());
@@ -208,7 +210,7 @@ class TestRetributionCalculation extends Command
protected function testAllBuildingTypes()
{
$area = $this->option('area') ?: 100;
$area = round($this->option('area') ?: 100, 2);
$floor = $this->option('floor') ?: 2;
$this->info("🧪 TESTING SEMUA BUILDING TYPES");

View File

@@ -1,291 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\BuildingType;
use App\Models\RetributionIndex;
use App\Models\HeightIndex;
use App\Models\RetributionConfig;
use App\Models\RetributionCalculation;
use App\Services\RetributionCalculatorService;
class TestRetributionData extends Command
{
protected $signature = 'retribution:data
{--save : Save calculation results to database}
{--show : Show existing data and relations}
{--clear : Clear calculation history}';
protected $description = 'Test retribution data storage and display database relations';
protected $calculatorService;
public function __construct(RetributionCalculatorService $calculatorService)
{
parent::__construct();
$this->calculatorService = $calculatorService;
}
public function handle()
{
$this->info('🗄️ SISTEM TEST DATA & RELASI RETRIBUSI PBG');
$this->info('=' . str_repeat('=', 55));
if ($this->option('clear')) {
$this->clearCalculationHistory();
return;
}
if ($this->option('show')) {
$this->showExistingData();
return;
}
if ($this->option('save')) {
$this->saveTestCalculations();
}
$this->showDatabaseStructure();
$this->showSampleData();
$this->showRelations();
}
protected function saveTestCalculations()
{
$this->info('💾 MENYIMPAN SAMPLE CALCULATIONS...');
$this->line('');
$testCases = [
['type_code' => 'KEAGAMAAN', 'area' => 200, 'floor' => 1],
['type_code' => 'SOSBUDAYA', 'area' => 150, 'floor' => 2],
['type_code' => 'CAMP_KECIL', 'area' => 1, 'floor' => 1],
['type_code' => 'UMKM', 'area' => 100, 'floor' => 2],
['type_code' => 'HUN_SEDH', 'area' => 80, 'floor' => 1],
['type_code' => 'USH_BESAR', 'area' => 500, 'floor' => 3],
];
foreach ($testCases as $case) {
$buildingType = BuildingType::where('code', $case['type_code'])->first();
if (!$buildingType) {
$this->warn("⚠️ Building type {$case['type_code']} not found");
continue;
}
$result = $this->calculatorService->calculate(
$buildingType->id,
$case['floor'],
$case['area']
);
// Save to database
RetributionCalculation::create([
'calculation_id' => 'TST' . now()->format('ymdHis') . rand(10, 99),
'building_type_id' => $buildingType->id,
'floor_number' => $case['floor'],
'building_area' => $case['area'],
'retribution_amount' => $result['total_retribution'],
'calculation_detail' => json_encode($result),
'calculated_at' => now()
]);
$this->info("✅ Saved: {$buildingType->name} - {$case['area']}m² - {$case['floor']} lantai - Rp " . number_format($result['total_retribution']));
}
$this->line('');
$this->info('💾 Sample calculations saved successfully!');
$this->line('');
}
protected function showExistingData()
{
$this->info('📊 DATA YANG TERSIMPAN DI DATABASE');
$this->info('=' . str_repeat('=', 40));
$calculations = RetributionCalculation::with('buildingType')
->orderBy('created_at', 'desc')
->limit(10)
->get();
if ($calculations->isEmpty()) {
$this->warn('❌ Tidak ada data calculation yang tersimpan');
$this->info('💡 Gunakan --save untuk menyimpan sample data');
return;
}
$headers = ['ID', 'Building Type', 'Area', 'Floor', 'Amount', 'Created'];
$rows = [];
foreach ($calculations as $calc) {
$rows[] = [
substr($calc->calculation_id, -8),
$calc->buildingType->name ?? 'N/A',
$calc->building_area . ' m²',
$calc->floor_number,
'Rp ' . number_format($calc->retribution_amount),
$calc->created_at->format('d/m H:i')
];
}
$this->table($headers, $rows);
}
protected function clearCalculationHistory()
{
$count = RetributionCalculation::count();
if ($count === 0) {
$this->info(' Tidak ada data calculation untuk dihapus');
return;
}
if ($this->confirm("🗑️ Hapus {$count} calculation records?")) {
RetributionCalculation::truncate();
$this->info("{$count} calculation records berhasil dihapus");
}
}
protected function showDatabaseStructure()
{
$this->info('🏗️ STRUKTUR DATABASE RETRIBUSI');
$this->info('=' . str_repeat('=', 35));
$tables = [
'building_types' => 'Hierarki dan metadata building types',
'retribution_indices' => 'Parameter perhitungan (coefficient, IP, dll)',
'height_indices' => 'Koefisien tinggi berdasarkan lantai',
'retribution_configs' => 'Konfigurasi global (base value, dll)',
'retribution_calculations' => 'History perhitungan dan hasil'
];
foreach ($tables as $table => $description) {
$this->line("📋 <info>{$table}</info>: {$description}");
}
$this->line('');
}
protected function showSampleData()
{
$this->info('📋 SAMPLE DATA DARI SETIAP TABEL');
$this->info('=' . str_repeat('=', 35));
// Building Types
$this->line('<comment>🏢 BUILDING TYPES:</comment>');
$buildingTypes = BuildingType::select('id', 'code', 'name', 'level', 'is_free')
->orderBy('level')
->orderBy('name')
->get();
$headers = ['ID', 'Code', 'Name', 'Level', 'Free'];
$rows = [];
foreach ($buildingTypes->take(5) as $type) {
$rows[] = [
$type->id,
$type->code,
substr($type->name, 0, 25) . '...',
$type->level,
$type->is_free ? '✅' : '❌'
];
}
$this->table($headers, $rows);
// Retribution Indices
$this->line('<comment>📊 RETRIBUTION INDICES:</comment>');
$indices = RetributionIndex::with('buildingType')
->select('building_type_id', 'coefficient', 'ip_permanent', 'ip_complexity', 'locality_index')
->get();
$headers = ['Building Type', 'Coefficient', 'IP Permanent', 'IP Complexity', 'Locality'];
$rows = [];
foreach ($indices->take(5) as $index) {
$rows[] = [
$index->buildingType->code ?? 'N/A',
number_format($index->coefficient, 4),
number_format($index->ip_permanent, 4),
number_format($index->ip_complexity, 4),
number_format($index->locality_index, 4)
];
}
$this->table($headers, $rows);
// Height Indices
$this->line('<comment>🏗️ HEIGHT INDICES:</comment>');
$heights = HeightIndex::orderBy('floor_number')->get();
$headers = ['Floor', 'Height Index'];
$rows = [];
foreach ($heights as $height) {
$rows[] = [
$height->floor_number,
number_format($height->height_index, 4)
];
}
$this->table($headers, $rows);
// Retribution Configs
$this->line('<comment>⚙️ RETRIBUTION CONFIGS:</comment>');
$configs = RetributionConfig::all();
$headers = ['Key', 'Value', 'Description'];
$rows = [];
foreach ($configs as $config) {
$rows[] = [
$config->key,
$config->value,
substr($config->description ?? '', 0, 30) . '...'
];
}
$this->table($headers, $rows);
}
protected function showRelations()
{
$this->info('🔗 RELASI ANTAR TABEL');
$this->info('=' . str_repeat('=', 25));
// Test relations dengan sample data
$buildingType = BuildingType::with(['indices', 'calculations'])
->where('code', 'UMKM')
->first();
if (!$buildingType) {
$this->warn('⚠️ Sample building type tidak ditemukan');
return;
}
$this->line("<comment>🏢 Building Type: {$buildingType->name}</comment>");
$this->line(" 📋 Code: {$buildingType->code}");
$this->line(" 📊 Level: {$buildingType->level}");
$this->line(" 🆓 Free: " . ($buildingType->is_free ? 'Ya' : 'Tidak'));
// Show indices relation
if ($buildingType->indices) {
$index = $buildingType->indices;
$this->line(" <comment>📊 Retribution Index:</comment>");
$this->line(" 💰 Coefficient: " . number_format($index->coefficient, 4));
$this->line(" 🏗️ IP Permanent: " . number_format($index->ip_permanent, 4));
$this->line(" 🔧 IP Complexity: " . number_format($index->ip_complexity, 4));
$this->line(" 📍 Locality Index: " . number_format($index->locality_index, 4));
}
// Show calculations relation
$calculationsCount = $buildingType->calculations()->count();
$this->line(" <comment>📈 Calculations: {$calculationsCount} records</comment>");
if ($calculationsCount > 0) {
$latestCalc = $buildingType->calculations()->latest()->first();
$this->line(" 📅 Latest: " . $latestCalc->created_at->format('d/m/Y H:i'));
$this->line(" 💰 Amount: Rp " . number_format($latestCalc->retribution_amount));
}
$this->line('');
$this->info('🎯 KESIMPULAN RELASI:');
$this->line(' • BuildingType hasOne RetributionIndex');
$this->line(' • BuildingType hasMany RetributionCalculations');
$this->line(' • RetributionCalculation belongsTo BuildingType');
$this->line(' • HeightIndex independent (digunakan berdasarkan floor_number)');
$this->line(' • RetributionConfig global settings');
}
}