|
|
<?php
namespace App\Models;
use App\Models\Model; use Illuminate\Support\Arr; use App\Utilities\Zarinpal\Laravel\Facade\Zarinpal;
class Transaction extends Model { protected $table = 'transactions';
protected $fillable = [ 'user_id', 'business_id', 'amount', 'succeeded', 'options' ];
protected $casts = [ 'options' => 'array', 'succeeded' => 'boolean', ];
protected $fillable_relations = [ 'user', 'business' ];
protected $reportable = [ 'user_id', 'business_id', 'amount', 'succeeded', 'options', // fields
];
public $perPage = 12;
public function getValueOf(?string $key) { $values = [ 'business_id' => $this->business_id, 'project_id' => null, 'sprint_id' => null, 'system_id' => null, 'user_id' => $this->user_id, 'workflow_id' => null, 'status_id' => null, 'task_id' => null, 'subject_id' => $this->id, ];
if ($key && isset($values, $key)) { return $values[$key]; }
return $values; }
public function rules(): array { return [ 'user_id' => 'required|', 'business_id' => 'required', 'amount' => 'required|integer|min:1', ]; }
public function updateRelations() { // user relations
if (!empty($this->filled_relations['user'])) { $this->dirties['user'] = $this->user_id; }
// business relations
if (!empty($this->filled_relations['business'])) { $this->dirties['business'] = $this->business_id; } }
public function reportActivity() {
}
public function user() { return $this->belongsTo(User::class, 'user_id','id',__FUNCTION__); }
public function business() { return $this->belongsTo(Business::class, 'business_id','id',__FUNCTION__); }
/** * Receive the authority key from the payment gateway */ public function prepare(): Transaction { $results = Zarinpal::request( config('services.zarinpal.callback-url'), $this->amount, config('services.zarinpal.description') );
$this->options = $results; $this->save();
return $this; }
/** * Redirect to the payment gateway */ public function redirect() { return Zarinpal::redirect(); }
public function verify(): Transaction { $results = Zarinpal::verify($this->amount, $this->options['Authority']); if ($results['Status'] == 'verified_before') { throw new \Exception("تراکنش قبلا تایید شده است."); }
if ($results['Status'] == 'success') { $this->succeeded = true; } else { $this->succeeded = false; }
$options = array_merge($this->options, $results); $this->options = $options; $this->save();
return $this; }
/** * Find a transaction via the authoriry key that psp provides us * * @throw ModelNotFound */ public static function findByAuthority(string $authority): Transaction { return static::where('options->Authority','=',$authority)->firstOrFail(); }
public function isWentToPaymentGateway(): bool { return !empty($this->options); }
public function hasBeenAppliedToWallet(): bool { return Arr::get($this->options,"applied", false); }
public function amountWasAppliedToWallet() { $options = $this->options; $options['applied'] = true; $this->options = $options;
$this->save(); } }
|