初始化仓库

This commit is contained in:
2024-09-19 11:32:39 +08:00
commit 8f5315e936
921 changed files with 76455 additions and 0 deletions

View File

@@ -0,0 +1,393 @@
<?php
namespace admin\controllers;
use admin\components\BaseAdminController;
use admin\models\Menu;
use common\enums\UserRoleEnum;
use common\helpers\ArrayHelper;
use common\models\SubAccountMenu;
use common\modelsgii\RoleMenu;
use Yii;
use admin\models\Admin;
use admin\models\search\AdminSearch;
use yii\base\Exception;
use yii\web\ForbiddenHttpException;
/**
* 后台用户控制器
* @author longfei <phphome@qq.com>
*/
class AdminController extends BaseAdminController
{
public $modelClass = Admin::class;
public $roles;
public $login_role;
/**
* ---------------------------------------
* 构造方法
* ---------------------------------------
*/
public function init()
{
parent::init();
}
//
//public function beforeAction($action)
//{
// $user_id = Yii::$app->user->identity->getId();
// $login_role = Yii::$app->authManager->getRolesByUser($user_id);
// $this->login_role = array_keys($login_role)[0];
//
// if(Yii::$app->params['admin'] == Yii::$app->user->id){
// $roles = Yii::$app->authManager->getRoles();
// }else{
// $roles = Yii::$app->authManager->getChildRoles($this->login_role);
// unset($roles[$this->login_role]);
// }
// $this->roles = $roles;
//
// $uid = Yii::$app->request->get('uid');
// if($uid){
// $assign = Yii::$app->authManager->getAssignments($uid);
// $role = array_keys($assign)[0];
// //管理员只能管理下级管理员,不能管理同级和上级管理员
// if(!in_array($role,array_keys($roles))){
// throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
// }
// }
// return parent::beforeAction($action); // TODO: Change the autogenerated stub
//}
/**
* ---------------------------------------
* 后台用户列表
* @doc-param int type 1内部账号2客户账号
* @doc-param string search 搜索 / optional
* @doc-return @List{is_sub-int-是否子账号0否1是}
* ---------------------------------------
*/
public function actionIndex()
{
/* 添加当前位置到cookie供后续操作调用 */
// $this->setForward();
$admin = Yii::$app->user->identity;
$get = Yii::$app->request->get();
$this->requestValidate($get,[
['type','required','message'=>'类型不能为空']
]);
$query = Admin::find();
switch ($get['type']){
case 1:
$query->andWhere(['<>','role',UserRoleEnum::STORE_ADMIN]);
break;
case 2:
$query->andWhere(['role'=>UserRoleEnum::STORE_ADMIN]);
break;
default:
throw new \yii\db\Exception('参数错误');
}
if (UserRoleEnum::STORE_ADMIN == $admin->role) {
$query->andWhere(['role' => UserRoleEnum::STORE_ADMIN, 'store_id' => $admin->store_id]);
}
if (!empty($get['search'])){
$query->andWhere([
'or',
['mobile'=>$get['search']],
['like','username',$get['search']]
]);
}
$this->field = [
Admin::class => [
'uid', 'username', 'password', 'mobile', 'store_id', 'store' => 'store.name', 'role_id' => 'role', 'role' => 'roles.name', 'is_sub','code','province_id','city_id',
'province'=>'province.name',
'city'=>'city.name',
'status'
]
];
return $this->create($query, $get);
}
/**
* ---------------------------------------
* 添加
* ---------------------------------------
*/
public function actionAdd()
{
$model = new Admin();
if (Yii::$app->request->isPost) {
/* 表单验证 */
$data = Yii::$app->request->post('Admin');
$data['reg_time'] = time();
$data['reg_ip'] = ip2long(Yii::$app->request->getUserIP());
$data['last_login_time'] = 0;
$data['last_login_ip'] = ip2long('127.0.0.1');
$data['update_time'] = 0;
/* 表单数据加载和验证,具体验证规则在模型rule中配置 */
/* 密码单独验证,否则setPassword后密码肯定符合rule */
if (empty($data['password']) || strlen($data['password']) < 6) {
$this->error('密码为空或小于6字符');
}
$model->setAttributes($data);
$model->generateAuthKey();
$model->setPassword($data['password']);
if (!isset($data['role']) || !$data['role']) {
$this->error('未选择任何角色');
}
/* 保存用户数据到数据库 */
if ($model->save()) {
/* 先删除 用户组-用户 记录 */
Yii::$app->authManager->revokeAll($model->uid);
/* 再添加记录 */
$role = Yii::$app->authManager->getRole($data['role']);
Yii::$app->authManager->assign($role, $model->uid);
$this->success('操作成功', $this->getForward());
} else {
$this->error('操作错误:' . array_values($model->getFirstErrors())[0]);
}
}
//获取下属角色
$roles = array_map(function ($n) {
return $n->name;
}, $this->roles);
$model->role = reset($roles);
$model->status = 1;
return $this->render('add', [
'model' => $model,
'roles' => $roles
]);
}
/**
* ---------------------------------------
* 编辑
* ---------------------------------------
*/
public function actionEdit($uid)
{
$model = Admin::findOne($uid);
if (Yii::$app->request->isPost) {
/* 表单验证 */
$data = Yii::$app->request->post('Admin');
$data['update_time'] = time();
/* 如果设置密码则重置密码,否则不修改密码 */
if (!empty($data['password'])) {
$model->generateAuthKey();
$model->setPassword($data['password']);
}
unset($data['password']);
if (!isset($data['role']) || !$data['role']) {
$this->error('未选择任何角色');
}
$model->setAttributes($data);
/* 保存用户数据到数据库 */
if ($model->save()) {
/* 先删除 用户组-用户 记录 */
Yii::$app->authManager->revokeAll($model->uid);
/* 再添加记录 */
$role = Yii::$app->authManager->getRole($data['role']);
Yii::$app->authManager->assign($role, $model->uid);
$this->success('操作成功', $this->getForward());
} else {
$this->error('操作错误');
}
}
$roles = array_map(function ($n) {
return $n->name;
}, $this->roles);
$assign = Yii::$app->authManager->getAssignments($model->uid);
$model->role = array_keys($assign)[0];
$model->password = '';
return $this->render('edit', [
'model' => $model,
'roles' => $roles
]);
}
/**
* ---------------------------------------
* 删除
* ---------------------------------------
*/
public function actionDelete()
{
$ids = Yii::$app->request->param('uid', 0);
$ids = implode(',', array_unique((array)$ids));
if (empty($ids)) {
$this->error('请选择要操作的数据!');
}
/* 不能删除超级管理员 */
if (in_array(Yii::$app->params['admin'], explode(',', $ids))) {
$this->error('不能删除超级管理员!');
}
$_where = 'uid in(' . $ids . ')';
if (Admin::deleteAll($_where)) {
foreach (explode(',', $ids) as $uid) {
Yii::$app->authManager->revokeAll($uid);
}
$this->success('删除成功', $this->getForward());
} else {
$this->error('删除失败!');
}
}
/**
* 个人信息
*/
public function actionPersonal()
{
$user_id = Yii::$app->user->identity->getId();
$model = Admin::findOne($user_id);
if (Yii::$app->request->isPost) {
/* 表单验证 */
$data = Yii::$app->request->post('Admin');
$data['update_time'] = time();
/* 如果设置密码则重置密码,否则不修改密码 */
if (!empty($data['password'])) {
$model->generateAuthKey();
$model->setPassword($data['password']);
}
unset($data['password']);
$model->setAttributes($data);
/* 保存用户数据到数据库 */
if ($model->save()) {
$this->success('操作成功', $this->getForward());
} else {
$this->error('操作错误');
}
}
$model->password = '';
return $this->render('personal', [
'model' => $model
]);
}
/**
* 个人信息
*/
public function actionEditPass()
{
$user_id = Yii::$app->user->identity->getId();
$model = Admin::findOne($user_id);
/* 表单验证 */
$data = Yii::$app->request->post();
$data['update_time'] = time();
/* 如果设置密码则重置密码,否则不修改密码 */
if (isset($data['password']) && !empty($data['password'])) {
if (strlen($data['password']) < 6) {
throw new Exception('密码小于6字符');
}
$model->generateAuthKey();
$model->setPassword($data['password']);
}
unset($data['password']);
$model->setAttributes($data);
/* 保存用户数据到数据库 */
$model->saveOrFail();
}
private function createMenuNode($name, $icon, $url)
{
return ['app' => 'index', 'name' => $name, 'title' => null, 'icon' => $icon, 'url' => $url, 'route' => '', 'topic' => '', 'hidden' => false, 'target' => null];
}
public function actionMyMenu()
{
$role = Yii::$app->user->identity->role;
//角色1为官方管理,2为市场专员,3为客服,4为供应商管理,5为业务员,6为门店管理
if ($role == 1) {
return ['list' => Yii::$app->params['menu']];
} else if ($role == 6) {
return ['list' => Yii::$app->params['store_menu']];
} else if ($role == 5) {
return ['list' => Yii::$app->params['agent_menu']];
} else if ($role == 4) {
return ['list' => Yii::$app->params['supplier_menu']];
}
}
public function actionMenu()
{
if (Yii::$app->user->identity->is_sub === 1) {
$userMenus = SubAccountMenu::findAll(['admin_id' => Yii::$app->user->identity->uid]);
} else {
$role = Yii::$app->user->identity->role;
$userMenus = RoleMenu::findAll(['role_id' => $role]);
}
$keys = ArrayHelper::getColumn($userMenus, 'menuUrl');
$menus = Menu::find()->where(['in', 'menuUrl', $keys])->orderBy(['sort' => SORT_ASC])->asArray()->all();
return ArrayHelper::itemsMerge($menus, 0, 'menuUrl', 'parentPath', 'children');
////当前用户menu
//return ['list'=> Yii::$app->params['menu']];
}
/**
* ---------------------------------------
* 用户授权
* ---------------------------------------
*/
// public function actionAuth($uid)
// {
// $auth = Yii::$app->authManager;
// /* 获取用户信息 */
// $model = Admin::findOne($uid);
//
// if (Yii::$app->request->isPost) {
// $data = Yii::$app->request->post();
// /* 用户权限组 */
// $item_name = $data['param'];
//
// /* 先删除 用户组-用户 记录 */
// $auth->revokeAll($uid);
// /* 再添加记录 */
// $role = $auth->getRole($item_name);
// $auth->assign($role, $uid);
//
// $this->success('授权成功!', $this->getForward());
//
// var_dump($data['param']);
// exit;
// }
//
// /* 获取所有权限组 */
// $roles = $auth->getRoles();
// /* 获取该用户的权限 */
// $group = array_keys($auth->getAssignments($uid));
// //var_dump($group);exit;
//
// return $this->render('auth', [
// 'model' => $model,
// 'roles' => $roles,
// 'group' => $group
// ]);
// }
}

View File

@@ -0,0 +1,27 @@
<?php
namespace admin\controllers;
use admin\components\BaseAdminController;
use common\models\Attachment;
use common\services\UploadService;
/**
* @doc-module 文件上传
*/
class AttachmentController extends BaseAdminController
{
public string $modelClass = Attachment::class;
public $optional = [];
/**
* @doc-name 上传
* @doc-param file file 文件file
* @doc-return string url url
*/
public function actionUpload($name = 'file')
{
$uploadService = new UploadService();
return ['url' => $uploadService->index($name)];
}
}

View File

