Junior
Funds transfer function in the banking service system
livecode
Task condition
Implement the function actionPerform for the transaction controller, which transfers funds between user accounts and records both operations (debit and credit) in the transaction log.
<?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();
//....
}
}