Passed
Pull Request — main (#63)
by Thierry
06:38
created

Debt::isPrincipal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Siak\Tontine\Model;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Casts\Attribute;
7
8
class Debt extends Base
9
{
10
    /**
11
     * Indicates if the model should be timestamped.
12
     *
13
     * @var bool
14
     */
15
    public $timestamps = false;
16
17
    /**
18
     * @const
19
     */
20
    const TYPE_PRINCIPAL = 'p';
21
22
    /**
23
     * @const
24
     */
25
    const TYPE_INTEREST = 'i';
26
27
    /**
28
     * The attributes that are mass assignable.
29
     *
30
     * @var array
31
     */
32
    protected $fillable = [
33
        'type',
34
        'amount',
35
    ];
36
37
    public function isPrincipal(): Attribute
38
    {
39
        return Attribute::make(
40
            get: fn() => $this->type === self::TYPE_PRINCIPAL,
41
        );
42
    }
43
44
    public function isInterest(): Attribute
45
    {
46
        return Attribute::make(
47
            get: fn() => $this->type === self::TYPE_INTEREST,
48
        );
49
    }
50
51
    public function typeStr(): Attribute
52
    {
53
        return Attribute::make(
54
            get: fn() => $this->type === self::TYPE_PRINCIPAL ? 'principal' : 'interest',
55
        );
56
    }
57
58
    /**
59
     * @return Attribute
60
     */
61
    protected function dueAmount(): Attribute
62
    {
63
        return Attribute::make(
64
            get: fn() => $this->amount - $this->partial_refunds->sum('amount'),
65
        );
66
    }
67
68
    /**
69
     * @param  Builder  $query
70
     *
71
     * @return Builder
72
     */
73
    public function scopePrincipal(Builder $query): Builder
74
    {
75
        return $query->where('type', self::TYPE_PRINCIPAL);
76
    }
77
78
    /**
79
     * @param  Builder  $query
80
     *
81
     * @return Builder
82
     */
83
    public function scopeInterest(Builder $query): Builder
84
    {
85
        return $query->where('type', self::TYPE_INTEREST);
86
    }
87
88
    public function loan()
89
    {
90
        return $this->belongsTo(Loan::class);
91
    }
92
93
    public function refund()
94
    {
95
        return $this->hasOne(Refund::class);
96
    }
97
98
    public function partial_refunds()
99
    {
100
        return $this->hasMany(PartialRefund::class);
101
    }
102
103
    /**
104
     * Will be used to get the unique partial refund for a given session
105
     */
106
    public function partial_refund()
107
    {
108
        // We use latest() instead of latestOfMany() because it is simpler to
109
        // add clauses with extra parameters to the subquery.
110
        return $this->hasOne(PartialRefund::class)->latest('id');
111
    }
112
}
113