add spatial plannings retribution calculations

This commit is contained in:
arifal hidayat
2025-06-18 02:54:41 +07:00
parent 6946fa7074
commit fc54e20fa4
29 changed files with 2926 additions and 416 deletions

View 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");
}
}
}

View 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;
}
}
}

View File

@@ -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));
}
}
}
}

View 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");
}
}

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