@@ -0,0 +1,453 @@
<?php
namespace admin\controllers;
use admin\components\BaseAdminController;
use admin\models\Admin;
use common\enums\UserRoleEnum;
use common\helpers\ArrayHelper;
use common\models\AuthRole;
use common\models\AuthRule;
use common\models\Role;
use yii\db\Exception;
use yii\web\ForbiddenHttpException;
class AuthController extends BaseAdminController
{
/**
* @var \common\core\rbac\DbManager
*/
public $authManager;
public $roles;
public $login_role;
/**
* @var bool 这里很多自定义的表单,就没有添加验证
*/
public $enableCsrfValidation = false;
public function init()
{
parent::init(); // TODO: Change the autogenerated stub
$this->authManager = \Yii::$app->authManager;
}
public function beforeAction($action)
{
parent::beforeAction($action); // TODO: Change the autogenerated stub
//验证权限
if ($this->actionCheckAuth()) {
return true;
}
throw new ForbiddenHttpException(\Yii::t('yii', 'You are not allowed to perform this action.'));
}
/**
* @doc-name 权限列表
* @doc-param int role_id 角色id
* @doc-return mixed @List{AuthRule{id,pid,component-string-组件地址,title-string-权限名称,path-string-权限对应路由,redirect-string-跳转路由,icon-string-菜单图标,api_url-int-接口地址,status-int-权限状态1启用 0禁用} 规则列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionRuleList()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
['role_id','required']
]);
if ($get['role_id']==UserRoleEnum::SUPER_ADMIN ){
$data=['217','218','219'];
$AuthRule = AuthRule::find()->where(['hidden' => 0])->andWhere(['not in','id',$data])->asArray()->all();
}elseif($get['role_id']==UserRoleEnum::STORE_ADMIN){
$data=['219'];
$AuthRule = AuthRule::find()->where(['hidden' => 0])->andWhere(['not in','id',$data])->asArray()->all();
}else{
$AuthRule = AuthRule::find()->where(['hidden' => 0])->asArray()->all();
}
return ArrayHelper::list_to_tree($AuthRule, 'id', 'pid', 'children');
}
/**
* @doc-name 添加权限
* @doc-param int pid 父级id / optional
* @doc-param string title 权限名称
* @doc-param string path 权限对应路由
* @doc-param string component 组件地址 / optional
* @doc-param string redirect 跳转路由 / optional
* @doc-param string icon 菜单图标 / optional
* @doc-param string api_url 接口地址 / optional
* @doc-param int status 权限状态 1启用 0 禁用 / optional
*/
public function actionAddRule()
{
if (\Yii::$app->request->isPost) {
$data = \Yii::$app->request->post();
$this->requestValidate($data, [
[['pid', 'title', 'path', 'status'], 'required'],
]);
$path = 'Admin/' . $data['path'];
$path = explode('/', $path);
foreach ($path as $value) {
$v = ucfirst($value);
$arr[] = $v;
}
$new_path = implode('/', $arr);
$AuthRule = AuthRule::find()->where(['path' => $new_path])->one();
if ($AuthRule) throw new Exception('权限已存在');
$data['path'] = $new_path;
$model = new AuthRule();
$model->setAttributes($data);
if (!$model->saveOrFail()) {
throw new Exception('添加失败' . array_values($model->getFirstErrors())[0]);
} else {
return ['添加成功'];
}
}
throw new Exception('请求方式错误');
}
/**
* @doc-name 编辑权限
* @doc-param int id id
* @doc-param int pid 父级id / optional
* @doc-param string title 权限名称
* @doc-param string path 权限对应路由
* @doc-param string component 组件地址 / optional
* @doc-param string redirect 跳转路由 / optional
* @doc-param string icon 菜单图标 / optional
* @doc-param string api_url 接口地址 / optional
* @doc-param int status 权限状态 1启用 0 禁用 / optional
*/
public function actionEditRule()
{
if (\Yii::$app->request->isPost) {
$data = \Yii::$app->request->post();
$this->requestValidate($data, [
['id', 'required'],
]);
$AuthRule = AuthRule::find()->where(['id' => $data['id']])->one();
if (!$AuthRule) throw new Exception('需要编辑的规则不存在');
$AuthRule->pid = $data['pid'] ?? $AuthRule->pid;
$AuthRule->title = $data['title'] ?? $AuthRule->title;
$AuthRule->path = $data['path'] ?? $AuthRule->path;
$AuthRule->component = $data['component'] ?? $AuthRule->component;
$AuthRule->redirect = $data['redirect'] ?? $AuthRule->redirect;
$AuthRule->icon = $data['icon'] ?? $AuthRule->icon;
$AuthRule->api_url = $data['api_url'] ?? $AuthRule->api_url;
$AuthRule->status = $data['status'] ?? $AuthRule->status;
if (!$AuthRule->saveOrFail()) {
throw new Exception('编辑失败');
}
return ['编辑成功'];
}
throw new Exception('请求方式错误');
}
/**
* @doc-name 删除权限
* @doc-param int id id
*/
public function actionDelRule()
{
$data = \Yii::$app->request->get();
$this->requestValidate($data, [
['id', 'required'],
]);
$id = AuthRule::find()->where(['id' => $data['id']])->one();
if (!$id) throw new Exception('所删除的权限不存在');
$t = \Yii::$app->db->beginTransaction();
try {
//删除权限
$id->delete();
//删除角色的权限
AuthRole::deleteAll(['rule_id' => $id]);
$t->commit();
return ['删除成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 角色列表
*/
public function actionRoleList()
{
$data = \Yii::$app->request->get();
$query = Role::find()->where(['>','id',9]);
$this->field = [
Role::class => [
'id', 'name', 'role_code', 'description',
'authRole' => function ($a) {
return AuthRole::find()->where(['role_id' => $a->id])->all();
}
]
];
return $this->create($query, $data);
}
/**
* @doc-name 添加角色
* @doc-param string name 名字
* @doc-param string role_code
* @doc-param string description 描述
*/
public function actionAddRole()
{
$data = \Yii::$app->request->post();
$this->requestValidate($data, [
['name', 'required'],
]);
$role = Role::find()->where(['name' => $data['name']])->one();
if ($role) throw new Exception('角色已经存在');
$t = \Yii::$app->db->beginTransaction();
try {
$model = new Role();
$model->name = $data['name'];
$model->role_code = $data['role_code'] ?? '';
$model->description = $data['description'] ?? '';
$model->save();
$path = 'Admin/Menu/List';
$AuthRule = AuthRule::find()->where(['path' => $path])->one();
if (!$AuthRule) throw new Exception('菜单列表不存在');
//添加菜单列表权限
$AuthRole = AuthRole::find()->where(['role_id' => $model->id, 'rule_id' => $AuthRule->id])->one();
if (!$AuthRole) {
$AuthRole = new AuthRole();
$AuthRole->role_id = $model->id;
$AuthRole->rule_id = $AuthRule->id;
$AuthRole->saveOrFail();
}
$t->commit();
return ['添加成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 编辑角色
* @doc-param int id id
* @doc-param string name 名字
* @doc-param string role_code
* @doc-param string description 描述
*/
public function actionEditRole()
{
if (\Yii::$app->request->isPost) {
$data = \Yii::$app->request->post();
$this->requestValidate($data, [
['id', 'required'],
]);
$edit_role = Role::find()->where(['id' => $data['id']])->one();
if (!$edit_role) throw new Exception('角色不存在');
if (!empty($data['name'])) {
$role = Role::find()->where(['name' => $data['name']])->andWhere(['!=', 'id', $data['id']])->one();
if ($role) {
throw new Exception('角色已存在');
}
}
$edit_role->name = $data['name'] ?? $edit_role->name;
$edit_role->role_code = $data['role_code'] ?? $edit_role->role_code;
$edit_role->description = $data['description'] ?? $edit_role->description;
if (!$edit_role->save()) {
throw new Exception('编辑失败');
}
return ['编辑成功'];
}
throw new Exception('请求方式错误');
}
/**
* @doc-name 删除角色
* @doc-param int id id
*/
public function actionDelRole()
{
$data = \Yii::$app->request->get();
$this->requestValidate($data, [
['id', 'required'],
]);
$role = Role::find()->where(['id' => $data['id']])->one();
if (!$role) throw new Exception('所删除的角色不存在');
$t = \Yii::$app->db->beginTransaction();
try {
//删除权限
$role->delete();
//删除角色的权限
AuthRole::deleteAll(['role_id' => $role->id]);
$t->commit();
return ['删除成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @@doc-name 给角色添加权限
* @doc-param int role_id role_id
* @doc-param int rule_id 权限id 1,2,3
* @doc-param int status 状态1启用 0禁用
*/
public function actionRoleAddRule()
{
$data = \Yii::$app->request->post();
$this->requestValidate($data, [
[['role_id', 'rule_id', 'status'], 'required'],
]);
$rule_id = explode(',', $data['rule_id']);
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($rule_id as $value) {
$AuthRole = AuthRole::find()->where(['rule_id' => $value, 'role_id' => $data['role_id']])->one();
if (!$AuthRole) {
$AuthRole = new AuthRole();
$AuthRole->role_id = $data['role_id'];
$AuthRole->rule_id = $value;
$AuthRole->status = $data['status'];
$AuthRole->saveOrFail();
}
}
$t->commit();
return ['添加成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @@doc-name 给角色修改权限
* @doc-param int role_id role_id
* @doc-param int rule_id 权限id 1,2,3,4,5
* @doc-param int status 状态1启用 0禁用
*/
public function actionRoleEditRule()
{
$data = \Yii::$app->request->post();
$this->requestValidate($data, [
[['role_id', 'rule_id', 'status'], 'required'],
]);
$rule_id = explode(',', $data['rule_id']);
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($rule_id as $value) {
$AuthRole = AuthRole::find()->where(['rule_id' => $value, 'role_id' => $data['role_id']])->one();
if (!$AuthRole) {
$AuthRole = new AuthRole();
$AuthRole->role_id = $data['role_id'];
$AuthRole->rule_id = $value;
$AuthRole->status = $data['status'];
$AuthRole->saveOrFail();
}
}
$all_rule_id = AuthRole::find()->select(['rule_id'])->where(['role_id' => $data['role_id']])->column();
$arr = array_diff($all_rule_id, $rule_id);
// if ($data['role_id']!=UserRoleEnum::SUPER_ADMIN){
foreach ($arr as $val) {
$AuthRole = AuthRole::find()->where(['role_id' => $data['role_id'], 'rule_id' => $val])->one();
if ($AuthRole) {
$AuthRole->delete();
}
}
// }
$t->commit();
return ['修改成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @@doc-name 给角色删除权限
* @doc-param int id id
*/
public function actionRoleDelRule()
{
$data = \Yii::$app->request->get();
$this->requestValidate($data, [
['id', 'required'],
]);
$AuthRole = AuthRole::find()->where(['id' => $data['id']])->one();
if (!$AuthRole) throw new Exception('该权限不存在');
$AuthRole->delete();
return ['删除成功'];
}
/**
* @doc-name 查看角色权限
* @doc-param int role_id 角色ID
* @doc-return mixed @List{id,role_id,rule_id,rule-string-权限} 查看角色权限列表
*/
public function actionQueryRoleRule()
{
$data = \Yii::$app->request->get();
$this->requestValidate($data, [
['role_id', 'required'],
]);
$query = AuthRole::find()->where(['role_id' => $data['role_id']]);
$this->field = [
AuthRole::class => [
'id', 'role_id', 'rule_id', 'rule' => 'authRule.title'
]
];
return $this->create($query, $data);
}
/**
* @doc-name 账号修改角色
* @doc-param string mobile 手机号
* @doc-param int role 角色
*/
public function actionAccountEditRole()
{
$data = \Yii::$app->request->get();
$this->requestValidate($data, [
[['mobile', 'role'], 'required'],
]);
$Admin = Admin::find()->where(['mobile' => $data['mobile']])->one();
if (!$Admin) {
throw new Exception('账号不存在');
}
$role = Role::find()->where(['id' => $data['role']])->one();
if (!$role) throw new Exception('角色不存在');
$Admin->role = $data['role'];
$Admin->saveOrFail();
return [];
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace admin\controllers;
use admin\models\forms\HospitalDocForm;
use common\core\BaseAppController;
use common\core\BaseController;
/**
* 后台操作医生控制器
* @author hyl
*/
class DoctorController extends BaseController
{
/**
* @doc-name 升级为互医
*/
public function actionDoctorUpgrade()
{
$post = \Yii::$app->request->post();
$HospitalDocForm = new HospitalDocForm();
$HospitalDocForm->attributes = $post;
return $HospitalDocForm->grade();
}
/**
* 获取互医信息
*/
public function actionHospitalDocInfo()
{
$post = \Yii::$app->request->post();
$HospitalDocForm = new HospitalDocForm();
$HospitalDocForm->attributes = $post;
return $HospitalDocForm->DocInfo();
}
/**
* 同步患者
*/
public function actionSyncPatient()
{
$post = \Yii::$app->request->post();
$HospitalDocForm = new HospitalDocForm();
$HospitalDocForm->attributes = $post;
return $HospitalDocForm->SyncPatient();
}
/**
* @doc-name 医生审核
* @doc-param int status 是否同意0否1是
* @doc-param int doctor_id 医生id
*/
public function actionDoctorExamine()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post,[
['status','required']
]);
$HospitalDocForm = new HospitalDocForm();
$HospitalDocForm->attributes = $post;
return $HospitalDocForm->ExamineDoc();
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace admin\controllers;
use admin\components\BaseAdminController;
use Yii;
/**
* 后台首页控制器
* @author longfei <phphome@qq.com>
*/
class IndexController extends BaseAdminController
{
public $defaultAction = 'login-page';
public function actionLoginPage()
{
return $this->render('login-page');
}
}

View File

@@ -0,0 +1,149 @@
<?php
namespace admin\controllers;
use admin\models\Admin;
use admin\models\forms\LoginForm;
use admin\models\RegisterForm;
use common\enums\UserRoleEnum;
use common\helpers\ArrayHelper;
use common\models\AdminAccessToken;
use common\models\Role;
use common\models\Store;
use Yii;
use yii\base\Exception;
use common\core\BaseAdminController;
class LoginController extends BaseAdminController
{
public $modelClass = Admin::class;
public $enableCsrfValidation = false;
public $defaultAction = 'register';
public $optional = ['register', 'logout', 'login'];
public $mallId;
public function actionLogin()
{
$model = new LoginForm();
// $model->attributes=Yii::$app->request->post();
if (Yii::$app->request->isPost) {
/** @var $adminAccessToken AdminAccessToken */
if ($model->load(Yii::$app->request->post(), '') && $adminAccessToken = $model->login()) {
$admin = Admin::find()->where(['uid' => $adminAccessToken->admin_id])->one();
$admin = ArrayHelper::toArray($admin, [
Admin::class => ['uid', 'username', 'role', 'mobile', 'store_id','code','city_id','province_id'],
]);
$title = '萧康管理后台';
switch ($admin['role']) {
case UserRoleEnum::SUPER_ADMIN:
$title = '萧康管理后台';
break;
case UserRoleEnum::STORE_ADMIN:
$name = Store::find()->select(['name'])->where(['id' => $admin['store_id']])->one();
$title = $name->name . '管理后台';
break;
case UserRoleEnum::PROVINCE_DAI :
case UserRoleEnum::CITY_DAI:
case UserRoleEnum::SUPPLY:
$title = $admin['username'].'的管理后台';
break;
default:
$title = $admin['username'].'的管理后台';
}
$admin['title'] = $title;
return [
'userInfo' => $admin,
'token' => $adminAccessToken->access_token
];
} else {
throw new Exception("登陆失败,帐号或者密码错误");
}
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return [];
}
/**
* @doc-name 后台注册
* @doc-param string mobile 手机号
* @doc-param string password 密码
* @doc-param string username 用户名
* @doc-param int role 角色id
* @doc-param int store_id 门店id / optional
* @doc-param int province_id 省份 / optional
* @doc-param int city_id 城市 / optional
*/
public function actionRegister()
{
$post = Yii::$app->request->post();
$model = new RegisterForm();
$model->attributes = $post;
return $model->register();
}
/**
* @doc-name 重置密码或忘记密码
* @doc-param string mobile 手机号
* @doc-param string password 密码
*/
public function actionResetPassword()
{
$post = Yii::$app->request->post();
$this->requestValidate($post, [
[['mobile', 'password'], 'required']
]);
$LoginForm = new LoginForm();
$LoginForm->attributes = $post;
return $LoginForm->ResetPassword();
}
/**
* @doc-name 所有角色
* @doc-return mixed @List{id,name-string-名字,role_code-string-role_code,description-string-描述} 医生列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionAllRole()
{
$post = Yii::$app->request->get();
$query = Role::find();
$this->field = [
Role::class => [
'id', 'name', 'role_code', 'description'
]
];
return $this->create($query, $post);
}
/**
* @doc-name 编辑管理员信息
* @doc-param string bank_user_name 开户人姓名 / optional
* @doc-param string bank_card 银行卡号 / optional
* @doc-param string bank_name 开户行 / optional
* @doc-param int bank_account_type 银行账户类型 1:对公,2:对私,5:存折 / optional
* @doc-param string bank_no 银行联行号bank_account_type=1或5或非62开头的对私银行账户时必选 / optional
*/
public function actionEditSuperInfo()
{
$post = Yii::$app->request->post();
$admin = \Yii::$app->user->identity;
if ($admin->role!=UserRoleEnum::SUPER_ADMIN){
throw new \yii\db\Exception('您不是超管,不能编辑信息');
}
$model = new RegisterForm();
$model->attributes = $post;
return $model->EditSuper();
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace admin\controllers;
use common\helpers\ArrayHelper;
use common\models\AuthRole;
use common\models\AuthRule;
use common\models\Menu;
use yii\base\Exception;
/**
* 后台菜单控制器
* @author longfei <phphome@qq.com>
*/
class MenuController extends AuthController
{
public $modelClass = Menu::class;
/**
* @doc-name 菜单列表
*/
public function actionList()
{
$user=\Yii::$app->user->identity;
$rule_id=AuthRole::find()->select(['rule_id'])->where(['role_id'=>$user->role])->column();
$AuthRule_path=AuthRule::find()->select(['path'])->where(['in','id',$rule_id])->andWhere(['type'=>1])->column();
$menu2s = Menu::find()->where(['in','menuUrl',$AuthRule_path])->andWhere(['hidden'=>0])->orderBy(['sort'=>SORT_ASC])->asArray()->all();
return ArrayHelper::itemsMerge($menu2s,0,'menuUrl','parentPath','children');
}
public function actionSave(){
$menuUrl = $this->post('menuUrl');
$model = Menu::findOne($menuUrl);
if(!$model){
$model = new Menu();
}
$model->load($this->post());
if( $model->load($this->post(),'') && $model->save()){
return $model->getAttributes();
}else{
throw new Exception("参数不对");
}
}
public function actionDel(){
$menuUrl = $this->post('menuUrl');
$model = Menu::findOne($menuUrl);
if (!$model) throw new \yii\db\Exception('菜单不存在');
if($model->delete()){
Menu::updateAll(['parentPath'=>''],['parentPath'=>$menuUrl]);
}
return ['删除成功'];
}
/**
* @doc-name 编辑菜单
*/
public function actionEdit()
{
$data= $this->post();
$menuUrl = $this->post('menuUrl');
$model = Menu::findOne($menuUrl);
if (!$model) throw new \yii\db\Exception('菜单不存在');
$model->attributes=$data;
$model->saveOrFail();
return ['编辑成功'];
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace admin\controllers;
use common\components\ApiErrorHandler;
use yii\rest\Controller;
class MobileController extends Controller
{
public function afterAction($action, $result)
{
$rs = parent::afterAction($action, $result);
// 也可以再定义 response
// $response = Yii::$app->response;
// $response->statusCode = 200;
// $response->data = ['message' => 'hello world'];
return ['data' => $rs, 'error' => '0'];
}
public function init()
{
parent::init();
$handler = new ApiErrorHandler();
\Yii::$app->set('errorHandler', $handler);
$handler->register();
}
public function formatDataBeforeSend($event){
$response = $event->sender;
//自已定义失败的返回
if ($response->data !== null && $response->isSuccessful==false) {
$response->data = [
'code' => 500,
'status' => "FAIL" ,
'message' => "系统繁忙,请稍后再试",
];
$response->statusCode = 200;
}
}
public function behaviors()
{
$behaviors = parent::behaviors();
unset($behaviors['contentNegotiator']['formats']['application/xml']);//去除xml格式就按剩下的json显示
return $behaviors;
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace admin\controllers;
use Yii;
use yii\helpers\ArrayHelper;
use common\modelsgii\Region;
use kartik\depdrop\DepDropAction;
/**
* 公共调用处理
* @author longfei <phphome@qq.com>
*/
class PublicController extends \common\core\Controller
{
/** @var bool */
public $layout = false;
/** @var bool */
public $enableCsrfValidation = false;
/**
* ---------------------------------------
* @inheritdoc
* ---------------------------------------
*/
public function actions()
{
return ArrayHelper::merge(parent::actions(), [
/* 省市区联动 */
'region' => [
'class' => DepDropAction::className(),
'enableCsrfValidation' => false,
'outputCallback' => function ($id, $params) {
$region = Region::find()->where(['parent_code' => $id])->orderBy('code ASC')->asArray()->all();
$_out = [];//var_dump($region);
foreach ($region as $value) {
$_tmp['id'] = $value['code'];
$_tmp['name'] = $value['fullname'];
$_out[] = $_tmp;
}
return $_out;
},
'selectedCallback' => function ($id, $params) {
return Yii::$app->getRequest()->get('sid');
}
],
/* ueditor文件上传 */
'ueditor' => [
'class' => 'common\actions\UEditorAction',
'config' => Yii::$app->params['ueditorConfig'],
],
/* 单图、多图上传 */
'uploadimage' => [
'class' => 'common\widgets\images\UploadAction',
],
/* migration备份数据 */
'backup' => [
'class' => 'e282486518\migration\WebAction',
'returnFormat' => 'json',
'migrationPath' => '@console/migrations'
]
]);
}
/**
* ---------------------------------------
* 通用的404错误处理
* @return string
* ---------------------------------------
*/
public function action404()
{
//渲染模板
return $this->render('404');
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace admin\controllers;
use common\core\BaseController;
use common\helpers\FuncHelper;
use common\models\Store;
use common\services\UploadService;
use common\services\WeappService;
use common\services\WechatService;
use yii\db\Exception;
//门店
class StoreController extends BaseController
{
/**
* @doc-name 生成门店二维码
* @doc-param int store_id 门店
* @doc-return string qrcode base64的二维码图片
*/
public static function actionQrcode($store_id=null)
{
$scene = 'STORE_QR_CODE'.'_'.$store_id;
// \Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$store = Store::find()->where([
'id' => $store_id
])->one();
if (!$store){
throw new Exception('门店不存在');
}
// if (!$store->qr_code) {
// $response = WechatService::getInstance()->app->app_code->getUnlimit($scene, [
// 'page' => 'pages/home/home',
// 'check_path' => false,
// ]);
//
// if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
// $path = 'uploads/STORE_QR_CODE/' . date('Ymd');
// $filename = $response->save('uploads/STORE_QR_CODE/' . date('Ymd'), 'STORE_QR_CODE_' . $store_id);
//
// $realpath = FuncHelper::getRealFilepath('service', $path . '/' . $filename);
//
// $uploadService = new UploadService();
// $url = $uploadService->saveFile($realpath);
//
// $store->setAttributes(['qr_code' => $url]);
// $store->save();
// }
// }
if (!$store->qr_code) {
$weappService = new WeappService();
$url= $weappService->getQrcode($scene);
$store->qr_code=$url;
$store->saveOrFail();
}
return $store->qr_code;
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace admin\controllers;
use admin\components\BaseAdminController;
use common\helpers\FuncHelper;
use common\models\Order;
use common\models\Prescription;
use common\models\Register;
use common\models\DoctorInfo;
use common\models\User;
use common\models\UserPatient;
use common\models\UserPatientHealthInquiry;
use yii\db\Exception;
/**
* @doc-module 用户管理
*/
class UserController extends BaseAdminController
{
/**
* @doc-name 用户端用户列表
* @doc-param string nickname 昵称 / optional
* @doc-param string mobile 电话 / optional
* @doc-param int gender 性别 / optional
* @doc-param string idcard 身份证 / optional
* @doc-return mixed @List{User{id,nickname-string-昵称,mobile-string-电话,created_at-string-首次访问时间,gender-int-性别,值为1时是男性,值为2时是女性,值为0时是未知性别,idcard-string-身份证,age-int-年龄,@UserPatientHealthInquiry{liver_function-int-肝功能状态0正常1异常,liver_index-string-肝功能异常指标,renal_function-int-肾功能状态0正常1异常,renal_index-string-肾功能异常指标,person_status-int-既往史0无1有,person_history-string-既往史,allergic_status-int-过敏史0无1有,allergic_status-string-过敏史,,allergic_status-int-家族遗传史0无1有,allergic_status-string-家族遗传史},@UserInquiry{id-int-订单id,user_id-int-用户id,order_no-string-订单号,total_pay_price-float-支付金额,is_pay-int-知否支付0否1是,@Inquiry{images-string-检查报告或患者照片,is_visit-string-是否就诊0否1是,visit_desc-string-就诊描述,patient_data-string-就诊人基础信息,liver_function-int-肝功能0正常1异常,renal_function-string-肾功能0正常1异常,person_status-int-个人病史0无1有,person_history-string-个人病史,allergic_status-int-过敏史0无1有,allergic_history-int-过敏史0无1有,family_status-int-家庭病史0无1有,family_history-string-家庭病史}},@Prescription{id-int-id,platform_prescription_no-string-平台处方单号,prescription_no-string-处方单号,order_id-int-订单id,status-int-状态0待审核1已通过2未通过3待使用4已使用5未使用6已失效7已初审,content-string-处方快照,prescription_type-int-1中药处方2西药处方3颗粒药处方,category-int-类别 1自费2医保,doctor_order-string-医嘱,clinical_diagnose-string-临床诊断,,医生签名-string-医生签名,type-int-类型1普通方2常用方,order_type-int-订单类型1处方2医技,total_pay_price-float-支付金额,}} 用户列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$query = User::find()->where([
'is_delete' => 0
]);
if (!empty($get['name'])) {//搜索姓名
$query->andWhere(['like', 'nickname', $get['name']]);
}
if (!empty($get['major_number'])) {//手机号
$query->andWhere(['mobile' => $get['major_number']]);
}
if (!empty($get['gender'])) {//性别
$query->andWhere(['gender' => $get['gender']]);
}
if (!empty($get['idcard'])) {//身份证
$query->andWhere(['idcard' => $get['idcard']]);
}
$this->field = [
User::class => [
'id', 'nickname', 'mobile', 'gender', 'idcard', 'created_at' => function ($model) {
return date('Y-m-d H:i:s', $model->created_at);
},
'age' => function ($model) {
return $model->idcard ? FuncHelper::getAgeFromIdNo($model->idcard) : '';
},
'UserPatientHealthInquiry' => function ($m) {
$UserPatient = UserPatient::find()->select('id')->where([
'user_id' => $m->id,
'relation' => 0
])->column();
return UserPatientHealthInquiry::find()->where([
'user_patient_id' => $UserPatient,
'is_delete' => 0
])->one();
},
'UserInquiry' => function ($i) {
return Order::find()->where([
'user_id' => $i->id,
])->with(['inquiry'])->asArray()->all();
},
'Prescription' => function ($p) {
return Prescription::find()->where([
'user_id' => $p->id,
'is_deleted' => 0
])->all();
},
'register'=>function($r){
return Register::find()->where([
'user_id'=>$r->id
])->all();
}
]
];
return $this->create($query, $get);
}
/**
* @doc-name 用户端用户详情
* @doc-param int id ID
* @doc-return mixed @User{id,nickname-string-昵称,mobile-string-电话,created_at-string-首次访问时间,gender-int-性别,值为1时是男性,值为2时是女性,值为0时是未知性别,idcard-string-身份证,age-int-年龄} 用户信息
* @doc-return mixed @UserPatientHealthInquiry{liver_function-int-肝功能状态0正常1异常,liver_index-string-肝功能异常指标,renal_function-int-肾功能状态0正常1异常,renal_index-string-肾功能异常指标,person_status-int-既往史0无1有,person_history-string-既往史,allergic_status-int-过敏史0无1有,allergic_status-string-过敏史,,allergic_status-int-家族遗传史0无1有,allergic_status-string-家族遗传史} 基本健康信息
* @doc-return mixed @UserInquiry{id-int-订单id,user_id-int-用户id,order_no-string-订单号,total_pay_price-float-支付金额,is_pay-int-知否支付0否1是,@Inquiry{images-string-检查报告或患者照片,is_visit-string-是否就诊0否1是,visit_desc-string-就诊描述,patient_data-string-就诊人基础信息,liver_function-int-肝功能0正常1异常,renal_function-string-肾功能0正常1异常,person_status-int-个人病史0无1有,person_history-string-个人病史,allergic_status-int-过敏史0无1有,allergic_history-int-过敏史0无1有,family_status-int-家庭病史0无1有,family_history-string-家庭病史}} 问诊记录
* @doc-return mixed @Prescription{id-int-id,platform_prescription_no-string-平台处方单号,prescription_no-string-处方单号,order_id-int-订单id,status-int-状态0待审核1已通过2未通过3待使用4已使用5未使用6已失效7已初审,content-string-处方快照,prescription_type-int-1中药处方2西药处方3颗粒药处方,category-int-类别 1自费2医保,doctor_order-string-医嘱,clinical_diagnose-string-临床诊断,,医生签名-string-医生签名,type-int-类型1普通方2常用方,order_type-int-订单类型1处方2医技,total_pay_price-float-支付金额} 处方记录
*/
public function actionInfo()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['id', 'required']
]);
$User = User::find()->where([
'id' => $get['id'],
'is_delete' => 0
])->with(['userPatient' => function ($u) {
$u->where(['relation' => 0]);
}])->asArray()->one();
$UserPatientId = $User['userPatient'][0]['id'];
if (!$User) throw new Exception('用户不存在');
$UserPatientHealthInquiry = UserPatientHealthInquiry::find()->where([
'user_patient_id' => $UserPatientId,
'is_delete' => 0
])->one();
$UserInquiry = Order::find()->where([
'user_id' => $get['id'],
])->with(['inquiry'])->asArray()->all();
$Prescription = Prescription::find()->where([
'user_id' => $get['id'],
'is_deleted' => 0
])->all();
$register=Register::find()->where([
'user_id'=>$get['id'],
])->all();
return [
'User' => $User,
'UserPatientHealthInquiry' => $UserPatientHealthInquiry,
'UserInquiry' => $UserInquiry,
'Prescription' => $Prescription,
'register' => $register,
];
}
public function actionPatientList(){
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['id', 'required']
]);
$user = User::find()->where([
'id' => $get['id'],
'is_delete' => 0
])->asArray()->one();
if (!$user) throw new Exception('用户不存在');
$userPatient = UserPatient::find()->select('id,name')->where(['user_id' => $get['id'],'is_delete' => 0])->orderBy('is_default desc,created_at asc')->all();
return $userPatient;
}
public function actionPatientInfo(){
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['patient_id', 'required']
]);
$userPatient = UserPatient::find()->where(['id' => $get['patient_id'],'is_delete' => 0])->one();
if(!$userPatient){
throw new Exception('就诊人不存在');
}
$UserPatientHealthInquiry = UserPatientHealthInquiry::find()->where([
'user_patient_id' => $get['patient_id'],
'is_delete' => 0
])->one();
return [
'info' => $userPatient,
'healthInquiry' => $UserPatientHealthInquiry
];
}
public function actionPatientPrescriptionList(){
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['patient_id', 'required']
]);
$userPatient = UserPatient::find()->where(['id' => $get['patient_id'],'is_delete' => 0])->one();
if(!$userPatient){
throw new Exception('就诊人不存在');
}
$prescriptionList = Prescription::find()->select(['id','su_id','clinical_diagnose','prescription_no','created_at'])->where(['up_id' => $get['patient_id'],'is_deleted' => 0,'cancel_status' => 0])->orderBy('created_at desc')->asArray()->all();
foreach($prescriptionList as &$v){
$v['created_at'] = date('Y年m月d日 H:i',$v['created_at']);
$v['doctor_name'] = DoctorInfo::find()->where(['su_id' => $v['su_id']])->select('name')->scalar();
}
return $prescriptionList;
}
}

View File

@@ -0,0 +1,144 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\ArticleForm;
use common\models\Categories;
use common\models\DoctorArticle;
use yii\db\Exception;
class ArticleController extends BaseAdminController
{
/**
* @doc-name 新增或编辑文章分类
* @doc-param int id 传id则修改 / optional
* @doc-param string name 分类
* @doc-param int pid 父级id
* @doc-param int level 级别
*/
public function actionSaveCategories()
{
$post=\Yii::$app->request->post();
$this->requestValidate($post,[
[['name','pid','level'],'required'],
]);
if (empty($post['id'])){
$Categories= Categories::find()->where(['name'=>$post['name'],'is_deleted'=>0])->one();
if (!$Categories){
$Categories= new Categories();
$Categories->name=$post['name'];
$Categories->pid=$post['pid'];
$Categories->level=$post['level'];
$Categories->save();
}
return ['已添加'];
}else{
$Categories= Categories::find()->where(['id'=>$post['id'],'is_deleted'=>0])->one();
if (!$Categories){
throw new Exception('分类不存在');
}
$Categories->name=$post['name']??$Categories->name;
$Categories->pid=$post['pid']??$Categories->pid;;
$Categories->level=$post['level']??$Categories->level;;
if (! $Categories->saveOrFail()){
throw new Exception('编辑失败');
};
return ['编辑成功'];
}
}
/**
* @doc-name 删除分类
* @doc-param int id ID
*/
public function actionDelCategories()
{
$get=\Yii::$app->request->get();
$this->requestValidate($get,[
['id','required'],
]);
$Categories= Categories::find()->where(['id'=>$get['id']])->one();
if (!$Categories){
throw new Exception('分类不存在');
}
$Categories->is_deleted=1;
if (!$Categories->saveOrFail()){
throw new Exception('删除失败');
};
return ['删除成功'];
}
/**
* @doc-name 文章分类列表
* @doc-return mixed @List{id,name-string-分类,pid-int-父级id,level-int-级别} 文章分类列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionCategoriesList()
{
$get=\Yii::$app->request->get();
$query= Categories::find()->where(['is_deleted'=>0])->orderBy(['id'=>SORT_DESC]);
$this->field=[
Categories::class=>[
'id','name','pid','level'
]
];
return $this->create($query,$get);
}
/**
* @doc-name 文章列表
* @doc-return mixed @List{id,su_id-int-医生id 0为后台发布,cover-string-封面,title-string-文章标题,intro-string-简介,content-string-内容,video_url-string-视频链接,read_num-int-阅读量,collection-string-货收藏),is_draft-int-是否是草稿0否1是} 文章列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionArticleList()
{
$get=\Yii::$app->request->get();
$query= DoctorArticle::find()->where(['is_delete'=>0])->orderBy(['id'=>SORT_DESC]);
$this->field=[
DoctorArticle::class=>[
'id','cid','su_id','cover','title','intro','content','video_url','read_num','collection','is_draft','categories'=>'categories.name','type'
]
];
return $this->create($query,$get);
}
/**
* @doc-name 新增或修改文章
* @doc-param int id 传id则修改 / optional
* @doc-param int type 文章类型1图文类型2图片 / optional
* @doc-param int cid 分类id / optional
* @doc-param int su_id 发部人 / optional
* @doc-param string cover 封面
* @doc-param string title 标题
* @doc-param string intro 简介 / optional
* @doc-param string content 内容
* @doc-param string video_url 视频链接 / optional
* @doc-param int is_draft 是否是草稿0否1是 / optional
*/
public function actionSaveArticle()
{
$post = \Yii::$app->request->post();
$ArticleForm= new ArticleForm();
$ArticleForm->attributes = $post;
return $ArticleForm->save();
}
/**
* @doc-name 删除文章
* @doc-param int id id
*/
public function actionDelArticle()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
['id','required'],
]);
$ArticleForm= new ArticleForm();
$ArticleForm->attributes = $get;
return $ArticleForm->del();
}
}

View File

@@ -0,0 +1,216 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\DepartForm;
use common\enums\UserRoleEnum;
use common\helpers\ArrayHelper;
use common\models\Department;
use common\models\Platform;
use common\models\Store;
/**
* @doc-module 科室与门店
*/
class DepartController extends BaseAdminController
{
/**
* @doc-name 科室列表(处理成二维数组)
* @doc-param int name 科室名字 / optional
* @doc-return mixed @List{id,name-string-名字,pid-int-父级id,level-int-等级,child_depart-string-子级科室} 科室信息
*/
public function actionDeptList()
{
$get = \Yii::$app->request->get();
$query = Department::find();
if (!empty($get['name'])) {
$query->andWhere([
'like', 'name', $get['name']
]);
}
$this->field = [
Department::class => [
'id', 'name', 'pid', 'level',
'child_depart' => 'child'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 科室列表
* @doc-param int name 科室名字 / optional
* @doc-return mixed @List{id,name-string-名字,pid-int-父级id,level-int-等级} 科室信息
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$query = Department::find();
if (!empty($get['name'])) {
$query->andWhere([
'like', 'name', $get['name']
]);
}
return $query->select(['id', 'name', 'level'])->all();
}
/**
* @doc-name 新增科室
* @doc-param string name 科室
* @doc-param int level 科室级别
* @doc-param int pid 父级id / optional
* @doc-param string is_recommend 是否推荐 / optional
* @doc-param int feature 是否是重点特色专科0不是1是 / optional
*/
public function actionSaveDept()
{
$post = \Yii::$app->request->post();
$DepartForm = new DepartForm();
$DepartForm->attributes = $post;
return $DepartForm->SaveDepart();
}
/**
* @doc-name 门店列表
* @doc-param int name 名字 / optional
* @doc-param string region 省 / optional
* @doc-param string city 市 / optional
* @doc-param int limit 每页条数 / optional
* @doc-return mixed @List{id,name-string-名字,drugstore_id-int-仓库id,drugstore-string-仓库,plate_id-int-平台id,position-string-位置,pic-string-图片,contact-string-联系人,mobile-string-联系电话,qr_code-string-门店二维码,start_time-string-开始营业时间,end_time-string-结束营业时间,see_rate-int-是否查看毛利率0否1是} 门店信息
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionStoreList()
{
$get = \Yii::$app->request->get();
$query = Store::find()->alias('s');
$name = \Yii::$app->request->get('name');
$region = \Yii::$app->request->get('region');
$city = \Yii::$app->request->get('city');
$admin = \Yii::$app->user->identity;
if ($admin->role==UserRoleEnum::STORE_ADMIN){
$query->andWhere(['s.id'=>$admin->store_id])->orderBy(['s.id'=>SORT_DESC]);
}elseif ($admin->role==UserRoleEnum::PROVINCE_DAI){
$query->andWhere(['s.province_id'=>$admin->province_id])->orderBy(['s.id'=>SORT_DESC]);
}elseif ($admin->role==UserRoleEnum::CITY_DAI){
$query->andWhere(['s.city_id'=>$admin->city_id])->orderBy(['s.id'=>SORT_DESC]);
}elseif ($admin->role==UserRoleEnum::SUPPLY){
$query->andWhere(['s.code'=>$admin->code])->orderBy(['s.id'=>SORT_DESC]);
}else{
$query->orderBy(['s.id'=>SORT_DESC]);
}
if (!empty($name) ) {
$query->andWhere([
'or',
['like', 's.name', $name],
['like', 's.shouzimu', $name],
]);
}
if ( !empty($region)) {
$query->joinWith(['province'=>function($p)use($region){
$p->alias('p');
$p->where(['like','p.name',$region]);
}]);
}
if ( !empty($city)) {
$query->joinWith(['city'=>function($p)use($city){
$p->alias('c');
$p->where(['like','c.name',$city]);
}]);
}
$this->field = [
Store::class => [
'id', 'plate_id', 'name', 'position', 'offical_seal', 'pic', 'contact', 'mobile', 'qr_code',
'start_time', 'end_time',
'drugstore_id', 'see_rate',
'drugstore' => 'drugStore.name',
'code','uid','supply'=>'admin.username',
'province'=>'province.name',
'city'=>'city.name',
'province_id',
'city_id','erp_id'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 新增或编辑门店
* @doc-desc 传id则修改
* @doc-param int id 门店id / optional
* @doc-param int plate_id 平台ID
* @doc-param int erp_id erp_id / optional
* @doc-param int drugstore_id 仓库ID
* @doc-param string name 名字
* @doc-param string contact 联系人
* @doc-param string position 位置
* @doc-param string mobile 电话
* @doc-param int province_id 省
* @doc-param int city_id 市
* @doc-param string code 推广码
* @doc-param string offical_seal 公章
* @doc-param string start_time 开始营业时间
* @doc-param string end_time 结束营业时间
* @doc-param string pic 图片 / optional
* @doc-param string bank_user_name 开户人姓名 / optional
* @doc-param string bank_card 银行卡号 / optional
* @doc-param string bank_name 开户行 / optional
* @doc-param int bank_account_type 银行账户类型 1:对公,2:对私,5:存折 / optional
* @doc-param string bank_no 银行联行号bank_account_type=1或5或非62开头的对私银行账户时必选 / optional
*/
public function actionSaveStore()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['code','required','message'=>'推广码不能为空'],
['plate_id','required','message'=>'平台ID不能为空'],
['drugstore_id','required','message'=>'仓库ID不能为空'],
['name','required','message'=>'名字不能为空'],
['contact','required','message'=>'联系人不能为空'],
['position','required','message'=>'联系人不能为空'],
['mobile','required','message'=>'电话不能为空'],
// ['offical_seal','required','message'=>'公章不能为空'],
['start_time','required','message'=>'开始营业时间不能为空'],
['end_time','required','message'=>'结束营业时间不能为空'],
['province_id','required','message'=>'省份不能为空'],
['city_id','required','message'=>'城市不能为空'],
]);
$post['store_name'] = $post['name'];
$post['shouzimu']=ArrayHelper::shouzimu($post['name']);
$DepartForm = new DepartForm();
$DepartForm->attributes = $post;
return $DepartForm->SaveStore();
}
/**
* @doc-name 平台列表
* @doc-param int name 名字 / optional
* @doc-return mixed @List{id,name-string-平台名称,token-string-平台密钥(后期使用),url-string-通讯地址,callbackurl-string-位置,status-int-1使用0不使用} 平台信息
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionPlatformList()
{
$get = \Yii::$app->request->get();
$query = Platform::find();
if (!empty($get['name'])) {
$query->andWhere([
'like', 'name', $get['name']
]);
}
$this->field = [
Platform::class => [
'id', 'name', 'token', 'callbackurl', 'url', 'status'
]
];
return $this->create($query, $get);
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\DiagnoseForm;
use common\modelsgii\Disease;
use moonland\phpexcel\Excel;
use yii\db\Exception;
use yii\web\UploadedFile;
/**
* @doc-module 诊断症状
*/
class DiagnoseController extends BaseAdminController
{
/**
* @doc-name 诊断症状列表
* @doc-param string name 名称 / optional
* @doc-param string major_number 主编号 / optional
* @doc-param string ref_number 次编号 / optional
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$query = Disease::find()->where(['is_delete' => 0]);
if (!empty($get['name'])){
$query->andWhere([
'like', 'name',$get['name']
]);
}
if (!empty($get['major_number'])){
$query->andWhere([
'major_number'=>$get['major_number']
]);
}
if (!empty($get['ref_number'])){
$query->andWhere([
'ref_number'=>$get['ref_number']
]);
}
$this->field = [
Disease::class => [
'id', 'diagnose_code','name', 'major_number', 'ref_number'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 新增或编辑诊断症状
* @doc-desc 传ID则编辑
* @doc-param int ID 症状id / optional
* @doc-param string name 名字
* @doc-param string diagnose_code 疾病诊断代码 / optional
* @doc-param string major_number 主编号 / optional
* @doc-param string ref_number 次编号 / optional
*/
public function actionSave()
{
$post = \Yii::$app->request->post();
$DiagnoseForm = new DiagnoseForm();
$DiagnoseForm->attributes = $post;
return $DiagnoseForm->save();
}
/**
* @doc-name 删除诊断症状
* @doc-param int id 诊断症状ID
*/
public function actionDel()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id', 'required']
]);
$DiagnoseForm = new DiagnoseForm();
$DiagnoseForm->attributes = $post;
return $DiagnoseForm->del();
}
/**
* @doc-name 导入诊断症状
* @doc-param file file 文件
*/
public function actionImport()
{
$request = \Yii::$app->request;
if ($request->isPost) {
//设置最大执行时间
ini_set("max_execution_time", "360");
$file = UploadedFile::getInstanceByName('file');
if ($file->size > 5 * 1024 * 1024) {
throw new Exception('excel文件不能超过5M!');
}
//文件名
$filename = date('His') . md5($file->getBaseName()) . mt_rand(1000, 9999) . '.' . $file->getExtension();
//保存文件
$file->saveAs($filename);
$data = Excel::import($filename, [
'setFirstRecordAsKeys' => true,
'getOnlySheet' => 'Sheet1',
]);
$DiagnoseForm = new DiagnoseForm();
return $DiagnoseForm->export($data);
} else {
throw new Exception('请求方式错误');
}
}
}

View File

@@ -0,0 +1,916 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\Admin;
use common\enums\UserRoleEnum;
use common\helpers\FuncHelper;
use common\models\CashAccount;
use common\models\CashApply;
use common\models\Ledger;
use common\models\LedgerLog;
use common\models\Log;
use common\models\Register;
use common\models\Store;
use common\modelsgii\ProductOrder;
use common\services\EplPayService;
use yii\base\Exception;
use yii\helpers\Json;
use yii\web\Response;
use common\services\ExportService;
/**
* @doc-module 分账
*/
class DivideAccountController extends BaseAdminController
{
/**
* @doc-name 诊所申请提现操作
* @doc-param string apply_cash 申请提现金额
* @doc-param string bank_user_name 开户人姓名
* @doc-param string bank_card 银行卡号
* @doc-param string bank_name 开户行名称
* @doc-param int bank_account_type 银行账户类型 1:对公,2:对私,5:存折
* @doc-param string bank_no 银行联行号bank_account_type=1或5或非62开头的对私银行账户时必选 / optional
* @doc-param int user_type 用户类型1诊所2总部
*/
public function actionStoreApply()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['apply_cash', 'bank_user_name', 'bank_card', 'bank_name', 'bank_account_type', 'user_type'], 'required']
]);
if ($post['apply_cash']<3){
throw new \yii\db\Exception('申请提现金额最少不能小于3元');
}
$user = \Yii::$app->user->identity;
if ($user->role != UserRoleEnum::STORE_ADMIN) {
throw new Exception('您还不是诊所管理员,没有权限申请打款');
}
if ($post['user_type'] != 1) throw new Exception('用户类型错误');
if ($post['bank_account_type'] == 1 || $post['bank_account_type'] == 5) {
if (empty($post['bank_no'])) {
throw new Exception('bank_no不能为空');
}
} else {
if (substr($post['bank_card'], 0, 2) != '62') {
if (empty($post['bank_no'])) {
throw new Exception('bank_no不能为空');
}
}
}
$t = \Yii::$app->db->beginTransaction();
try {
$order_no = 'DK' . time() . rand(111111, 999999);
$Account = CashAccount::find()->where([
'user_id' => $user->store_id,
'user_type' => 1
])->one();
if (!$Account) throw new Exception('账号不存在');
if (bcsub($Account->able_cash ,$Account->frozen_cash,2) < $post['apply_cash']) {
throw new Exception('sorry,您的账户没有那么多提现金额');
}
$CashAccount = CashAccount::find()->where([
'user_id' => $user->store_id,
'user_type' => 1
])->one();
$Platform= CashAccount::find()->where([
'user_id' => 0,
'user_type' => 2
])->one();
// $CashAccount->able_cash = bcsub($CashAccount->able_cash, $post['apply_cash'], 2);
$CashAccount->frozen_cash = bcadd($post['apply_cash'], $CashAccount->frozen_cash, 2);
$CashAccount->last_apply_time = date('Y-m-d H:i:s', time());
$CashAccount->saveOrFail();
$qianliuwu=bcdiv(0.65,100,4);
$shouxufei=bcadd(bcmul($post['apply_cash'],$qianliuwu,2),2,3);
// $Platform->updateAllCounters(['able_cash'=>1]);
// $Platform->updateAllCounters(['total_cash'=>1]);
$CashApply = new CashApply();
$CashApply->user_id = $user->store_id;//诊所id
$CashApply->user_type = 1;//用户类型1诊所2总部
$CashApply->order_no = $order_no;//申请提现金额
$CashApply->apply_cash = $post['apply_cash'];//申请提现金额
$CashApply->charge_cash =$shouxufei;//手续费
$CashApply->true_cash = bcsub($CashApply->apply_cash, $shouxufei, 2);//实际到账金额
$CashApply->apply_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '诊所申请打款';
$log->mold = 3;//财务操作
$log->content = '诊所管理员ID:' . $user->uid . '申请打款:' . $post['apply_cash'] . '元,订单号为:' . $order_no . ',开户人姓名为:' . $post['bank_user_name'] . ',银行卡号:' . $post['bank_card'] . ',开户行名称:' . $post['bank_name'] . ',银行账户类型:' . $post['bank_account_type'] . ',账户的冻结金额由原来的:' . $Account->frozen_cash . '元变为:' . $CashAccount->frozen_cash . '元';
$log->save();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
$t->commit();
return ['申请成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 平台申请提现操作
* @doc-param string apply_cash 申请提现金额
* @doc-param string bank_user_name 开户人姓名
* @doc-param string bank_card 银行卡号
* @doc-param string bank_name 开户行名称
* @doc-param int bank_account_type 银行账户类型 1:对公,2:对私,5:存折
* @doc-param string bank_no 银行联行号bank_account_type=1或5或非62开头的对私银行账户时必选 / optional
* @doc-param int user_type 用户类型1诊所2总部
*/
public function actionPlatformApply()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['apply_cash', 'bank_user_name', 'bank_card', 'bank_name', 'bank_account_type', 'user_type'], 'required']
]);
if ($post['apply_cash']<3){
throw new \yii\db\Exception('申请提现金额最少不能小于3元');
}
$user = \Yii::$app->user->identity;
if ($user->role != UserRoleEnum::SUPER_ADMIN) throw new \yii\base\Exception('您还不是超级管理员,没有权限申请打款');
if ($post['user_type'] != 2) throw new \yii\db\Exception('用户类型错误');
if ($post['bank_account_type'] == 1 || $post['bank_account_type'] == 5) {
if (empty($post['bank_no'])) {
throw new \yii\base\Exception('bank_no不能为空');
}
} else {
if (substr($post['bank_card'], 0, 2) != '62') {
if (empty($post['bank_no'])) {
throw new Exception('bank_no不能为空');
}
}
}
$t = \Yii::$app->db->beginTransaction();
try {
$order_no = 'DK' . time() . rand(111111, 999999);
$Account = CashAccount::find()->where([
'user_type' => 2,
'user_id' => 0,
])->one();
if (!$Account) throw new Exception('账号不存在');
if (bcsub($Account->able_cash,$Account->frozen_cash,2) < $post['apply_cash'])
throw new Exception('sorry,您的账户没有那么多提现金额');
$CashAccount = CashAccount::find()->where([
'user_type' => 2,//平台
'user_id' => 0,
])->one();
// $CashAccount->able_cash = bcsub($CashAccount->able_cash, $post['apply_cash'], 2);
$CashAccount->frozen_cash = bcadd($post['apply_cash'], $CashAccount->frozen_cash, 2);
$CashAccount->last_apply_time = date('Y-m-d H:i:s', time());
$CashAccount->saveOrFail();
$qianliuwu=bcdiv(0.65,100,4);
$shouxufei=bcadd(bcmul($post['apply_cash'],$qianliuwu,2),2,3);
$CashApply = new CashApply();
$CashApply->user_type = 2;
$CashApply->user_id = 0;//用户ID
$CashApply->order_no = $order_no;
$CashApply->apply_cash = $post['apply_cash'];//申请提现金额
$CashApply->charge_cash = $shouxufei;//手续费
$CashApply->true_cash = bcsub($CashApply->apply_cash, $shouxufei, 2);//实际到账金额
$CashApply->apply_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '平台申请打款';
$log->content = '平台ID:' . $user->uid . '申请打款:' . $post['apply_cash'] . '元,订单号为::' . $order_no . ',开户人姓名为:' . $post['bank_user_name'] . ',银行卡号:' . $post['bank_card'] . ',开户行名称:' . $post['bank_name'] . ',银行账户类型:' . $post['bank_account_type'] . ',账户冻结金额由原来的:' . $Account->frozen_cash . '元变为:' . $CashAccount->frozen_cash . '元';
$log->mold = 3;//财务操作
$log->save();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
$t->commit();
return ['申请成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 分账申请打款审核(超级管理员)--通过
* @doc-param int id 申请id
* @doc-param int user_type 类型1诊所2总部
* @doc-param string check_result 审核结果
*/
public function actionApplyAgree()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['id', 'check_result', 'user_type'], 'required'],
]);
$user = \Yii::$app->user->identity;
if ($user->role != UserRoleEnum::SUPER_ADMIN) throw new Exception('你不是超级管理员,没有分账申请打款审核权限');
$CashApply = CashApply::find()->where([
'id' => $post['id'],
'user_type' => $post['user_type'],
'check_status' => 1
])->one();
if (!$CashApply) throw new Exception('申请不存在');
if ($post['user_type'] == 1) {//诊所
$Account = CashAccount::find()->where([
'user_id' => $CashApply->user_id,
'user_type' => $CashApply->user_type
])->one();
$config=Store::find()->where(['id'=>$CashApply->user_id])->one();
} else {//平台
$Account = CashAccount::find()->where([
'user_id' => 0,
'user_type' => $CashApply->user_type
])->one();
$config=Admin::find()->where(['role'=>UserRoleEnum::SUPER_ADMIN])->one();
}
if (!$Account) throw new Exception('诊所或平台的账号不存在');
$CashAccount = CashAccount::find()->where([
'user_type' => $CashApply->user_type,
'user_id' => $CashApply->user_id
])->one();
if (empty($config['bank_user_name']) || empty($config['bank_card']) || empty($config['bank_name']) || empty($config['bank_account_type'])){
$CashAccount->frozen_cash = bcsub($CashAccount->frozen_cash, $CashApply->apply_cash, 2);//申请提现冻结的金额
$CashAccount->saveOrFail();
$CashApply->check_id = $user->uid;
$CashApply->check_status = 4;//提现失败
$CashApply->check_result = '银行卡相关配置不完善';
$CashApply->check_time = date('Y-m-d H:i:s', time());
$CashApply->dakuan_status = -1;//失败
$CashApply->dakuan_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '分账申请打款审核';
$log->content = '超级管理员:' . $user->uid . '打款操作,订单号:' . $CashApply->order_no . ',打款金额:' . bcadd($CashApply->true_cash,2,2) . '元,开户人姓名:' . $config->bank_user_name . ',银行卡号:' . $config->bank_card . ',银行名称:' . $config->bank_name . ',银行账户类型:' . $config->bank_account_type . ',打款失败,原因:银行卡相关配置不完善' ;
$log->mold = 3;//财务操作
$log->saveOrFail();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
throw new \yii\db\Exception('银行卡相关配置不能为空');
}
$param=[
'order_no'=>$CashApply->order_no,
'apply_cash'=>bcadd($CashApply->true_cash,1,2),
'bank_name'=>$config->bank_name,
'bank_account_type'=>$config->bank_account_type,
'bank_no'=>$config->bank_no,
'bank_user_name' => $config->bank_user_name,
'bank_card' => $config->bank_card,
];
//打款
$res = EplPayService::getInstance()->withDraw($param);
//打款失败
if ($res['returnCode'] != 0000) {
try {
$transaction=\Yii::$app->db->beginTransaction();
$CashAccount->frozen_cash = bcsub($CashAccount->frozen_cash, $CashApply->apply_cash, 2);//申请提现冻结的金额
$CashAccount->saveOrFail();
$CashApply->check_id = $user->uid;
$CashApply->check_status = 4;//提现失败
$CashApply->check_result = $res['returnMsg'];
$CashApply->check_time = date('Y-m-d H:i:s', time());
$CashApply->dakuan_status = -1;//失败
$CashApply->dakuan_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '分账申请打款审核';
$log->content = '打款失败:超级管理员:' . $user->uid . '打款操作,订单号:' . $CashApply->order_no . ',打款金额:' . bcadd($CashApply->true_cash,2,2) . '元,开户人姓名:' . $config->bank_user_name . ',银行卡号:' . $config->bank_card . ',银行名称:' . $config->bank_name . ',银行账户类型:' . $config->bank_account_type . ',打款失败,原因:' . $res['returnMsg'];
$log->mold = 3;//财务操作
$log->saveOrFail();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
$transaction->commit();
return $res;
}catch (\Exception $e){
$transaction->rollBack();
throw new \yii\db\Exception($e->getMessage());
}
}else{
$t = \Yii::$app->db->beginTransaction();
try {
//打款成功
$CashAccount->able_cash = bcsub($CashAccount->able_cash, $CashApply->apply_cash, 2);//账户余额
$CashAccount->frozen_cash = bcsub($CashAccount->frozen_cash, $CashApply->apply_cash, 2);//申请提现冻结的金额
$CashAccount->withdrawn_cash = bcadd($CashAccount->withdrawn_cash, $CashApply->true_cash, 2);//已提现金额
$CashAccount->charge_cash = bcadd($CashAccount->charge_cash, $CashApply->charge_cash, 2);//手续费
$CashAccount->saveOrFail();
$CashApply->check_id = $user->uid;
$CashApply->check_status = 2;//成功
$CashApply->check_result = $post['check_result'];
$CashApply->check_time = date('Y-m-d H:i:s', time());
$CashApply->check_time = date('Y-m-d H:i:s', time());
$CashApply->dakuan_status = 1;//成功
$CashApply->dakuan_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '分账申请打款审核';
$log->content = $user->uid . '通过了ID为:' . $post['id'] . '的打款申请,打款结果:成功';
$log->mold = 3;//财务操作
$log->save();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
$t->commit();
return ['审核成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
}
/**
* @doc-name 分账申请打款审核(超级管理员)--拒绝
* @doc-param int id 申请id
* @doc-param int user_type 类型1诊所2总部
* @doc-param string check_result 审核结果
*/
public function actionApplyRefuse()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['id', 'check_result', 'user_type'], 'required'],
]);
$user = \Yii::$app->user->identity;
if ($user->role != UserRoleEnum::SUPER_ADMIN) throw new Exception('你不是超级管理员,没有分账申请打款审核权限');
$CashApply = CashApply::find()->where([
'id' => $post['id'],
'user_type' => $post['user_type'],
'check_status' => 1,
])->one();
if (!$CashApply) throw new Exception('申请不存在');
$Account = CashAccount::find()->where([
'user_id' => $CashApply->user_id,
'user_type' => $CashApply->user_type
])->one();
if (!$Account) throw new Exception('平台或技术方的账号不存在');
$t = \Yii::$app->db->beginTransaction();
try {
$CashApply->check_id = $user->uid;
$CashApply->check_status = 3;//拒绝
$CashApply->check_result = $post['check_result'];
$CashApply->check_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$CashAccount = CashAccount::find()->where([
'user_type' => $CashApply->user_type
])->one();
$CashAccount->frozen_cash = bcsub($CashAccount->frozen_cash, $CashApply->apply_cash, 2);
$CashAccount->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '分账申请打款审核';
$log->content = '管理员:' . $user->uid . '拒绝了ID为:' . $post['id'] . '的打款申请,可提现账户ID为:' . $Account->id . '的账户的冻结的金额由' . $Account->frozen_cash . '变为' . $CashAccount->frozen_cash;
$log->mold = 3;//财务操作
$log->save();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
$t->commit();
return ['成功拒绝'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 分账打款
* @doc-param int apply_id 提现申请ID
* @doc-param string order_no 订单号
* @doc-param string order_no 订单号
* @doc-param string bank_user_name 开户人姓名
* @doc-param string bank_card 银行卡号
* @doc-param string bank_name 银行名称
* @doc-param string bank_account_type 1对公2对私5存
*/
public function actionPayment()
{
$post = \Yii::$app->request->post();
$user = \Yii::$app->user->identity;
if ($user->role != UserRoleEnum::SUPER_ADMIN) throw new \yii\db\Exception('您不是超级管理员,没权限打款');
$this->requestValidate($post, [
[['apply_id', 'order_no', 'bank_user_name', 'bank_card', 'bank_name', 'bank_account_type'], 'required']
]);
$CashApply = CashApply::find()->where(['id' => $post['apply_id']])->one();
if (!$CashApply) throw new Exception('提现申请不存在');
if ($CashApply->check_status != 2) {//不是已通过状态
throw new Exception('提现申请不是已通过状态,您还不能打款');
}
$CashAccount = CashAccount::find()->where([
'user_type' => $CashApply->user_type,
'user_id' => $CashApply->user_id
])->one();
if (!$CashAccount) throw new Exception('账户不存在');
$post['apply_cash'] = $CashApply->apply_cash;
$t = \Yii::$app->db->beginTransaction();
try {
//打款
$res = EplPayService::getInstance()->withDraw($post);
//打款失败
if ($res['returnCode'] != 0000) {
$CashAccount->frozen_cash = bcsub($CashAccount->frozen_cash, $CashApply->apply_cash, 2);//申请提现冻结的金额
// $CashAccount->able_cash=bcadd($CashAccount->able_cash,$CashApply->apply_cash,2);//可提现金额
$CashAccount->saveOrFail();
$CashApply->dakuan_status = -1;
$CashApply->dakuan_time = date('Y-m-d H:i:s', time());
$CashApply->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '超级管理员';
$log->content = '打款失败:超级管理员:' . $user->uid . '打款操作,订单号:' . $post['order_no'] . ',打款金额:' . $post['apply_cash'] . '元,开户人姓名:' . $post['bank_user_name'] . ',银行卡号:' . $post['bank_card'] . ',银行名称:' . $post['bank_name'] . ',银行账户类型:' . $post['bank_account_type'] . '打款失败:失败原因' . $res;
$log->mold = 3;//财务操作
$log->saveOrFail();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
return $res;
}
//打款成功
$CashAccount->able_cash = bcsub($CashAccount->able_cash, $CashApply->apply_cash, 2);//账户余额
$CashAccount->frozen_cash = bcsub($CashAccount->frozen_cash, $CashApply->apply_cash, 2);//申请提现冻结的金额
$CashAccount->withdrawn_cash = bcadd($CashAccount->withdrawn_cash, $CashApply->apply_cash, 2);//已提现金额
$CashAccount->charge_cash = bcadd($CashAccount->charge_cash, $CashApply->charge_cash, 2);//手续费
$CashAccount->saveOrFail();
$CashApply->dakuan_status = 1;
$CashApply->dakuan_time = date('Y-m-d H:i:s', time());
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '超级管理员';
$log->content = '打款成功:超级管理员:' . $user->uid . '打款操作:订单号:' . $post['order_no'] . ',打款金额:' . $post['apply_cash'] . '元,开户人姓名:' . $post['bank_user_name'] . ',银行卡号:' . $post['bank_card'] . ',银行名称:' . $post['bank_name'] . ',银行账户类型:' . $post['bank_account_type'];
$log->mold = 3;//财务操作
$log->saveOrFail();
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
$t->commit();
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 分账资金流水
* @doc-param string type 1增2减 / optional
* @doc-param string content 内容 / optional
* @doc-return mixed @List{id,order_id-int-订单id,user_id-int-业务员id或仓库id其他为0,user_type-int-用户类型 1诊所 2平台,type-int-1增2减,amount-float-金额,content-string-内容,created_at-string-流水时间} 快递公司
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionDivideFundWater()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
$query = LedgerLog::find()->orderBy(['id' => SORT_DESC]);
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$query->andWhere(['user_type' => 1]);
}
if ($user->role == UserRoleEnum::SUPER_ADMIN) {
$query->andWhere(['user_type' => [1, 2]]);
}
if (!empty($get['type'])) {
$query->andWhere(['type' => $get['type']]);
}
if (!empty($get['content'])) {
$query->andWhere(['like', 'content', $get['content']]);
}
$this->field = [
LedgerLog::class => [
'id', 'order_id', 'user_id', 'username' => function ($m) {
return Admin::find()->select(['username'])->where(['uid' => $m->user_id])->column();
}, 'user_type', 'type', 'amount', 'content',
'created_at' => function ($m) {
return date('Y-m-d H:i:s', $m->created_at);
}
]
];
return $this->create($query, $get);
}
/**
* @doc-name 首页数据
* @doc-return mixed @List{id,user_id-int-用户ID,total_cash-float-累计收益,able_cash-int-账户余额,frozen_cash-int-申请提现冻结的金额,withdrawn_cash-int-已提现金额,wait_cash-float-待结算收益,charge_cash-float-手续费,user_type-int-用户类型 1诊所 2平台,last_apply_time-string-最近提现申请时间,account-string-账户} 首页数据
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionHomeData()
{
$get = \Yii::$app->request->get();
$QUERY = CashAccount::find();
$this->field = [
CashAccount::class => [
'id', 'user_id', 'total_cash', 'able_cash', 'frozen_cash', 'withdrawn_cash', 'wait_cash', 'charge_cash',
'account' => function ($m) {
if ($m->user_id == 0) {
return Admin::find()->where(['role' => UserRoleEnum::SUPER_ADMIN])->one();
} else {
return Store::find()->where(['id' => $m->user_id])->one();
}
},
'user_type',
'last_apply_time'
]
];
return $this->create($QUERY, $get);
}
/**
* @doc-name 平台的提现账户
* @doc-return string user_id 用户
* @doc-return string total_cash 累计收益
* @doc-return string able_cash 账户余额
* @doc-return string frozen_cash 申请提现冻结的金额
* @doc-return string withdrawn_cash 待结算收益
* @doc-return string wait_cash 已提现金额
* @doc-return string charge_cash 手续费
* @doc-return string user_type 用户类型 1诊所 2平台
* @doc-return string last_apply_time 最近提现申请时间
*/
public function actionPlatformAccount()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
$CashAccount = CashAccount::find()->where(['user_id' => 0, 'user_type' => 2])->one();
if (!$CashAccount) throw new \yii\db\Exception('账户不存在');
$price=Ledger::find()->where(['status'=>0,'user_type'=>2,'user_id'=>0])->sum('money');
$CashAccount->total_cash=bcadd(bcadd($CashAccount->able_cash,$CashAccount->withdrawn_cash,2),$CashAccount->charge_cash,2);
$CashAccount->wait_cash=$price;
$CashAccount->saveOrFail();
return $CashAccount;
}
/**
* @doc-name 诊所提现账户
* @doc-param int store_id 诊所ID
* @doc-return string user_id 用户
* @doc-return string total_cash 累计收益
* @doc-return string able_cash 账户余额
* @doc-return string frozen_cash 申请提现冻结的金额
* @doc-return string withdrawn_cash 待结算收益
* @doc-return string wait_cash 已提现金额
* @doc-return string charge_cash 手续费
* @doc-return string user_type 用户类型 1诊所2平台
* @doc-return string last_apply_time 最近提现申请时间
*/
public function actionStoreAccount()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['store_id', 'required'],
]);
$store = Store::find()->where(['id' => $get['store_id']])->one();
if (!$store) throw new \yii\db\Exception('诊所不存在');
$CashAccount = CashAccount::find()->where(['user_id' => $get['store_id'], 'user_type' => 1])->one();
if (!$CashAccount) throw new \yii\db\Exception('账户不存在');
$price=Ledger::find()->where(['status'=>0,'user_type'=>1,'user_id'=>$CashAccount->user_id])->sum('money');
$CashAccount->total_cash=bcadd(bcadd($CashAccount->able_cash,$CashAccount->withdrawn_cash,2),$CashAccount->charge_cash,2);
$CashAccount->wait_cash=$price??0;
$CashAccount->saveOrFail();
return $CashAccount;
}
/**
* @doc-name 分账--审核管理列表
* @doc-param int status 1待审核2审核通过3审核拒绝
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,apply_cash-float-申请提现金额,true_cash-float-实际到账金额,charge_cash-string-手续费,check_id-string-关联admin表 审核人ID,check_status-string-审核状态0待审核1审核中2已通过3已拒绝,check_result-string-审核结果/拒绝原因,check_time-string-审核时间,apply_time-string-申请时间,dakuan_status-string-打款状态-1失败0未知1成功,dakuan_time-string-打款时间,payee-string-收款人} 审核管理列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionCheckManage()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['status', 'required']
]);
$query = CashApply::find()->orderBy(['id' => SORT_DESC]);
switch ($get['status']) {
case 1:
$query->andWhere(['check_status' => [0, 1]]);
break;
case 2:
$query->andWhere(['check_status' => 2]);
break;
case 3:
$query->andWhere(['check_status' => 3]);
break;
default:
throw new \yii\db\Exception('参数错误');
}
if(!empty($get['start_time']) && !empty($get['end_time'])){
$start_time=strtotime($get['start_time'].' '.'00:00:00');
$end_time=strtotime($get['end_time'].' '.'23:59:59');
$query->andWhere(['between','created_at',$start_time,$end_time]);
}
if(!empty($get['name'])){
if($get['name'] == '平台'){
$query->andWhere(['user_id' => 0]);
}else{
$store = Store::find()->where(['name'=>$get['name']])->asArray()->one();
if($store){
$query->andWhere(['user_id' => intval($store['id'])]);
}else{
$query->andWhere(['user_id' => -1]);
}
}
}
$this->field = [
CashApply::class => [
'id', 'user_id', 'user_type', 'order_no', 'apply_cash', 'true_cash', 'charge_cash', 'check_id', 'check_status', 'check_result', 'check_time', 'apply_time', 'dakuan_status', 'dakuan_time', 'payee' => function ($m) {
if ($m->user_id == 0) {
return Admin::find()->where(['role' => UserRoleEnum::SUPER_ADMIN])->one();
} else {
return Store::find()->where(['id' => $m->user_id])->one();
}
}
]
];
return $this->create($query, $get);
}
/**
* @doc-name 导出提现审核
*/
public function actionExportWithDraw()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params = \Yii::$app->request->get();
$parameter['header'] = ['订单号', '平台/诊所', '收款人', '申请提现金额', '审核状态', '时间'];
$parameter['data'] = CashApply::inventory($params,\Yii::$app->user->identity->store_id);
ExportService::ExportByCors($parameter);
}
/**
* @doc-name 分账--财务数据
* @doc-param float total_cash 累计收益
* @doc-param float able_cash 账户余额
* @doc-param float withdrawn_cash 已体现
* @doc-param float charge_cash 手续费
* @doc-param float wait_cash 待结算
*/
public function actionFenzhangFinance()
{
//总收入
$total_price=CashAccount::find()->sum('total_cash');
//账户余额
$account_price=CashAccount::find()->sum('able_cash');
$withdrawn_cash=CashAccount::find()->sum('withdrawn_cash');
$charge_cash=CashAccount::find()->sum('charge_cash');
// $wait_cash=CashAccount::find()->sum('wait_cash');
$wait_cash=Ledger::find()->where(['status'=>0])->sum('money');
return [
'total_cash'=>$total_price,
'able_cash'=>$account_price,
'withdrawn_cash'=>$withdrawn_cash,
'charge_cash'=>$charge_cash,
'wait_cash'=>$wait_cash??0,
];
}
/**
* @doc-name 分账--财务数据的明细
*/
public function actionFenzhangFinanceDetail()
{
$CashApply=CashApply::find()->orderBy(['id'=>SORT_DESC])->all();
$Ledger=Ledger::find()->orderBy(['id'=>SORT_DESC])->with(['productOrder'])->asArray()->all();
return [
'CashApply'=>$CashApply,
'Ledger'=>$Ledger,
];
}
/**
* @doc-name 平台/诊所提现管理
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,apply_cash-float-申请提现金额,true_cash-float-实际到账金额,charge_cash-string-手续费,check_id-string-关联admin表 审核人ID,check_status-string-审核状态0待审核1审核中2已通过3已拒绝,check_result-string-审核结果/拒绝原因,check_time-string-审核时间,apply_time-string-申请时间,dakuan_status-string-打款状态-1失败0未知1成功,dakuan_time-string-打款时间,payee-string-收款人} 平台/诊所提现管理
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionWithdrawnManage()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
$order_no=$get['order_no'];
$query = CashApply::find()->alias('c')->orderBy(['id' => SORT_DESC]);
if (!empty($order_no)){
$query->andWhere(['c.order_no'=>$order_no]);
}
if (!empty($get['start_time']) && !empty($get['end_time'])){
$query->andWhere(['between','c.apply_time',$get['start_time'],$get['end_time']]);
}
if ($user->role==UserRoleEnum::SUPER_ADMIN){//平台
$query->andWhere(['c.user_id'=>0,'c.user_type'=>2]);
}else{
$query->andWhere(['c.user_id'=>$user->store_id,'c.user_type'=>1]);
}
$this->field = [
CashApply::class => [
'id', 'user_id', 'user_type', 'order_no', 'apply_cash', 'true_cash', 'charge_cash', 'check_id', 'check_status', 'check_result', 'check_time', 'apply_time', 'dakuan_status', 'dakuan_time', 'payee' => function ($m) {
if ($m->user_id == 0) {
return Admin::find()->where(['role' => UserRoleEnum::SUPER_ADMIN])->one();
} else {
return Store::find()->where(['id' => $m->user_id])->one();
}
},
'type' => function ($c) {//结算类别
return '提现记录';
},
'status' => function ($ca) {
if ($ca->check_status == 1 ) {
return '审核中';
} elseif($ca->check_status == 2) {
return '审核通过,提现成功';
}elseif($ca->check_status == 3) {
return '申请已拒绝,手续费未扣';
}elseif($ca->check_status == 4 ) {
return '审核通过,提现失败';
}else{
return '未知';
}
},
'tixian_person'=>function($m){
if ($m->user_type==1)return '诊所';
if ($m->user_type==2)return '平台';
},
],
];
return $this->create($query, $get);
}
/**
* @doc-name 平台/诊所结算列表
* @doc-param string order_no 产品订单号
* @doc-param string register_no 挂号订单号
* @doc-param string start_time 开始时间
* @doc-param string end_time 结束时间
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,order_id-int-订单id,su_id-int-医生id,drugstore_id-int-仓库id,drug_id-string-药品id,status-string-结算状态 0待结算 1已结算 2已取消,money-string-分佣金额,time-string-时间} 平台/诊所是否结算管理
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionJiesuanList()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
$order_no=$get['order_no'];
$register_no=$get['register_no'];
$start_time=strtotime($get['start_time']);
$end_time=strtotime($get['end_time']);
$query = Ledger::find()->alias('l')->where(['l.status'=>[0,1]])->orderBy(['l.id' => SORT_DESC]);
if (!empty($order_no)){
$query->joinWith(['productOrder'=>function($p)use($order_no){
$p->where(['order_no'=>$order_no]);
}]);
}
if (!empty($register_no)){
$query->joinWith(['register'=>function($p)use($register_no){
$p->where(['order_no'=>$register_no]);
}]);
}
if (!empty($start_time) && !empty($end_time)){
if ($start_time==$end_time){//筛选某一天
$time=FuncHelper::getDayBE($get['start_time']);
$end_time=$time[1];
}
$query->andWhere(['between','l.created_at',$start_time,$end_time]);
}
if ($user->role==UserRoleEnum::SUPER_ADMIN){//平台
$query->andWhere(['l.user_id'=>0,'l.user_type'=>2])->groupBy('l.order_id,l.order_type');
}else{
$query->andWhere(['l.user_id'=>$user->store_id,'l.user_type'=>1])->groupBy('l.order_id,l.order_type');
}
$this->field = [
Ledger::class => [
'id', 'user_id','order_id', 'user_type','su_id', 'drugstore_id', 'drug_id', 'status', 'money'=> function ($m) {
return $this->actionTotal($m->order_id,$m->user_type,$m->order_type);
},
'order_no'=> function ($order) {
if ($order->order_type == 1) {
return ProductOrder::find()->select(['order_no'])->where(['id' => $order->order_id])->column();
}
if ($order->order_type == 2) {
return Register::find()->select(['order_no'])->where(['id' => $order->order_id])->column();
}
},
'type'=>function($l){
if ($l->order_type==1){
return '产品订单';
}else{
return '挂号订单';
}
},
'fee_type'=>function($f){
if ($f->fee_type==1){
return '药品费用';
}elseif($f->fee_type==2){
return '挂号费用';
}elseif($f->fee_type==3){
return '快递费用';
}elseif($f->fee_type==4){
return '代煎费用';
}else{
return '其他';
}
},
'price_from'=>'productOrder.user.nickname',
'time'=>function($le){
return date('Y-m-d H:i:s',$le->created_at);
}
],
];
return $this->create($query, $get);
}
public function actionTotal($order_id='',$user_type=1,$order_type='')
{
$money = Ledger::find()->alias('l')->where(['l.order_id' => $order_id, 'l.status' => [0, 1]])->andWhere(['l.user_type'=>$user_type,'l.order_type'=>$order_type])->sum('money');
return $money ?? 0;
}
}

View File

@@ -0,0 +1,439 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\Admin;
use common\enums\UserRoleEnum;
use common\forms\ProductRefundForm;
use common\helpers\FuncHelper;
use common\models\CashApply;
use common\models\FundWater;
use common\models\Ledger;
use common\models\ProductOrder;
use common\models\ProductOrderRefund;
use common\models\Register;
use common\models\Store;
use common\models\SystemNotice;
use common\services\ExportService;
use yii\db\Exception;
use yii\web\Response;
class FinanceController extends BaseAdminController
{
/**
* @doc-name 退款申请记录
* @doc-param string refund_no 退款单号 / optional
* @doc-return @List{id,order_id-int-订单id,user_id-int-用户ID,reason-string-原因,remark-string-备注,refund_images-string-退款图片,refund_type-int-0仅退款 1退货退款,refund_no-string-退款单号,fail_reason-string-失败原因,refund_price-float-金额,is_refund-int-0待退款 1已退款 -1退款失败,refund_time-string-退款时间,status-int-0退款申请中 1申请通过 2撤销申请3拒绝退款} 退款申请记录
*/
public function actionRefundApply()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$query = ProductOrderRefund::find()->alias('po')->where([
'po.is_deleted' => 0
])->orderBy(['po.id' => SORT_DESC]);
// $query->joinWith(['order' => function ($model) use ($user) {
// $model->andWhere(['drugstore_id' => $user->drugstore]);
// }]);
}
if ($user->role == UserRoleEnum::SUPER_ADMIN) {
$query = ProductOrderRefund::find()->alias('po')->where([
'is_deleted' => 0
])->orderBy(['po.id' => SORT_DESC]);
}
if (!empty($get['refund_no'])) {
$query->andWhere(['refund_no' => $get['refund_no']]);
}
$this->field = [
ProductOrderRefund::class => [
'id', 'order_id', 'user_id', 'reason', 'remark', 'refund_images', 'refund_type', 'refund_no', 'refund_price', 'is_refund', 'refund_time',
'status', 'created_at' => function ($m) {
return date('Y-m-d H:i:s', $m->created_at);
}
]
];
return $this->create($query, $get);
}
/**
* @doc-name 同意退款操作
* @doc-param int id 退款申请记录ID
*/
public function actionRefundAgree()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id', 'required'],
]);
$user = \Yii::$app->user->identity;
$t = \Yii::$app->db->beginTransaction();
try {
$ProductOrderRefund = ProductOrderRefund::find()->where([
'id' => $post['id'],
'is_deleted' => 0,
])->with(['order'])->one();
if (!$ProductOrderRefund) {
throw new Exception('退款申请记录不存在');
}
$ProductOrder = ProductOrder::find()->where(['id' => $ProductOrderRefund->order_id])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
$ProductOrder->refund_status = 3;//已退款
$ProductOrder->saveOrFail();
$ProductOrderRefund->is_refund = 1;
$ProductOrderRefund->status = 1;
$ProductOrderRefund->refund_time = date('Y-m-d H:i:s', time());
$ProductOrderRefund->saveOrFail();
$form = new ProductRefundForm();
$form->refundMoney($ProductOrderRefund);
$t->commit();
return ['success'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 拒绝退款操作
* @doc-param int id 退款申请记录ID
* @doc-param string check_result 拒绝原因
*/
public function actionRefundRefuse()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['id_id', 'check_result'], 'required'],
]);
$id = $post['id_id'];
$user = \Yii::$app->user->identity;
if ($user->role == UserRoleEnum::SUPER_ADMIN) {//超管
$ProductOrderRefund = ProductOrderRefund::find()->where([
'id' => $id,
'is_deleted' => 0,
])->with(['order'])->one();
}
if ($user->role == UserRoleEnum::STORE_ADMIN) {//门店管理员
$ProductOrderRefund = ProductOrderRefund::find()->alias('po')->where([
'po.id' => $id,
'po.is_deleted' => 0,
])->with(['order'])->one();
}
if (!$ProductOrderRefund) throw new Exception('退款申请记录不存在');
$t = \Yii::$app->db->beginTransaction();
try {
$ProductOrder = ProductOrder::find()->where(['id' => $ProductOrderRefund->order_id])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
if ($ProductOrder->is_send == 1) {
$ProductOrder->status = 6;//确认收货
} else {
$ProductOrder->status = 1;//待发货
}
$ProductOrder->refund_status = 4;//拒绝退款
$ProductOrder->saveOrFail();
$ProductOrderRefund->is_refund = 0;
$ProductOrderRefund->status = 3;//拒绝退款
$ProductOrderRefund->check_result = $post['check_result'];//审核结果
$ProductOrderRefund->refund_time = date('Y-m-d H:i:s', time());
$ProductOrderRefund->saveOrFail();
//拒绝退款通知
$systemNotice = new SystemNotice();
$systemNotice->store_id = $ProductOrder->store_id;
$systemNotice->content = '工作人员已拒绝退款,原因:' . $post['check_result'];
$systemNotice->base_type = 7;
$systemNotice->scene_type = 1;
$systemNotice->user_id = $ProductOrderRefund->user_id;
$systemNotice->notice_at = date('Y-m-d h:i:s', time());
$systemNotice->saveOrFail();
$t->commit();
return ['success'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 资金流水记录
* @doc-param string start_time 时间 / optional
* @doc-param string end_time 时间 / optional
* @doc-param string doctor 医生 / optional
* @doc-param string store 诊所 / optional
* @doc-param string order_no 订单号 / optional
* @doc-param string refund_no 退款单号 / optional
* @doc-return @List{id,order_id-int-订单id,order_type-int-订单类型1产品订单2问诊订单,user_id-int-用户ID,type-string-类型enter入账refund出账,price-float-金额,order_no-string-订单号,refund_no-string-退款单号,created_at-string-收入或支出时间,pay_type-int-支付类型1为微信} 资金流水记录
*/
public function actionFundWater()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
$start_time=strtotime($get['start_time']);
$end_time=strtotime($get['end_time']);
$doctor = $get['doctor'];
$store = $get['store'];
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$query = FundWater::find()->where([
'f.store_id' => $user->store_id
])->alias('f')->orderBy(['id' => SORT_DESC]);
}
if ($user->role == UserRoleEnum::SUPER_ADMIN) {
$query = FundWater::find()->alias('f')->orderBy(['id' => SORT_DESC]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time==$end_time){//筛选当天
$time=FuncHelper::getDayBE($get['start_time']);
$end_time=$time[1];
}
$query->andWhere(['between', 'f.created_at', $start_time,$end_time]);
}
if (!empty($doctor)) {
$query->joinWith(['doctor' => function ($d) use ($doctor) {
$d->alias('d');
$d->andWhere(['like', 'd.name', $doctor]);
}]);
}
if (!empty($store)) {
$query->joinWith(['store' => function ($s) use ($store) {
$s->alias('s');
$s->andWhere(['like', 's.name', $store]);
}]);
}
if (!empty($get['order_no'])) {
$query->andWhere(['f.order_no' => $get['order_no']]);
}
if (!empty($get['refund_no'])) {
$query->andWhere(['f.refund_no' => $get['refund_no']]);
}
$this->field = [
FundWater::class => [
'id', 'order_id', 'order_type', 'user_id', 'type', 'price', 'order_no', 'refund_no', 'pay_type', 'store_id',
'created_at' => function ($m) {
return date('Y-m-d H:i:s', $m->created_at);
},
'store' => 'store.name', 'service_user_id', 'doctor' => 'doctor.name',
'user' => 'user.nickname'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 导出资金流水
*/
public function actionExportFundWater()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params = \Yii::$app->request->post();
$parameter['header'] = ['订单类型', '医生', '用户', '价格', '诊所', '时间'];
$parameter['data'] = FundWater::inventory($params,\Yii::$app->user->identity->store_id);
ExportService::ExportByCors($parameter);
}
/**
* @doc-name 财务数据--结算记录(包括平台和门诊的)
* @doc-param string order_no 产品订单号
* @doc-param string register_no 挂号订单号
* @doc-param string start_time 开始时间
* @doc-param string end_time 结束时间
* @doc-param string order_no 订单
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,order_id-int-订单id,su_id-int-医生id,drugstore_id-int-仓库id,drug_id-string-药品id,status-string-结算状态 0待结算 1已结算 2已取消,money-string-分佣金额,time-string-时间} 平台/诊所是否结算管理
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionJiesuanList()
{
$get = \Yii::$app->request->get();
$order_no = $get['order_no'];
$register_no = $get['register_no'];
$start_time=strtotime($get['start_time'].' '.'00:00:00');
$end_time=strtotime($get['end_time'].' '.'23:59:59');
$query = Ledger::find()->alias('l')->where(['l.status' => [0, 1]])->orderBy(['id' => SORT_DESC])->groupBy('l.order_id,l.order_type');
if (!empty($order_no)) {
$query->joinWith(['productOrder' => function ($p) use ($order_no) {
$p->where(['order_no' => $order_no]);
}]);
}
if (!empty($register_no)){
$query->joinWith(['register'=>function($p)use($register_no){
$p->where(['order_no'=>$register_no]);
}]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time==$end_time){//筛选当天
$time=FuncHelper::getDayBE($get['start_time']);
$end_time=$time[1];
}
$query->andWhere(['between', 'l.created_at', $start_time, $end_time]);
}
$this->field = [
Ledger::class => [
'id', 'user_id', 'user_type', 'su_id', 'drugstore_id', 'drug_id', 'status', 'money' => function ($m) {
return $this->actionTotal($m->order_id);
},
'order_id',
'order_no' => function ($order) {
if ($order->order_type == 1) {
return ProductOrder::find()->select(['order_no'])->where(['id' => $order->order_id])->column();
}
if ($order->order_type == 2) {
return Register::find()->select(['order_no'])->where(['id' => $order->order_id])->column();
}
},
'type' => function ($l) {
if ($l->order_type == 1) {
return '产品订单';
} else {
return '挂号订单';
}
},
'fee_type' => function ($f) {
if ($f->fee_type == 1) {
return '药品费用';
} elseif ($f->fee_type == 2) {
return '挂号费用';
} elseif ($f->fee_type == 3) {
return '快递费用';
} elseif ($f->fee_type == 4) {
return '代煎费用';
} else {
return '其他';
}
},
'price_from' => 'productOrder.user.nickname',
'time' => function ($le) {
return date('Y-m-d H:i:s', $le->created_at);
}
],
];
return $this->create($query, $get);
}
public function actionTotal($order_id)
{
$money = Ledger::find()->alias('l')->where(['l.order_id' => $order_id, 'l.status' => [0, 1]])->sum('money');
return $money ?? 0;
}
/**
* @doc-name 财务数据--提现记录
* @doc-param string order_no 订单号
* @doc-param string start_time 开始时间
* @doc-param string end_time 结束时间
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,apply_cash-float-申请提现金额,true_cash-float-实际到账金额,charge_cash-string-手续费,check_id-string-关联admin表 审核人ID,check_status-string-审核状态0待审核1审核中2已通过3已拒绝,check_result-string-审核结果/拒绝原因,check_time-string-审核时间,apply_time-string-申请时间,dakuan_status-string-打款状态-1失败0未知1成功,dakuan_time-string-打款时间,payee-string-收款人} 平台/诊所提现管理
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionWithdrawnManage()
{
$get = \Yii::$app->request->get();
$order_no = $get['order_no'];
$start_time=strtotime($get['start_time'].' '.'00:00:00');
$end_time=strtotime($get['end_time'].' '.'23:59:59');
$query = CashApply::find()->alias('c')->orderBy(['id' => SORT_DESC]);
if (!empty($order_no)) {
$query->where(['c.order_no' => $order_no]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time==$end_time){//筛选当天
$time=FuncHelper::getDayBE($get['start_time']);
$start_time=$get['start_time'];
$end_time=date('Y-m-d H:i:s',$time);
}else{
$start_time=$get['start_time'];
$end_time=$get['end_time'];
}
$query->andWhere(['between', 'c.apply_time',$start_time,$end_time]);
}
$this->field = [
CashApply::class => [
'id', 'user_id', 'user_type', 'order_no', 'apply_cash', 'true_cash', 'charge_cash', 'check_id', 'check_status', 'check_result', 'check_time', 'apply_time', 'dakuan_status', 'dakuan_time', 'payee' => function ($m) {
if ($m->user_id == 0) {
return Admin::find()->where(['role' => UserRoleEnum::SUPER_ADMIN])->one();
} else {
return Store::find()->where(['id' => $m->user_id])->one();
}
},
'type' => function ($c) {//结算类别
return '提现记录';
},
'status' => function ($ca) {
if ($ca->check_status == 1) {
return '审核中';
} elseif ($ca->check_status == 2) {
return '审核通过,提现成功';
} elseif ($ca->check_status == 3) {
return '申请已拒绝,手续费未扣';
} elseif ($ca->check_status == 4) {
return '审核通过,提现失败';
} else {
return '未知';
}
},
'tixian_person' => function ($m) {
if ($m->user_type == 1) return '诊所';
if ($m->user_type == 2) return '平台';
},
],
];
return $this->create($query, $get);
}
/**
* @doc-name 导出提现、结算记录
*/
public function actionExportSettlement()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params = \Yii::$app->request->get();
if($params['type'] == 1){
$parameter['header'] = ['单号','提现方', '提现金额', '到账金额','手续费', '状态', '时间'];
$parameter['data'] = CashApply::inventory1($params);
}else{
$parameter['header'] = ['单号','订单类型', '用户', '金额', '状态', '时间'];
$parameter['data'] = Ledger::inventory($params,\Yii::$app->user->identity->store_id);
}
ExportService::ExportByCors($parameter);
}
}

