Назад к задачамПолучайте помощь с лайвкодингом в реальном времени с Sobes Copilot
Junior
9
Функция перевода средств в системе банковского обслуживания
Условие задачи
Реализовать функцию actionPerform для контроллера транзакций, который осуществляет перевод денежных средств между пользовательскими аккаунтами и фиксирует обе операции (списание и зачисление) в журнале транзакций.
<?php
namespace app\controllers\transaction;
use yii\rest\ActiveController;
use yii\filters\auth\HttpBearerAuth;
use yii;
use app\models\Account;
use app\models\Transaction;
/**
* Models:
* Account: account_number, account_balance, user_id
* Transaction: type(debit, credit), description, amount, account_id
*
* Inputs: POST from_account, to_account, amount
*
* Create actionPerform: transfer funds between accounts of two users, specified by from_ and to_ account_number.
* Return 200 OK {"status":"success"} if ok, else 400 Bad Request {"status":"failed", "message":"Some error message"}
*
* App: Yii::$app
* CurrentUser: Yii::$app->getUser()
*/
class TransactionController extends ActiveController
{
public function checkAccess($action, $model = null, $params = [])
{
if (Yii::$app->getUser()->getIsGuest()) {
throw new yii\web\UnauthorizedHttpException();
}
}
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
];
return $behaviors;
}
function actionPerform() {
$request = Yii::$app->request;
$to = $request->post('to_acc');
$from = $request->post('from_acc');
$amount = (float)$request->post('amount');
$userAccount = Account::find(["account_number" => $from, "user_id" => Yii::$app->getUser()->getIdentity()->getId()])->where([">", "account_balance", $amount])->one();
if (!$userAccount) {
throw new yii\web\NotFoundHttpException();
}
$db = Yii::$app->getDb()->beginTransaction();
//....
}
}