81 lines
2.8 KiB
PHP
81 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Http\Requests\CalculateProjectionRequest;
|
|
use App\Http\Requests\PreviewAllocationRequest;
|
|
use App\Http\Resources\ProjectionResource;
|
|
use App\Models\Bucket;
|
|
use App\Models\Scenario;
|
|
use App\Services\Projection\PipelineAllocationService;
|
|
use App\Services\Projection\ProjectionGeneratorService;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Http\JsonResponse;
|
|
|
|
class ProjectionController extends Controller
|
|
{
|
|
public function __construct(
|
|
private readonly ProjectionGeneratorService $projectionGeneratorService,
|
|
private readonly PipelineAllocationService $pipelineAllocationService,
|
|
) {}
|
|
|
|
public function calculate(CalculateProjectionRequest $request, Scenario $scenario): ProjectionResource
|
|
{
|
|
$startDate = Carbon::parse($request->input('start_date'));
|
|
$endDate = Carbon::parse($request->input('end_date'));
|
|
|
|
$projections = $this->projectionGeneratorService->generateProjections(
|
|
$scenario,
|
|
$startDate,
|
|
$endDate
|
|
);
|
|
|
|
return new ProjectionResource($projections);
|
|
}
|
|
|
|
public function preview(PreviewAllocationRequest $request, Scenario $scenario): JsonResponse
|
|
{
|
|
$amountInCents = (int) round($request->input('amount') * 100);
|
|
|
|
$draws = $this->pipelineAllocationService->allocateInflow($scenario, $amountInCents);
|
|
|
|
/** @var array<int, Bucket> $bucketLookup */
|
|
$bucketLookup = $scenario->buckets->keyBy('id')->all();
|
|
|
|
$allocations = $draws->map(function ($draw) use ($bucketLookup) {
|
|
$bucket = $bucketLookup[$draw->bucket_id];
|
|
|
|
return [
|
|
'bucket_id' => $bucket->uuid,
|
|
'bucket_name' => $bucket->name,
|
|
'bucket_type' => $bucket->type->value,
|
|
'allocated_amount' => (float) $draw->amount_currency,
|
|
'remaining_capacity' => $this->remainingCapacity($bucket, $draw->amount),
|
|
];
|
|
})->values();
|
|
|
|
$totalAllocatedCents = $draws->sum('amount');
|
|
|
|
return response()->json([
|
|
'allocations' => $allocations,
|
|
'total_allocated' => (float) round($totalAllocatedCents / 100, 2),
|
|
'unallocated' => (float) round(($amountInCents - $totalAllocatedCents) / 100, 2),
|
|
]);
|
|
}
|
|
|
|
private function remainingCapacity(Bucket $bucket, int $allocatedCents): ?float
|
|
{
|
|
$effectiveCapacity = $bucket->getEffectiveCapacity();
|
|
|
|
if ($effectiveCapacity === PHP_FLOAT_MAX) {
|
|
return null;
|
|
}
|
|
|
|
// PipelineAllocationService treats getEffectiveCapacity() as cents,
|
|
// so we compute remaining in the same unit, then convert to dollars.
|
|
$capacityCents = (int) round($effectiveCapacity);
|
|
$remainingCents = max(0, $capacityCents - $allocatedCents);
|
|
|
|
return round($remainingCents / 100, 2);
|
|
}
|
|
}
|