View File

@@ -0,0 +1,174 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\NavForm;
use common\enums\UserRoleEnum;
use common\models\Nav;
use yii\db\Exception;
class NavController extends BaseAdminController
{
/**
* @doc-name 轮播图类型
*/
public function actionTypeList()
{
return [
['key' => 0, 'value' => '轮播图'],
];
}
/**
* @doc-name 轮播图列表
* @doc-param int is_home 是否首页0否1是 / optional
* @doc-param int type 类型1活动2专题 / optional
* @doc-return mixed @nav{id,pic,external_link-string-外部链接,is_home-int-是否首页0否1是,home_time-string-首页时间,type-int-类型1活动2专题} 轮播图
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['store_id', 'required']
]);
$admin = \Yii::$app->user->identity;
$query = Nav::find()->where([
'store_id' => $get['store_id'],
'is_delete' => 0,
])->orderBy(['id' => SORT_DESC]);
if (!empty($get['is_home'])) {
$query->andWhere([
'is_home' => $get['is_home']
]);
}
if (!empty($get['type'])) {
$query->andWhere([
'type' => $get['type']
]);
}
$this->field = [
Nav::class => [
'id', 'pic', 'external_link', 'is_home', 'home_time', 'type', 'sort', 'store_id','link_type'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 新增轮播图
* @doc-param int store_id 门店ID / optional
* @doc-param int sort 排序 / optional
* @doc-param string pic 轮播图
* @doc-param int link_type 1内部2外部 / optional
* @doc-param string external_link 外部链接 / optional
* @doc-param int is_home 是否首页0否1是 / optional
* @doc-param int type 类型1轮播图 / optional
*/
public function actionSaveNav()
{
$post = \Yii::$app->request->post();
$NavForm = new NavForm();
$NavForm->attributes = $post;
return $NavForm->save();
}
/**
* @doc-name 修改轮播图
* @doc-param int id 轮播图id
* @doc-param string store_id 门店ID
* @doc-param string sort 排序
* @doc-param string pic 轮播图
* @doc-param string external_link
* @doc-param int is_home 是否首页0否1是
* @doc-param int type 类型1活动2专题
*/
public function actionEditNav()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id', 'required']
]);
$NavForm = new NavForm();
$NavForm->attributes = $post;
return $NavForm->update();
}
/**
* @doc-name 删除轮播图
* @doc-param int id 轮播图id
*/
public function actionDel()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['id', 'required']
]);
$NavForm = new NavForm();
$NavForm->attributes = $get;
return $NavForm->del();
}
/**
* @doc-name 轮播图详情
* @doc-param int id 轮播图id
* @doc-return mixed @nav{*} 轮播图
*/
public function actionInfo()
{
$get =\Yii::$app->request->get();
$this->requestValidate($get, [
['id', 'required']
]);
$nav = Nav::find()->where([
'id' => $get['id'],
'is_delete' => 0
])->one();
if (!$nav) throw new Exception('轮播图不存在');
return $nav;
}
/**
* @doc-name 是否推送的首页
* @doc-param int id 轮播图id
* @doc-param int status 状态0否1是
*/
public function actionIsHome()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['id', 'status'], 'required']
]);
$nav = Nav::find()->where([
'id' => $post['id'],
'is_delete' => 0
])->one();
if (!$nav) throw new Exception('轮播图不存在');
switch ($post['status']) {
case 0:
$nav->is_home = 0;
$nav->home_time = date('Y-m-d H:i:s', time());
$nav->saveOrFail();
return ['已取消'];
break;
case 1:
$nav->is_home = 1;
$nav->home_time = date('Y-m-d H:i:s', time());
$nav->saveOrFail();
return ['已推送'];
break;
default:
throw new Exception('参数错误');
}
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\models\SystemNotice;
/**
* @doc-module 公告
*/
class NoticeController extends BaseAdminController
{
/**
* @doc-name 公告列表
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$query = SystemNotice::find()->where(['base_type'=>99]);
$this->field = [
SystemNotice::class => [
'id', 'scene_type', 'content','base_type'
]
];
return $this->create($query,$get);
}
/**
* @doc-name 发送公告
* @doc-param string content 发送公告
* @doc-param int type 3全部4所有医生5所有用户 发送公告
*/
public function actionAddNotice()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
[['type', 'content'], 'required']
]);
$SystemNotice = new SystemNotice();
$SystemNotice->content = $get['content'];
$SystemNotice->scene_type = $get['type'];
$SystemNotice->base_type = 99;
$SystemNotice->saveOrFail();
}
}

View File

