Materials created before billing months existed have no period, so the profitability report left out what they billed. Their month is now the month they were created in, as in the export repository. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
51 lines
2.3 KiB
PHP
51 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Modules\Billing\Infrastructure\Persistence\Repositories;
|
|
|
|
use App\Modules\Billing\Application\Contracts\BilledRevenueQueries;
|
|
use App\Modules\Billing\Application\DTOs\BilledJobRevenue;
|
|
use App\Modules\Billing\Domain\Enums\ExportStatus;
|
|
use App\Modules\Billing\Domain\Enums\LineKind;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class EloquentBilledRevenueQueries implements BilledRevenueQueries
|
|
{
|
|
public function byJob(string $fromMonth, string $toMonth): array
|
|
{
|
|
$rows = DB::table('billing_lines')
|
|
->join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id')
|
|
->join('billing_exports', 'billing_exports.id', '=', 'billing_invoices.billing_export_id')
|
|
->where('billing_exports.status', ExportStatus::Created->value)
|
|
// Materials created before billing months existed have none: their month is the month they were created in, as in the export repository.
|
|
->whereRaw('COALESCE(billing_exports.period, SUBSTR(billing_exports.created_at, 1, 7)) BETWEEN ? AND ?', [$fromMonth, $toMonth])
|
|
->groupBy('billing_lines.customer_job_id')
|
|
->select('billing_lines.customer_job_id')
|
|
->selectRaw(self::sumOf(LineKind::Hours, 'net_cents').' as hours_cents')
|
|
->selectRaw(self::sumOf(LineKind::FixedPrice, 'net_cents').' as fixed_cents')
|
|
->selectRaw(self::sumOf(LineKind::MonthlyFee, 'net_cents').' as monthly_cents')
|
|
->selectRaw(self::sumOf(LineKind::Expense, 'net_cents').' as expense_cents')
|
|
->selectRaw(self::sumOf(LineKind::Hours, 'quantity_quarters').' as billed_quarters')
|
|
->get();
|
|
|
|
$result = [];
|
|
foreach ($rows as $row) {
|
|
$jobId = (int) $row->customer_job_id;
|
|
$result[$jobId] = new BilledJobRevenue(
|
|
$jobId,
|
|
(int) $row->hours_cents,
|
|
(int) $row->fixed_cents,
|
|
(int) $row->monthly_cents,
|
|
(int) $row->expense_cents,
|
|
(int) $row->billed_quarters,
|
|
);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private static function sumOf(LineKind $kind, string $column): string
|
|
{
|
|
return "SUM(CASE WHEN billing_lines.kind = '{$kind->value}' THEN COALESCE(billing_lines.{$column}, 0) ELSE 0 END)";
|
|
}
|
|
}
|