add Telegram bot id dialogs table and API methods

This commit is contained in:
iIronside 2023-10-25 14:37:29 +03:00
parent da08bcf1b2
commit 5df755ff8b
16 changed files with 450 additions and 33 deletions

View File

@ -0,0 +1,78 @@
<?php
namespace common\models;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
/**
* This is the model class for table "user_tg_bot_dialog".
*
* @property int $id
* @property int $user_id
* @property int $dialog_id
* @property string $created_at
* @property string $updated_at
*
* @property User $user
*/
class UserTgBotDialog extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'user_tg_bot_dialog';
}
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new Expression('NOW()'),
],
];
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['user_id', 'dialog_id'], 'integer'],
[['dialog_id'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['dialog_id'], 'unique'],
[['user_id'], 'unique'],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'dialog_id' => 'Dialog ID',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}

View File

@ -2,7 +2,9 @@
namespace common\models; namespace common\models;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery; use yii\db\ActiveQuery;
use yii\db\Expression;
/** /**
* This is the model class for table "user_tg_bot_token". * This is the model class for table "user_tg_bot_token".
@ -26,6 +28,18 @@ class UserTgBotToken extends \yii\db\ActiveRecord
return 'user_tg_bot_token'; return 'user_tg_bot_token';
} }
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new Expression('NOW()'),
],
];
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */

View File

@ -0,0 +1,32 @@
<?php
use yii\db\Migration;
/**
* Handles the creation of table `{{%user_tg_bot_dialog}}`.
*/
class m231024_132757_create_user_tg_bot_dialog_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('{{%user_tg_bot_dialog}}', [
'id' => $this->primaryKey(),
'user_id' => $this->integer(),
'dialog_id' => $this->integer()->notNull()->unique(),
'created_at' => $this->dateTime(),
'updated_at' => $this->dateTime(),
]);
$this->addForeignKey('user_user_tg_bot_dialog', 'user_tg_bot_dialog', 'user_id', 'user', 'id');
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('{{%user_tg_bot_dialog}}');
}
}

View File

@ -86,6 +86,16 @@ return [
'api/profile/<id:\d+>' => 'api/profile/index', 'api/profile/<id:\d+>' => 'api/profile/index',
'api/reports/<id:\d+>' => 'api/reports/view', 'api/reports/<id:\d+>' => 'api/reports/view',
'' => 'card/user-card/index', '' => 'card/user-card/index',
'GET api/tg-bot/token' => 'api/user-tg-bot/get-token',
'GET api/tg-bot/user' => 'api/user-tg-bot/get-user',
'POST api/tg-bot/dialog/create' => 'api/user-tg-bot/set-dialog',
'GET api/tg-bot/dialog/user/id' => 'api/user-tg-bot/get-user-id-by-dialog-id',
'GET api/tg-bot/dialog/dialog/id' => 'api/user-tg-bot/get-dialog-id-by-user-id',
['class' => 'yii\rest\UrlRule', 'controller' => 'skills'], ['class' => 'yii\rest\UrlRule', 'controller' => 'skills'],
], ],
], ],

View File

@ -4,8 +4,8 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use common\models\User; use common\models\User;
use frontend\modules\api\models\profile\ProfileChangeEmailForm; use frontend\modules\api\models\profile\forms\ProfileChangeEmailForm;
use frontend\modules\api\models\profile\ProfileChangePersonalDataForm; use frontend\modules\api\models\profile\forms\ProfileChangePersonalDataForm;
use frontend\modules\api\services\UserService; use frontend\modules\api\services\UserService;
use Yii; use Yii;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;

View File

