Files
timebank-cc-public/app/Models/Transaction.php
T

129 lines
3.4 KiB
PHP

<?php
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Transaction extends Model
{
use HasFactory;
use Searchable; // laravel/scout with ElasticSearch
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'from_account_id',
'to_account_id',
'creator_user_id',
'from_authorised_by_user_id',
'from_authorisation_time',
'to_authorised_by_user_id',
'to_authorisation_time',
'amount',
'programmed_time',
'description',
'from_reference',
'to_reference',
'transaction_type_id',
'transaction_status_id',
'cancelled_by_user_id',
'cancelled_time',
'advertisement_id',
];
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'transactions';
/**
* Refuse invalid transactions whichever code path creates them. Transactions are
* immutable once stored, and the table has no foreign keys or check constraints.
*/
protected static function booted(): void
{
static::creating(function (Transaction $transaction) {
if (!is_numeric($transaction->amount) || (int) $transaction->amount != $transaction->amount || $transaction->amount <= 0) {
throw new \InvalidArgumentException('Transaction amount must be a positive whole number of minutes.');
}
if ((int) $transaction->from_account_id === (int) $transaction->to_account_id) {
throw new \InvalidArgumentException('Transaction from and to account must differ.');
}
if (Account::whereKey([$transaction->from_account_id, $transaction->to_account_id])->count() !== 2) {
throw new \InvalidArgumentException('Transaction from and to account must exist.');
}
if (!TransactionType::whereKey($transaction->transaction_type_id)->exists()) {
throw new \InvalidArgumentException('Transaction type must exist.');
}
});
}
/**
* Get the index name for the model.
*
* @return string
*/
public function searchableAs()
{
return 'transactions_index';
}
/**
* Convert the transaction model to a searchable array.
*
* @return array
*/
public function toSearchableArray()
{
return [
'id' => $this->id,
'from_account_id' => $this->from_account_id,
'to_account_id' => $this->to_account_id,
'amount' => $this->amount,
'description' => $this->description ?? '',
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
];
}
public function accountFrom()
{
return $this->belongsTo(Account::class, 'from_account_id');
}
public function accountTo()
{
return $this->belongsTo(Account::class, 'to_account_id');
}
public function creator()
{
return $this->belongsTo(User::class, 'creator_user_id');
}
/**
* Get the transaction type that owns the transaction.
*/
public function transactionType()
{
return $this->belongsTo(TransactionType::class);
}
}