@@ -0,0 +1,511 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\events\ProductOrderEvent;
use common\forms\ProductCancelForm;
use common\forms\ProductRefundForm;
use common\helpers\FuncHelper;
use common\jobs\ProductOrderSendJob;
use common\models\DrugStore;
use common\models\Prescription;
use common\models\ProductOrder;
use common\models\ProductOrderItems;
use common\models\ProductOrderRefund;
use common\models\Store;
use common\models\SystemConfig;
use common\models\UserPatient;
use common\services\ExportService;
use common\services\ExpressService;
use yii\db\Exception;
use yii\helpers\Json;
use yii\web\Response;
class OrderController extends BaseAdminController
{
/**
* @doc-name 产品订单列表
* @doc-param string order_no 订单编号 / optional
* @doc-param string good_name 商品名称 / optional
* @doc-param string accept_name 收件人姓名 / optional
* @doc-param string accept_tel 收件人电话 / optional
* @doc-param string doctor 医生搜索 / optional
* @doc-param string store 门店 / optional
* @doc-param int status 产品订单状态0未支付1待发货2待收货3待评价4已退款5退款中6已收货7确认收货9已取消 / optional
* @doc-param int after_status 售后状态1申请退款2同意退款3已退款9取消退款 / optional
* @doc-param string start_time 开始时间 / optional
* @doc-param string end_time 结束时间 / optional
* @doc-return mixed @List{id,store_id-int-门店ID,p_id,user_id-int-用户id,up_id-int-就诊人id,status-int-产品订单状态0未支付1待发货2待收货3待评价4已退款5退款中6已收货7确认收货,cancel_status-int-取消状态1已取消,cancel_time-string-取消时间,cancel_remark-string-取消备注(未支付超时取消,主动取消,拒绝取消),refund_status-int-退款状态1退款中2已退款,refund_type-int-退款类型0仅退款1退货退款,refund_time-string-退款时间,drugstore-string-发货仓库,total_pay_price-float-总价,pay_time-string-支付时间,order_no-string-订单编号,is_has-int-是否有处方,doctor-string-开方医生,good-int-商品信息,trans_expenses-float-运费(默认包邮),free_ship-int-是否包邮,remark-string-留言备注,express_name-string-收货人,express_mobile-string-收货电话,express_region-string-收货省市区,@Prescription{id-int-id,platform_prescription_no-string-平台处方单号,prescription_no-string-处方单号,order_id-int-订单id,status-int-状态 0待审核,1已通过,2未通过,content-string-处方快照,prescription_type-int-1中药处方2西药处方3颗粒药处方,category-int-类别1自费2医保,doctor_order-string-医嘱,clinical_diagnose-string-临床诊断,医生签名-string-医生签名,type-int-类型1普通方2常用方,order_type-int-订单类型1处方2医技,total_pay_price-float-支付金额},decoct_price-float-代煎费用,is_decoct-int-1需要代煎} 商品订单列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionProductList()
{
$get = \Yii::$app->request->get();
$good_name = $get['good_name'];
$store = $get['store'];
$doctor = $get['doctor'];
$type=$get['type'];
$admin = \Yii::$app->user->identity;
$start_time=strtotime($get['start_time'].' '.'00:00:00');
$end_time=strtotime($get['end_time'].' '.'23:59:59');
if ($admin->role == UserRoleEnum::STORE_ADMIN) {//门店
$query = ProductOrder::find()->alias('pd')->where(['pd.store_id' => $admin->store_id])->orderBy(['pd.id' => SORT_DESC]);
} elseif ($admin->role == UserRoleEnum::PROVINCE_DAI){//省代
$store_id = Store::find()->select(['id'])->where(['province_id' => $admin->province_id])->column();
$query = ProductOrder::find()->alias('pd')->where(['in','pd.store_id',$store_id])->orderBy(['pd.id' => SORT_DESC]);
} elseif ($admin->role == UserRoleEnum::CITY_DAI){//市代
$store_id = Store::find()->select(['id'])->where(['city_id' => $admin->city_id])->column();
$query = ProductOrder::find()->alias('pd')->where(['in','pd.store_id',$store_id])->orderBy(['pd.id' => SORT_DESC]);
} elseif ($admin->role == UserRoleEnum::SUPPLY){//业务员
$store_id = Store::find()->select(['id'])->where(['code' => $admin->code])->column();
$query = ProductOrder::find()->alias('pd')->where(['in','pd.store_id',$store_id])->orderBy(['pd.id' => SORT_DESC]);
}else {//总后台
$query = ProductOrder::find()->alias('pd')->orderBy(['pd.id' => SORT_DESC]);
}
if (!empty($get['order_no'])) {//订单编号
$query->andWhere(['pd.order_no' => $get['order_no']]);
}
$query->joinWith(['prescription' => function ($p) use ($good_name) {
$p->alias('p');
if (!empty($good_name)) {//商品名称
$p->where(['like', 'p.content', $good_name]);
}
}]);
if (!empty($get['accept_name'])) {//收件人姓名
$query->where(['like', 'pd.express_name', $get['accept_name']]);
}
if (!empty($post['accept_tel'])) {//收件人电话
$query->where(['like', 'pd.express_mobile', $get['accept_tel']]);
}
$query->joinWith(['doctor' => function ($doc) use ($doctor) {
$doc->alias('doc');
if (!empty($doctor)) {//医生搜索
$doc->andWhere(['like', 'doc.name', $doctor]);
}
}]);
if (isset($get['status']) && is_numeric($get['status'])) {//产品订单状态
if ($get['status'] == 3) {
$query->andWhere(['pd.status' => [3, 6, 7]]);
} else {
$query->andWhere(['pd.status' => $get['status']]);
}
}
if (!empty($store)) {//门店
$query->andWhere(['pd.store_id' => $store]);
}
if (!empty($get['after_status'])) {//售后状态
$query->andWhere(['pd.refund_status' => $get['after_status']]);
}
if (!empty($type)) {
$query->andWhere(['pd.prescription_type' => $type]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time==$end_time){//筛选某一天
$time=FuncHelper::getDayBE($get['start_time']);
$end_time=$time[1];
}
$query->andWhere(['between', 'pd.created_at', $start_time,$end_time]);
}
$this->field = [
ProductOrder::class => [
'id', 'store_id','prescription_type', 'user_id', 'up_id', 'p_id', 'status', 'cancel_status', 'order_type', 'order_no', 'total_pay_price', 'type', 'items_price','market_price', 'process_price', 'treatement_price','address_id', 'status', 'trans_expenses', 'free_ship',
'cancel_time' => function ($pd) {
if($pd->cancel_time){
return date('Y-m-d H:i:s', $pd->cancel_time);
}
}, 'cancel_remark', 'refund_status',
'refund_time' => function ($pd) {
if($pd->refund_time){
return date('Y-m-d H:i:s', $pd->refund_time);
}
},
'store' => function ($d) {
return Store::find()->select(['id','drugstore_id','erp_id','plate_id','name','shouzimu','contact','mobile','offical_seal','code','position'])->where([
'id' => $d->store_id
])->one();
},
'drugstore' => function ($d) {
$drugstore_id = Store::find()->select(['drugstore_id'])->where([
'id' => $d->store_id
])->column();
return DrugStore::find()->select(['name'])->where(['in', 'id', $drugstore_id])->all();
},
'pay_time' => function ($m) {
if($m->pay_time){
return date('Y-m-d H:i:s', $m->pay_time);
}
},
'is_has' => function ($i) {
return $i->p_id ? '有处方' : '无处方';
},
'doctor' => 'doctor.name',
// 'good' => function ($model) {
// return $this->actionProductOrderDetail($model->id);
// },
'prescription' => function ($p) {
if($p->p_id){
$prescription = Prescription::find()->where([
'id' => $p->p_id,
'is_deleted' => 0
])->with(['pharmacistInfo','doctorInfo.depart'])->asArray()->one();
$content = Json::decode($prescription['content']);
$repice = $content['repice'];
if($prescription['prescription_type'] == 2){ //西药
foreach($repice as $k => $v){
$repice[$k]['content'] = Json::decode($v['content']);
}
} else {
$repiceContent = Json::decode($repice[0]['content']);
// foreach($repiceContent as $k=>$v){
// $repiceContent[$k]['content'] = Json::decode($v['content']);
// }
$repice[0]['content'] = $repiceContent;
}
$content['repice'] = $repice;
$prescription['content'] = $content;
}
return $prescription;
},
'address' => function ($m) {
return json_decode($m->address);
},
'created_at' => function ($mo) {
return date('Y-m-d H:i:s', $mo->created_at);
},
'express_name'=>function($e){
return $this->actionReceiveInfo($e->id,1);
},
'express_mobile'=>function($e){
return $this->actionReceiveInfo($e->id,2);
},
'express_region'=>function($e){
return $this->actionReceiveInfo($e->id,3);
},
'express_address'=>function($e){
return $this->actionReceiveInfo($e->id,4);
},
'patient' => 'userPatient.name',
'user' => 'user.nickname',
'product_order_items' => function ($m) {
return $this->actionProductOrderItem($m->id);
},
'patient_sex' => 'userPatient.sex',
'patient_age' => 'userPatient.age',
'patient_mobile' => 'userPatient.mobile',
'category' => 'prescription.category',
'productOrderRefund_status' => 'productOrderRefund.status',
'productOrderRefund_id' => function($m){
return $this->actionProductOrderRefund($m->id);
},
'service_price'=>function($m){
return $this->actionDaijianFei($m->id);
},
'is_decoct','decoct_price','express_no_id',
'delivery_method',
]
];
return $this->create($query, $get);
}
/**
* @doc-name 收获信息
* @doc-author huangyuling
*/
public function actionReceiveInfo($id,$type){
$info=ProductOrder::find()->where(['id'=>$id])->asArray()->one();
switch ($type){
case 1:
if ($info['delivery_method']==0){
return $info['express_name'];
}else{
$user_patient=UserPatient::find()->where(['id'=>$info['up_id']])->asArray()->one();
if (!$user_patient){
throw new Exception('患者信息不存在');
} return $user_patient['name'];
}
break;
case 2:
if ($info['delivery_method']==0){
return $info['express_name'];
}else{
$user_patient=UserPatient::find()->where(['id'=>$info['up_id']])->asArray()->one();
if (!$user_patient){
throw new Exception('患者信息不存在');
}
return $user_patient['mobile'];
}
break;
case 3:
if ($info['delivery_method']==0){
return $info['express_region'];
}else{
$store=Store::find()->where(['id'=>$info['store_id']])->with(['province','city'])->asArray()->one();
if (!$store){
throw new Exception('门店信息不存在');
}
return $store['province']['name'].$store['city']['name'];
}
break;
case 4:
if ($info['delivery_method']==0){
return $info['express_address'];
}else{
$store=Store::find()->where(['id'=>$info['store_id']])->asArray()->one();
if (!$store){
throw new Exception('门店信息不存在');
}
return $store['position'];
}
break;
default:
throw new Exception('类型错误');
}
}
/**
* @doc-name 退款申请ID
* @doc-return int id id
*/
public function actionProductOrderRefund($id)
{
$ProductOrderRefund=ProductOrderRefund::find()->select(['id','reason'])->where(['order_id'=>$id])->orderBy(['id'=>SORT_DESC])->one();
return $ProductOrderRefund;
}
/**
* @doc-name 取消商品(或产品)订单
* @doc-param int order_id 商品(或产品)订单id
* @doc-param int user_id 用户id
*/
public function actionGoodCancel()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['order_id', 'user_id'], 'required']
]);
$form = new ProductCancelForm();
return $form->cancel($post);
}
/**
* @doc-name 商品订单退款
* @doc-param int order_id 商品(或产品)订单id
* @doc-param int user_id 用户id
* @doc-param string reason 退款原因
* @doc-param string refund_images 退款图片 / optional
*/
public function actionGoodRefund()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['order_id', 'user_id', 'reason'], 'required']
]);
$form = new ProductRefundForm();
return $form->refund($post);
}
/**
* @doc-name 发货
* @doc-param int order_id 商品(或产品)订单id
*/
public function actionSendOperate()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['order_id', 'required']
]);
$user = \Yii::$app->user->identity;
if ($user->role != UserRoleEnum::STORE_ADMIN) {
throw new Exception('您没有该门店权限');
}
$ProductOrder = ProductOrder::find()->where([
'store_id' => $user->store_id,
'id' => $post['order_id']
])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
$Prescription=Prescription::find()->where(['id'=>$ProductOrder['p_id'],'is_deleted'=>0])->one();
if ($Prescription['status']!=1){
throw new Exception('处方未通过,不能发货');
}
$ProductOrder->is_send = 1;
$ProductOrder->send_time = date('Y-m-d H:i:s', time());
if (!$ProductOrder->saveOrFail()) {
throw new Exception('发货失败');
}
//订单发货3天后分账结算
// if($ProductOrder->type == 2){ //易票联支付的产品订单
// $config = \Yii::$app->params;
// $orderAutoSettlementTime = isset($config['product_order']['settlement_time']) ? $config['product_order']['settlement_time'] : 72*3600;
// $TIME=180;
// \Yii::$app->queue->delay($TIME)->push(new ProductOrderSendJob([
// 'orderId' => $ProductOrder->id
// ]));
// }
return ['发货成功'];
}
/**
* @doc-name 产品订单详情
* @doc-param int product_id 产品订单id
*/
public function actionProductDetail()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['product_id', 'required']
]);
$ProductOrder = ProductOrder::find()->where([
'id' => $get['product_id']
])->with(['expressNos', 'prescription', 'orderItems'])->asArray()->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
if ($ProductOrder['prescription']['prescription_type'] == 1) {
$SystemConfig = SystemConfig::findOne(['type' => 1]);
$ProductOrder['daijianfei'] = $SystemConfig['value'];
}
return $ProductOrder;
}
/**
* 订单物流详情
*/
public function actionExpress(){
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['order_id', 'required']
]);
$express = (new ExpressService())->detail($get['order_id']);
return $express;
}
/**
* @doc-name 处理处方快照
*/
public function actionProductOrderDetail($id = null)
{
$p_id = ProductOrder::find()->select(['p_id'])->where(['id' => $id])->column();
$prescription_type = Prescription::find()->select(['prescription_type'])->where(['id' => $p_id, 'is_deleted' => 0])->column();
if ($prescription_type[0] == 1 || $prescription_type[0] == 3) {//中药 配方颗粒
$content = Prescription::find()->where(['id' => $p_id, 'is_deleted' => 0])->one();
$recipe = json_decode($content['content'], true)['repice'];
$data['content'] = json_decode($recipe[0]['content']);
$data['deployment'] = $recipe[0]['deployment'];
$data['dosage'] = $recipe[0]['dosage'];
$data['consumption'] = $recipe[0]['consumption'];
$data['directions'] = $recipe[0]['directions'];
$data['usage'] = $recipe[0]['usage'];
$data['fufa_id'] = $recipe[0]['fufa_id'];
$data['volume'] = $recipe[0]['volume'];
$data['is_deepfry'] = $recipe[0]['is_deepfry'];
$data['cm_id'] = $recipe[0]['cm_id'];
$data['total_price'] = $recipe[0]['total_price'];
$data['remark'] = $recipe[0]['remark'];
return $data;
} else {//西药
$Prescription = Prescription::find()->where(['id' => $p_id, 'is_deleted' => 0])->one();
if (!$Prescription) throw new Exception('处方不存在');
$repice = json_decode($Prescription['content'], true)['repice'];
$data = [];
foreach ($repice as $v) {
$item = [
'id' => $v['id'],
'content' => json_decode($v['content']),
'drug_name' => json_decode($v['content'])->drug_name,
'source' => json_decode($v['content'])->source,
'function' => json_decode($v['content'])->function,
'usage' => json_decode($v['content'])->usage,
'specification' => json_decode($v['content'])->specification,
'instruction' => json_decode($v['content'])->instruction,
'image' => json_decode($v['content'])->image,
'number' => $v['number'],
'available_days' => $v['available_days'],
'total_price' => $v['total_price'],
'created_at' => $v['created_at'],
'type_id' => json_decode($v['content'])->type_id,
'time_id' => json_decode($v['content'])->time_id,
'frequency_id' => json_decode($v['content'])->frequency_id,
'unit_id' => json_decode($v['content'])->unit_id,
'usetime' => $v['usetime']['name'],
'frequency' => $v['frequency']['name'],
'grain_number' => $v['grain_number'],
'westUnit' => $v['westUnit']['name'],
'types' => $v['usetype']['name'], //药的使用方式
];
$data[] = $item;
}
return $data;
}
}
//商品订单的商品明细
public function actionProductOrderItem($id = null)
{
return ProductOrderItems::find()->with('drug')->where(['product_order_id' => $id])->asArray()->all();
}
/**
* @doc-name 导出产品订单
*/
public function actionExportProductOrder()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params = \Yii::$app->request->get();
$parameter['header'] = ['易票联订单号','订单号','诊所名称', '商品名称', '规格', '厂家', '单价', '加工费', '诊疗费', '销售价', '采购价','总价', '运费', '医生', '订单状态', '售后状态', '下单时间', '收件人姓名', '电话', '地址', '支付时间'];
$parameter['data'] = ProductOrder::inventory($params,\Yii::$app->user->identity->store_id);
ExportService::ExportByCors($parameter);
}
/**
* @doc-name 代煎费
*/
public function actionDaijianFei($id=null)
{
$ProductOrder=ProductOrder::find()->where(['id'=>$id])->one();
if (!$ProductOrder)throw new Exception('产品订单不存在');
$Prescription=Prescription::findOne(['id'=>$ProductOrder['p_id'],'is_deleted'=>0]);
if ($Prescription['prescription_type'] == 1 || $Prescription['prescription_type']==3 ) {
$SystemConfig = SystemConfig::findOne(['type' => 1]);
return $SystemConfig['value'];
}else{
return '无';
}
}
}

View File

@@ -0,0 +1,234 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\helpers\FuncHelper;
use common\models\Prescription;
use common\models\ProductOrder;
use common\services\ExportService;
use yii\db\Exception;
use yii\helpers\Json;
use yii\web\Response;
/**
* @doc-module 处方
*/
class PrescriptionController extends BaseAdminController
{
/**
* @doc-name 处方列表
* @doc-param string prescription_no 处方编号 / optional
* @doc-param string name 患者 / optional
* @doc-param string doctor 开方医生 / optional
* @doc-param string clinical_diagnose 临床诊断 / optional
* @doc-param int status 处方状态0待审核1已通过2未通过3待使用4已使用5未使用6已失效7已初审 / optional
* @doc-return mixed @List{id,prescription_no-string-处方编号,name-string-患者,sex-int-性别,clinical_diagnose-string-临床诊断,doctor-string-开方医生,doctor_sign-string-医生签名,pharmacist-string-审核药师,pharmacist_view_time-string-审核时间,patient_mobile-string-患者电话,created_at-int-开方时间,status-int-处方状态0待审核1已通过2未通过3待使用4已使用5未使用6已失效7已初审,is_get-int-是否取药0否1是,prescription_type-int-1中药处方2西药处方3颗粒药处方,category-int-类别1自费2医保,is_pay-int-是否支付0否1是,pay_time-string-支付时间,pay_type-int-支付类型1微信2支付宝3银行卡4其他,type-int-类型1普通方2常用方,@OrderInfo{platform_id-int-平台id,platform_store_id-int-平台门店id,platform_order_id-int-平台订单ID,drugstore_id-string-仓库id,order_no-string-产品顶单号,p_id-int-处方id,order_type-int-订单类型1处方订单2商城订单3商城处方订单,type-int-支付类型1微信2支付宝3银行卡4其他,address-string-地址,is_pay-int-是否支付0否1是,total_pay_price-float-支付金额,free_ship-int-是否包邮0否1是,trans_expenses-float-运费(默认包邮),pay_method-int-支付方式1线上2线下,status-int-产品订单状态0未支付1待发货2待收货3已完成}} 处方列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$admin=\Yii::$app->user->identity;
$start_time=strtotime($get['start_time'].' '.'00:00:00');
$end_time=strtotime($get['end_time'].' '.'23:59:59');
if ($admin->role==UserRoleEnum::STORE_ADMIN){//门店
$query = Prescription::find()->where([
'store_id' => $admin->store_id,
'is_deleted' => 0,
])->orderBy(['id'=>SORT_DESC]);
}else{
$query = Prescription::find()->where([
'is_deleted' => 0
])->orderBy(['id'=>SORT_DESC]);
}
$name = $get['name'];
$doctor = $get['doctor'];
if (!empty($get['prescription_no'])) {//处方编号
$query->andWhere(['prescription_no' => $get['prescription_no']]);
}
if (!empty($name)) {//患者
$query->joinWith(['userPatient' => function ($u) use ($name) {
$u->where([
'like', 'name', $name
]);
}]);
}
if (!empty($doctor)) {//开方医生
$query->joinWith(['doctorInfo' => function ($d) use ($doctor) {
$d->where([
'like', 'name', $doctor
]);
}]);
}
if (!empty($get['clinical_diagnose'])) {//临床诊断
$query->andWhere(['like', 'yii_prescription.clinical_diagnose', $get['clinical_diagnose']]);
}
if (!empty($get['status'])) {//处方状态
$query->andWhere(['yii_prescription.status' => $get['status']]);
}
if (!empty($get['is_dispense'])) {//是否配药
$query->andWhere(['yii_prescription.is_dispense' => $get['is_dispense']]);
}
if (!empty($get['start_time']) && !empty($get['end_time'])){
if ($start_time==$end_time){//筛选某一天
$time=FuncHelper::getDayBE($get['start_time']);
$end_time=$time[1];
}
$query->andWhere(['between','yii_prescription.created_at',$start_time,$end_time]);
}
$this->field = [
Prescription::class => [
'id', 'prescription_no','online_prescription_no','valid_hours','is_online',
'content' => function ($p) {
$repice = Json::decode($p->content, true)['repice'];
return $repice;
},
'name' => 'userPatient.name',
'sex' => 'userPatient.sex',
'patient_age' => 'userPatient.age',
'dept' => 'doctorInfo.depart.name',
'patient_mobile' => 'userPatient.mobile',
'clinical_diagnose', 'doctor_order', 'prescription_type', 'category', 'doctor_sign',
'doctor' => 'doctorInfo.name',
'status', 'pharmacist' => 'pharmacistInfo.name', 'pharmacist_view_time'=>function($m){
return date('Y-m-d H:i:s',$m->pharmacist_view_time);
},
'is_pay', 'pay_type', 'pay_time', 'type','register_id','total_pay_price','cancel_status','cancel_time','cancel_remark','refund_status','refund_time','auto_expire_time',
'is_get' => function ($model) {
return ProductOrder::find()->select('is_pay')->where([
'p_id' => $model->id
])->column();
},
'order_info' => function ($q) {
return ProductOrder::find()->where([
'p_id' => $q->id
])->one();
}, 'created_at' => function ($m) {
return date('Y-m-d H:i:s', $m->created_at);
},
]
];
return $this->create($query, $get);
}
/**
* @doc-name 打印pdf
*/
public function actionPdf()
{
$prescription = \Yii::$app->request->post('prescription');
$mpdf = new \Mpdf\Mpdf([
'mode' => 'UTF-8', 'format' => 'A4', 'default_font_size' => 15, 'default_font' => '', 'margin_left' => 20, 'margin_right' => 20]);
$mpdf->autoScriptToLang = true;//支持中文设置
$mpdf->autoLangToFont = true;//支持中文设置
$mpdf->WriteHTML($prescription);
$path = 'FILE_UPLOAD' . date('YmdHis') . '_' . mt_rand(1, 5) . '.pdf';
$mpdf->Output();//直接在页面显示pdf页面内容
//$mpdf->Output($path,'f');//保存pdf文件到指定目录
}
/**
* @doc-name 处方详情
* @doc-param int id 处方id
*/
public function actionPrescriptionDetail()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
['id','required']
]);
$Prescription= Prescription::find()->alias('p')->where([
'p.id'=>$get['id'],
'p.is_deleted' => 0
])->with(['register','store'])->joinWith(['userPatient'])->asArray()->one();
if (!$Prescription) throw new Exception('处方不存在');
if ( $Prescription['prescription_type']== 1 || $Prescription['prescription_type'] == 3) {//中药 配方颗粒
$content=$Prescription['content'];
$recipe = json_decode($content, true)['repice'];
$data['content']= json_decode($recipe[0]['content']);
$data['deployment']=$recipe[0]['deployment'];
$data['dosage']=$recipe[0]['dosage'];
$data['consumption']=$recipe[0]['consumption'];
$data['directions']=$recipe[0]['directions'];
$data['usage']=$recipe[0]['usage'];
$data['fufa_id']=$recipe[0]['fufa_id'];
$data['volume']=$recipe[0]['volume'];
$data['is_deepfry']=$recipe[0]['is_deepfry'];
$data['cm_id']=$recipe[0]['cm_id'];
$data['total_price']=$recipe[0]['total_price'];
$data['remark']=$recipe[0]['remark'];
} else {//西药
$repice = json_decode($Prescription['content'], true)['repice'];
$data = [];
foreach ($repice as $v) {
$item = [
'id' => $v['id'],
'content' => json_decode($v['content']),
'drug_name' => json_decode($v['content'])->drug_name,
'source' => json_decode($v['content'])->source,
'function' => json_decode($v['content'])->function,
'usage' => json_decode($v['content'])->usage,
'specification' => json_decode($v['content'])->specification,
'instruction' => json_decode($v['content'])->instruction,
'image' => json_decode($v['content'])->image,
'number' => $v['number'],
'available_days' => $v['available_days'],
'total_price' => $v['total_price'],
'created_at' => $v['created_at'],
'type_id' => json_decode($v['content'])->type_id,
'time_id' => json_decode($v['content'])->time_id,
'frequency_id' => json_decode($v['content'])->frequency_id,
'unit_id' => json_decode($v['content'])->unit_id,
'usetime' => $v['usetime']['name'],
'frequency' => $v['frequency']['name'],
'grain_number' => $v['grain_number'],
'westUnit' => $v['westUnit']['name'],
'types' => $v['usetype']['name'], //药的使用方式
];
$data[] = $item;
}
}
$ProductOrder=ProductOrder::find()->where([
'p_id'=>$get['id']
])->one();
return [
'content'=>$data,
'prescription'=>$Prescription,
'ProductOrder'=>$ProductOrder
];
}
/**
* @doc-name 导出处方
*/
public function actionExportPrescription()
{
// \Yii::$app->response->format = Response::FORMAT_RAW;
$params=\Yii::$app->request->get();
$parameter['header']=['订单号','医生','患者','订单状态','价格','是否取药','时间'];
$parameter['data']=Prescription::inventory($params,\Yii::$app->user->identity->store_id);
// $Name='处方记录';
// $class=new Prescription();
ExportService::ExportByCors($parameter);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\helpers\ArrayHelper;
use common\helpers\FuncHelper;
use common\models\Region;
use yii\db\Exception;
class RegionController extends BaseAdminController
{
/**
* @doc-name 快递费--地区列表
*/
public function actionRegionList()
{
$get = \Yii::$app->request->get();
$query = Region::find()->where(['level'=>1]);
$this->field = [
Region::class => [
'id', 'name', 'pid', 'level', 'express_fee'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 编辑快递费
* @doc-param int id id
* @doc-param float express_fee 快递费
*/
public function actionEditFee()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['id', 'express_fee'], 'required'],
]);
$Region = Region::find()->where(['id' => $post['id']])->one();
if (!$Region) throw new Exception('地区不存在');
$Region->express_fee = $post['express_fee'];
if (!$Region->saveOrFail()) {
throw new Exception('修改失败');
};
return ['修改成功'];
}
/**
* @doc-name 地区列表
*/
public function actionAllRegionList()
{
$Region = Region::find()->asArray()->all();
return ArrayHelper::list_to_tree($Region, 'id', 'pid', 'children');
}
}

View File

@@ -0,0 +1,182 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use common\enums\UserRoleEnum;
use common\helpers\FuncHelper;
use common\models\DoctorService;
use common\models\Register;
use common\models\ServiceUser;
use yii\db\Exception;
class RegisterController extends BaseAdminController
{
/**
* @doc-name 挂号列表
* @doc-param string mobile 电话 / optional
* @doc-param string name 患者 / optional
* @doc-param string order_no 订单号 / optional
* @doc-param string doctor 医生 / optional
* @doc-return mixed @List{User{id,user_id,doctor-string-医生,user_patient-string-患者,created_at-string-挂号时间,patient_mobile-string-患者点电话,order_no-string-订单号,depart-int-科室} 用户列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$admin = \Yii::$app->user->identity;
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
}
if ($admin->role == UserRoleEnum::STORE_ADMIN) {//门店
$query = Register::find()->alias('r')->where([
'r.store_id' => $admin->store_id,
'r.is_delete' => 0,
])->orderBy(['r.id' => SORT_DESC]);
} else {
$query = Register::find()->alias('r')->where([
'r.is_delete' => 0
])->orderBy(['r.id' => SORT_DESC]);
}
$patient = $get['patient_name'];
$mobile = $get['mobile'];
$doctor = $get['doctor_name'];
$query->joinWith(['patient' => function ($p) use ($patient, $mobile) {
$p->alias('p');
if (!empty($patient)) {//患者
$p->andWhere(['like', 'p.name', $patient]);
}
if (!empty($mobile)) {//手机号
$p->andWhere(['p.mobile' => $mobile]);
}
}]);
$query->joinWith(['doctor' => function ($d) use ($doctor) {
$d->alias('d');
if (!empty($doctor)) {//医生
$d->andWhere(['like', 'd.name', $doctor]);
}
}]);
if (!empty($get['order_no'])) {//订单号
$query->andWhere(['like', 'order_no', $get['order_no']]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time == $end_time) {//筛选当天
$time = FuncHelper::getDayBE($get['start_time']);
$end_time = $time[1];
}
$query->andWhere(['between', 'r.created_at', $start_time, $end_time]);
}
$this->field = [
Register::class => [
'id', 'doctor' => 'doctor.name', 'user_patient' => 'patient.name', 'patient_mobile' => 'patient.mobile', 'user_id', 'order_no', 'depart' => 'depart.name', 'order_number', 'price', 'is_pay', 'status', 'refuse_reason', 'pay_type',
'pay_time' => function ($p) {
if (!empty($p->pay_time)) {
return date('Y-m-d H:i:s', $p->pay_time);
} else {
return '无';
}
},
'is_cancel', 'cancel_status', 'cancel_time', 'cancel_remark', 'refund_status', 'refund_time', 'created_at',
'patient_age' => 'patient.age'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 挂号设置
* @doc-param int su_id 医生ID
* @doc-param int status 1开启0不开启
* @doc-param float price 价格 /
*/
public function actionRegisterSet()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
[['su_id', 'status'], 'required'],
]);
$ServiceUser = ServiceUser::find()->where(['id' => $get['su_id'], 'is_delete' => 0])->one();
if (!$ServiceUser) throw new Exception('医生不存在');
$DoctorService = DoctorService::findOne(['su_id' => $get['su_id']]);
if (!$DoctorService) {
throw new Exception('医生基本信息不存在');
}
if ($get['status'] == 1) {
$DoctorService->register_status = 1;
$DoctorService->register_price = $get['price'] ?? 0;
$DoctorService->saveOrFail();
return ['已开启挂号服务'];
} else {
$DoctorService->register_status = 0;
$DoctorService->register_price = 0;
$DoctorService->saveOrFail();
return ['已关闭挂号服务'];
}
}
/**
* @doc-name 挂号费汇总
*/
public function actionRegisterStatistic()
{
$get = \Yii::$app->request->get();
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
}
$user = \Yii::$app->user->identity;
$register_query = Register::find()->alias('re');
$month_start = strtotime(date('Y-m-01 00:00:00'));
$month_end = strtotime(date('Y-m-t 23:59:59'));
if (!empty($start_time) && !empty($end_time)) {
$register_data = ['between', 're.created_at', $start_time, $end_time];
} else {
$register_data = ['between', 're.created_at', $month_start, $month_end];
}
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$register_query->where(['re.store_id' => $user->store_id]);
}
//挂号
$register_price = $register_query
->andWhere([
'and',
['=', 'is_pay', 1],
['<>', 'is_cancel', 1],
['<>', 're.refund_status', 1],
['=','is_delete' , 0]
])
->andWhere([
'and',
['<>', 're.status', 0],
['<>', 're.status', 4],
['<>', 're.status', 7],
])
->andWhere($register_data ?? '')->sum('price');
return [
'register_price' => $register_price ?? 0,
];
}
}

View File