@ -5,27 +5,13 @@ namespace frontend\modules\api\controllers;
use Exception; use Exception;
use frontend\modules\api\models\profile\User; use frontend\modules\api\models\profile\User;
use frontend\modules\api\models\UserTgBotToken; use frontend\modules\api\models\tg_bot\forms\TgBotDialogForm;
use frontend\modules\api\models\tg_bot\UserTgBotToken;
use frontend\modules\api\services\UserTgBotTokenService; use frontend\modules\api\services\UserTgBotTokenService;
use Yii; use Yii;
use yii\helpers\ArrayHelper;
class UserTgBotController extends ApiController class UserTgBotController extends ApiController
{ {
public function behaviors(): array
{
return ArrayHelper::merge(parent::behaviors(), [
'verbs' => [
'class' => \yii\filters\VerbFilter::class,
'actions' => [
'get-token' => ['get'],
'get-user-by-token' => ['get'],
],
]
]);
}
/** /**
* @var UserTgBotTokenService * @var UserTgBotTokenService
*/ */
@ -43,13 +29,13 @@ class UserTgBotController extends ApiController
} }
/** /**
* @OA\Get(path="/user-tg-bot/get-token", * @OA\Get(path="/tg-bot/token",
* summary="Токен ТГ бота", * summary="Токен ТГ бота",
* description="Метод для возвращает токен для ТГ бота", * description="Метод для возвращает токен для ТГ бота",
* security={ * security={
* {"bearerAuth": {}} * {"bearerAuth": {}}
* }, * },
* tags={"UserTgBotToken"}, * tags={"TgBot"},
* @OA\Response( * @OA\Response(
* response=200, * response=200,
* description="Возвращает объект токен ТГ бота", * description="Возвращает объект токен ТГ бота",
@ -63,20 +49,20 @@ class UserTgBotController extends ApiController
* @return UserTgBotToken * @return UserTgBotToken
* @throws Exception * @throws Exception
*/ */
public function actionGetToken() public function actionGetToken(): UserTgBotToken
{ {
return $this->userTgBotTokenService->getToken(Yii::$app->user->id); return $this->userTgBotTokenService->getToken(Yii::$app->user->id);
} }
/** /**
* *
* @OA\Get(path="/user-tg-bot/get-user", * @OA\Get(path="/tg-bot/user",
* summary="Получить данные пользователя", * summary="Получить данные пользователя",
* description="Метод для получения данныех пользователя по токену ТГ бота", * description="Метод для получения данныех пользователя по токену ТГ бота",
* security={ * security={
* {"bearerAuth": {}} * {"bearerAuth": {}}
* }, * },
* tags={"UserTgBotToken"}, * tags={"TgBot"},
* @OA\Parameter( * @OA\Parameter(
* name="token", * name="token",
* in="query", * in="query",
@ -104,4 +90,124 @@ class UserTgBotController extends ApiController
{ {
return $this->userTgBotTokenService->getUserByToken($token); return $this->userTgBotTokenService->getUserByToken($token);
} }
/**
*
* @OA\Post(path="/tg-bot/dialog/create",
* summary="Сохранить новый id диалога",
* description="Метод создает новую запись с id пользователя и id диалога",
* security={
* {"bearerAuth": {}}
* },
* tags={"TgBot"},
* @OA\Parameter(
* name="userId",
* in="query",
* example="1",
* required=true,
* description="id пользователя",
* @OA\Schema(
* type="integer",
* )
* ),
* @OA\Parameter(
* name="dialogId",
* in="query",
* example="2355",
* required=true,
* description="id диалога",
* @OA\Schema(
* type="integer",
* )
* ),
* @OA\Response(
* response=200,
* description="Возвращает сообщение об успехе",
* @OA\MediaType(
* mediaType="application/json",
* ),
* ),
* )
*
* @return TgBotDialogForm|string[]
* @throws Exception
*/
public function actionSetDialog()
{
return $this->userTgBotTokenService->createDialog(Yii::$app->request->post());
}
/**
*
* @OA\Get(path="/tg-bot/dialog/dialog/id",
* summary="Получить id диалога по id пользователя",
* description="Метод для получения id пользователя по id пользователя",
* security={
* {"bearerAuth": {}}
* },
* tags={"TgBot"},
* @OA\Parameter(
* name="userId",
* in="query",
* example="1",
* required=true,
* description="id пользователя",
* @OA\Schema(
* type="integer",
* )
* ),
* @OA\Response(
* response=200,
* description="Возвращает dialog_id",
* @OA\MediaType(
* mediaType="application/json",
* ),
* ),
* )
*
* @param string $userId
* @return array
* @throws Exception
*/
public function actionGetDialogIdByUserId(string $userId): array
{
return $this->userTgBotTokenService->getDialogIdByUserId($userId);
}
/**
*
* @OA\Get(path="/tg-bot/dialog/user/id",
* summary="Получить id пользователя по id диалога",
* description="Метод для получения id пользователя по id диалога",
* security={
* {"bearerAuth": {}}
* },
* tags={"TgBot"},
* @OA\Parameter(
* name="dialogId",
* in="query",
* example="225",
* required=true,
* description="id диалога",
* @OA\Schema(
* type="integer",
* )
* ),
* @OA\Response(
* response=200,
* description="Возвращает user_id",
* @OA\MediaType(
* mediaType="application/json",
* ),
* ),
* )
*
* @param string $dialogId
* @return array
* @throws Exception
*/
public function actionGetUserIdByDialogId(string $dialogId): array
{
return $this->userTgBotTokenService->getUserIdByDialogId($dialogId);
}
} }

View File

