Files
MKM/app/Models/Sale.php
Jp 7899ed75ea feat(sales): add discount support with ledger accounting
- Add discount_type column to transactions table via migration
- Update Sale model to use fillable instead of guarded for better security
- Implement discount account ledger creation when discount is applied
- Fix net amount calculation to include discount in CreateSaleAction
- Remove unused "Exempt" column from sale transaction table
- Make discount_type required when discount is enabled in form
- Update form data mutation to properly handle discount calculations
2026-02-18 21:40:39 +08:00

70 lines
1.7 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Sale extends Model
{
use HasFactory;
protected $fillable = [
'branch_id',
'user_id',
'client_id',
'happened_on',
'reference_number',
'buyer'
];
protected $casts = [
'happened_on' => 'date:Y-m-d',
];
/**
* Get all the transactions for the Sale
*/
public function transactions(): MorphMany
{
return $this->morphMany(Transaction::class, 'transactionable');
}
protected static function booted()
{
static::deleting(function ($sale) {
$sale->transactions->each(function ($transaction) {
// Delete associated ledgers first to trigger any ledger deletion logic if exists
$transaction->ledgers->each(function ($ledger) {
$ledger->balances()->delete(); // Delete balances associated with ledger
$ledger->delete();
});
$transaction->delete();
});
});
}
public function branch(): BelongsTo
{
return $this->belongsTo(Branch::class);
}
public function accounts(): BelongsToMany
{
return $this->belongsToMany(Account::class, 'account_sale')->withTimestamps();
}
public function getAccountsListAttribute(): string
{
return $this->accounts->pluck('account')->implode(', ');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}