@@ -0,0 +1,141 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\AgreeForm;
use common\models\BaseConfig;
use common\models\SystemConfig;
use yii\db\Exception;
/**
* @doc-module 设置
*/
class SetController extends BaseAdminController
{
/**
* @doc-name 协议列表
* @doc-return mixed @List{id,end-int-1用户端2服务端 ,type-int-类型1服务协议2隐私政策3其他,desc-string-描述,content-string-内容,change_at-string-变更时间,status-int-是否删除0否1是,created_at-int-创建时间} 协议列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionAgreeList()
{
$get= \Yii::$app->request->get();
$query=BaseConfig::find()->where([
'status'=>0
]);
$this->field=[
BaseConfig::class=>[
'id','type','desc','content','change_at'=>function($m){
return date('Y-m-d H:i:s',$m->change_at);
},
'status','end',
'created_at'=>function($model){
return date('Y-m-d H:i:s',$model->created_at);
}
]
];
return $this->create($query,$get);
}
/**
* @doc-name 删除协议
* @doc-param int id 协议ID
*/
public function actionAgreeDel()
{
$get= \Yii::$app->request->get();
$this->requestValidate($get,[
['id','required']
]);
$AgreeForm=new AgreeForm();
$AgreeForm->attributes=$get;
return $AgreeForm->del();
}
/**
* @doc-name 编译协议及新增协议
* @doc-desc 传id即为编辑
* @doc-param int id 协议ID / optional
* @doc-param string type 类型1服务协议2隐私政策3其他
* @doc-param string desc 描述 / optional
* @doc-param string content 内容
*/
public function actionAgreeSave()
{
$post = \Yii::$app->request->post();
$AgreeForm=new AgreeForm();
$AgreeForm->attributes=$post;
return $AgreeForm->save();
}
/**
* @doc-name 西药包邮
* @doc-desc 传id即为编辑
* @doc-param string name name
* @doc-param string rule 规则
* @doc-param string value 值
*/
public function actionFreeShip()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post,[
['name','required'],
['rule','required'],
['value','required'],
]);
$SystemConfig=SystemConfig::find()->where([
'config_type'=>2,
'type'=>2
])->one();
if (!$SystemConfig){
throw new Exception('西药包邮配置不存在');
}
$SystemConfig->name=$post['name'];
$SystemConfig->rule=$post['rule'];
$SystemConfig->value=$post['value'];
$SystemConfig->saveOrFail();
return ['设置成功'];
}
/**
* 小程序版本
*/
public function actionXcxVersion(){
$SystemConfig=SystemConfig::find()->where([
'config_type'=>3,
])->one();
if (!$SystemConfig){
throw new Exception('小程序版本配置不存在');
}
return $SystemConfig;
}
/**
* 小程序版本设置
*/
public function actionXcxVersionSet(){
$post = \Yii::$app->request->post();
$this->requestValidate($post,[
['value','required'],
]);
$SystemConfig=SystemConfig::find()->where([
'config_type'=>3,
])->one();
if (!$SystemConfig){
throw new Exception('小程序版本配置不存在');
}
$SystemConfig->value=$post['value'];
$SystemConfig->saveOrFail();
return ['设置成功'];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,405 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\models\Admin;
use common\models\ProductOrder;
use common\models\Reconciliation;
use common\models\Store;
use yii\db\Exception;
/**
* @doc-module 业务员
*/
class SupplyController extends BaseAdminController
{
/**
* @doc-name 列表
* @doc-param int type 1销售数据2产品数据
* @doc-param int sort 1诊所2业务员3省4市
* @doc-param string start_time / optional
* @doc-param string end_time / optional
* @doc-param string limit_time 1当月2上月3累计 / optional
* @doc-return mixed @List{supply-string-业务员,position-string-诊所位置,mobile-string-诊所电话,offical_seal-string-公章,code-string-推广码,sale_price-float-销售金额,drug_number-string-药品编码,drug_name-string-药名}
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$admin = \Yii::$app->user->identity;
$this->requestValidate($get, [
['type', 'required'],
]);
$search = $get['search'];
$sort = $get['sort'];
$limit_time = $get['limit_time'];
if ($admin->role == UserRoleEnum::PROVINCE_DAI) {//省代
switch ($get['type']) {
case 1:
$query = Store::find()->alias('s')->where(['s.is_delete' => 0, 's.province_id' => $admin->province_id]);
break;
case 2:
$query = Reconciliation::find()->orderBy(['id' => SORT_DESC])->alias('r')->where(['r.status' => 1])->joinWith(['store' => function ($store) use ($admin) {
$store->alias('st');
$store->where(['st.province_id' => $admin->province_id]);
}]);
break;
default:
throw new Exception('参数错误');
}
} elseif ($admin->role == UserRoleEnum::CITY_DAI) {//市代
switch ($get['type']) {
case 1:
$query = Store::find()->alias('s')->where(['s.is_delete' => 0, 's.city_id' => $admin->city_id]);
break;
case 2:
$query = Reconciliation::find()->orderBy(['id' => SORT_DESC])->alias('r')->where(['r.status' => 1])->joinWith(['store' => function ($store) use ($admin) {
$store->alias('st');
$store->where(['st.city_id' => $admin->city_id]);
}]);
break;
default:
throw new Exception('参数错误');
}
} elseif ($admin->role == UserRoleEnum::SUPPLY) {//业务员
switch ($get['type']) {
case 1:
$query = Store::find()->alias('s')->where(['s.code' => $admin->code, 's.is_delete' => 0]);
break;
case 2:
$query = Reconciliation::find()->orderBy(['id' => SORT_DESC])->alias('r')->where(['r.status' => 1])->joinWith(['store' => function ($store) use ($admin) {
$store->where(['uid' => $admin->uid]);
}]);
break;
default:
throw new Exception('参数错误');
}
} else {
throw new Exception('角色错误');
}
switch ($get['type']) {
case 1:
if ($limit_time == 1) {
$start_time = strtotime(date('Y-m-01 00:00:00'));
$end_time = strtotime(date('Y-m-t 23:59:59'));
$query->joinWith(['reconciliation' => function ($r) use ($start_time, $end_time) {
$r->alias('re');
$r->where(['re.status' => 1])->andWhere([
'between', 're.pay_time', $start_time, $end_time]);
}]);
}
if ($limit_time == 2) {
$now = new \DateTime();
$now->modify('first day of last month');
$start_time = $now->format('Y-m-01 00:00:00');
$end_time = date("Y-m-d 23:59:59", strtotime(-date('d') . 'day'));
$query->joinWith(['reconciliation' => function ($r) use ($start_time, $end_time) {
$r->alias('re');
$r->where(['re.status' => 1])->andWhere([
'between', 're.pay_time', strtotime($start_time), strtotime($end_time)]);
}]);
}
if (!empty($sort)) {
switch ($sort) {
case 1:
if (!empty($search)) $query->andWhere(['like', 's.name', $search]);
break;
case 2:
if (!empty($search)) {
$query->joinWith(['admin' => function ($a) use ($search) {
$a->andWhere(['like', 'username', $search]);
}]);
}
break;
case 3:
if (!empty($search)) {
$query->joinWith(['province' => function ($p) use ($search) {
$p->alias('p')->where(['like', 'p.name', $search]);
}]);
}
break;
case 4:
if (!empty($search)) {
$query->joinWith(['city' => function ($c) use ($search) {
$c->alias('c')->where(['like', 'c.name', $search]);
}]);
}
break;
default:
throw new Exception('参数错误');
}
}
$this->field = [
Store::class => [
'id', 'name', 'position', 'mobile', 'offical_seal', 'code', 'uid',
'supply' => 'admin.username',
'province' => 'province.name',
'city' => 'city.name',
'city_id',
'province_id',
'sale_price' => function ($s) {
return $this->actionSalePrice($s->id);
}
]
];
return $this->create($query, $get);
case 2:
if ($limit_time == 1) {
$start_time = strtotime(date('Y-m-01 00:00:00'));
$end_time = strtotime(date('Y-m-t 23:59:59'));
$query->andWhere(['between', 'r.pay_time', $start_time, $end_time]);
}
if ($limit_time == 2) {
$now = new \DateTime();
$now->modify('first day of last month');
$start_time = $now->format('Y-m-01 00:00:00');
$end_time = date("Y-m-d 23:59:59", strtotime(-date('d') . 'day'));
$query->andWhere(['between', 'r.pay_time', strtotime($start_time), strtotime($end_time)]);
}
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$query->andWhere(['between', 'r.pay_time', strtotime($get['start_time']), strtotime($get['end_time'])]);
}
if (!empty($sort)) {
switch ($sort) {
case 1:
$query->joinWith(['store' => function ($s) use ($search) {
$s->alias('s');
$s->andWhere([
'or',
['like', 's.name', $search],
['like', 's.shouzimu', $search],
]);
}]);
break;
case 2:
if (!empty($search)) {
$query->joinWith(['store' => function ($s) use ($search) {
$s->joinWith(['admin' => function ($a) use ($search) {
$a->andWhere(['like', 'username', $search]);
}]);
}]);
}
break;
case 3:
if (!empty($search)) {
$query->joinWith(['store' => function ($s) use ($search) {
$s->joinWith(['province' => function ($ss) use ($search) {
$ss->alias('pro');
$ss->andWhere(['like', 'pro.name', $search]);
}]);
}]);
}
break;
case 4:
if (!empty($search)) {
$query->joinWith(['store' => function ($s) use ($search) {
$s->joinWith(['city' => function ($ct) use ($search) {
$ct->alias('city');
$ct->andWhere(['like', 'city.name', $search]);
}]);
}]);
}
break;
default:
throw new Exception('参数错误');
}
}
//
// $query->joinWith(['drug' => function ($d) use ($search) {
// $d->alias('d');
// $d->andWhere([
// 'or',
// ['like', 'd.drug_name', $search],
// ['like', 'd.pinyin_simple', $search],
// ]);
// }]);
if (!empty($search)) {
if ($search == 1) {
$query->andWhere(['r.drug_type' => [1, 3]]);
} else {
$query->andWhere(['r.drug_type' => [2, 4]]);
}
}
$this->field = [
Reconciliation::class => [
'id', 'order_id', 'store_id', 'pay_time' => function ($m) {
return date('Y-m-d H:i:s', $m->pay_time);
},
'drug_id', 'drug_type', 'number', 'total_buy_price', 'total_price', 'status',
'drug_number' => 'drug.drug_number',
'drug_name' => 'drug.drug_name',
'store_number' => 'productOrder.store.id',
'store' => 'store.name',
'supply' => 'store.admin.username',
'province' => 'store.province.name',
'city' => 'store.city.name',
'province_id' => 'store.province_id',
'city_id' => 'store.city_id',
]
];
return $this->create($query, $get);
default:
throw new Exception('参数错误');
}
}
public function actionSalePrice($store)
{
$Reconciliation = Reconciliation::find()->where(['store_id' => $store, 'status' => 1])->sum('total_price');
return $Reconciliation ?? 0;
}
/**
* @doc-name 按照诊所统计
* @doc-param string start_time 起始时间
* @doc-param string end_time 终止时间
* @doc-param string limit_time 1当月2上月3累计 / optional
*/
public function actionStoreStatics()
{
$admin = \Yii::$app->user->identity;
$get = \Yii::$app->request->get();
$limit_time = $get['limit_time'];
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$data = ['between', 'pay_time', strtotime($get['start_time']), strtotime($get['end_time'])];
}
if ($limit_time == 1) {
$start_time = strtotime(date('Y-m-01 00:00:00'));
$end_time = strtotime(date('Y-m-t 23:59:59'));
$data = ['between', 'pay_time', $start_time, $end_time];
}
if ($limit_time == 2) {
$now = new \DateTime();
$now->modify('first day of last month');
$start_time = $now->format('Y-m-01 00:00:00');
$end_time = date("Y-m-d 23:59:59", strtotime(-date('d') . 'day'));
$data = ['between', 'pay_time', strtotime($start_time), strtotime($end_time)];
}
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$data = ['between', 'pay_time', strtotime($get['start_time']), strtotime($get['end_time'])];
}
if ($admin->role == UserRoleEnum::PROVINCE_DAI) {//省代
$store_id = Store::find()->select(['id'])->where(['province_id' => $admin->province_id])->column();
$total_price = Reconciliation::find()->where(['in', 'store_id', $store_id])->andWhere(['status' => 1])->andWhere($data ?? '')->sum('total_price');
$total_buy_price= Reconciliation::find()->where(['in', 'store_id', $store_id])->andWhere(['status' => 1])->andWhere($data ?? '')->sum('total_buy_price');
$store = Store::find()->where(['province_id' => $admin->province_id])->count();
} elseif ($admin->role == UserRoleEnum::CITY_DAI) {//市代
$store_id = Store::find()->select(['id'])->where(['city_id' => $admin->city_id])->column();
$total_price = Reconciliation::find()->where(['in', 'store_id', $store_id])->andWhere(['status' => 1])->andWhere($data ?? '')->sum('total_price');
$total_buy_price= Reconciliation::find()->where(['in', 'store_id', $store_id])->andWhere(['status' => 1])->andWhere($data ?? '')->sum('total_buy_price');
$store = Store::find()->where(['city_id' => $admin->city_id])->count();
} elseif ($admin->role == UserRoleEnum::SUPPLY) {//业务员
$store_id = Store::find()->select(['id'])->where(['code' => $admin->code])->column();
$total_price = Reconciliation::find()->where(['in', 'store_id', $store_id])->andWhere(['status' => 1])->andWhere($data ?? '')->sum('total_price');
$total_buy_price= Reconciliation::find()->where(['in', 'store_id', $store_id])->andWhere(['status' => 1])->andWhere($data ?? '')->sum('total_buy_price');
$store = Store::find()->where(['code' => $admin->code])->count();
} else {
throw new Exception('角色错误');
}
return [
'store_num' => $store ?? 0,
'total_price' => $total_price ?? 0,
'total_buy_price' => $total_buy_price ?? 0,
];
}
/**
* @doc-name 按照产品统计
* @doc-param string start_time 起始时间
* @doc-param string end_time 终止时间
* @doc-param string limit_time 1当月2上月3累计 / optional
*/
public function actionProductStatics()
{
$get = \Yii::$app->request->get();
$admin = \Yii::$app->user->identity;
$limit_time = $get['limit_time'];
if ($limit_time == 1) {
$start_time = strtotime(date('Y-m-01 00:00:00'));
$end_time = strtotime(date('Y-m-t 23:59:59'));
$data = ['between', 'pay_time', $start_time, $end_time];
}
if ($limit_time == 2) {
$now = new \DateTime();
$now->modify('first day of last month');
$start_time = $now->format('Y-m-01 00:00:00');
$end_time = date("Y-m-d 23:59:59", strtotime(-date('d') . 'day'));
$data = ['between', 'pay_time', strtotime($start_time), strtotime($end_time)];
}
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$data = ['between', 'pay_time', strtotime($get['start_time']), strtotime($get['end_time'])];
}
if ($admin->role == UserRoleEnum::PROVINCE_DAI) {//省代
$store_id = Store::find()->select(['id'])->where(['province_id' => $admin->province_id])->column();
$all_sale = Reconciliation::find()->alias('r')->andWhere([
'and',
['r.status' => 1],
['in', 'r.store_id', $store_id]
])->andWhere($data ?? '')->sum('number');
$all_total_price = Reconciliation::find()->alias('r')->andWhere([
'and',
['r.status' => 1],
['in', 'r.store_id', $store_id]
])->andWhere($data ?? '')->sum('total_price');
} elseif ($admin->role == UserRoleEnum::CITY_DAI) {//市代
$store_id = Store::find()->select(['id'])->where(['city_id' => $admin->city_id])->column();
$all_sale = Reconciliation::find()->alias('r')->andWhere([
'and',
['r.status' => 1],
['in', 'r.store_id', $store_id]
])->andWhere($data ?? '')->sum('number');
$all_total_price = Reconciliation::find()->alias('r')->andWhere([
'and',
['r.status' => 1],
['in', 'r.store_id', $store_id]
])->andWhere($data ?? '')->sum('total_price');
} elseif ($admin->role == UserRoleEnum::SUPPLY) {//业务员
$store_id = Store::find()->select(['id'])->where(['code' => $admin->code])->column();
$all_sale = Reconciliation::find()->alias('r')->andWhere([
'and',
['r.status' => 1],
['in', 'r.store_id', $store_id]
])->andWhere($data ?? '')->sum('number');
$all_total_price = Reconciliation::find()->alias('r')->andWhere([
'and',
['r.status' => 1],
['in', 'r.store_id', $store_id]
])->andWhere($data ?? '')->sum('total_price');
} else {
throw new Exception('角色错误');
}
return [
'all_sale' => $all_sale ?? 0,
'all_total_price' => $all_total_price ?? 0,
];
}
}

View File

@@ -0,0 +1,226 @@
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\jobs\SyncHospitalJob;
use common\models\DrugStoreDrug;
use common\models\DrugStoreRelations;
use common\models\Store;
use common\services\PlatformService;
use linslin\yii2\curl\Curl;
use yii\db\Exception;
class SyncController extends BaseAdminController
{
/**
* @doc-name 同步所有的门店门店----总后台同步
*/
public function actionSyncStore()
{
$admin = \Yii::$app->user->identity;
if ($admin->role != UserRoleEnum::SUPER_ADMIN) {
throw new Exception('非超管,您不能同步药品');
}
$DrugStoreDrug_chinese = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 1])->asArray()->all();
$DrugStoreDrug_west = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 2])->asArray()->all();
$DrugStoreDrug_grain = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 3])->asArray()->all();
$DrugStoreDrug_zongcheng = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 4])->asArray()->all();
$store = Store::find()->select(['id', 'z_buy_percent', 'z_sale_percent', 'g_bug_percent', 'g_sale_percent'])->where(['is_delete' => 0])->all();
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($store as $value) {//中药
foreach ($DrugStoreDrug_chinese as $val) {
$Drug = DrugStoreRelations::find()->where([
'store_id' => $value['id'],
'drug_id' => $val['drug_id']
])->one();
if (!$Drug) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $value['id'];
$DrugStoreRelations->drug_id = $val['drug_id'];
$DrugStoreRelations->price = bcdiv(bcmul($val['price'], $value['z_sale_percent']??100, 4), 100, 4);
$DrugStoreRelations->buy_price = bcdiv(bcmul($val['market_price'], $value['z_buy_percent']??100, 4), 100, 4);
$DrugStoreRelations->status = $val['status'];
$DrugStoreRelations->saveOrFail();
}
}
}
foreach ($store as $value) {//西药
foreach ($DrugStoreDrug_west as $v) {
$DrugStore = DrugStoreRelations::find()->where([
'store_id' => $value['id'],
'drug_id' => $v['drug_id']
])->one();
if (!$DrugStore) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $value['id'];
$DrugStoreRelations->drug_id = $v['drug_id'];
$DrugStoreRelations->price = $v['price'];
$DrugStoreRelations->buy_price = $v['market_price'] ?? $v['price'];
$DrugStoreRelations->status = $v['status'];
$DrugStoreRelations->saveOrFail();
}
}
}
foreach ($store as $value) {//配方
foreach ($DrugStoreDrug_grain as $vv) {
$DrugStoreRelations = DrugStoreRelations::find()->where([
'store_id' => $value['id'],
'drug_id' => $vv['drug_id']
])->one();
if (!$DrugStoreRelations) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $value['id'];
$DrugStoreRelations->drug_id = $vv['drug_id'];
$DrugStoreRelations->price = bcdiv(bcmul($vv['price'], $value['g_sale_percent']??100, 4), 100, 4);
$DrugStoreRelations->buy_price = bcdiv(bcmul($vv['market_price'], $value['g_bug_percent']??100, 4), 100, 4);
$DrugStoreRelations->status = $vv['status'];
$DrugStoreRelations->saveOrFail();
}
}
}
foreach ($store as $value) {//中成药
foreach ($DrugStoreDrug_zongcheng as $vv) {
$DrugStoreRelations_z = DrugStoreRelations::find()->where([
'store_id' => $value['id'],
'drug_id' => $vv['drug_id']
])->one();
if (!$DrugStoreRelations_z) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $value['id'];
$DrugStoreRelations->drug_id = $vv['drug_id'];
$DrugStoreRelations->price = $vv['price'];
$DrugStoreRelations->buy_price = $vv['market_price'] ?? $vv['price'];
$DrugStoreRelations->status = $vv['status'];
$DrugStoreRelations->saveOrFail();
}
}
}
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
$t->commit();
return ['同步成功'];
}
/**
* @doc-name 同步互医
*/
public function actionSyncHospital()
{
$type=4;
$admin=\Yii::$app->user->identity;
\Yii::$app->queue->delay(0)->push(new SyncHospitalJob([
'admin_id'=>$admin->uid,
'type'=>$type,
]));
}
/**
* @doc-name 同步单个门店
* @doc-param int store_id 门店ID
*/
public function actionSyncUnitStore()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['store_id', 'required']
]);
$DrugStoreDrug_chinese = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 1])->asArray()->all();
$DrugStoreDrug_west = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 2])->asArray()->all();
$DrugStoreDrug_grain = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 3])->asArray()->all();
$DrugStoreDrug_zongcheng = DrugStoreDrug::find()->select(['drug_id', 'price', 'market_price', 'status'])->where(['type' => 4])->asArray()->all();
$store = Store::find()->select(['id', 'z_buy_percent', 'z_sale_percent', 'g_bug_percent', 'g_sale_percent'])->where(['id' => $get['store_id'], 'is_delete' => 0])->one();
if (!$store) throw new Exception('门店不存在');
$t = \Yii::$app->db->beginTransaction();
try {
//中药
foreach ($DrugStoreDrug_chinese as $val) {
$Drug = DrugStoreRelations::find()->where([
'store_id' => $get['store_id'],
'drug_id' => $val['drug_id']
])->one();
if (!$Drug) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $get['store_id'];
$DrugStoreRelations->drug_id = $val['drug_id'];
$DrugStoreRelations->price = bcdiv(bcmul($val['price'], $store['z_sale_percent']??100, 4), 100, 4);
$DrugStoreRelations->buy_price = bcdiv(bcmul($val['market_price'], $store['z_buy_percent']??100, 4), 100, 4);
$DrugStoreRelations->status = $val['status'];
$DrugStoreRelations->saveOrFail();
}
}
//西药
foreach ($DrugStoreDrug_west as $v) {
$DrugStore = DrugStoreRelations::find()->where([
'store_id' => $get['store_id'],
'drug_id' => $v['drug_id']
])->one();
if (!$DrugStore) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $get['store_id'];
$DrugStoreRelations->drug_id = $v['drug_id'];
$DrugStoreRelations->price = $v['price'];
$DrugStoreRelations->buy_price = $v['market_price'] ?? $v['price'];
$DrugStoreRelations->status = $v['status'];
$DrugStoreRelations->saveOrFail();
}
}
//配方
foreach ($DrugStoreDrug_grain as $vv) {
$DrugStoreRelations = DrugStoreRelations::find()->where([
'store_id' => $get['store_id'],
'drug_id' => $vv['drug_id']
])->one();
if (!$DrugStoreRelations) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $get['store_id'];
$DrugStoreRelations->drug_id = $vv['drug_id'];
$DrugStoreRelations->price = bcdiv(bcmul($vv['price'], $store['g_sale_percent']??100, 4), 100, 4);
$DrugStoreRelations->buy_price = bcdiv(bcmul($vv['market_price'], $store['g_bug_percent']??100, 4), 100, 4);
$DrugStoreRelations->status = $vv['status'];
$DrugStoreRelations->saveOrFail();
}
}
//中成药
foreach ($DrugStoreDrug_zongcheng as $vv) {
$DrugStoreRelations_z = DrugStoreRelations::find()->where([
'store_id' => $get['store_id'],
'drug_id' => $vv['drug_id']
])->one();
if (!$DrugStoreRelations_z) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->store_id = $get['store_id'];
$DrugStoreRelations->drug_id = $vv['drug_id'];
$DrugStoreRelations->price = $vv['price'];
$DrugStoreRelations->buy_price = $vv['market_price'] ?? $vv['price'];
$DrugStoreRelations->status = $vv['status'];
$DrugStoreRelations->saveOrFail();
}
}
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
$t->commit();
return ['同步成功'];
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace admin\controllers\dashboard;
use admin\components\BaseAdminController;
use admin\models\forms\statistics\DataForm;
use common\models\Order;
use yii\web\Response;
/**
* @doc-module 工作台
*/
class IndexController extends BaseAdminController
{
/**
* @doc-name 头部数据
* @doc-return mixed @Total_data{@Today{order_num-int-今日订单数,total_pay_price-double-今日支付金额,user_num-int-今日用户数},@Yestoday-mixed-昨日比较{*_status-string-昨日比较up上升down下降equal相等,*_abs-int-差额},@Lastweek-mixed-上周比较{*_status-string-上周比较up上升down下降equal相等,*_abs-int-差额}} 今日数据
* @doc-return mixed @Wait_data{wait_send_num-int-待发货数量,wait_refund_num-int-待处理退款储量} wait数据
*/
public function actionAllData()
{
$form = new DataForm();
$form->attributes = \Yii::$app->request->get();
$form->attributes = \Yii::$app->request->post();
return $form->data_search();
}
/**
* @doc-name 销量排行榜
* @doc-return mixed @Week_top_list{num-int-销量,brand-string-品牌,name-string-商品名称} 近7天
* @doc-return mixed @Mouth_top_list{num-int-销量,brand-string-品牌,name-string-商品名称} 近30天
*/
public function actionSalesTop()
{
$form = new DataForm();
$form->attributes = \Yii::$app->request->get();
$form->attributes = \Yii::$app->request->post();
return $form->sales_top();
}
/**
* @doc-name 图表
* @doc-param string date_start 开始时间YYMMDD
* @doc-param string date_end 开始时间YYMMDD
* @doc-return string created_at 日期
* @doc-return int order_num 订单数量
* @doc-return double total_pay_price 支付金额
* @return mixed
*/
public function actionTable()
{
$form = new DataForm();
$form->attributes = \Yii::$app->request->get();
$form->attributes = \Yii::$app->request->post();
return $form->table_search();
}
}

View File

@@ -0,0 +1,804 @@
<?php
namespace admin\controllers\doctor;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\enums\UserStatusEnum;
use common\helpers\FuncHelper;
use common\models\Department;
use common\models\DoctorInfo;
use common\models\DoctorPracticing;
use common\models\DoctorService;
use common\models\DoctorTitle;
use common\models\Ledger;
use common\models\ProductOrder;
use common\models\Reconciliation;
use common\models\Register;
use common\models\ServiceUser;
use common\models\Store;
use common\models\StoreDoctor;
use GuzzleHttp\Client;
use yii\base\Exception;
use function Symfony\Component\String\s;
class DoctorController extends BaseAdminController
{
/**
* @doc-name 医生列表
* @doc-param int status 状态0待激活1待审核2已认证3拒绝(需要修改激活资料)4全部医生5停用
* @doc-param string name 姓名 / optional
* @doc-param string mobile 电话 / optional
* @doc-param int depart_id 科室id / optional
* @doc-param int title_id 职称id / optional
* @doc-param int identity 身份1中医2西医 / optional
* @doc-param int page 页码 1 optional
* @doc-param int page_size 每页条数 10 optional
* @doc-return mixed @List{ServiceUser{id,is_vip-int-是否平台搜索1否2是,reason-string-拒绝原因,status-int-状态0待激活1待审核2已认证3拒绝(需要修改激活资料),created_at-string-注册时间,updated_at-string-审核通过时间,avator-string-医生头像,is_star-int-是否是名医0否1是,name-string-医生姓名,depart-string-医生科室,hospital_id-int-医院ID,hospital-string-医院,yard-string-院区,title-string-职称,good_at-string-擅长,process-int-用户同步状态0身份审核通过1证书签发2设置签章3用户注销4申请拒绝5用户停用6修改手机号7用户启用9用户删除,note-string-当拒绝时或证书签发时:审核拒绝原因/证书信息,@Service{DoctorService{register_status,register_price},@Practicing{qualification-string-资格证书,practicing-string-执业证书,title-职称证书},@store{store_id-int-门店ID}}} 医生列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['status', 'required']
]);
$name = $get['name'];
$mobile = $get['mobile'];
$depart_id = $get['depart_id'];
$title_id = $get['title_id'];
$identity = $get['identity'];
$admin = \Yii::$app->user->identity;
switch ($get['status']) {
case 0:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => UserStatusEnum::WAIT_JH,
'su.is_delete' => 0
]);
break;
case 1:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => UserStatusEnum::WAIT_SH,
'su.is_delete' => 0
]);
break;
case 2:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => UserStatusEnum::OK,
'su.is_delete' => 0
]);
break;
case 3:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => UserStatusEnum::REFUSED,
'su.is_delete' => 0
]);
break;
case 4://全部医生
//门店
if ($admin->role == UserRoleEnum::STORE_ADMIN) {
$su_id = StoreDoctor::find()->select('su_id')->where([
'store_id' => $admin->store_id,
'is_delete' => 0
])->column();
return ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => [UserStatusEnum::REFUSED, UserStatusEnum::OK, UserStatusEnum::WAIT_SH, UserStatusEnum::FORBID],
'su.is_delete' => 0
])->andWhere(['in', 'su.id', $su_id])->with(['docInfo', 'docPracticing', 'docService'])->asArray()->all();
}
//超管
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => [UserStatusEnum::REFUSED, UserStatusEnum::OK, UserStatusEnum::WAIT_SH, UserStatusEnum::FORBID],
'su.is_delete' => 0
]);
break;
case 5:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => UserStatusEnum::FORBID,
'su.is_delete' => 0
]);
break;
default:
throw new \yii\db\Exception('参数错误');
}
$departs = Department::find()->select('id,name')->where(['<>', 'id', 0])->asArray()->all();
$id = 0;
foreach ($departs as $v) {
if (in_array($depart_id, $v) == true) {
$id = $v['id'];
}
}
$query->joinWith(['docInfo' => function ($q) use ($name, $id, $mobile, $depart_id, $title_id, $identity) {
$q->alias('i');
if (!empty($name)) {//搜索姓名
$q->andWhere(['like', 'i.name', $name]);
}
if (!empty($mobile)) {//手机号
$q->andWhere(['i.mobile' => $mobile]);
}
if (!empty($depart_id)) {//科室
$q->andWhere(['i.depart_id' => $depart_id]);
}
if (!empty($title_id)) {//职称搜索
$q->andWhere(['i.title_id' => $title_id]);
}
if (!empty($identity)) {//身份1中医2西医
$q->andWhere(['i.identity' => $identity]);
}
}]);
$this->field = [
ServiceUser::class => [
'id',
'reason', 'status', 'created_at', 'updated_at',
'depart_id' => 'docInfo.depart_id',
'avator' => 'docInfo.avatar',
'is_star' => 'docInfo.star',
'name' => 'docInfo.name',
'mobile',
'is_sync'=> 'docInfo.is_sync',
'depart' => 'docInfo.depart.name',
'title1' => 'docInfo.title.name',
'intro' => 'docInfo.intro',
'good_at' => 'docInfo.good_at',
'identity' => 'docInfo.identity',
'service' => 'docService',
'practicing' => 'docPracticing',
'idcard' => 'docInfo.idcard',
'store' => function ($m) {
return StoreDoctor::find()->select(['store_id'])->where([
'su_id' => $m->id,
'is_delete' => 0
])->with(['store'])->asArray()->all();
}
],
DoctorService::class => [
'su_id', 'register_status', 'register_price'
],
DoctorPracticing::class => [
'su_id', 'qualification', 'practicing', 'title',
]
];
return $this->create($query, $get);
}
/**
* @doc-name 审核通过操作+拒绝操作(入驻)
* @doc-desc 当status为2时必填reason
* @doc-param int status 状态1审核通过操作2拒绝操作
* @doc-param string reason 拒绝的原因 / optional
* @doc-param int doctor_id 医生id
*/
public function actionIntoCheck()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['status', 'doctor_id'], 'required']
]);
$is_exist = ServiceUser::find()->alias('su')->where([
'id' => $post['doctor_id'],
'su.role' => UserRoleEnum::DOCTOR,
'su.status' => UserStatusEnum::WAIT_SH,
'su.is_delete' => 0
])->one();
switch ($post['status']) {
case 1:
if (!$is_exist) throw new Exception('待审核的医生不存在');
$is_exist->status = UserStatusEnum::OK;
$is_exist->updated_at = time();
$is_exist->saveOrFail();
return ['审核通过'];
case 2:
if (!$is_exist) throw new Exception('医生不存在');
if (empty($post['reason'])) throw new Exception('拒绝的原因不能为空');
$is_exist->status = UserStatusEnum::REFUSED;
$is_exist->updated_at = time();
$is_exist->reason = $post['reason'];
$is_exist->saveOrFail();
return ['拒绝审核'];
default:
throw new \yii\db\Exception('参数错误');
}
}
/**
* @doc-name 医生详情
* @doc-param int doctor_id 医生id
* @doc-return mixed @List{ServiceUser{id,is_vip-int-是否平台搜索1否2是,reason-string-拒绝原因,status-int-状态0待激活1待审核2已认证3拒绝(需要修改激活资料),created_at-string-注册时间,updated_at-string-审核通过时间,avator-string-医生头像,is_star-int-是否是名医0否1是,name-string-医生姓名,depart-string-医生科室,hospital_id-int-医院ID,hospital-string-医院,yard-string-院区,title-string-职称,good_at-string-擅长,process-int-用户同步状态0身份审核通过1证书签发2设置签章3用户注销4申请拒绝5用户停用6修改手机号7用户启用9用户删除,note-string-当拒绝时或证书签发时:审核拒绝原因/证书信息,@Service{DoctorService{register_status,register_price},@Practicing{qualification-string-资格证书,practicing-string-执业证书,title-职称证书},@store{store_id-int-门店ID}}} 医生列表
*/
public function actionInfo()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['doctor_id', 'required']
]);
$doctor = $get['doctor_id'];
$ServiceUser = ServiceUser::find()->alias('su')->where([
'su.id' => $get['doctor_id'],
'su.role' => UserRoleEnum::DOCTOR,
'su.is_delete' => 0
])->with(['docInfo', 'docIdentity', 'docPracticing', 'docService'])
->asArray()->one();
if (!$ServiceUser) throw new Exception('医生不存在');
$ServiceUser['store'] = StoreDoctor::find()->select(['store_id'])->where([
'su_id' => $doctor,
'is_delete' => 0
])->with(['store'])->asArray()->all();
return $ServiceUser;
}
/**
* 医生同步互医审核通过
* @return string[]
* @throws Exception
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function actionSyncDoctor()
{
$serviceUserId = \Yii::$app->request->post('doctor_id');
if(empty($serviceUserId)){
throw new Exception('医生id不能为空');
}
$serviceUser = ServiceUser::find()->where([
'id' => $serviceUserId
])->with('docInfo', 'docIdentity', 'docPracticing')->one();
if (empty($serviceUser) || empty($serviceUser->docInfo) || empty($serviceUser->docIdentity) || empty($serviceUser->docPracticing)) {
throw new Exception('医生信息错误');
}
if($serviceUser->docInfo->is_sync == 2){
throw new Exception('该医生已同步至互医');
}
$params = [
'id' => $serviceUserId,
'store_id' => implode(',', json_decode($serviceUser->docInfo->store_id, true)),
'mobile' => $serviceUser->mobile,
'avatar' => $serviceUser->docInfo->avatar,
'name' => $serviceUser->docInfo->name,
'id_card' => $serviceUser->docInfo->idcard,
'good_at' => $serviceUser->docInfo->good_at,
'intro' => $serviceUser->docInfo->intro,
'card_up' => $serviceUser->docIdentity->card_up,
'card_down' => $serviceUser->docIdentity->card_down,
'work_avatar' => $serviceUser->docIdentity->work_avator,
'qualification' => $serviceUser->docPracticing->qualification,
'practicing' => $serviceUser->docPracticing->practicing,
'title' => $serviceUser->docPracticing->title
];
$response = (new Client(['http_errors' => false]))->post(
\Yii::$app->params['platform']['url'] . "/platform/v1/sync/doctor",
[
'headers' => ['Content-Type' => 'application/json', 'Authorization' => "Bearer " . \Yii::$app->params['platform']['token']],
\GuzzleHttp\RequestOptions::JSON => $params
]
);
$result = json_decode($response->getBody(), true);
if ($result['errcode']) {
throw new Exception($result['msg']);
}
DoctorInfo::updateAll(['is_sync' => 1], ['su_id' => $serviceUserId]);
return ['同步互医完成'];
}
/**
* @doc-name 中西医
* @doc-return array aa bb
*/
public function actionIdentity()
{
return [
['key' => 0, 'value' => '中医'],
['key' => 1, 'value' => '西医'],
];
}
/**
* @doc-name 职称列表
* @doc-return mixed @DoctorTitle{*} 职称
*/
public function actionTitle()
{
return DoctorTitle::find()->all();
}
/**
* @doc-name 医生绑定门店
* @doc-param int doctor_id 医生ID
* @doc-param string store_id 门店
*/
public function actionDocTieStore()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['doctor_id', 'store_id'], 'required']
]);
$store_id = StoreDoctor::find()->select(['store_id'])->where([
'su_id' => $post['doctor_id'],
'is_delete' => 0
])->column();
$ids = explode(',', $post['store_id']);
$tie_id = array_diff($ids, $store_id);//要绑定的
$del_id = array_diff($store_id, $ids);//解除绑定的
$t = \Yii::$app->db->beginTransaction();
try {
if (empty($tie_id) && !empty($del_id)) {
foreach ($del_id as $val) {
\Yii::$app->db->createCommand()->update('yii_store_doctor', ['is_delete' => 1], ['store_id' => $val, 'su_id' => $post['doctor_id']])->execute();
}
} else {
foreach ($tie_id as $v) {
$store_doctor = new StoreDoctor();
$store_doctor->store_id = $v;
$store_doctor->su_id = $post['doctor_id'];
$store_doctor->saveOrFail();
}
}
$DoctorInfo = DoctorInfo::find()->where([
'su_id' => $post['doctor_id']
])->one();
if (!$DoctorInfo) throw new \Exception('医生基本信息未完善');
$DoctorInfo->store_id = '[' . $post['store_id'] . ']';
$DoctorInfo->saveOrFail();
$t->commit();
return ['绑定成功'];
} catch (\Exception $exception) {
$t->rollBack();
throw new \Exception($exception->getMessage());
}
}
/**
* @doc-name 账号停用或恢复
* @doc-param int doctor_id 医生
*/
public function actionAccountForbid()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['doctor_id', 'required']
]);
$ServiceUser = ServiceUser::find()->alias('su')->where([
'id' => $post['doctor_id'],
'su.role' => UserRoleEnum::DOCTOR,
'su.is_delete' => 0
])->andWhere([
'or',
['su.status' => UserStatusEnum::OK],
['su.status' => UserStatusEnum::FORBID],
])->one();
if (!$ServiceUser) throw new \yii\db\Exception('医生不存在或账号非已认证状态!!');
$ServiceUser->status == UserStatusEnum::FORBID ? $ServiceUser->status = UserStatusEnum::OK : $ServiceUser->status = UserStatusEnum::FORBID;
$ServiceUser->saveOrFail();
return ['success'];
}
/**
* @doc-name 门店的医生明细
* @doc-param int store_id 医生
*/
public function actionDoctorDetail()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['store_id', 'required']
]);
$store_id = \Yii::$app->request->get();
$store = Store::find()->where(['id' => $get['store_id']])->one();
if (!$store) {
throw new \yii\db\Exception('门店不存在!!');
}
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time == $end_time) {//筛选当天
$time = FuncHelper::getDayBE($get['start_time']);
$end_time = $time;
}
}
$doctor = StoreDoctor::find()->select('su_id')->where(['store_id' => $get['store_id']])->column();
$query = DoctorInfo::find()->where(['in', 'su_id', $doctor]);
$this->field = [
DoctorInfo::class => [
'su_id',
'name',
'register_price' => function ($r) use ($start_time, $end_time, $store_id) {
return $this->actionRegisterPrice($r->su_id, $store_id, $start_time, $end_time);
},
'drug_sale_price' => function ($r) use ($start_time, $end_time, $store_id) {
return $this->actionDrugSale($r->su_id, $store_id, $start_time, $end_time);
},
'drug_give_price' => function ($r) use ($start_time, $end_time, $store_id) {
return $this->actionDrugGive($r->su_id, $store_id, $start_time, $end_time);
},
'drug_profit_price' => function ($r) use ($start_time, $end_time, $store_id) {
return $this->actionDrugProfit($r->su_id, $store_id, $start_time, $end_time);
},
'treatement_price' => function ($r) use ($start_time, $end_time, $store_id) {
return $this->actionTreatementPrice($r->su_id, $store_id, $start_time, $end_time);
},
'process_price' => function ($r) use ($start_time, $end_time, $store_id) {
return $this->actionProcessPrice($r->su_id, $store_id, $start_time, $end_time);
},
]
];
return $this->create($query, $get);
}
/**
* @doc-name 加工费
* @doc-param int su_id 医生
*/
public function actionProcessPrice($su_id = '', $store_id = '', $start_time = '', $end_time = '')
{
if (!empty($start_time) && !empty($end_time)) {
$get_start_time = date('Y-m-d H:i:s', $start_time);
if ($start_time == $end_time) {//筛选某一天
$time = FuncHelper::getDayBE($get_start_time);
$start_time = strtotime($get_start_time);
$end_time = $time[1];
}
$data = ['between', 'r.xd_time', $start_time, $end_time];
}
$price = Ledger::find()->alias('r')->where(['r.su_id' => $su_id, 'r.user_id' => $store_id, 'r.status' => 1, 'r.user_type' => 1, 'r.order_type' => 1, 'r.fee_type' => 5])->andWhere($data ?? '')->sum('money');
return $price ?? 0;
}
/**
* @doc-name 诊疗费
* @doc-param int su_id 医生
*/
public function actionTreatementPrice($su_id = '', $store_id = '', $start_time = '', $end_time = '')
{
if (!empty($start_time) && !empty($end_time)) {
$get_start_time = date('Y-m-d H:i:s', $start_time);
if ($start_time == $end_time) {//筛选某一天
$time = FuncHelper::getDayBE($get_start_time);
$start_time = strtotime($get_start_time);
$end_time = $time[1];
}
$data = ['between', 'r.xd_time', $start_time, $end_time];
}
$price = Ledger::find()->alias('r')->where(['r.su_id' => $su_id, 'r.user_id' => $store_id, 'r.status' => 1, 'r.user_type' => 1, 'r.order_type' => 1, 'r.fee_type' => 6])->andWhere($data ?? '')->sum('money');
return $price ?? 0;
}
/**
* @doc-name 挂号费
* @doc-param int su_id 医生
*/
public function actionRegisterPrice($su_id = '', $store_id = '', $start_time = '', $end_time = '')
{
if (!empty($start_time) && !empty($end_time)) {
$get_start_time = date('Y-m-d H:i:s', $start_time);
if ($start_time == $end_time) {//筛选某一天
$time = FuncHelper::getDayBE($get_start_time);
$start_time = strtotime($get_start_time);
$end_time = $time[1];
}
$data = ['between', 'r.xd_time', $start_time, $end_time];
}
$price = Ledger::find()->alias('r')->where(['r.su_id' => $su_id, 'r.user_id' => $store_id, 'r.status' => 1, 'r.user_type' => 1, 'r.order_type' => 2])->andWhere($data ?? '')->sum('money');
return $price ?? 0;
}
/**
* @doc-name 药品总销售额
*/
public function actionDrugSale($su_id = null, $store_id = null, $start_time = '', $end_time = '')
{
if (!empty($start_time) && !empty($end_time)) {
$get_start_time = date('Y-m-d H:i:s', $start_time);
if ($start_time == $end_time) {//筛选某一天
$time = FuncHelper::getDayBE($get_start_time);
$start_time = strtotime($get_start_time);
$end_time = $time[1];
}
$data = ['between', 'r.xd_time', $start_time, $end_time];
}
$order_id = ProductOrder::find()->select('id')->where(['su_id' => $su_id, 'is_pay' => 1, 'store_id' => $store_id])->column();
$total_price = Reconciliation::find()->alias('r')->where([
'in', 'r.order_id', $order_id,
'r.status' => 1
])->andWhere($data ?? '')->sum('total_price');
return $total_price ?? 0;
}
/**
* @doc-name 药品总供货金额
*/
public function actionDrugGive($su_id = null, $store_id = null, $start_time = '', $end_time = '')
{
if (!empty($start_time) && !empty($end_time)) {
$get_start_time = date('Y-m-d H:i:s', $start_time);
if ($start_time == $end_time) {//筛选某一天
$time = FuncHelper::getDayBE($get_start_time);
$start_time = strtotime($get_start_time);
$end_time = $time[1];
}
$data = ['between', 'r.xd_time', $start_time, $end_time];
}
$order_id = ProductOrder::find()->select('id')->where(['su_id' => $su_id, 'is_pay' => 1, 'store_id' => $store_id])->column();
//供货金额
$total_buy_price = Reconciliation::find()->alias('r')->where([
'in', 'r.order_id', $order_id,
'r.status' => 1
])->andWhere($data ?? '')->sum('total_buy_price');
return $total_buy_price ?? 0;
}
/**
* @doc-name 药品总利润
*/
public function actionDrugProfit($su_id = null, $store_id = null, $start_time = '', $end_time = '')
{
if (!empty($start_time) && !empty($end_time)) {
$get_start_time = date('Y-m-d H:i:s', $start_time);
if ($start_time == $end_time) {//筛选某一天
$time = FuncHelper::getDayBE($get_start_time);
$start_time = strtotime($get_start_time);
$end_time = $time[1];
}
$data = ['between', 'r.xd_time', $start_time, $end_time];
}
$order_id = ProductOrder::find()->select('id')->where(['su_id' => $su_id, 'is_pay' => 1, 'store_id' => $store_id])->column();
//销售额
$total_price = Reconciliation::find()->alias('r')->where([
'in', 'r.order_id', $order_id,
'r.status' => 1
])->andWhere($data ?? '')->sum('total_price');
//供货金额
$total_buy_price = Reconciliation::find()->alias('r')->where([
'in', 'r.order_id', $order_id,
'r.status' => 1
])->andWhere($data ?? '')->sum('total_buy_price');
$profit = bcsub($total_price, $total_buy_price, 4);
return $profit ?? 0;
}
/**
* @doc-name 门诊收入药品销售
*/
public function actionStoreIncomeDrugSale()
{
$get = \Yii::$app->request->get();
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
}
$user = \Yii::$app->user->identity;
$query = ProductOrder::find()->alias('p');
// $Reconciliation_query = Reconciliation::find()->alias('r');
$Ledger_query = Ledger::find()->alias('re')->where(['order_type' => 2, 'status' => [0, 1]]);
$month_start = strtotime(date('Y-m-01 00:00:00'));
$month_end = strtotime(date('Y-m-t 23:59:59'));
if (!empty($start_time) && !empty($end_time)) {
$data = ['between', 'p.created_at', $start_time, $end_time];
}
// if (!empty($start_time) && !empty($end_time)) {
// $datas = ['between', 'r.xd_time', $start_time, $end_time];
// }
if (!empty($start_time) && !empty($end_time)) {
$register_data = ['between', 're.xd_time', $start_time, $end_time];
}
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$query->andWhere(['p.store_id' => $user->store_id]);
// $Reconciliation_query->andWhere(['r.store_id' => $user->store_id, 'r.status' => 1]);
$Ledger_query->andWhere(['re.user_id' => $user->store_id]);
}
//订单销售
$order_sale = $query->andWhere([
'and',
['<>', 'p.refund_status', 3],
['<>', 'p.status', '4'],
['=', 'p.is_pay', 1],
])->andWhere($data ?? '')->sum('total_pay_price');
$order_id = $query->andWhere([
'and',
['<>', 'p.refund_status', 3],
['<>', 'p.status', '4'],
['=', 'p.is_pay', 1],
])->column();
$price = 0;
if ($user->role == UserRoleEnum::STORE_ADMIN) {
foreach ($order_id as $val) {
$Ledger = Ledger::find()->alias('re')->where(['re.user_id' => $user->store_id, 'order_id' => $val, 'order_type' => 1, 'status' => [0, 1]])->all();
foreach ($Ledger as $v) {
$price_data[] = $v['money'];
$price += $v['money'];
}
}
} else {
foreach ($order_id as $val) {
$Ledger = Ledger::find()->alias('re')->where(['order_id' => $val, 'order_type' => 1, 'status' => [0, 1]])->all();
foreach ($Ledger as $v) {
$price_data[] = $v['money'];
$price += $v['money'];
}
}
}
$register_price_data = $Ledger_query->select('money')->andWhere($register_data ?? '')->column();
$register_price = $Ledger_query->andWhere($register_data ?? '')->sum('money');
//利润
$profit = bcadd($price, $register_price, 4);
return [
'order_sale' => $order_sale ?? 0,
'store_income' => $profit ?? 0,
'register_price' => $register_price ?? 0,
'register_price_data' => $register_price_data,
'price' => $price ?? 0,//利润
'price_data' => $price_data,
];
}
/**
* @doc-name 平台门诊收入药品销售
*/
public function actionPlatformStoreIncomeDrugSale()
{
$get = \Yii::$app->request->get();
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
}
$data = [];
if (!empty($start_time) && !empty($end_time)) {
$data = ['between', 'created_at', $start_time, $end_time];
}
$where = [];
$admin = \Yii::$app->user->identity;
if($admin->store_id){
$where['store_id'] = $admin->store_id;
}
$total=ProductOrder::find()->where([
'and',
['<>', 'refund_status', 3],
['=', 'is_pay', 1],
['<>', 'status', '4'],
])->andWhere($data)->andWhere($where)->select('sum(total_pay_price) as total_sale_price,sum(market_price+trans_expenses+process_price) as total_market_price')->asArray()->one();
// $register_price = 0;
// $order_sale = 0;
// $all_price = 0;
// $all_store = ProductOrder::find()->alias('p')->select('p.store_id')->andWhere([
// 'and',
// ['<>', 'p.refund_status', 3],
// ['=', 'p.is_pay', 1],
// ['<>', 'p.status', '4'],
// ])->andWhere($data ?? '')->groupBy('store_id')->column();
// foreach ($all_store as $key => $value) {
// //订单销售
// $order_sale = ProductOrder::find()->alias('p')->andWhere([
// 'and',
// ['<>', 'p.refund_status', 3],
// ['=', 'p.is_pay', 1],
// ['=','p.store_id' ,$value],
// ['<>', 'p.status', '4'],
// ])->andWhere($data ?? '')->sum('total_pay_price');
// $order_id = ProductOrder::find()->alias('p')->andWhere([
// 'and',
// ['<>', 'p.refund_status', 3],
// ['<>', 'p.status', '4'],
// ['=', 'p.is_pay', 1],
// ['=','p.store_id' ,$value],
// ])->andWhere($data ?? '')->column();
// foreach ($order_id as $val) {
// $all_price += Ledger::find()->alias('re')->andWhere(['re.user_id' => $value,'re.user_type'=>1, 'order_id' => $val, 'order_type' => 1, 'status' => [0, 1]])->sum('money');
// }
// $register_price += Ledger::find()->alias('re')->where(['re.order_type' => 2 ,'re.user_type'=>1,'status' => [0, 1]])->andWhere(['re.user_id' => $value])->andWhere($register_data ?? '')->sum('money');
// }
// //利润
// $profit = bcadd($all_price, $register_price, 4);
return [
'order_sale' => $total['total_sale_price'] ?? 0,
'store_income' => bcsub($total['total_sale_price'],$total['total_market_price'],4),
];
}
}

