la_bot_back/kernel/app_modules/card/services/CardTransactionService.php
2025-01-20 00:12:30 +03:00

108 lines
3.5 KiB
PHP

<?php
namespace kernel\app_modules\card\services;
use kernel\app_modules\card\models\Card;
use kernel\app_modules\card\models\CardTemplate;
use kernel\app_modules\card\models\CardTransaction;
use kernel\FormModel;
class CardTransactionService
{
protected array $errors = [];
public function create(FormModel $form_model): false|CardTransaction
{
$model = new CardTransaction();
$fromId = (int)$form_model->getItem('from');
$toId = (int)$form_model->getItem('to');
if ($fromId !== 1001){
$fromCard = Card::where("id", $form_model->getItem('from'))->first();
if (!$fromCard){
$this->errors[] = ["error_id" => 3, "error_msg" => "Sender not found"];
return false;
}
}
if ($toId !== 1001){
$toCard = Card::where("id", $form_model->getItem('to'))->first();
if (!$toCard){
$this->errors[] = ["error_id" => 3, "error_msg" => "Recipient not found"];
return false;
}
}
if ($fromId !== 1001){
if ($fromCard->balance < $form_model->getItem('amount')){
$this->errors[] = ["error_id" => 3, "error_msg" => "Insufficient funds of the sender"];
}
}
// Пример заполнения:
$model->from = $form_model->getItem('from');
$model->to = $form_model->getItem('to');
$model->status = $form_model->getItem('status');
$model->type = $form_model->getItem('type');
$model->amount = $form_model->getItem('amount');
// $model->slug = Slug::createSlug($form_model->getItem('title'), Card::class); // Генерация уникального slug
if ($model->save()) {
if ($fromCard){
$fromCard->balance = $fromCard->balance - (int)$form_model->getItem('amount');
$fromCard->save();
}
if ($toCard){
$toCard->balance = $toCard->balance + (int)$form_model->getItem('amount');
$toCard->save();
}
return $model;
}
return false;
}
public function update(FormModel $form_model, CardTransaction $cardTransaction): false|CardTransaction
{
$fromCard = Card::where("id", $form_model->getItem('from'))->first();
if (!$fromCard){
$this->errors[] = ["error_id" => 3, "error_msg" => "Sender not found"];
return false;
}
$toCard = Card::where("id", $form_model->getItem('to'))->first();
if (!$toCard){
$this->errors[] = ["error_id" => 3, "error_msg" => "Recipient not found"];
return false;
}
if ($fromCard->balance < $form_model->getItem('amount')){
$this->errors[] = ["error_id" => 3, "error_msg" => "Insufficient funds of the sender"];
}
// Пример обновления:
$cardTransaction->from = $form_model->getItem('from');
$cardTransaction->to = $form_model->getItem('to');
$cardTransaction->amount = $form_model->getItem('amount');
$cardTransaction->type = $form_model->getItem('type');
$cardTransaction->status = $form_model->getItem('status');
if ($cardTransaction->save()) {
return $cardTransaction;
}
return false;
}
public function getErrorsString(): string
{
$errStr = "";
foreach ($this->errors as $error){
$errStr .= $error['error_msg'] . ". ";
}
return $errStr;
}
}