@ -1,11 +1,11 @@
<?php <?php
namespace frontend\modules\api\models\profile; namespace frontend\modules\api\models\profile\forms;
use frontend\modules\api\models\profile\User;
use yii\base\Model; use yii\base\Model;
class ProfileChangeEmailForm extends Model class ProfileChangeEmailForm extends Model
{ {
public $newEmail; public $newEmail;
/** /**
@ -28,5 +28,4 @@ class ProfileChangeEmailForm extends Model
{ {
return ''; return '';
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
namespace frontend\modules\api\models\profile; namespace frontend\modules\api\models\profile\forms;
use yii\base\Model; use yii\base\Model;
class ProfileChangePasswordForm extends Model class ProfileChangePasswordForm extends Model

View File

@ -1,6 +1,6 @@
<?php <?php
namespace frontend\modules\api\models\profile; namespace frontend\modules\api\models\profile\forms;
use yii\base\Model; use yii\base\Model;

View File

@ -0,0 +1,33 @@
<?php
namespace frontend\modules\api\models\tg_bot;
use frontend\modules\api\models\profile\User;
use yii\db\ActiveQuery;
class UserTgBotDialog extends \common\models\UserTgBotDialog
{
public function fields(): array
{
return [
'user_id',
'dialog_id',
];
}
/**
* @return string[]
*/
public function extraFields(): array
{
return [];
}
/**
* @return ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::class, ['id' => 'user_id']);
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
namespace frontend\modules\api\models; namespace frontend\modules\api\models\tg_bot;
use frontend\modules\api\models\profile\User; use frontend\modules\api\models\profile\User;

View File

@ -0,0 +1,30 @@
<?php
namespace frontend\modules\api\models\tg_bot\forms;
use yii\base\Model;
class TgBotDialogForm extends Model
{
public $userId;
public $dialogId;
/**
* @return array
*/
public function rules()
{
return [
[['dialogId', 'userId'], 'integer'],
[['dialogId', 'userId'], 'required'],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace frontend\modules\api\models\tg_bot\forms;
use yii\base\Model;
class TgBotDialogIdForm extends Model
{
public $dialogId;
/**
* @return array
*/
public function rules()
{
return [
[['dialogId'], 'integer'],
[['dialogId'], 'required'],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace frontend\modules\api\models\tg_bot\forms;
use yii\base\Model;
class TgBotUserIdForm extends Model
{
public $userId;
/**
* @return array
*/
public function rules()
{
return [
[['userId'], 'integer'],
[['userId'], 'required'],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -4,9 +4,9 @@ namespace frontend\modules\api\services;
use Exception; use Exception;
use frontend\modules\api\models\LoginForm; use frontend\modules\api\models\LoginForm;
use frontend\modules\api\models\profile\ProfileChangeEmailForm; use frontend\modules\api\models\profile\forms\ProfileChangeEmailForm;
use frontend\modules\api\models\profile\ProfileChangePasswordForm; use frontend\modules\api\models\profile\forms\ProfileChangePasswordForm;
use frontend\modules\api\models\profile\ProfileChangePersonalDataForm; use frontend\modules\api\models\profile\forms\ProfileChangePersonalDataForm;
use frontend\modules\api\models\profile\User; use frontend\modules\api\models\profile\User;
use Yii; use Yii;
use yii\web\BadRequestHttpException; use yii\web\BadRequestHttpException;

View File

@ -5,8 +5,10 @@ namespace frontend\modules\api\services;
use DateTime; use DateTime;
use Exception; use Exception;
use frontend\modules\api\models\tg_bot\forms\TgBotDialogForm;
use frontend\modules\api\models\profile\User; use frontend\modules\api\models\profile\User;
use frontend\modules\api\models\UserTgBotToken; use frontend\modules\api\models\tg_bot\UserTgBotDialog;
use frontend\modules\api\models\tg_bot\UserTgBotToken;
use Yii; use Yii;
class UserTgBotTokenService class UserTgBotTokenService
@ -128,4 +130,61 @@ class UserTgBotTokenService
return $model; return $model;
} }
/**
* @param array $params
* @return TgBotDialogForm|string[]
* @throws Exception
*/
public function createDialog(array $params)
{
$form = new TgBotDialogForm();
$form->load($params);
if (!$form->validate()){
return $form;
}
$dialog = new UserTgBotDialog();
$dialog->user_id = $form->userId;
$dialog->dialog_id = $form->dialogId;
if (!$dialog->save()) {
throw new Exception('User dont save');
}
return ['status' => 'success'];
}
/**
* @param string $userId
* @return array
* @throws Exception
*/
public function getDialogIdByUserId(string $userId)
{
$model = UserTgBotDialog::findOne(['user_id' => $userId]);
if (!$model) {
throw new \Exception('dialog_id не найден!');
}
return ['dialog_id' => $model->dialog_id];
}
/**
* @param string $dialogId
* @return array
* @throws Exception
*/
public function getUserIdByDialogId(string $dialogId)
{
$model = UserTgBotDialog::findOne(['dialog_id' => $dialogId]);
if (!$model) {
throw new \Exception('user_id не найден!');
}
return ['user_id' => $model->user_id];
}
} }