View File

@@ -0,0 +1,236 @@
<?php
namespace admin\controllers\doctor;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\enums\UserStatusEnum;
use common\models\Department;
use common\models\PharmacistrInfo;
use common\models\ServiceUser;
/**
* 药师
*/
class PharmacistController extends BaseAdminController
{
/**
* @doc-name 药师列表
* @doc-param int status 状态0待激活1待审核2已认证3拒绝(需要修改激活资料)4全部药师
* @doc-param string name 姓名 / optional
* @doc-param string mobile 电话 / optional
* @doc-param int depart_id 科室id / optional
* @doc-param int title_id 职称id / optional
* @doc-param int identity 身份1中医2西医 / optional
* @doc-return mixed @List{ServiceUser{id,reason-string-拒绝原因,status-int-状态0待激活1待审核2已认证3拒绝(需要修改激活资料),created_at-string-注册时间,updated_at-string-审核通过时间,identity-string-身份1中医2西医,avatar-string-药师头像,name-string-药师姓名,mobile-string-药师电话,depart-string-药师科室,title-string-职称,type-int-1初审2复审,@Identity{sign_type-string-签章类型1电子2手写,sign_image-string-签章图片},@DrugPracticing{qualification-string-资格证书}}}} 药师列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionList()
{
$post = \Yii::$app->request->get();
$this->requestValidate($post,[
['status','required']
]);
$name=$post['name'];
$mobile=$post['mobile'];
$depart_id=$post['depart_id'];
$title_id=$post['title_id'];
$identity=$post['identity'];
switch ($post['status']){
case 0:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DRUG,
'su.status' => UserStatusEnum::WAIT_JH,
'su.is_delete' => 0
]);
break;
case 1:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DRUG,
'su.status' => UserStatusEnum::WAIT_SH,
'su.is_delete' => 0
]);
break;
case 2:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DRUG,
'su.status' => UserStatusEnum::OK,
'su.is_delete' => 0
]);
break;
case 3:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DRUG,
'su.status' => UserStatusEnum::REFUSED,
'su.is_delete' => 0
]);
break;
case 4:
$query = ServiceUser::find()->alias('su')->where([
'su.role' => UserRoleEnum::DRUG,
'su.status' =>[ UserStatusEnum::REFUSED,UserStatusEnum::OK, UserStatusEnum::WAIT_SH],
'su.is_delete' => 0
]);
break;
default:
throw new \yii\db\Exception('参数错误');
}
$departs = Department::find()->select('id,name')->where(['<>', 'id', 0])->asArray()->all();
$id = 0;
foreach ($departs as $v) {
if (in_array($depart_id, $v) == true) {
$id = $v['id'];
}
}
$query->joinWith(['drugInfo' => function ($q) use ($name,$id,$mobile, $depart_id, $title_id,$identity) {
$q->alias('d');
if (!empty($name)) {//搜索姓名
$q->andWhere(['like', 'd.name', $name]);
}
if (!empty($mobile)) {//手机号
$q->andWhere(['d.mobile'=>$mobile]);
}
if (!empty($depart_id)) {//科室
$q->andWhere(['d.depart_id'=>$depart_id]);
}
if (!empty($title_id)) {//职称搜索
$q->andWhere(['d.title_id' => $title_id]);
}
if (!empty($identity)) {//身份1中医2西医
$q->andWhere(['d.identity' => $identity]);
}
}]);
$this->field = [
ServiceUser::class => [
'id','reason','status','created_at','updated_at',
'identity'=>'drugInfo.identity',
'depart_id'=>'drugInfo.depart_id',
'avatar' => 'drugInfo.avatar',
'name' => 'drugInfo.name',
'mobile',
'depart' => 'drugInfo.depart.name',
'title1' => 'drugInfo.titles.name',
'drugIdentity' => 'drugIdentity',
'drugPracticing' => 'drugPracticing',
'type'=>'drugInfo.type',
'id_card'=>'drugInfo.idcard'
],
];
return $this->create($query, $post);
}
/**
* @doc-name 药师审核通过操作+拒绝操作(入驻)
* @doc-desc 当status为2时必填reason
* @doc-param int status 状态1审核通过2拒绝操作
* @doc-param string reason 拒绝的原因 / optional
* @doc-param int drug_id 药师id
*/
public function actionIntoCheck()
{
$post = \Yii::$app->request->get();
$this->requestValidate($post,[
[['status','drug_id'],'required']
]);
$is_exist = ServiceUser::find()->alias('su')->where([
'id'=>$post['drug_id'],
'su.role' => UserRoleEnum::DRUG,
'su.status' => UserStatusEnum::WAIT_SH,
'su.is_delete' => 0
])->one();
switch ($post['status']){
case 1:
if (!$is_exist){
throw new \Exception('药师不存在');
}
$is_exist->status=UserStatusEnum::OK;
$is_exist->updated_at=time();
if (!$is_exist->saveOrFail()){
throw new \Exception('error');
}
return ['药师审核通过'];
case 2:
if (!$is_exist){
throw new \Exception('药师不存在');
}
if (empty($post['reason'])){
throw new \Exception('拒绝原因不能为空');
}
$is_exist->status=UserStatusEnum::REFUSED;
$is_exist->updated_at=time();
$is_exist->reason=$post['reason'];
$is_exist->saveOrFail();
return ['药师审核拒绝'];
default:
throw new \yii\db\Exception('参数错误');
}
}
/**
* @doc-name 药师详情
* @doc-param int drug_id 药师id
*/
public function actionInfo()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post,[
['drug_id','required']
]);
$ServiceUser = ServiceUser::find()->alias('su')->where([
'id'=>$post['drug_id'],
'su.role' => UserRoleEnum::DRUG,
'su.is_delete' => 0
])->with(['drugInfo','drugIdentity','drugPracticing'])->asArray()->one();
if (!$ServiceUser){
throw new \Exception('药师不存在');
};
return $ServiceUser;
}
/**
* @doc-name 设置药师初审或复审
* @doc-param int drug_id 药师ID
* @doc-param int type 1初审2复审
*/
public function actionSetFirstAgain()
{
$get= \Yii::$app->request->get();
$this->requestValidate($get,[
[['drug_id','type'],'required']
]);
$ServiceUser = ServiceUser::find()->alias('su')->where([
'id'=>$get['drug_id'],
'su.role' => UserRoleEnum::DRUG,
'status'=>UserStatusEnum::OK,
'su.is_delete' => 0
])->one();
if (!$ServiceUser){
throw new \Exception('药师不存在');
}
$PharmacistrInfo=PharmacistrInfo::find()->where([
'su_id'=>$get['drug_id']
])->one();
if (!$PharmacistrInfo){
throw new \Exception('药师没完善信息');
}
$PharmacistrInfo->type=$get['type'];
$PharmacistrInfo->saveOrFail();
return ['设置成功'];
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace admin\controllers\drug;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\ChineseForm;
use admin\models\forms\drug\ImportForm;
use common\models\SystemConfig;
use moonland\phpexcel\Excel;
use yii\db\Exception;
use yii\web\UploadedFile;
/**
* @doc-module 中药饮片库
*/
class ChineseController extends BaseAdminController
{
/**
* @doc-name 煎法列表
*/
public function actionDecotion()
{
return [
['key'=>0,'value'=>'先煎'],
['key'=>1,'value'=>'后下'],
];
}
/**
* @doc-name 新增中药
* @doc-param string drug_name 药名
* @doc-param string pinyin_simple 拼音首拼
* @doc-param string drug_number 编号
* @doc-param string drug_alias 别名 / optional
* @doc-param int unit_id 单位
* @doc-param int status 状态1草稿2下架3上架
* @doc-param string place 产地 / optional
* @doc-param string instruction 说明书图片 / optional
* @doc-param json drugstore[{"drugstore_id":1,"price":100,"type":1,"stock":100},{"drugstore_id":2,"price":100,"type":1,"stock":200}] 仓库
*/
public function actionSave()
{
$post=\Yii::$app->request->post();
$ChineseForm=new ChineseForm();
$ChineseForm->attributes=$post;
return $ChineseForm->save();
}
/**
* @doc-name 修改中药
* @doc-param int id 药品ID
* @doc-param string drug_name 药名 / optional
* @doc-param string pinyin_simple 拼音首拼 / optional
* @doc-param string drug_number 编号/ optional
* @doc-param string drug_alias 别名 / optional
* @doc-param int unit_id 单位 / optional
* @doc-param int status 状态1草稿2下架3上架 / optional
* @doc-param string place 产地 / optional
* @doc-param string instruction 说明书图片 / optional
*/
public function actionUpdate()
{
$post=\Yii::$app->request->post();
$this->requestValidate($post,[
['id','required']
]);
$ChineseForm=new ChineseForm();
$ChineseForm->attributes=$post;
return $ChineseForm->update();
}
/**
* @doc-name 查看中药
* @doc-param int id 药品ID
*/
public function actionInfo()
{
$get=\Yii::$app->request->get();
$this->requestValidate($get,[
['id','required']
]);
$ChineseForm=new ChineseForm();
$ChineseForm->attributes=$get;
return $ChineseForm->info();
}
/**
* @doc-name 导入中药
* @doc-param file file 文件
*/
public function actionChineseImport()
{
$request = \Yii::$app->request;
if ($request->isPost) {
//设置最大执行时间
ini_set("max_execution_time", "360");
$file = UploadedFile::getInstanceByName('file');
if ($file->size > 5 * 1024 * 1024) {
return ['excel文件不能超过5M!'];
}
//文件名
$filename = date('His') . $file->getBaseName() . mt_rand(1000, 9999) . '.' . $file->getExtension();
//保存文件
$file->saveAs( $filename);
$data = Excel::import($filename, [
'setFirstRecordAsKeys' => true,
'getOnlySheet' => 'Sheet1',
]);
$ImportForm=new ImportForm();
return $ImportForm->ChineseImport($data);
} else {
throw new Exception('请求方式错误');
}
}
/**
* @doc-name 设置代煎费
* @doc-param int value 值
* @doc-param int type 类型1中药2西药3配方颗粒
* @doc-param int id id
*/
public function actionDaijianPrice()
{
$post=\Yii::$app->request->post();
$this->requestValidate($post,[
[['id','type','value'],'required']
]);
$t=\Yii::$app->db->beginTransaction();
$SystemConfig=SystemConfig::find()->where([
'id'=>$post['id'],'config_type'=>1,'type'=>$post['type']
])->one();
if (!$SystemConfig) throw new Exception('配置不存在');
$SystemConfig->value=$post['value'];
if (!$SystemConfig->saveOrFail()){
$t->rollBack();
throw new Exception('设置失败');
}
$t->commit();
return ['设置成功'];
}
/**
* @doc-name 配置
* @doc-return mixed @List{id,name-string-name,config-int-配置类型1代煎费配置2包邮配置,type-int-类型1中药3配方颗粒,value-int-值} 配置
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionSystemConfig()
{
$get = \Yii::$app->request->get();
$query = SystemConfig::find();
$this->field = [
SystemConfig::class => [
'id', 'name', 'type', 'value','config_type','rule'
]
];
return $this->create($query, $get);
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace admin\controllers\drug;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\DrugCategoryForm;
use common\models\DrugCategories;
class DrugCategoryController extends BaseAdminController
{
/**
* @doc-name 药品分类列表
* @doc-param string name 名字 / optional
* @doc-return mixed @List{id,category_name-string-分类,parent_id-int-父级id,level-int-等级,sort-int-排序,child_cate-string-子级分类} 列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionDrugList()
{
$get= \Yii::$app->request->get();
$query = DrugCategories::find()->where([
'deleted_at' => null
]);
if (!empty($get['name'])){
$query->andWhere([
'like','category_name',$get['name']
]);
}
$this->field = [
DrugCategories::class => [
'id', 'category_name',
// 'child_category' => 'child',
'parent_id', 'level', 'sort',
],
];
return $this->create($query, $get);
}
/**
* @doc-name 药品分类新增
* @doc-param string category_name 名字
* @doc-param int level 级别
* @doc-param int pid 父级id / optional
* @doc-param int sort 排序
*/
public function actionSave()
{
$post = \Yii::$app->request->post();
$DrugCategoryForm = new DrugCategoryForm();
$DrugCategoryForm->attributes = $post;
return $DrugCategoryForm->save();
}
/**
* @doc-name 药品分类修改
* @doc-param int id ID
* @doc-param string category_name 名字
* @doc-param int level 级别
* @doc-param int pid 父级id / optional
* @doc-param int sort 排序
*/
public function actionUpdate()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id', 'required']
]);
$DrugCategoryForm = new DrugCategoryForm();
$DrugCategoryForm->attributes = $post;
return $DrugCategoryForm->update();
}
/**
* @doc-name 药品分类删除
* @doc-param int id 药品分类id
*/
public function actionDelete()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['id', 'required']
]);
$DrugCategoryForm = new DrugCategoryForm();
$DrugCategoryForm->attributes = $get;
return $DrugCategoryForm->del();
}
/**
* @doc-name 药品分类查看详情
* @doc-param int id 药品分类id
*/
public function actionInfo()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['id', 'required']
]);
$DrugCategoryForm = new DrugCategoryForm();
$DrugCategoryForm->attributes = $get;
return $DrugCategoryForm->info();
}
}

View File

@@ -0,0 +1,477 @@
<?php
namespace admin\controllers\drug;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\DrugForm;
use admin\models\forms\drug\ImportForm;
use common\enums\UserRoleEnum;
use common\helpers\FuncHelper;
use common\models\Drug;
use common\models\DrugUseFrequency;
use common\models\DrugUseTime;
use common\models\DrugUseType;
use common\models\DrugUseWay;
use common\models\Prescription;
use common\models\WestUnit;
use common\services\ExportService;
use moonland\phpexcel\Excel;
use yii\db\Exception;
use yii\web\Response;
use yii\web\UploadedFile;
class DrugController extends BaseAdminController
{
/**
* @doc-name 药品类别列表
*/
public function actionTypeList()
{
return [
['key' => 0, 'value' => '中药'],
['key' => 1, 'value' => '西药'],
['key' => 2, 'value' => '颗粒配方'],
['key' => 3, 'value' => '中成药'],
];
}
/**
* @doc-name 中药的煎熬方式
*/
public function actionUseWay()
{
return DrugUseWay::find()->all();
}
/**
* @doc-name 药使用时间
*/
public function actionUseTime()
{
return DrugUseTime::find()->all();
}
/**
* @doc-name 药的使用频率
*/
public function actionUseFrequency()
{
return DrugUseFrequency::find()->all();
}
/**
* @doc-name 药的使用方式
*/
public function actionUseType()
{
return DrugUseType::find()->all();
}
/**
* @doc-name 西药单位
*/
public function actionWestUnit()
{
return WestUnit::find()->all();
}
/**
* @doc-name 药品基本信息列表
* @doc-param int status 状态类型1中药2西药3颗粒配方5全部列表
* @doc-param string name 搜素药名、编号、条形码、厂家、中西药标签、拼音首拼、别名
* @doc-return mixed @List{id,drug_name-string-药名,drug_number-string-编号,drug_alias-string-别名,bar_code-string-条形码,guozi_no-string-国字准号,category_first-int-一级分类,category_second-int-二级分类,source-string-货源(厂家),function-string-功能主治,decotion-string-煎法,is_otc-int-是否处方药,usage-string-用法,specification-string-规格,instruction-string-说明书图片,image-string-药品图片,time-string-使用时间,use_type-string-使用方法,frequency-string-频率,unit-string-单位,small_info-string-简介,info-string-基础信息,content-string-详情信息,status-int-状态1草稿2下架3上架,is_shalving-int-状态1下架2上架,stock-int-库存,store-int-门店,type-int-类别1中药2西药3颗粒配方4中成药} 药品列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionList()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['status', 'required']
]);
if (!empty($get['start_time']) && !empty($get['end_time'])) {
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
}
$query = Drug::find()->alias('d')->orderBy(['id' => SORT_ASC]);
$user = \Yii::$app->user->identity;
if ($user->role == UserRoleEnum::STORE_ADMIN) { //门店
$query->joinWith(['drugStoreRelationes' => function ($drug) use ($user) {
$drug->alias('ds');
$drug->andWhere(['ds.store_id' => $user->store_id,'ds.is_forbid'=>0,'ds.status'=>2]);
}]);
}
switch ($get['status']) {
case 1:
$query->andWhere(['d.type' => 1]);
break;
case 2:
$query->andWhere(['d.type' => 2]);
break;
case 3:
$query->andWhere(['d.type' => 3]);
break;
case 4:
$query->andWhere(['d.type' => 4]);
break;
case 5:
$query->andWhere(['d.type' => [1, 2, 3, 4]]);
break;
default:
throw new Exception('参数错误');
}
if (!empty($get['name'])) {
$query->andWhere([
'or',
['like', 'drug_name', $get['name']],
['like', 'drug_number', $get['name']],
['like', 'bar_code', $get['name']],
['like', 'source', $get['name'] ],
['like', 'pinyin_simple', $get['name'] ],
['like', 'drug_alias', $get['name'] ],
]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time==$end_time){//筛选当天
$time=FuncHelper::getDayBE($get['start_time']);
$end_time=$time;
}
$query->andWhere(['between', 'd.created_at', $start_time,$end_time]);
}
// if (!empty($get['drug_name'])) {
// $query->andWhere(['like', 'drug_name', $get['drug_name']]);
// }
// if (!empty($get['drug_number'])) {
// $query->andWhere(['like', 'drug_number', $get['drug_number']]);
// }
// if (!empty($get['bar_code'])) {
// $query->andWhere(['like', 'bar_code', $get['bar_code']]);
// }
// if (!empty($get['source'])) {
// $query->andWhere(['like', 'source', $get['source']]);
// }
if (!empty($get['type'])) {
$query->andWhere(['type' => $get['type']]);
}
$this->field = [
Drug::class => [
'id', 'pinyin_simple', 'drug_name', 'source', 'type', 'is_otc', 'category_first', 'category_second', 'small_info', 'info', 'content', 'usage', 'specification', 'image', 'status', 'drug_number', 'drug_alias', 'bar_code', 'guozi_no', 'place', 'function', 'instruction', 'decotion_id' => 'decotion', 'decotion' => 'drugUseWay.name', 'unit' => 'unit.name',
'store' => 'drugStoreRelationes.store_id',
'price' => 'drugStoreRelationes.price',
'buy_price' => 'drugStoreRelationes.buy_price',
'stock' => 'drugStoreRelationes.drugStoreDrug.stock',
'is_shalving' => 'drugStoreRelationes.status',
'type_id', 'frequency_id', 'unit_id', 'time_id',
'use_frequency' => 'drugUseFrequency.name', 'use_type' => 'drugUseType.name',
'use_time' => 'drugUseTime.name',
'is_forbid'=>'drugStoreRelationes.is_forbid',
],
];
return $this->create($query, $get);
}
/**
* @doc-name 基础商品库列表
* @doc-param string drug_name 药名 / optional
* @doc-param string drug_number 编号 / optional
* @doc-param string bar_code 条形码 / optional
* @doc-param int category_first 一级分类 / optional
* @doc-param int category_second 二级分类 / optional
* @doc-param string source 厂家 / optional
* @doc-param int type 中西药标签 / optional
* @doc-return mixed @List{id,drug_name-string-药名,drug_number-string-编号,drug_alias-string-别名,bar_code-string-条形码,guozi_no-string-国字准号,category_first-int-一级分类,category_second-int-二级分类,source-string-货源(厂家),function-string-功能主治,decotion-string-煎法,is_otc-int-是否处方药,usage-string-用法,specification-string-规格,instruction-string-说明书图片,image-string-药品图片,time-string-使用时间,use_type-string-使用方法,frequency-string-频率,unit-string-单位,small_info-string-简介,info-string-基础信息,content-string-详情信息,status-int-状态1草稿2下架3上架,type-int-类别1中药2西药3颗粒配方4中成药} 药品列表
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionBaseGood()
{
$get = \Yii::$app->request->get();
$query = Drug::find()->alias('d');
if (!empty($get['drug_name'])) {
$query->andWhere(['like', 'drug_name', $get['drug_name']]);
}
if (!empty($get['drug_number'])) {
$query->andWhere(['like', 'drug_number', $get['drug_number']]);
}
if (!empty($get['bar_code'])) {
$query->andWhere(['like', 'bar_code', $get['bar_code']]);
}
if (!empty($get['category_first'])) {
$query->andWhere(['category_first' => $get['category_first']]);
}
if (!empty($get['category_second'])) {
$query->andWhere(['category_second' => $get['category_second']]);
}
if (!empty($get['source'])) {
$query->andWhere(['like', 'source', $get['source']]);
}
if (!empty($get['type'])) {
$query->andWhere(['type' => $get['type']]);
}
$this->field = [
Drug::class => [
'id', 'pinyin_simple', 'drug_name', 'source', 'type', 'is_otc', 'category_first', 'category_second', 'small_info', 'info', 'content', 'usage', 'specification', 'image', 'status', 'drug_number', 'drug_alias', 'bar_code', 'guozi_no', 'place', 'function', 'instruction', 'decotion_id' => 'decotion', 'decotion' => 'drugUseWay.name', 'unit' => 'unit.name', 'time_id', 'type_id', 'frequency_id', 'unit_id',
'use_frequency' => 'drugUseFrequency.name', 'use_type' => 'drugUseType.name',
'use_time' => 'drugUseTime.name',
],
];
return $this->create($query, $get);
}
/**
* @doc-name 导出基础药品
*/
public function actionExportDrug()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params=\Yii::$app->request->get();
$parameter['header']=['ID','药名','拼音首拼','货源(厂家)','类型','是否处方药','详情信息','用法','功能主治','规格','药品编号','条形码','国字准号','药品别名','状态'];
$parameter['data']=Drug::inventory($params);
ExportService::ExportByCors($parameter);
}
/**
* @doc-name 新增西药/或中成药
* @doc-param string drug_name 药名
* @doc-param string pinyin_simple 拼音首拼
* @doc-param int is_otc 是否处方药
* @doc-param string drug_number 编号
* @doc-param string bar_code 条形码
* @doc-param string specification 规格
* @doc-param string guozi_no 国字准号
* @doc-param string function 功能主治
* @doc-param string source 厂家
* @doc-param string instruction['1','2'] 说明书图片
* @doc-param json image['1','2'] 药品图片
* @doc-param int type 分类类型1中药2西药3颗粒配方4中成药
* @doc-param int status 状态1草稿2下架3上架
* @doc-param int unit_id 单位 / optional
* @doc-param int frequency_id 频次
* @doc-param int type_id 方法 / optional
* @doc-param int time_id 时间 / optional
* @doc-param string drug_alias 别名 / optional
* @doc-param string usage 用法
*/
public function actionSave()
{
$post = \Yii::$app->request->post();
$DrugForm = new DrugForm();
$DrugForm->attributes = $post;
return $DrugForm->save();
}
/**
* @doc-name 基础药品上下架
* @doc-param int id 药品ID
* @doc-param int type 类型类型1中药2西药3颗粒配方
*/
public function actionIsSale()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
[['id', 'type', 'status'], 'required']
]);
$DrugForm = new DrugForm();
$DrugForm->attributes = $get;
return $DrugForm->IsSale();
}
/**
* @doc-name 基础药品-草稿
* @doc-param int id 药品ID
* @doc-param int type 类型类型1中药2西药3颗粒配方
*/
public function actionDraft()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
[['id', 'type'], 'required']
]);
$DrugForm = new DrugForm();
$DrugForm->attributes = $get;
return $DrugForm->Draft();
}
/**
* @doc-name 修改西药/或中成药
* @doc-param int id 药品ID
* @doc-param string drug_name 药名
* @doc-param int is_otc 是否处方药
* @doc-param string drug_number 编号
* @doc-param string bar_code 条形码
* @doc-param string specification 规格
* @doc-param string guozi_no 国字准号
* @doc-param string function 功能主治
* @doc-param string source 厂家
* @doc-param string place 产地 / optional
* @doc-param int category_first 一级分类
* @doc-param int category_second 二级分类
* @doc-param string instruction['1','2'] 说明书图片
* @doc-param json image['1','2'] 药品图片
* @doc-param int type 分类类型1中药2西药3颗粒配方4中成药
* @doc-param int unit_id 单位
* @doc-param int frequency_id 频次
* @doc-param int type_id 方法
* @doc-param int time_id 时间
* @doc-param string drug_alias 别名 / optional
* @doc-param string usage 用法
*/
public function actionUpdate()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id', 'required']
]);
$DrugForm = new DrugForm();
$DrugForm->attributes = $post;
return $DrugForm->update();
}
/**
* @doc-name 查看详情(西药)
* @doc-param int id 药品ID
* @doc-param int type 类型1中药2西药3颗粒配方4中成药
*/
public function actionInfo()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
[['id', 'type'], 'required']
]);
$DrugForm = new DrugForm();
$DrugForm->attributes = $get;
return $DrugForm->info();
}
/**
* @doc-name 导入西药
* @doc-param file file 文件
*/
public function actionImport()
{
$request = \Yii::$app->request;
if ($request->isPost) {
$post = \Yii::$app->request->post();
//设置最大执行时间
ini_set("max_execution_time", "360");
$file = UploadedFile::getInstanceByName('file');
if ($file->size > 5 * 1024 * 1024) {
return ['excel文件不能超过5M!'];
}
// $relative_path = 'excel/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
// $absolute_path = rtrim(\Yii::$app->params['upload_dir'], '/') . '/' . $relative_path;
// if (!file_exists($absolute_path)) {
// try {
// FileHelper::createDirectory($absolute_path, 0777, true);
// } catch (\Exception $e) {
// return ['errno' => 0, 'msg' => '目录创建失败,' . $e->getMessage()];
// }
// }
//文件名
$filename = date('His') . md5($file->getBaseName()) . mt_rand(1000, 9999) . '.' . $file->getExtension();
//保存文件
$file->saveAs($filename);
// $fullFileName = $absolute_path . $filename;
$data = Excel::import($filename, [
'setFirstRecordAsKeys' => true,
'getOnlySheet' => 'Sheet1',
]);
$ImportForm = new ImportForm();
$ImportForm->attributes = $post;
return $ImportForm->WestImport($data);
} else {
throw new Exception('请求方式错误');
}
}
/**
* @doc-name 导入中成药
* @doc-param file file 文件
*/
public function actionImportZhongcheng()
{
$request = \Yii::$app->request;
if ($request->isPost) {
$post = \Yii::$app->request->post();
//设置最大执行时间
ini_set("max_execution_time", "360");
$file = UploadedFile::getInstanceByName('file');
if ($file->size > 5 * 1024 * 1024) {
return ['excel文件不能超过5M!'];
}
//文件名
$filename = date('His') . md5($file->getBaseName()) . mt_rand(1000, 9999) . '.' . $file->getExtension();
//保存文件
$file->saveAs($filename);
// $fullFileName = $absolute_path . $filename;
$data = Excel::import($filename, [
'setFirstRecordAsKeys' => true,
'getOnlySheet' => 'Sheet1',
]);
$ImportForm = new ImportForm();
$ImportForm->attributes = $post;
return $ImportForm->ImportZhongcheng($data);
} else {
throw new Exception('请求方式错误');
}
}
/**
* @doc-name 单位列表
*/
public function actionUnit()
{
return WestUnit::find()->all();
}
/**
* @doc-name 仓库导入药品
*/
public function actionExportReal()
{
$request = \Yii::$app->request;
if ($request->isPost) {
$post = \Yii::$app->request->post();
//设置最大执行时间
ini_set("max_execution_time", "360");
$file = UploadedFile::getInstanceByName('file');
if ($file->size > 5 * 1024 * 1024) {
return ['excel文件不能超过5M!'];
}
//文件名
$filename = date('His') . md5($file->getBaseName()) . mt_rand(1000, 9999) . '.' . $file->getExtension();
//保存文件
$file->saveAs($filename);
// $fullFileName = $absolute_path . $filename;
$data = Excel::import($filename, [
'setFirstRecordAsKeys' => true,
'getOnlySheet' => 'Sheet1',
]);
$ImportForm = new ImportForm();
$ImportForm->attributes = $post;
return $ImportForm->ExportRealDrug($data);
} else {
throw new Exception('请求方式错误');
}
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace admin\controllers\drug;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\forms\drug\GranularForm;
use admin\models\forms\drug\ImportForm;
use moonland\phpexcel\Excel;
use yii\web\UploadedFile;
/**
* @doc-module 配方颗粒库
*/
class GranularController extends BaseAdminController
{
/**
* @doc-name 新增配方颗粒库
* @doc-param string drug_name 药名
* @doc-param string pinyin_simple 拼音首拼
* @doc-param string drug_number 编号
* @doc-param string drug_alias 别名
* @doc-param int unit_id 单位
* @doc-param int status 状态1草稿2下架3上架
* @doc-param string place 产地 / optional
* @doc-param string instruction 说明书图片 / optional
* @doc-param json drugstore[{"drugstore_id":1,"price":100,"type":1,"stock":100},{"drugstore_id":2,"price":100,"type":1,"stock":200}] 仓库
*/
public function actionSave()
{
$post=\Yii::$app->request->post();
$GranularForm=new GranularForm();
$GranularForm->attributes=$post;
return $GranularForm->save();
}
/**
* @doc-name 删除配方颗粒库
* @doc-param int id 药品ID
*/
public function actionDelete()
{
$post=\Yii::$app->request->post();
$this->requestValidate($post,[
['id','required']
]);
$GranularForm=new GranularForm();
$GranularForm->attributes=$post;
return $GranularForm->del();
}
/**
* @doc-name 修改配方颗粒库
* @doc-param int id 药品ID
* @doc-param string drug_name 药名
* @doc-param string pinyin_simple 拼音首拼
* @doc-param string drug_number 编号
* @doc-param string drug_alias 别名
* @doc-param int unit_id 单位
* @doc-param string place 产地 / optional
* @doc-param string instruction 说明书图片 / optional
*/
public function actionUpdate()
{
$post=\Yii::$app->request->post();
$this->requestValidate($post,[
['id','required']
]);
$GranularForm=new GranularForm();
$GranularForm->attributes=$post;
return $GranularForm->update();
}
/**
* @doc-name 查看配方颗粒库
* @doc-param int id 药品ID
*/
public function actionInfo()
{
$get=\Yii::$app->request->get();
$this->requestValidate($get,[
['id','required']
]);
$GranularForm=new GranularForm();
$GranularForm->attributes=$get;
return $GranularForm->info();
}
/**
* @doc-name 导入配方颗粒库
* @doc-param file file 文件
*/
public function actionGranularImport()
{
$request = \Yii::$app->request;
if ($request->isPost) {
//设置最大执行时间
ini_set("max_execution_time", "360");
$file = UploadedFile::getInstanceByName('file');
if ($file->size > 5 * 1024 * 1024) {
return ['excel文件不能超过5M!'];
}
//文件名
$filename = date('His') . md5($file->getBaseName()) . mt_rand(1000, 9999) . '.' . $file->getExtension();
//保存文件
$file->saveAs($filename);
$data = Excel::import($filename, [
'setFirstRecordAsKeys' => true,
'getOnlySheet' => 'Sheet1',
]);
$ImportForm=new ImportForm();
return $ImportForm->GranularImport($data);
} else {
return ['请求方式错误'];
}
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace admin\controllers\drug;
use admin\components\BaseAdminController;
use common\models\ProcessRule;
use common\models\ProcessRuleNote;
use admin\components\Tree;
class ProcessRuleController extends BaseAdminController
{
public function actionList(){
$processRule = ProcessRule::find()->asArray()->all();
$processRuleTree = Tree::ruleTree($processRule);
return $processRuleTree;
}
public function actionNoteList(){
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['rule_id', 'required']
]);
$ruleNotes = ProcessRuleNote::find()->where(['rule_id' => $get['rule_id']])->asArray()->all();
return $ruleNotes;
}
public function actionAdd(){
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['name', 'required'],
['pid','required'],
['calc_method','in','range'=>[1,2,3]],
[['name','unit'],'string'],
['price','double']
]);
$processRule = new ProcessRule();
$processRule->attributes = $post;
$res = $processRule->save();
if(!$res){
throw new \Exception('添加加工规则失败');
}
return ['success'];
}
public function actionAddNote(){
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['rule_id', 'required'],
['note', 'required']
]);
$processRuleNote = new ProcessRuleNote();
$processRuleNote->attributes = $post;
$res = $processRuleNote->save();
if(!$res){
throw new \Exception('添加加工规则备注失败');
}
return ['success'];
}
public function actionUpdate(){
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['name', 'required'],
['id','required']
]);
$processRule = ProcessRule::find()->where(['id' => $post['id']])->one();
$processRule->name = $post['name'];
$processRule->calc_method = $post['calc_method'];
$processRule->price = $post['price'];
$processRule->unit = $post['unit'];
$res = $processRule->saveOrFail();
if(!$res){
throw new \Exception('更新加工规则失败');
}
return ['success'];
}
public function actionUpdateNote(){
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['note', 'required'],
['id','required']
]);
$processRuleNote = ProcessRuleNote::find()->where(['id' => $post['id']])->one();
$processRuleNote->note = $post['note'];
$res = $processRuleNote->saveOrFail();
if(!$res){
throw new \Exception('更新加工规则备注失败');
}
return ['success'];
}
public function actionDelete(){
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id','required']
]);
$processRule = ProcessRule::find()->where(['id' => $post['id']])->one();
if(!$processRule){
throw new \Exception("规则不存在");
}
if($processRule->pid){
$processRuleNote = new ProcessRuleNote();
$processRuleNote->rule_id = $processRule->id;
$processRuleNote->delete();
}
$processRule->delete();
return ['success'];
}
public function actionDeleteNote(){
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id','required']
]);
$processRuleNote = ProcessRuleNote::find()->where(['id' => $post['id']])->one();
if(!$processRuleNote){
throw new \Exception("规则备注不存在");
}
$processRuleNote->delete();
return ['success'];
}
}

