Mutation.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Models;
  3. use App\Services\CurrencyFormatService;
  4. use Carbon\Carbon;
  5. use Illuminate\Database\Eloquent\Casts\Attribute;
  6. use Illuminate\Database\Eloquent\Factories\HasFactory;
  7. use Illuminate\Database\Eloquent\Model;
  8. class Mutation extends Model
  9. {
  10. use HasFactory;
  11. protected $fillable = [
  12. 'type',
  13. 'amount',
  14. 'outlet_id',
  15. 'transaction_id',
  16. 'expense_id',
  17. ];
  18. protected function createdAt(): Attribute
  19. {
  20. return Attribute::make(
  21. get:fn($value) => Carbon::parse($value)->translatedFormat('l d/m/Y')
  22. );
  23. }
  24. protected function amount(): Attribute
  25. {
  26. return Attribute::make(
  27. get:function ($value) {
  28. if ($this->getRawOriginal('type') == 1) {
  29. return (new CurrencyFormatService)->setRupiahFormat($value, true);
  30. } else {
  31. return (new CurrencyFormatService)->setRupiahFormat(-$value, true);
  32. }
  33. },
  34. );
  35. }
  36. protected function type(): Attribute
  37. {
  38. return Attribute::make(
  39. get:fn($value) => $value == 1 ? __('words.income') : __('words.expense')
  40. );
  41. }
  42. public function outlet()
  43. {
  44. return $this->belongsTo(Outlet::class);
  45. }
  46. public function scopeFilter($query, array $filters)
  47. {
  48. $query->when($filters['startDate'] ?? null, function ($query, $date) {
  49. $query->whereDate('created_at', '>=', $date);
  50. })->when($filters['endDate'] ?? null, function ($query, $date) {
  51. $query->whereDate('created_at', '<=', $date);
  52. })->when($filters['outlet'] ?? null, function ($query, $outlet) {
  53. $query->where('outlet_id', $outlet);
  54. });
  55. }
  56. }