Queries::getRefundQuery()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 0
loc 19
rs 9.9666
c 0
b 0
f 0
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