Queries   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 24
rs 10
c 0
b 0
f 0
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A getRefundQuery() 0 19 2
1
<?php
2
3
namespace Siak\Tontine\Service\Report\Traits;
4
5
use Illuminate\Database\Query\Builder;
6
use Illuminate\Support\Facades\DB;
7
8
trait Queries
9
{
10
    /**
11
     * @return Builder
12
     */
13
    private function getRefundQuery(): Builder
14
    {
15
        /*
16
         * How it is calculated.
17
         * When a debt is refuunded in a given session, the corresponding amount is
18
         * the debt initial amount, minus the sum of partial refunds for that debt.
19
         */
20
        $debtPartialRefund = DB::table('partial_refunds')
21
            ->select(DB::raw('sum(partial_refunds.amount)'))
22
            ->whereColumn('partial_refunds.debt_id', 'debts.id')
23
            ->toSql();
24
        // PostgreSQL aggregate functions return null when applied to empty resultsets,
25
        // making some other operations (like addition with the aggregate value) also null.
26
        // We then need to explicitely convert null values of aggregate functions to 0.
27
        $debtPartialRefund = DB::connection()->getDriverName() === 'pgsql' ?
28
            "coalesce(($debtPartialRefund),0)" : "($debtPartialRefund)";
29
        return DB::table('refunds')
30
            ->join('debts', 'refunds.debt_id', '=', 'debts.id')
31
            ->select(DB::raw("sum(debts.amount - $debtPartialRefund) as total_amount"));
32
    }
33
}
34