View File

@@ -0,0 +1,335 @@
<?php
namespace admin\controllers\store;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use admin\models\Admin;
use common\enums\UserRoleEnum;
use common\models\AdminAccessToken;
use common\models\DrugStoreDrug;
use common\models\DrugStoreRelations;
use common\models\Role;
use common\models\Store;
use common\modelsgii\Drug;
use yii\db\Exception;
/**
* @doc-module 门店
*/
class StoreController extends BaseAdminController
{
/**
* @doc-name 门店药品列表--西药中成药
* @doc-param int store_id 门店id
* @doc-return mixed @List{id,drug_id,type-int-类型1中药2西药3颗粒配方,stock-int-库存,store_price-int-门店销售价格,drugstore_price-int-仓库销售价格,market_price-int-市场价,buy_price-float-采购价,store_status-int-门店状态1下架2上架,drugstore_status-int-仓库状态1下架2上架,name-string-药名,pinyin_simple-string-拼音首拼,is_otc-int-是否处方,price_percent-string-销售价比例,buy_price_percent-string-采购价比例} 门店药品信息
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionDrugList()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['store_id', 'required']
]);
$query = DrugStoreRelations::find()->alias('ds')->where(['ds.store_id' => $get['store_id']]);
$query->joinWith(['drug' => function ($d) {
$d->andWhere(['type' =>[ 2,4]]);
}]);
if (!empty($get['status'])) {
$query->andWhere(['ds.status' => $get['status']]);
}
$this->field = [
DrugStoreRelations::class => [
'id', 'drug_id',
'type' => 'drug.type',
'name' => 'drug.drug_name',
'pinyin_simple' => 'drug.pinyin_simple',
'is_otc' => 'drug.is_otc',
'store_price' => 'price',
'drugstore_price' => 'drugStoreDrug.price',
'market_price' => 'drugStoreDrug.market_price',
'stock' => 'drugStoreDrug.stock',
'buy_price',
'store_status' => 'status',
'drugstore_status' => 'drugStoreDrug.status',
'image' => 'drug.image',
'is_forbid'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 门店设置西药价格
* @doc-param int store_id 门店ID
* @doc-param int drug_id 药品ID
* @doc-param float price 销售价 / optional
*/
public function actionUpdatePrice()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['store_id', 'drug_id'], 'required']
]);
$DrugStoreDrug = DrugStoreDrug::find()->where([
'drug_id' => $post['drug_id']
])->one();
if (!$DrugStoreDrug) throw new Exception('仓库中没有该药品');
// if ($DrugStoreDrug->type == 1 || $DrugStoreDrug->type == 3) throw new Exception('您不能修改中药或配方颗粒的销售价格');
$DrugStoreRelations = DrugStoreRelations::find()->where([
'store_id' => $post['store_id'],
'drug_id' => $post['drug_id'],
])->one();
if (!$DrugStoreRelations) throw new Exception('门店没有该药品');
$DrugStoreRelations->price = $post['price'] ?? $DrugStoreRelations->price;
if (!$DrugStoreRelations->saveOrFail()) throw new Exception('修改失败');
return ['修改成功'];
}
/**
* @doc-name 门店设置上下架
* @doc-param int store_id 门店ID
* @doc-param int drug_id 药品ID
* @doc-param int status 1下架2上架
*/
public function actionUpdateStatus()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['store_id', 'drug_id', 'status'], 'required']
]);
$DrugStoreRelations = DrugStoreRelations::find()->where([
'store_id' => $post['store_id'],
'drug_id' => $post['drug_id'],
])->one();
if (!$DrugStoreRelations) throw new Exception('门店中药品不存在');
$DrugStoreRelations->status = $post['status'];
if (!$DrugStoreRelations->saveOrFail()) {
throw new Exception('修改失败');
}
return ['修改成功'];
}
/**
* @doc-name 添加子账号
* @doc-param string mobile 手机号
* @doc-param string role 角色
* @doc-param string password 密码
* @doc-param string username 用户名
* @doc-param int store_id 门店
*/
public function actionAddAccount()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['mobile', 'password', 'username','store_id','role'], 'required']
]);
$admin = \Yii::$app->user->identity;
$t = \Yii::$app->db->beginTransaction();
try {
$is_admin = Admin::find()->where([
'mobile' => $post['mobile'],
'is_delete' => 0
])->one();
if ($is_admin) throw new Exception('该账号已注册过');
if (! Store::find()->where(['id'=>$post['store_id']])->one()){
throw new Exception('门店不存在');
}
if (! Role::find()->where(['id'=>$post['role']])->one()){
throw new Exception('角色不存在');
}
$model = new Admin();
$model->is_sub = 1;//子账号
$model->mobile = $post['mobile'];
$model->role = $post['role'];
$model->username = $post['username'];
$model->store_id = $post['store_id'];
$model->setPassword($post['password']);
$model->role = $admin->role;
$model->store_id = $admin->store_id ?? '';
$model->saveOrFail();
$token = AdminAccessToken::createToken($model->id, 'admin');
$t->commit();
return [
'token' => $token,
'user' => Admin::findOne($model->uid),
];
} catch (\yii\db\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 门店设置自己的销售比例
* @doc-param float store_set_sale_z 门店自己设置中药销售比例
* @doc-param float store_set_sale_g 门店自己设置配方颗粒的销售比例
*/
public function actionStoreSetPercent()
{
$post = \Yii::$app->request->post();
$admin = \Yii::$app->user->identity;
if ($admin->role != UserRoleEnum::STORE_ADMIN) {
throw new Exception('你不是门店管理员');
}
$Store = Store::find()->where(['id' => $admin->store_id])->one();
$t = \Yii::$app->db->beginTransaction();
try {
$Store->z_sale_percent = $post['store_set_sale_z'] ?? $Store->z_sale_percent;
$Store->g_sale_percent = $post['store_set_sale_g'] ?? $Store->g_sale_percent;
$Store->store_set_sale_z = $post['store_set_sale_z'] ?? $Store->store_set_sale_z;
$Store->store_set_sale_g = $post['store_set_sale_g'] ?? $Store->store_set_sale_g;
$Store->saveOrFail();
if (!empty($post['store_set_sale_z'])) {
$chinese = DrugStoreDrug::find()->select(['drug_id'])->where(['type' => 1])->column();
$chinese_price = DrugStoreDrug::find()->select(['drug_id', 'market_price','price'])->where(['type' => 1])->all();
$DrugStoreRelations = DrugStoreRelations::find()->select(['id', 'drug_id'])->where([
'store_id' => $admin->store_id,
])->andWhere(['in','drug_id',$chinese])->all();
foreach ($DrugStoreRelations as $val) {
foreach ($chinese_price as $v) {
if ($val['drug_id'] == $v['drug_id']) {
\Yii::$app->db->createCommand()->update('yii_drug_store_relations', ['price' =>bcdiv(bcmul($post['store_set_sale_z'],$v['price'],4) ,100,4)], ['id' => $val['id']])->execute();
}
}
}
}
if (!empty($post['store_set_sale_g'])) {
$granular= DrugStoreDrug::find()->select(['drug_id'])->where(['type' => 3])->column();
$granular_price = DrugStoreDrug::find()->select(['drug_id', 'market_price','price'])->where(['type' => 3])->all();
$DrugStoreRelations = DrugStoreRelations::find()->select(['id', 'drug_id'])->where([
'store_id' => $admin->store_id,
])->andWhere(['in','drug_id',$granular])->all();
foreach ($DrugStoreRelations as $val) {
foreach ($granular_price as $v) {
if ($val['drug_id'] == $v['drug_id']) {
\Yii::$app->db->createCommand()->update('yii_drug_store_relations', ['price' =>bcdiv(bcmul( $post['store_set_sale_g'],$v['price'],4) ,100,4) ], ['id' => $val['id']])->execute();
}
}
}
}
$t->commit();
return ['设置成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 设置是否开启查看毛利率
* @doc-param int store_id 门店id
*/
public function actionSeeRate()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
['store_id','required']
]);
$admin = \Yii::$app->user->identity;
if ($admin->role != UserRoleEnum::STORE_ADMIN) {
throw new Exception('你不是门店管理员');
}
$Store = Store::find()->where(['id' => $get['store_id']])->one();
if (!$Store) throw new Exception('诊所不存在');
$t = \Yii::$app->db->beginTransaction();
try {
$Store->see_rate=$Store->see_rate==0? 1:0;
$Store->saveOrFail();
$t->commit();
return [$Store->see_rate==0?'关闭':'开启'];
}catch (\Exception $exception){
$t->rollBack();
throw new $exception;
}
}
/**
* @doc-name 门店查看是否开启毛利
* @doc-param int store_id 门店id
*/
public function actionIsSeeRate()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
['store_id','required']
]);
$admin = \Yii::$app->user->identity;
if ($admin->role != UserRoleEnum::STORE_ADMIN) {
throw new \yii\db\Exception('你不是门店管理员');
}
$Store = Store::find()->where(['id' => $get['store_id']])->one();
if (!$Store) throw new \yii\base\Exception('诊所不存在');
return $Store;
}
/**
* @doc-name 平台控制门店西药是否禁售
* @doc-param int store_id 门店id
* @doc-param int drug_id 药品id
*/
public function actionSetDrugStatus()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
[['store_id','drug_id'],'required']
]);
$Drug=Drug::find()->where(['id'=>$get['drug_id']])->one();
if (!$Drug) throw new Exception('药品不存在');
$DrugStoreRelations=DrugStoreRelations::find()->where(['store_id'=>$get['store_id'],'drug_id'=>$get['drug_id']])->one();
if (!$DrugStoreRelations) throw new Exception('门店没有该药品');
$DrugStoreRelations->is_forbid=$DrugStoreRelations->is_forbid==0?1 :0;
if ($DrugStoreRelations->is_forbid==1){//禁售
$DrugStoreRelations->status=1;//下架
}else{//在售
$DrugStoreRelations->status=2;//上架
}
$DrugStoreRelations->saveOrFail();
return [ $DrugStoreRelations->is_forbid==1?'禁售':'在售'];
}
/**
* @doc-name 查看门店信息
*/
public function actionSeeStorePercent()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get,[
['store_id','required']
]);
$Store = Store::find()->select(['z_buy_percent','z_sale_percent','g_bug_percent','g_sale_percent'])->where(['id' => $get['store_id'],'is_delete'=>0])->one();
if (!$Store) throw new Exception('门店不存在');
return $Store;
}
}

View File

@@ -0,0 +1,628 @@
<?php
namespace admin\controllers\store;
use admin\components\BaseAdminController;
use admin\controllers\AuthController;
use common\enums\UserRoleEnum;
use common\jobs\ProductOrderAutoReceived;
use common\jobs\ProductOrderSendJob;
use common\jobs\templateMessage\ProductOrderSend;
use common\models\DrugStoreDrug;
use common\models\DrugStoreRelations;
use common\models\ExpressCompanies;
use common\models\ExpressNos;
use common\models\Log;
use common\models\ProductOrder;
use common\models\Store;
use GuzzleHttp\Client;
use yii\db\Exception;
use yii\helpers\Json;
/**
* @doc-module 仓库
*/
class WareController extends BaseAdminController
{
/**
* @doc-name 仓库药品列表
* @doc-param int status 状态1下架2上架 / optional
* @doc-param string name 搜索别名,拼音首拼,药名 / optional
* @doc-param int type 类型1中药2西药3颗粒配方4中成药 / optional
* @doc-return mixed @List{id,drug_id,type-int-类型1中药2西药3颗粒配方,stock-int-库存,price-int-销售价格,market_price-int-采购价,status-int-状态1下架2上架,name-string-药名,pinyin_simple-string-拼音首拼,is_otc-int-是否处方} 药品信息
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionWareGoodList()
{
$get = \Yii::$app->request->get();
$name = $get['name'];
$query = DrugStoreDrug::find()->alias('ds');
$query->joinWith(['drug' => function ($d) use ($name) {
if (!empty($name)) {
$d->andWhere([
'or',
['like', 'drug_name', $name],
['like', 'pinyin_simple', $name],
['like', 'pinyin_simple', $name],
]);
}
}]);
if (!empty($get['type'])) {
$query->andWhere(['ds.type' => $get['type']]);
}
if (!empty($get['status'])) {
$query->andWhere(['ds.status' => $get['status']]);
}
$this->field = [
DrugStoreDrug::class => [
'id', 'drug_id', 'type', 'stock', 'price', 'market_price', 'status',
'name' => 'drug.drug_name',
'image' => 'drug.image',
'pinyin_simple' => 'drug.pinyin_simple',
'is_otc' => 'drug.is_otc','drug_number'=>'drug.drug_number',
'drug_alias'=>'drug.drug_alias',
]
];
return $this->create($query, $get);
}
/**
* @doc-name 添加仓库商品
* @doc-param int drug_id 药id
* @doc-param int type 药品类型 1中药 2西药 3颗粒药 4中成药
* @doc-param float price 销售价格
* @doc-param float market_price 市场价格
* @doc-param int stock 库存
*/
public function actionSaveWareDrug()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['drug_id', 'type', 'price', 'stock'], 'required']
]);
$DrugStoreDrug = DrugStoreDrug::find()->where([
'drugstore_id' => 1,
'drug_id' => $post['drug_id'],
])->one();
if ($DrugStoreDrug) throw new Exception('已存在,请勿重复添加');
if ($post['type']==1 || $post['type']==3 ){
if (empty($post['market_price'])){
throw new Exception('市场价格不能为空');
}
}
$t = \Yii::$app->db->beginTransaction();
try {
$drug = new DrugStoreDrug();
$drug->drugstore_id = 1;//仓库默认为1
$drug->drug_id = $post['drug_id'];
$drug->type = $post['type'];
$drug->price = $post['price'];
$drug->market_price = $post['market_price']??0;
$drug->stock = $post['stock'];
$drug->saveOrFail();
$Store = Store::find()->select(['id','z_buy_percent','z_sale_percent','g_bug_percent','g_sale_percent','store_set_sale_z','store_set_sale_g'])->where(['is_delete' => 0])->all();
if ($post['type']==1){
foreach ($Store as $val) {
if (!empty($val['store_set_sale_z'])){
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->drug_id = $post['drug_id'];
$DrugStoreRelations->store_id = $val['id'];
$DrugStoreRelations->price =bcdiv(bcmul($post['price'], $val['store_set_sale_z']??100, 4), 100, 4);//销售价
$DrugStoreRelations->buy_price = bcdiv(bcmul($post['market_price'], $val['z_buy_percent']??100, 4), 100, 4);//进货(采购)价
$DrugStoreRelations->status = 2;//上架
$DrugStoreRelations->created_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->updated_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->saveOrFail();
}else{
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->drug_id = $post['drug_id'];
$DrugStoreRelations->store_id = $val['id'];
$DrugStoreRelations->price =bcdiv(bcmul($post['price'], $val['z_sale_percent']??100, 4), 100, 4);//销售价
$DrugStoreRelations->buy_price = bcdiv(bcmul($post['market_price'], $val['z_buy_percent']??100, 4), 100, 2);//进货(采购)价
$DrugStoreRelations->status = 2;//上架
$DrugStoreRelations->created_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->updated_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->saveOrFail();
}
}
}
if ($post['type']==3){
foreach ($Store as $val){
if (!empty($val['store_set_sale_g'])){
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->drug_id = $post['drug_id'];
$DrugStoreRelations->store_id = $val['id'];
$DrugStoreRelations->price =bcdiv(bcmul($post['price'], $val['store_set_sale_g']??100, 4), 100, 4);//销售价
$DrugStoreRelations->buy_price = bcdiv(bcmul($post['market_price'], $val['g_bug_percent']??100, 4), 100, 4);//进货(采购)价
$DrugStoreRelations->status = 2;//上架
$DrugStoreRelations->created_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->updated_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->saveOrFail();
}else{
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->drug_id = $post['drug_id'];
$DrugStoreRelations->store_id = $val['id'];
$DrugStoreRelations->price =bcdiv(bcmul($post['price'], $val['g_sale_percent']??100, 4), 100, 4);//销售价
$DrugStoreRelations->buy_price = bcdiv(bcmul($post['market_price'], $val['g_bug_percent']??100, 4), 100, 4);//进货(采购)价
$DrugStoreRelations->status = 2;//上架
$DrugStoreRelations->created_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->updated_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->saveOrFail();
}
}
}
if ($post['type']==2|| $post['type']==4){
foreach ($Store as $val) {
$DrugStoreRelations = new DrugStoreRelations();
$DrugStoreRelations->drug_id = $post['drug_id'];
$DrugStoreRelations->store_id = $val['id'];
$DrugStoreRelations->price =$post['price'];//销售价
$DrugStoreRelations->buy_price = $post['market_price']??$post['price'];//进货(采购)价
$DrugStoreRelations->status = 2;//上架
$DrugStoreRelations->created_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->updated_at = date('Y-m-d H:i:s', time());
$DrugStoreRelations->saveOrFail();
}
}
$t->commit();
return ['添加成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 仓库上架下架
* @doc-param int drug_id 药品ID
* @doc-param int type 类型1中药2西药3颗粒配方4中成药
* @doc-param int status 1下架2上架
*/
public function actionIsSale()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['drug_id', 'type', 'status'], 'required']
]);
$DrugStoreDrug = DrugStoreDrug::find()->where([
'drug_id' => $post['drug_id'],
'drugstore_id' => 1,
'type' => $post['type'],
])->one();
if (!$DrugStoreDrug) {
throw new Exception('药品不存在');
}
$t = \Yii::$app->db->beginTransaction();
try {
$DrugStoreDrug->status= $post['status'];
$DrugStoreDrug->saveOrFail();
$ids = DrugStoreRelations::find()->select(['id'])->where([
'drug_id' => $post['drug_id']
])->column();
DrugStoreRelations::updateAll(['status' => $post['status']], ['id' => $ids]);//修改门店
$t->commit();
return ['success'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 修改仓库价格
* @doc-param int drug_id 药品ID
* @doc-param int type 类型1中药2西药3颗粒配方4中成药
* @doc-param float price 销售价 / optional
* @doc-param int stock 库存 / optional
* @doc-param float market_price 市场价 / optional
*/
public function actionUpdateDrugstorePrice()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['drug_id', 'type'], 'required']
]);
$DrugStoreDrug = DrugStoreDrug::find()->where([
'drugstore_id' => 1,
'drug_id' => $post['drug_id'],
'type' => $post['type'],
])->one();
if (!$DrugStoreDrug) throw new Exception('药品不存在');
$t = \Yii::$app->db->beginTransaction();
try {
$DrugStoreDrug->price = $post['price'] ?? $DrugStoreDrug->price;
$DrugStoreDrug->stock = $post['stock'] ?? $DrugStoreDrug->stock;
$DrugStoreDrug->market_price = $post['market_price'] ?? $DrugStoreDrug->market_price;
$DrugStoreDrug->saveOrFail();
switch ($post['type']) {
case 1://中药
$DrugStoreRelations = DrugStoreRelations::find()->where(['drug_id' => $post['drug_id']])->asArray()->all();
if ($DrugStoreRelations) {
foreach ($DrugStoreRelations as $val) {
$store = Store::find()->where(['id' => $val['store_id']])->one();
\Yii::$app->db->createCommand()->update('yii_drug_store_relations',
['price' =>bcdiv(bcmul($store['z_sale_percent']??100,$DrugStoreDrug->price,4),100,4),
'buy_price' =>bcdiv(bcmul($store['z_buy_percent']??100,$DrugStoreDrug->market_price,4),100,4)],
['drug_id' => $val['drug_id'], 'store_id' => $val['store_id']])->execute();
}
}
break;
case 2://西药
$DrugStoreRelations = DrugStoreRelations::find()->where(['drug_id' => $post['drug_id']])->asArray()->all();
if ($DrugStoreRelations) {
foreach ($DrugStoreRelations as $val) {
\Yii::$app->db->createCommand()->update('yii_drug_store_relations',
['price' =>$DrugStoreDrug->price,
'buy_price' => $DrugStoreDrug->market_price??0],
['drug_id' => $val['drug_id'], 'store_id' => $val['store_id']])->execute();
}
}
break;
case 3://配方颗粒
$DrugStoreRelations = DrugStoreRelations::find()->where(['drug_id' => $post['drug_id']])->asArray()->all();
if ($DrugStoreRelations) {
foreach ($DrugStoreRelations as $val) {
$store = Store::find()->where(['id' => $val['store_id']])->one();
\Yii::$app->db->createCommand()->update('yii_drug_store_relations',
['price' =>bcdiv(bcmul($store['g_sale_percent']??100,$DrugStoreDrug->price,4),100,4),
'buy_price' =>bcdiv(bcmul($store['g_buy_percent']??100,$DrugStoreDrug->market_price,4),100,4)],
['drug_id' => $val['drug_id'], 'store_id' => $val['store_id']])->execute();
}
}
break;
case 4://中成药
$DrugStoreRelations = DrugStoreRelations::find()->where(['drug_id' => $post['drug_id']])->asArray()->all();
if ($DrugStoreRelations) {
foreach ($DrugStoreRelations as $val) {
\Yii::$app->db->createCommand()->update('yii_drug_store_relations',
['price' =>$DrugStoreDrug->price,
'buy_price' => $DrugStoreDrug->market_price??$DrugStoreDrug->price],
['drug_id' => $val['drug_id'], 'store_id' => $val['store_id']])->execute();
}
}
break;
default:
throw new Exception('参数错误');
}
$t->commit();
return ['修改成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 仓库修改门店西药价格
* @doc-param int store_id 门店id
* @doc-param int drug_id 药品ID
* @doc-param float price 销售价 / optional
* @doc-param float buy_price 采购价 / optional
*/
public function actionUpdatePrice()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['store_id', 'drug_id'], 'required']
]);
if (empty($post['drug_id'])) {
throw new Exception('药品ID不能为空');
}
$DrugStoreRelations = DrugStoreRelations::find()->where([
'store_id' => $post['store_id'],
'drug_id' => $post['drug_id']
])->one();
if (!$DrugStoreRelations) throw new Exception('药品不存在');
$DrugStoreRelations->price = $post['price'] ?? $DrugStoreRelations->price;
$DrugStoreRelations->buy_price = $post['buy_price'] ?? $DrugStoreRelations->buy_price;
if (!$DrugStoreRelations->saveOrFail()) throw new Exception('修改失败');
return ['修改成功'];
}
/**
* @doc-name 仓库修改门店比例(中药/配方颗粒)
* @doc-param int store_id 门店ID
* @doc-param int type 类别1中药3配方颗粒
* @doc-return string z_buy_percent 中药采购比例 / optional
* @doc-return string z_sale_percent 中药销售比例 / optional
* @doc-return string g_bug_percent 配方颗粒采购比例 / optional
* @doc-return string g_sale_percent 配方颗粒销售比例 / optional
*/
public function actionEditPercent()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['store_id', 'type'], 'required']
]);
switch ($post['type']) {
case 1:
$beginTransaction = \Yii::$app->db->beginTransaction();
try {
$Store = Store::find()->where([
'id' => $post['store_id']
])->one();
if (!$Store) throw new Exception('门店不存在');
$Store->z_buy_percent = $post['z_buy_percent'] ?? $Store->z_buy_percent;
$Store->z_sale_percent = $post['z_sale_percent'] ?? $Store->z_sale_percent;
$Store->saveOrFail();
$chinese = DrugStoreDrug::find()->select(['drug_id'])->where(['type' => 1])->column();
$chinese_price = DrugStoreDrug::find()->select(['drug_id', 'market_price','price'])->where(['type' => 1])->all();
$DrugStoreRelations_chinese = DrugStoreRelations::find()->select(['id', 'drug_id'])->where([
'store_id' => $post['store_id'],
])->andWhere(['in', 'drug_id', $chinese])->all();
foreach ($DrugStoreRelations_chinese as $val) {
foreach ($chinese_price as $v) {
if ($val['drug_id'] == $v['drug_id']) {
\Yii::$app->db->createCommand()->update('yii_drug_store_relations',
['price' =>bcdiv(bcmul($post['z_sale_percent'] ??100,$v['price'],4),100,4) ,
'buy_price' =>bcdiv(bcmul($post['z_buy_percent'] ??100,$v['market_price'],4),100,4)],
['id' => $val['id']])->execute();
}
}
}
$beginTransaction->commit();
return ['修改成功'];
} catch (\Exception $e) {
$beginTransaction->rollBack();
throw new Exception($e->getMessage());
}
break;
case 3:
try {
$t = \Yii::$app->db->beginTransaction();
$Store = Store::find()->where([
'id' => $post['store_id']
])->one();
if (!$Store) throw new Exception('门店不存在');
$Store->g_bug_percent = $post['g_bug_percent'] ?? $Store->g_bug_percent;
$Store->g_sale_percent = $post['g_sale_percent'] ?? $Store->g_sale_percent;
$Store->saveOrFail();
$grain = DrugStoreDrug::find()->select(['drug_id'])->where(['type' => 3])->column();
$grain_price = DrugStoreDrug::find()->select(['drug_id', 'market_price','price'])->where(['type' => 3])->all();
$DrugStoreRelations_grain = DrugStoreRelations::find()->select(['id', 'drug_id'])->where([
'store_id' => $post['store_id'],
])->andWhere(['in', 'drug_id', $grain])->all();
foreach ($DrugStoreRelations_grain as $value) {
foreach ($grain_price as $vv) {
if ($value['drug_id'] == $vv['drug_id']) {
\Yii::$app->db->createCommand()->update('yii_drug_store_relations',
['price' =>bcdiv(bcmul($post['g_sale_percent'] ??100,$vv['price'],4),100,4),
'buy_price' =>bcdiv(bcmul($post['g_bug_percent']??100 ,$vv['market_price'],4),100,4)],
['id' => $value['id']])->execute();
}
}
}
$t->commit();
return ['修改成功'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
break;
default:
throw new Exception('参数错误');
}
}
/**
* @doc-name 仓库查看比例
* @doc-param int store_id 门店ID
* @doc-return string z_buy_percent 中药采购比例
* @doc-return string z_sale_percent 中药销售比例
* @doc-return string g_bug_percent 配方颗粒采购比例
* @doc-return string g_sale_percent 配方颗粒销售比例
*/
public function actionPercent()
{
$get = \Yii::$app->request->get();
$this->requestValidate($get, [
['store_id', 'required']
]);
$Store = Store::find()->where([
'id' => $get['store_id']
])->one();
if (!$Store) {
throw new Exception('门店不存在');
}
return $Store;
}
/**
* @doc-name 仓库发货
* @doc-param int order_id 商品(或产品)订单id
* @doc-param string express_company_name 快递公司 / optional
* @doc-param string express_company_code 公司编码
* @doc-param string express_no 快递单号
* @doc-param string mobile 手机号码 / optional
* @doc-param string state 物流状态 / optional
*/
public function actionWareSend()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['order_id', 'express_company_code', 'express_no'], 'required']
]);
$user = \Yii::$app->user->identity;
// if ($user->role != UserRoleEnum::SUPER_ADMIN) {
// throw new Exception('您不是超管,没有发货权限');
// }
$ProductOrder = ProductOrder::find()->where([
'id' => $post['order_id']
])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
if($ProductOrder->is_online == 1 && $ProductOrder->online_prescription_status != 1){
throw new Exception('处方暂未审核,无法发货');
}
$t = \Yii::$app->db->beginTransaction();
try {
//快递单号信息
$ExpressNos = new ExpressNos();
$ExpressNos->express_company_name = $post['express_company_name'];
$ExpressNos->express_company_code = $post['express_company_code'];
$ExpressNos->express_no = $post['express_no'];
$ExpressNos->mobile = $post['mobile'];
$ExpressNos->state = $post['state'];
$ExpressNos->sync_at = null;
$ExpressNos->created_at = date('Y-m-d H:i:s', time());
$ExpressNos->updated_at = date('Y-m-d H:i:s', time());
$ExpressNos->saveOrFail();
// $result = json_decode($response->getBody(), true);
$ProductOrder->is_send = 1;
$ProductOrder->status = 2;
$ProductOrder->send_time = date('Y-m-d H:i:s', time());
$ProductOrder->express_no_id = $ExpressNos->attributes['id'];
$ProductOrder->saveOrFail();
$log = new Log();
$log->admin_id = $user->uid;
$log->operate_time = date('Y-m-d H:i:s', time());
$log->type = '仓库发货';
$log->mold = 2;//订单操作
$log->content = $user->uid . '操作仓库发货:';
$log->save();
//订单发货自动结算
\Yii::$app->queue->push(new ProductOrderSend([
'orderId' => $ProductOrder->id,
]));
//订单自动收货- 发货7天后
$config = \Yii::$app->params;
$orderAutoReceivedTime = isset($config['product_order']['received_time']) ? $config['product_order']['received_time'] : 7*24*3600;
\Yii::$app->queue->delay($orderAutoReceivedTime)->push(new ProductOrderAutoReceived([
'orderId' => $ProductOrder->id
]));
\Yii::$app->db->createCommand()->update('yii_log', ['content' => Json::encode($log->attributes)], ['id' => $log->attributes['id']])->execute();
//订单发货3天后分账结算
// if($ProductOrder->type == 2){ //易票联支付的产品订单
// $config = \Yii::$app->params;
// $orderAutoSettlementTime = isset($config['product_order']['settlement_time']) ? $config['product_order']['settlement_time'] : 72*3600;
// \Yii::$app->queue->delay($orderAutoSettlementTime)->push(new ProductOrderSendJob([
// 'orderId' => $ProductOrder->id
// ]));
// }
// //触发订单发货事件-3天后分账结算
// $event = new ProductOrderEvent();
// $event->order = $ProductOrder;
// $event->sender = $this;
// \Yii::$app->trigger(ProductOrder::EVENT_SEND, $event);
$t->commit();
(new Client(['http_errors' => false]))->get("https://shop.xiaokang88.com/t/express_update", [
'query' => [
'id' => $ExpressNos->id,
],
]);
return ['发货成功'];
} catch (\Exception $exception) {
$t->rollBack();
throw new Exception($exception->getMessage());
}
}
/**
* @doc-name 快递公司
* @doc-return mixed @List{id,name-string-公司名称,code-string-公司编码,type-string-公司类型,sort-int-排序} 快递公司
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionExpressCompanyList()
{
$get = \Yii::$app->request->get();
$query = ExpressCompanies::find()->orderBy(['sort' => SORT_ASC]);
$this->field = [
ExpressCompanies::class => [
'id', 'name', 'code', 'type', 'sort'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 修改物流
* @doc-param int express_no_id 快递单号信息ID
* @doc-param string express_company_name 公司名称 / optional
* @doc-param string express_company_code 公司编码 / optional
* @doc-param string express_no 快递单号 / optional
* @doc-param string mobile 手机号码 / optional
* @doc-param int state 物流状态0揽收1揽收2疑难4退签5派件6退回7转投8清关14拒签 / optional
*/
public function actionUpdateExpressNos()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['express_no_id', 'required','message'=>'快递单号信息ID不能为空']
]);
$ExpressNos=ExpressNos::find()->where(['id'=>$post['express_no_id']])->one();
if (!$ExpressNos) throw new Exception('物流信息不存在');
$ExpressNos->express_company_name=$post['express_company_name']??$ExpressNos->express_company_name;
$ExpressNos->express_company_code=$post['express_company_code']?? $ExpressNos->express_company_code;
$ExpressNos->express_no=$post['express_no']??$ExpressNos->express_no;
$ExpressNos->mobile=$post['mobile']??$ExpressNos->mobile;
$ExpressNos->state=$post['state']??$ExpressNos->state;
$ExpressNos->saveOrFail();
(new Client(['http_errors' => false]))->get("https://shop.xiaokang88.com/t/express_update", [
'query' => [
'id' => $ExpressNos->id,
],
]);
return ['修改成功'];
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace admin\controllers\system;
use admin\controllers\AuthController;
use admin\exceptions\ApiException;
use admin\models\Admin;
use common\core\BaseAdminController;
use common\enums\UserRoleEnum;
use common\models\Store;
use yii\base\DynamicModel;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
class AdminController extends BaseAdminController
{
/**
* 管理员列表
*/
public function actionList()
{
$m = new DynamicModel(['page','pageSize']);
//$m->addRule('aa',DateRangeValidator::class);
//$m->addRule('xx','string');
$m->addRule('page','default',['value'=>1]);
$m->addRule('pageSize','default',['value'=>10]);
$m->addRule('page','integer',['max'=>1000]);
$m->addRule('pageSize','integer',['min'=>1,'max'=>50]);
$m->load($this->post());
if(!$m->validate()){
throw new Exception(json_encode($m->getFirstErrors()));
}
$query = Admin::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=>[
'defaultOrder'=>['uid'=>SORT_DESC]
],
'pagination'=>[
'defaultPageSize'=>$m->pageSize,
'params'=>['page'=>$m->page]
]
]);
// add conditions that should always apply here
return $dataProvider;
}
/**
* 账号信息
*/
public function actionInfo()
{
$admin= \Yii::$app->user->identity;
if ($admin->role==UserRoleEnum::SUPER_ADMIN){
$info= Admin::find()->where(['uid'=>$admin->uid,'role'=>UserRoleEnum::SUPER_ADMIN])->one();
}
if ($admin->role==UserRoleEnum::STORE_ADMIN){
$info= Store::find()->where(['id'=>$admin->store_id,'is_delete'=>0])->one();
}
if (!$info) throw new \yii\db\Exception('账号信息不存在');
return $info;
}
/**
* @doc-name 账号禁用
* @doc-param int admin_id 后台用户ID
*/
public function actionAccountDisabled()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['admin_id', 'required']
]);
$role=\Yii::$app->user->identity->role;
if ($role!=UserRoleEnum::SUPER_ADMIN) throw new \yii\db\Exception('非超级管理员,没有禁用账号的权限');
$Admin = Admin::find()->where([
'uid' => $post['admin_id'],
])->one();
if (!$Admin) throw new \yii\db\Exception('账号不存在');
$status=$Admin->status==1?0:1;
$Admin->status=$status;
$Admin->saveOrFail();
return ['修改成功'];
}
}

View File

@@ -0,0 +1,172 @@
<?php
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/25
* Time: 2:08 PM
*/
namespace admin\controllers\goods;
use common\core\BaseAdminController;
use admin\models\forms\AttachmentUploadForm;
use common\models\Attachment;
use common\models\AttachmentGroup;
use common\services\UploadService;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
/**
* @doc-module 上传
*/
class AttachmentController extends BaseAdminController
{
public function actionIndex(){
return ['node'=>['nodeName'=>'fileManage']];
return $this->render('index');
}
public function actionGroupList($type = null, $is_recycle = null)
{
$params = $this->requestValidate($this->get(),[
['is_recycle','integer'],
['type','string']
]);
$query = AttachmentGroup::find()->where([
'mall_id' => \Yii::$app->mallId,
'is_delete' => 0,
]);
isset($params->type) || $query->andWhere(['type' => $params->type === 'video' ? 1 : 0]);
return $query->all();
}
public function actionDo(){
$params = $this->requestValidate($this->get(),[
['type','in','range'=>['folder-create','files','folder-delete','folder']],
['keyword','string'],
['name','string'],
['id','integer'],
['page','integer']
]);
/**
* upload: props.uploadUrl,
list: props.fileUrl + '?type=files',
del: props.fileUrl + '?type=files-delete',
cateList: props.fileUrl + '?type=folder',
cateAdd: props.fileUrl + '?type=folder-create',
cateDel: props.fileUrl + '?type=folder-delete'
*/
switch ($params->type){
case 'folder':
$activeRecords = AttachmentGroup::find()->where(['mall_id' => \Yii::$app->mallId])->andWhere(['is_delete' => 0])->all();
return ArrayHelper::toArray($activeRecords,[
AttachmentGroup::class=>[
'dir_id'=>'id','name'
]
]);
break;
case 'folder-create';
$attachmentGroup = new AttachmentGroup();
$attachmentGroup->setAttributes([
'mall_id'=>\Yii::$app->mallId,
'name'=>$params->name,
]);
if($attachmentGroup->save()){
return ['id'=>$attachmentGroup->id,'name'=>$attachmentGroup->name];
}else{
return ['error'=>$attachmentGroup->getErrors()];
}
break;
case 'folder-delete';
Attachment::updateAll(['is_delete'=>1,'deleted_at'=>time()],['attachment_group_id'=>$params->id,'mall_id'=>\Yii::$app->mallId]);
AttachmentGroup::updateAll(['is_delete'=>1,'deleted_at'=>time()],['id'=>$params->id,'mall_id'=>\Yii::$app->mallId]);
return [];
break;
case 'files':
$query = Attachment::find()->where(['mall_id' => \Yii::$app->mallId])->andWhere(['is_delete' => 0])->orderBy('id desc');;
if(isset($params->id) && $params->id>0) {
$query->andWhere(['attachment_group_id'=>$params->id]);
}
$query->andFilterWhere(['like','name',$params->keyword]);
$this->field = [
Attachment::class=>[
'id',
'title'=>'name',
'url',
'ext'=>function($m){
$implode = explode('.', $m['name']);
return mb_strtolower(array_pop($implode));
},
'time'=>function($model){
return date("Y-m-d H:i:s",$model['created_at']);
},
'size'=>function($model){
return app_filesize($model['size']);
},
]
];
$post = array_merge(\Yii::$app->request->post(),\Yii::$app->request->get());
return $this->create($query,$post);
break;
}
}
public function actionUpload(){
$params = $this->requestValidate($this->post(),[
['id','integer'],
['id','default','value'=>0],
['file','file']
]);
$form = new AttachmentUploadForm();
$form->file = UploadedFile::getInstanceByName('file');
$form->attachment_group_id = $params->id;
return $form->save();
}
/**
* @doc-name oss直传-保存上传信息
* @doc-param int attachment_group_id 上传的分组
* @doc-param string name 上传的文件名称
* @doc-param int size 上传的文件大小
* @doc-param string url 上传的文件链接
*/
public function actionSave()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post,[
[['attachment_group_id','name','size','url'],'required']
]);
$ext = pathinfo($post['url'])['extension'];
$type = (new AttachmentUploadForm())->checkExt($ext);
$attachment = new Attachment();
$attachment->attributes = $post;
$attachment->storage_id = 0;
$attachment->user_id = 0;
$attachment->type = $type;
$attachment->mall_id = \Yii::$app->mallId;
$attachment->thumb_url = $post['url'];
$attachment->saveOrFail();
return $attachment;
}
/**
* @doc-name oss直传-获取上传参数
*/
public function actionParams()
{
$callbackUrl = \Yii::$app->request->hostInfo.'/api/v1/callback/upload-notify';
$dir = \Yii::$app->mallId ? 'uploads/' . \Yii::$app->mallId.'/' . date('Ymd').'/' : 'uploads/' . date('Ymd').'/';
$data = [
'callbackUrl' => $callbackUrl,
'dir' => $dir
];
return (new UploadService())->redirectFile($data);
}
}

View File

@@ -0,0 +1,167 @@
<?php
namespace admin\controllers\system;
use common\core\BaseAdminController;
use common\helpers\ArrayHelper;
use Yii;
use common\models\Config;
use admin\models\search\ConfigSearch;
use yii\base\Exception;
use yii\web\NotFoundHttpException;
/**
* 配置
*/
class ConfigController extends BaseAdminController
{
/**
* 配置项列表
*/
public function actionList()
{
$searchModel = new ConfigSearch();
$this->field = $this->_listMap();
return $searchModel->search(Yii::$app->request->queryParams);
}
/**
* 保存配置项
*/
public function actionSave()
{
$id = Yii::$app->request->get('id', 0);
$model = $this->findModel($id);
if ($model->load($this->post(),'') && $model->save()) {
$event = 'add';
if($id>0){
$event = 'edit';
}
$this->callbackEvent(ArrayHelper::toArray([$model],$this->_listMap()),'id',$event);
return [];
}else{
throw new Exception(current($model->getErrors())[0]);
}
}
/**
* 配置项详情1
* @doc-param int id ID
* @doc-return mixed @Config{name,type-int-配置类型0数字1字符2文本3数组4单选5富文本6多选,title,group,extra,remark,value,sort,status,created_at} 配置信息
*/
public function actionInfo()
{
$post = Yii::$app->request->post();
$this->requestValidate($post,[
['id','required']
]);
$config = Config::findOne($post['id']);
if ($config['extra']) {
$config['extra'] = Config::parse(3, $config['extra']);
}
return $config;
}
/**
* 删除配置项
*/
public function actionDel()
{
$id = (int)$this->get('id');
if($id<1){
throw new \Exception('删除失败!');
}
if(in_array($id,[1])){
throw new \Exception('禁止删除!');
}
$model = $this->findModel($id);
if ($model->delete()) {
$this->callbackEvent([$model->toArray()],'id','del');
return [];
} else {
throw new \Exception('删除失败!');
}
}
/**
* 配置
* @doc-desc 20处理成number,1是text,2textarea,3textarea,4select或者radio,5富文本,6多选
* @doc-return mixed Data{name-string-分组名称,@Groups{Config{name,type-int-配置类型0数字1字符2文本3数组4单选5富文本6多选,title,group,extra,remark,value,sort,status}}} 配置数据
*/
public function actionGroup()
{
$config = \common\models\Config::find()->where([
'name' => 'GROUP'
])->one();
$tab_groups = Config::parse(3, $config['value']);
$data = [];
foreach($tab_groups as $id => $group)
{
$groups = Config::find()
->where(['and', ['group' => $id], ['status' => 1]])
->orderBy('sort ASC')->asArray()->all();
foreach ($groups as $key => $value) {
if ($value['extra']) {
$groups[$key]['extra'] = Config::parse(3, $value['extra']);
}
}
$data[$id] = [
'name' => $group,
'groups' => $groups,
];
}
return $data;
}
/**
* 配置保存
* @doc-param array param 提交的修改数据[配置项name=>配置项的值,配置项name=>配置项的值]
*/
public function actionGroupSave()
{
$data = Yii::$app->request->post('param');
/* 更改配置值 */
$isSuccess = true;
foreach ($data as $name => $value) {
$model = Config::findOne(['name' => $name]);
$model->value = $value;
$model->update_time = time();
if (!$model->save()) {
$isSuccess = false;
continue;
}
}
if ($isSuccess) {
return [];
} else {
throw new Exception('有配置值修改失败');
}
}
protected function findModel($id)
{
if ($id == 0) {
return new Config();
}
if (($model = Config::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
private function _listMap()
{
return [
Config::class=>[
'id','title','name',
'type'=>function($m){
return Yii::$app->params['config_type'][$m->type];
},
'group','sort','status'
]
];
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/21
* Time: 11:50 AM
*/
namespace admin\controllers\system;
use app\forms\common\CommonPostageRules;
use admin\components\BaseAdminController;
use admin\components\UI\Form;
use admin\components\UI\Layout;
use admin\components\UI\Table;
use admin\components\UI\Tabs;
use admin\exceptions\ApiException;
use admin\models\forms\PostageRulesEditForm;
use admin\models\search\CommonSearch;
use common\models\FreeDeliveryRules;
use common\models\PostageRules;
use yii\db\ActiveQuery;
class DeliveryController extends BaseAdminController
{
public function actionPostageRule(){
$table = new Table(new PostageRules());
//$table->model();
$table->title('角色管理');
$table->key('id');
$table->eventName(md5(get_called_class()));//设置事件名,后面更改数据对应
$table->url(\Yii::$app->urlManager->createUrl("system/delivery/postage-rule-list"));
$table->filter('配置名', 'name',false)->text('请输入配置名')->quick();
$table->action()->button('添加', $this->createUrl('system/delivery/postage-edit'));
$table->column('规则名','name');
$table->column('是否默认','status')->status(['否','是'],['gray','red']);
$column = $table->column('操作')->width(200);
$column->link('设为默认',$this->createUrl('system/delivery/postage-status'), ['id' => 'id'])->type('ajax', ['method' => 'post']);
$column->link('编辑', $this->createUrl('system/delivery/postage-edit'), ['id' => 'id']);
$column->link('删除', $this->createUrl('system/delivery/postage-del'), ['id' => 'id'])->type('ajax', ['method' => 'post']);
return $table->renderArray();
}
public function actionPostageStatus(){
$params = $this->requestValidate($this->get(),[
['id','required'],
['id','integer']
]);
$this->callbackEvent([],'id','refresh');
return PostageRules::setStatus($params->id);
}
public function actionPostageRuleList()
{
$commonSearch = new CommonSearch(['name']);
$commonSearch->setQuery(PostageRules::find()
->select(['id', 'name', 'status'])
->where(['mall_id'=>\Yii::$app->mallId])->andWhere(['is_delete'=>0]));
$commonSearch->additionRules = [
['name', 'string']
];
$commonSearch->bindFilter(function(/** @var ActiveQuery $q */ $q) {
$q->andFilterWhere(['like','name',$this->name]);
});
return $commonSearch->search($this->get());
}
public function actionPostageInfo(){
$id = $this->get('id');
$model = PostageRules::findOne([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
'id' => $id
]);
if (!$model) {
$model = new PostageRules();
$model->mall_id = \Yii::$app->mallId;
} else {
$model->detail = $model->decodeDetail();
}
return [
'model' => $model,
];
}
public function actionPostageEditSave(){
$id = $this->get('id');
$model = PostageRules::findOne([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
'id' => $id
]);
if (!$model) {
$model = new PostageRules();
$model->mall_id = \Yii::$app->mallId;
} else {
$model->detail = $model->decodeDetail();
}
$form = new PostageRulesEditForm();
$form->attributes = \Yii::$app->request->post('form');
$form->model = $model;
return $form->save();
}
public function actionPostageEdit(){
return $this->render('postage-edit');
}
public function actionAllList(){
$allList = PostageRules::find()->where([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
])->select('id as value,name as label')->asArray()->all();
foreach ($allList as &$v){
$v['value'] = (int)$v['value'];
}
unset($v);
array_unshift($allList, [
'value' => 0,
'label' => '默认运费'
]);
return [
'list' => $allList
];
}
public function actionPostageDel(){
$id = $this->get('id');
if(PostageRules::updateAll(['is_delete'=>1],['id'=>$id,'mall_id'=>\Yii::$app->mallId])){
$this->callbackEvent([],'id','refresh');
return [];
}else{
throw new ApiException("删除失败");
}
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace admin\controllers\system;
use admin\components\BaseAdminController;
use common\models\DistrictArr;
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/21
* Time: 7:57 PM
*/
class DistrictController extends BaseAdminController{
public function actionIndex(){
if (\Yii::$app->request->isPost) {
$level = $this->post('level',3);
} elseif (\Yii::$app->request->isGet) {
$level = $this->get('level',3);
}
switch ($level) {
case 3:
$level = null;
break;
case 2:
$level = 'district';
break;
case 1:
$level = 'city';
break;
default:
$level = null;
}
$list = DistrictArr::getArr();
$district = DistrictArr::getList($list, $level);
return [
'district' => $district
];
}
}

View File

@@ -0,0 +1,140 @@
<?php
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/21
* Time: 11:50 AM
*/
namespace admin\controllers\system;
use app\forms\common\CommonPostageRules;
use admin\components\BaseAdminController;
use admin\components\UI\Form;
use admin\components\UI\Layout;
use admin\components\UI\Table;
use admin\components\UI\Tabs;
use admin\exceptions\ApiException;
use admin\models\forms\FreeRuleEditForm;
use admin\models\forms\PostageRulesEditForm;
use admin\models\search\CommonSearch;
use common\models\FreeDeliveryRules;
use common\models\PostageRules;
use yii\db\ActiveQuery;
class FreeRuleController extends BaseAdminController
{
public function actionIndex(){
$table = new Table(new FreeDeliveryRules());
//$table->model();
$table->title('包邮设置');
$table->key('id');
$table->eventName(md5(get_called_class()));//设置事件名,后面更改数据对应
$table->url(\Yii::$app->urlManager->createUrl("system/free-rule/list"));
$table->filter('规则名称', 'name',false)->text('请输入配置名')->quick();
$table->action()->button('添加', $this->createUrl('system/free-rule/edit'));
$table->column('规则名称','name');
$table->column('包邮类型','typeText');
$table->column('是否默认','status')->status(['否','是'],['gray','red']);
$column = $table->column('操作')->width(200);
$column->link('设为默认',$this->createUrl('system/free-rule/status'), ['id' => 'id'])->type('ajax', ['method' => 'post']);
$column->link('编辑', $this->createUrl('system/free-rule/edit'), ['id' => 'id']);
$column->link('删除', $this->createUrl('system/free-rule/del'), ['id' => 'id'])->type('ajax', ['method' => 'post']);
return $table->renderArray();
}
public function actionEdit(){
return $this->render('edit');
}
public function actionStatus(){
$params = $this->requestValidate($this->get(),[
['id','required'],
['id','integer']
]);
$this->callbackEvent([],'id','refresh');
return FreeDeliveryRules::setStatus($params->id);
}
public function actionInfo(){
$id = $this->get('id');
$model = FreeDeliveryRules::findOne([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
'id' => $id
]);
if (!$model) {
$model = new FreeDeliveryRules();
$model->mall_id = \Yii::$app->mallId;
} else {
$model->detail = $model->decodeDetail();
}
return [
'model' => $model,
];
}
public function actionEditSave(){
$id = $this->get('id');
$model = FreeDeliveryRules::findOne([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
'id' => $id
]);
if (!$model) {
$model = new FreeDeliveryRules();
$model->mall_id = \Yii::$app->mallId;
} else {
$model->detail = $model->decodeDetail();
}
$form = new FreeRuleEditForm();
$form->attributes = \Yii::$app->request->post('form');
$form->model = $model;
return $form->save();
}
public function actionList()
{
$commonSearch = new CommonSearch(['name']);
$commonSearch->setQuery(FreeDeliveryRules::find()
->select(['id', 'name', 'type','status'])
->where(['mall_id'=>\Yii::$app->mallId])->andWhere(['is_delete'=>0]));
$commonSearch->additionRules = [
['name', 'string']
];
$commonSearch->bindFilter(function(/** @var ActiveQuery $q */ $q) {
$q->andFilterWhere(['like','name',$this->name]);
});
$this->field = [
FreeDeliveryRules::class=>[
'id','name','type','status','typeText'
]
];
return $commonSearch->search($this->get());
}
public function actionAllList(){
$allList = FreeDeliveryRules::find()->where([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
])->select('id as value,name as label')->asArray()->all();
foreach ($allList as &$v){
$v['value'] = (int)$v['value'];
}
unset($v);
array_unshift($allList, [
'value' => 0,
'label' => '默认包邮规则'
]);
return [
'list' => $allList
];
}
public function actionDel(){
$id = $this->get('id');
if(FreeDeliveryRules::updateAll(['is_delete'=>1],['id'=>$id,'mall_id'=>\Yii::$app->mallId])){
$this->callbackEvent([],'id','refresh');
return [];
}else{
throw new ApiException("删除失败");
}
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace admin\controllers\system;
use admin\components\BaseAdminController;
use admin\exceptions\ApiException;
use admin\generators\model\Generator;
use admin\models\Menu;
use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
use common\models\Role;
use common\modelsgii\Menu2;
use common\modelsgii\RoleMenu;
use yii\web\Controller;
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/14
* Time: 7:43 PM
*/
class GeneratorController extends BaseAdminController {
public $enableCsrfValidation=false;
public function actionTables(){
$db = \Yii::$app->db;
if ($db === null) {
return [];
}
$tableNames = [];
//if (strpos($this->tableName, '*') !== false) {
// if (($pos = strrpos($this->tableName, '.')) !== false) {
// $schema = substr($this->tableName, 0, $pos);
// $pattern = '/^' . str_replace('*', '\w+', substr($this->tableName, $pos + 1)) . '$/';
// } else {
// $schema = '';
// $pattern = '/^' . str_replace('*', '\w+', $this->tableName) . '$/';
// }
$schema = '';
foreach ($db->schema->getTableNames($schema) as $table) {
$tableNames[] = $schema === '' ? $table : ($schema . '.' . $table);
}
//} elseif (($table = $db->getTableSchema($this->tableName, true)) !== null) {
// $tableNames[] = $this->tableName;
// $this->classNames[$this->tableName] = $this->modelClass;
//}
return $tableNames;
}
public function actionFields(){
$tableName = $this->post('table_name');
$db = \Yii::$app->db;
if ($db === null) {
return [];
}
$tableSchema = $db->getTableSchema($tableName);
return $tableSchema->columns;
}
public function actionConfig(){
return [
'controllerClass'=>'backend\controllers\\',
'baseControllerClass'=>'backend\components\BaseBackendController',
'actionIds'=>'list,save,info,del',
'vuePath'=>'/Users/chatfeed/arco-work/',
'controllerNamespace'=>'backend\controllers\\',
];
}
public function actionGenerate(){
//model generate
$modelGen = new Generator();
$modelGen->setAttributes(
[
'db'=>'db',
'useTablePrefix'=>$this->post('useTablePrefix'),
'ns'=>'common\modelsgii',
'tableName'=>$this->post('table_name'),
'baseClass'=>'common\core\BaseActiveRecord',
'queryNs'=>'common\models',
],
);
$modelClass = $modelGen->generateClassName($this->post('table_name'));
$files = $modelGen->generate();
//controller 生成
$conGEn = new \backend\generators\controller\Generator();
$conGEn->setAttributes([
'controllerClass'=>$this->post('controllerClass'),
'baseClass'=>$this->post('baseControllerClass'),
'actions'=>$this->post('actionIds'),
'controllerNamespace'=>$this->post('controllerNamespace')
]);
$files = $conGEn->generate();
foreach ($files as $f){
$f->save();
}
//vue生成
$vueGen = new \backend\generators\vue\Generator();
$vueGen->setAttributes([
'className'=>$modelClass,
'vuePath'=>$this->post('vuePath'),
'columns'=>$this->post('columns'),
'pagePath'=>$this->post('pagePath'),
'apiPath'=>$conGEn->getControllerSubPath().$conGEn->getControllerID(),
'actions'=>$this->post('actionIds'),
]);
$files = $vueGen->generate();
foreach ($files as $f){
$f->save();
}
return $files;
}
private function generatePHP(){
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/18
* Time: 3:19 PM
*/
namespace admin\controllers\system;
use admin\components\BaseAdminController;
use admin\components\UI\Elements\Button;
use admin\components\UI\Form;
use admin\components\UI\Layout;
use admin\components\UI\Node;
use admin\components\UI\Tabs;
use admin\components\UI\Widget;
use admin\models\Config;
use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
class IndexController extends BaseAdminController
{
public function actionIndex2()
{
$configs = Config::find()->where(['status'=>StatusEnum::ACTIVE])->orderBy('sort ASC')->asArray()->all();
$configGroups = [];
foreach ($configs as $config){
$configGroups[$config['group']][] = $config;
}
foreach (\Yii::$app->params['config_group'] as $idx=>$name){
}
}
public function actionIndex(){
$layout = new Layout("基础配置");
$tabs = new Tabs();
//return ['node'=>$layout->render(),'setupScript'=>"\n return {}"];
//$data = [];
$layout->addChild(Widget::alert("非专业人士或不清楚选项请勿随意修改,否则可能会导致系统崩溃",'安全提示',function ($alert){
return $alert->type('warning');
}));
$configs = Config::find()->where(['status'=>StatusEnum::ACTIVE])->orderBy('sort ASC')->asArray()->all();
$configGroups = [];
foreach ($configs as $config){
$configGroups[$config['group']][] = $config;
}
foreach (\Yii::$app->params['config_group'] as $idx=>$name){
$configGroup = isset($configGroups[$idx])?$configGroups[$idx]:[];
if(!empty($configGroup)){
$data = ArrayHelper::map($configGroup, 'name', 'value');
$form = new Form($data);
$form->action(\Yii::$app->urlManager->createUrl('system/index/save'));
foreach ($configGroup as $config){
$this->buildItem($form,$config);
}
$tabs->addTab($name,$idx,'',$form->renderFormWithoutNode());
}
}
$layout->addChild($tabs->render());
return $layout->render();
}
public function actionSave(){
/* 表单验证 */
$data =$this->post();
//var_dump($data);exit;
/* 更改配置值 */
$error = [];
foreach ($data as $name => $value) {
$model = Config::findOne(['name' => $name]);
$model->value = (string)$value;
$model->update_time = time();
if (!$model->save()) {
$error[$model->name] = $model->getFirstErrors();
}
}
if (empty($error)) {
return [];
} else {
return ['error'=>$error];
}
}
private function buildItem(Form $form,$config){
//params config_type
/**
* 'config_type' => [
0 => '数字',
1 => '字符',
2 => '文本',
3 => '数组',
4 => '枚举',
5 => '富文本'
],
*/
switch ($config['type']){
case 0:
case 1:
case 2:
$form->text($config['title'], $config['name'])->help($config['remark']);
break;
case 3:
$form->radio($config['title'],$config['name'],Config::parse(3,$config['extra']))->help($config['remark']);
break;
case 4:
$form->textarea($config['title'],$config['name'])->help($config['remark']);
break;
case 5:
$form->editor($config['title'],$config['name']);
//@todo
break;
}
}
private function _parseExtra($str){
$explode = explode("\n", trim($str));
$ret =[];
foreach ($explode as $itemStr){
list($name,$val) = explode(":",$itemStr);
$ret[$val] = $name;
}
return $ret;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace admin\controllers\system;
use common\core\BaseAdminController;
use admin\models\Menu;
use common\helpers\ArrayHelper;
use yii\base\Exception;
class MenuController extends BaseAdminController {
public $modelClass = Menu::class;
public function actionList()
{
$menu2s = Menu::find()->asArray()->all();
return ArrayHelper::itemsMerge($menu2s,0,'menuUrl','parentPath','children');
}
public function actionSave(){
$menuUrl = $this->post('menuUrl');
$model = Menu::findOne($menuUrl);
if(!$model){
$model = new Menu();
}
$model->load($this->post());
if( $model->load($this->post(),'') && $model->save()){
return $model->getAttributes();
}else{
throw new Exception("参数不对");
}
}
public function actionDel(){
$menuUrl = $this->post('menuUrl');
$model = Menu::findOne($menuUrl);
if($model->delete()){
Menu::updateAll(['parentPath'=>''],['parentPath'=>$menuUrl]);
}
return [];
}
}

View File

@@ -0,0 +1,139 @@
<?php
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/21
* Time: 11:50 AM
*/
namespace admin\controllers\system;
use app\forms\common\CommonPostageRules;
use admin\components\BaseAdminController;
use admin\components\UI\Form;
use admin\components\UI\Layout;
use admin\components\UI\Table;
use admin\components\UI\Tabs;
use admin\exceptions\ApiException;
use admin\models\forms\FreeRuleEditForm;
use admin\models\forms\PostageRulesEditForm;
use admin\models\forms\RefundAddressEditForm;
use admin\models\search\CommonSearch;
use common\models\DistrictArr;
use common\models\FreeDeliveryRules;
use common\models\PostageRules;
use common\models\RefundAddress;
use yii\db\ActiveQuery;
use yii\web\NotFoundHttpException;
class RefundAddressController extends BaseAdminController
{
public function actionIndex(){
$table = new Table(new RefundAddress());
//$table->model();
$table->title('退货地址');
$table->key('id');
$table->eventName(md5(get_called_class()));//设置事件名,后面更改数据对应
$table->url(\Yii::$app->urlManager->createUrl("system/refund-address/list"));
$table->filter('关键字', 'keyword',false)->text('请输入收件人姓名或联系方式')->quick();
$table->action()->button('添加', $this->createUrl('system/refund-address/edit'))->type('dialog');
$table->column('ID','id');
$table->column('收件人姓名','name');
$table->column('详细地址','full_address');
$table->column('备注','remark');
$column = $table->column('操作')->width(200);
$column->link('编辑', $this->createUrl('system/refund-address/edit'), ['id' => 'id'])->type('dialog');
$column->link('删除', $this->createUrl('system/refund-address/del'), ['id' => 'id'])->type('ajax', ['method' => 'post']);
return $table->renderArray();
}
public function actionEdit(){
$id = (int)$this->get('id');
$config = $this->findModel($id);
$form = new Form($config->getAttributes(['id','name','mobile','address_id','address_detail','remark']),false);
$form->title('配置信息');
$form->action($this->createUrl('system/refund-address/edit-save'));
$arr = DistrictArr::getArr();
unset($arr['1']);
$form->card(function (/** @var Form $form */$form) use($arr) {
$form->text("收件人姓名",'name');
$form->text("联系方式",'mobile');
$form->cascader('省市区','address_id',$arr);
$form->textarea('详细地址','address_detail');
$form->textarea('备注','remark');
});
return $form->renderArray();
}
public function actionDistrict()
{
$district_arr = DistrictArr::getArr();
$arr = DistrictArr::getList($district_arr);
$str = str_replace('list','children',json_encode($arr));
$arr = json_decode($str,true);
return $arr;
}
public function actionEditSave(){
$id = $this->get('id');
$model = RefundAddress::findOne([
'is_delete' => 0,
'mall_id' => \Yii::$app->mallId,
'id' => $id
]);
if (!$model) {
$model = new RefundAddress();
$model->mall_id = \Yii::$app->mallId;
}
$model->load($this->post(),'');
if($model->save()){
$this->callbackEvent([],'id','refresh');
return [];
}else{
return ['error'=>$model->getErrors()];
}
}
public function actionDel(){
$id = $this->get('id');
if(RefundAddress::updateAll(['is_delete'=>1],['id'=>$id,'mall_id'=>\Yii::$app->mallId])){
$this->callbackEvent([],'id','refresh');
return [];
}else{
throw new ApiException("删除失败");
}
}
public function actionList()
{
$commonSearch = new CommonSearch(['keyword']);
$commonSearch->setQuery(RefundAddress::find()
->select(['id', 'name','address','address_detail','remark'])
->where(['mall_id'=>\Yii::$app->mallId])->andWhere(['is_delete'=>0]));
$commonSearch->additionRules = [
['keyword', 'string']
];
$commonSearch->bindFilter(function(/** @var ActiveQuery $q */ $q) {
$q->andFilterWhere(['like','name',$this->keyword]);
});
$this->field = [
RefundAddress::class =>[
'id','name','full_address','remark'
]
];
return $commonSearch->search($this->get());
}
protected function findModel($id)
{
if ($id == 0) {
return new RefundAddress();
}
if (($model = RefundAddress::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace admin\controllers\system;
use common\core\BaseAdminController;
use admin\models\Menu;
use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
use common\models\Role;
use common\modelsgii\RoleMenu;
class RoleController extends BaseAdminController {
public $modelClass = Role::class;
public function actionList()
{
$roles = Role::find()->asArray()->all();
return $roles;
}
public function actionSaveUserMenu(){
$params = $this->requestValidate($this->post(),[
['role_id','required'],
['role_id','integer'],
['ids','required']
]);
if(is_array($params->ids)){
$insert = [];
foreach ($params->ids as $id){
$insert[] = [
'role_id'=>$params->role_id,
'menuUrl'=>$id,
'created_at'=>time(),
'updated_at'=>time()
];
}
RoleMenu::deleteAll(['role_id'=>$params->role_id]);
RoleMenu::getDb()->createCommand()->batchInsert(RoleMenu::tableName(),array_keys($insert[0]),$insert)->execute();
}
return [];
}
public function actionMenuByRoleId(){
$params = $this->requestValidate($this->post(),[
['roleId','required'],
]);
$roleMenus = RoleMenu::findAll(['role_id' => $params->roleId]);
$keys = ArrayHelper::getColumn($roleMenus,'menuUrl');
$menus = Menu::find()->asArray()->all();
return[
'menus'=>ArrayHelper::itemsMerge($menus,0,'menuUrl','parentPath','children'),
'checked'=>$keys
];
}
public function actionDel(){
$menuUrl = $this->post('menuUrl');
$model = Menu::findOne($menuUrl);
if($model->delete()){
Menu::updateAll(['parentPath'=>''],['parentPath'=>$menuUrl]);
}
return [];
}
}

View File

@@ -0,0 +1,147 @@
<?php
namespace admin\controllers\system;
use admin\models\Admin;
use admin\models\Menu;
use common\helpers\ArrayHelper;
use common\models\SubAccountMenu;
use common\modelsgii\RoleMenu;
use common\validators\DateRangeValidator;
use yii\base\DynamicModel;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
use yii\web\NotFoundHttpException;
use common\core\BaseAdminController;
class SubAccountController extends BaseAdminController
{
public $modelClass = Admin::class;
public function actionList()
{
$m = new DynamicModel(['page','pageSize']);
//$m->addRule('aa',DateRangeValidator::class);
//$m->addRule('xx','string');
$m->addRule('page','default',['value'=>1]);
$m->addRule('pageSize','default',['value'=>10]);
$m->addRule('page','integer',['max'=>1000]);
$m->addRule('pageSize','integer',['min'=>1,'max'=>50]);
$m->load($this->post());
if(!$m->validate()){
throw new Exception(json_encode($m->getFirstErrors()));
}
$query = Admin::find()->where(['is_sub'=>1])->andWhere([
'role'=>\Yii::$app->user->identity->role,
'mall_id'=>\Yii::$app->user->identity->mall_id,
'is_delete'=>0
]);
$this->field = [
Admin::class => [
'uid','username','mobile','last_login_time','last_login_ip'=>function($m){
return $m->last_login_ip ? long2ip($m->last_login_ip) : '';
}
]
];
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=>[
'defaultOrder'=>['uid'=>SORT_DESC]
],
'pagination'=>[
'defaultPageSize'=>$m->pageSize,
'params'=>['page'=>$m->page]
]
]);
// add conditions that should always apply here
return $dataProvider;
}
public function actionSave(){
$id = (int)$this->get('id');
$model = $this->findModel($id);
$data = $this->post();
$data['password'] = \Yii::$app->security->generatePasswordHash($data['password']);
$data['role'] = \Yii::$app->user->identity->role;
$data['mall_id'] = \Yii::$app->user->identity->mall_id;
$data['is_sub'] = 1;
$data['last_login_ip'] = isset($data['last_login_ip']) && $data['last_login_ip'] ? ip2long($data['last_login_ip']) : 0;
if($model->load($data,'') && $model->save()){
return [];
}else{
throw new Exception("保存失败:".current($model->getFirstErrors()));
}
}
public function actionMenuByUid(){
$params = $this->requestValidate($this->post(),[
['admin_id','required'],
]);
$roleMenus = RoleMenu::findAll(['role_id' => \Yii::$app->user->identity->role]);
$roleKeys = ArrayHelper::getColumn($roleMenus,'menuUrl');
$menus = Menu::find()->where(['in','menuUrl',$roleKeys])->asArray()->all();
$userMenus = SubAccountMenu::findAll(['admin_id'=>$params->admin_id]);
$keys = ArrayHelper::getColumn($userMenus,'menuUrl');
return[
'menus'=>ArrayHelper::itemsMerge($menus,0,'menuUrl','parentPath','children'),
'checked'=>$keys
];
}
public function actionDel(){
$params = $this->requestValidate($this->post(),[
['admin_id','required']
]);
$model = $this->findModel($params->admin_id);
if(!$model || $model->is_sub!==1){
throw new Exception("账号不存在");
}
$model->delete();
// $model->updateAttributes(['is_delete'=>1]);
return [];
}
public function actionSaveMenu(){
$params = $this->requestValidate($this->post(),[
['admin_id','required'],
['admin_id','integer'],
['ids','required']
]);
if(is_array($params->ids)){
$insert = [];
foreach ($params->ids as $id){
$insert[] = [
'admin_id'=>$params->admin_id,
'menuUrl'=>$id,
'created_at'=>time(),
'updated_at'=>time()
];
}
SubAccountMenu::deleteAll(['admin_id'=>$params->admin_id]);
SubAccountMenu::getDb()->createCommand()->batchInsert(SubAccountMenu::tableName(),array_keys($insert[0]),$insert)->execute();
}
return [];
}
/**
* @param $id
* @return ActiveRecord
* @throws NotFoundHttpException
*/
protected function findModel($id)
{
if ($id == 0) {
return new $this->modelClass();
}
if (($model = $this->modelClass::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}