初始化仓库

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,80 @@
<?php
namespace admin\models\forms;
use common\models\Activity;
use common\validators\MobieValidator;
use Yii;
use common\core\BaseModel;
use yii\base\Exception;
class ActivityForm extends BaseModel
{
public $id;
public $mall_id;
public $title;
public $price;
public $start_time;
public $end_time;
public $p_commission;
public $pp_commission;
public $content;
public $contact;
public $mobile;
/**
* @inheritdoc
*/
public function rules()
{
return [
['id','default','value'=>0],
[['mall_id','title','contact','mobile','price','start_time','end_time','p_commission','pp_commission'],'required'],
['content','default','value'=>''],
['mobile',MobieValidator::class,'message'=>'手机号格式不正确'],
[['price'],'number','min'=>0],
[['p_commission','pp_commission'],'number','min'=>1],
[['p_commission','pp_commission'], 'match', 'pattern' => '/^\d+(\.\d{1,2})?$/i','message'=>'佣金最多只能有两位小数']
];
}
public function attributeLabels()
{
return [
'mall_id' => '活动门店',
'title' => '活动标题',
'contact' => '联系人',
'mobile' => '联系电话',
'price' => '活动价格',
'start_time' => '活动开始时间',
'end_time' => '活动结束时间',
'p_commission' => '上级返佣',
'pp_commission' => '上上级返佣'
];
}
public function save()
{
if (!$this->validate()) {
throw new Exception($this->getErrorMsg($this));
}
if($this->id){
$model = Activity::find()->where([
'id' => $this->id,
'is_delete' => 0
])->one();
if(!$model){
throw new Exception('活动不存在');
}
}else{
$model = new Activity();
}
$model->attributes = $this->attributes;
$model->start_time = strtotime($this->start_time);
$model->end_time = strtotime($this->end_time);
$model->saveOrFail();
return [];
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace admin\models\forms;
use common\models\Attachment;
use OSS\OssClient;
use yii\web\UploadedFile;
class AttachmentUpload extends \yii\base\Model
{
public $storage;
public $file;
public $attachment_group_id;
public $type;
public $mall_id;
public $mch_id;
public $saveFileFolder;
public $saveThumbFolder;
public $saveFileName;
public $url;
public $thumbUrl;
protected $docExt = ['txt', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv', 'pdf', 'md'];
protected $imageExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',];
protected $videoExt = ['mp4', 'ogg', 'm4a',];
/**
* @return Attachment
* @throws \Exception
*/
public function upload()
{
$dateFolder = date('Ymd');
$this->saveFileFolder = '/uploads/' . \Yii::$app->mallId.'/' . $dateFolder;
$this->saveThumbFolder = '/uploads/thumbs/' . \Yii::$app->mallId.'/' . $dateFolder;
$this->saveFileName = md5_file($this->file->tempName) . '.' . $this->file->getExtension();
$this->saveToAliOss();
return $this->attachmentSave();
}
public function attachmentSave()
{
$attachment = new Attachment();
$attachment->storage_id = $this->storage ? $this->storage->id : 0;
$attachment->user_id = 0;
$attachment->name = $this->file->name;
$attachment->size = $this->file->size;
$attachment->is_delete = 0;
$attachment->url = $this->url;
$attachment->thumb_url = $this->thumbUrl;
$attachment->attachment_group_id = $this->attachment_group_id;
$attachment->type = $this->type;
$attachment->mall_id = $this->mall_id;
$attachment->mch_id = $this->mch_id;
if (!$attachment->save()) {
throw new \Exception(json_encode($attachment->getErrors()));
}
return $attachment;
}
public function saveToAliOss()
{
$config = \Yii::$app->params['upload']['alioss'];
$isCName = (isset($config['is_cname']) && $config['is_cname'] == 1) ? true : false;
$client = new OssClient($config['access_key'], $config['secret_key'], $config['domain'], $isCName);
$object = trim($this->saveFileFolder . '/' . $this->saveFileName, '/');
$client->uploadFile($config['bucket'], $object, $this->file->tempName);
if (!$isCName) {
$endpointNameStart = mb_stripos($config['domain'], '://') + 3;
$urlPrefix = mb_substr($config['domain'], 0, $endpointNameStart)
. $config['bucket']
. '.'
. mb_substr($config['domain'], $endpointNameStart);
} else {
$urlPrefix = $config['domain'];
}
$this->url = $urlPrefix . $this->saveFileFolder . '/' . $this->saveFileName;
if (in_array($this->file->extension, $this->imageExt) && isset($config['style_api']) && $config['style_api']) {
$this->url = $this->url . $config['style_api'];
}
$this->thumbUrl = $this->url;
}
public static function getInstanceFromFile($localFilePath)
{
if (!is_string($localFilePath)) {
throw new \Exception('文件名称不是字符串。');
}
if (!file_exists($localFilePath)) {
throw new \Exception('文件`' . $localFilePath . '`不存在。');
}
$localFilePath = str_replace('\\', '/', $localFilePath);
$pathInfo = pathinfo($localFilePath);
$name = $pathInfo['basename'];
$size = filesize($localFilePath);
$type = mimetype_from_filename($localFilePath);
return new UploadedFile([
'name' => $name,
'type' => $type,
'tempName' => $localFilePath,
'error' => 0,
'size' => $size,
]);
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace admin\models\forms;
use OSS\OssClient;
use yii\web\UploadedFile;
use function GuzzleHttp\Psr7\mimetype_from_filename;
class AttachmentUploadForm extends \yii\base\Model
{
/** @var UploadedFile */
public $file;
public $type;
public $attachment_group_id;
protected $docExt = ['txt', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv', 'pdf', 'md'];
protected $imageExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',];
protected $videoExt = ['mp4', 'ogg', 'm4a','mp3'];
protected $maxSize = ['img'=>20,'video'=>100,'doc'=>5];
public function rules()
{
return [
[['file'], 'file'],
[['file'], 'validateExt'],
[['attachment_group_id'], 'integer'],
[['type'], 'string'],
];
}
public function validateExt($a, $p)
{
$supportExt = array_merge($this->docExt, $this->imageExt, $this->videoExt);
if (!in_array($this->file->extension, $supportExt)) {
$this->addError($a, '不支持的文件类型: ' . $this->file->extension);
}
if (in_array($this->file->extension, $this->imageExt)) {
if ( $this->file->size > ($this->maxSize['img'] * 1024 * 1024)) {
$this->addError($a, '图片大小超出限制,当前大小为: '
. (round($this->file->size / 1024 / 1024, 4)) . 'MB,最大限制为:'
. $this->maxSize['img'] . 'MB');
}
}
if (in_array($this->file->extension, $this->videoExt)) {
if ($this->file->size > ($this->maxSize['video'] * 1024 * 1024)) {
$this->addError($a, '视频大小超出限制,当前大小为: '
. (round($this->file->size / 1024 / 1024, 4)) . 'MB,最大限制为:'
. $this->maxSize['maxSize'] . 'MB');
}
}
}
public function checkExt($ext)
{
if (in_array($ext, $this->imageExt)) {
$type = 1;
} elseif (in_array($ext, $this->videoExt)) {
$type = 2;
} elseif (in_array($ext, $this->docExt)) {
$type = 3;
} else {
$type = 0;
}
return $type;
}
public function save()
{
if (!$this->validate()) {
return ['error'=>$this->getErrors()];
}
if ($this->type === 'image') {
$type = 1;
} elseif ($this->type === 'video') {
$type = 2;
} else {
if (in_array($this->file->extension, $this->imageExt)) {
$type = 1;
} elseif (in_array($this->file->extension, $this->videoExt)) {
$type = 2;
} elseif (in_array($this->file->extension, $this->docExt)) {
$type = 3;
} else {
$type = 0;
}
}
$mallId = \Yii::$app->mallId;
$mchId = 0;
$attachmentUpload = new AttachmentUpload([
'file' => $this->file,
'type' => $type,
'mall_id' => $mallId,
'mch_id' => $mchId,
'attachment_group_id' => $this->attachment_group_id ? $this->attachment_group_id : 0
]);
$attachment = $attachmentUpload->upload();
$attachment->thumb_url = $attachment->thumb_url ? $attachment->thumb_url : $attachment->url;
return $attachment;
}
public static function getInstanceFromFile($localFilePath)
{
return AttachmentUpload::getInstanceFromFile($localFilePath);
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace admin\models\forms;
use admin\exceptions\ApiException;
use common\models\FreeDeliveryRules;
use yii\base\Model;
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/23
* Time: 6:02 PM
*/
/**
* @property FreeDeliveryRules $model
*/
class FreeRuleEditForm extends Model
{
public $model;
public $price;
public $detail;
public $name;
public $type;
public $status;
public function rules()
{
return [
[['type', 'status'], 'integer'],
[['price', 'status'], 'default', 'value' => 0],
['price', 'number', 'min' => 0],
['detail', 'safe'],
['name', 'required'],
];
}
public function save()
{
if (!$this->validate()) {
return ['error'=>$this->model->getErrors()];
}
if ($this->model->isNewRecord) {
$this->model->is_delete = 0;
}
$conditionList = [];
foreach ($this->detail as &$item) {
if (isset($item['condition'])) {
if (in_array($item['condition'], $conditionList)) {
throw new ApiException("同一条规则下,包邮条件不能相同");
}
$conditionList[] = $item['condition'];
$item['condition'] = trim($item['condition']);
if (!is_numeric($item['condition']) || $item['condition'] < 0 || $item['condition'] > 99999999) {
throw new ApiException("包邮条件必须大于等于0,小于99999999");
}
if (empty($this->type)) {
throw new ApiException("请选择包邮类型");
}
if (in_array($this->type, [2, 4])) {
$item['condition'] = (int)$item['condition'];
}
} else {
throw new ApiException("请设置包邮条件");
}
}
unset($item);
$this->model->detail = json_encode($this->detail);
$this->model->price = $this->price;
$this->model->name = $this->name;
$this->model->type = $this->type;
$this->model->status = $this->status;
if ($this->model->save()) {
return [];
} else {
return ['error'=>$this->model->getErrors()];
}
}
}

View File

@@ -0,0 +1,194 @@
<?php
namespace admin\models\forms;
use common\core\BaseModel;
use common\enums\UserRoleEnum;
use common\models\DoctorApply;
use common\models\DoctorPatient;
use common\models\ServiceUser;
use common\models\StoreDoctor;
use GuzzleHttp\Client;
use linslin\yii2\curl\Curl;
use yii\db\Exception;
class HospitalDocForm extends BaseModel
{
public $store_id;
public $doctor_id;
public $status;
public function rules()
{
return [
['doctor_id','required'],
[['status','store_id'],'integer']
];
}
public function attributes()
{
return [];
}
//获取互医信息
public function DocInfo()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
ServiceUser::find()->where([
'id' => $this->doctor_id,
'role' => UserRoleEnum::DOCTOR,
'is_delete' => 0,
])->one();
$sql = "select * from yii_doctor_platform where platform_doctor_id= $this->doctor_id and platform_store_id=$store";
$doctor_is_exist = \Yii::$app->db1->createCommand($sql)->queryOne();
if (!$doctor_is_exist){
throw new Exception('您还没成为互医');
}
$doctor_id = $doctor_is_exist['su_id'];
$doctor_info = "select * from yii_doctor_info where su_id=$doctor_id";
$doctor_info_exist = \Yii::$app->db1->createCommand($doctor_info)->queryOne();
$doctor_identity = "select * from yii_doctor_identity where su_id=$doctor_id";
$doctor_identity_exist = \Yii::$app->db1->createCommand($doctor_identity)->queryOne();
$doctor_practicing = "select * from yii_doctor_practicing where su_id=$doctor_id";
$doctor_practicing_exist = \Yii::$app->db1->createCommand($doctor_practicing)->queryOne();
$doctor_service = "select * from yii_doctor_service where su_id=$doctor_id";
$doctor_service_exist = \Yii::$app->db1->createCommand($doctor_service)->queryOne();
return [
'doctor'=>$doctor_is_exist,
'doctor_info'=>$doctor_info_exist,
'doctor_identity'=>$doctor_identity_exist,
'doctor_practicing'=>$doctor_practicing_exist,
'doctor_service'=>$doctor_service_exist
];
}
/**
* 升级为互医
*/
public function grade()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$ServiceUser = ServiceUser::find()->where([
'id' => $this->doctor_id,
'role' => UserRoleEnum::DOCTOR,
'is_delete' => 0,
'plate_type'=>2 //萧康的医生
])->one();
if (!$ServiceUser){
throw new Exception('萧康不存在该医生');
}
if (!$ServiceUser->docIdentity || !$ServiceUser->docPracticing || !$ServiceUser->docInfo || !$ServiceUser->docService)
throw new Exception('请完善基本信息');
$store_ids=StoreDoctor::find()->where([
'su_id'=>$this->doctor_id
])->select('store_id')->column();
if (!$store_ids){
throw new Exception('您还没有任何门店');
}
$params=[
'id' => $this->doctor_id,
'store_id'=>$store_ids,
'mobile'=>$ServiceUser->mobile,
'docInfo' =>$ServiceUser->docInfo,
'docIdentity'=> $ServiceUser->docIdentity,
'docPracticing'=>$ServiceUser->docPracticing,
'docService'=> $ServiceUser->docService,
];
$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']);
}
return ['升级成功'];
}
//同步患者
public function SyncPatient()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$store=\Yii::$app->store;
$patient=DoctorPatient::find()->where([
'su_id'=>$this->doctor_id,
])->all();
$sql = "select * from yii_doctor_platform where platform_doctor_id=$this->doctor_id and platform_store_id=$store";
$doctor_is_exist = \Yii::$app->db1->createCommand($sql)->queryOne();
if (!$doctor_is_exist){
throw new Exception('您还没成为互医');
}
$rows=[];
foreach ($patient as $value){
$rows[]=[
'su_id'=>$doctor_is_exist['su_id'],
'user_id'=>$value['user_id'],
'up_id'=>$value['up_id'],
'name'=>$value['name'],
'avatar'=>$value['avatar'],
'id_card'=>$value['id_card'],
'sex'=>$value['sex'],
'mobile'=>$value['mobile'],
'created_at' => time(),
'updated_at' => time(),
];
}
\Yii::$app->db1->createCommand()->batchInsert('yii_doctor_patient', ['su_id','user_id','up_id','name','avatar','id_card','sex','mobile','created_at','updated_at'],$rows)->execute();
return ['患者同步成功'];
}
//医生审核
public function ExamineDoc()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$DoctorApply=DoctorApply::find()->where([
'service_user_id'=>$this->doctor_id,
'status'=>0,
'is_delete'=>0,
])->one();
if (!$DoctorApply){
throw new Exception('该医生没有升级申请');
}
$DoctorApply->id=$DoctorApply->id;
$DoctorApply->service_user_id=$this->doctor_id;
$DoctorApply->status=$this->status;
$DoctorApply->update();
return [];
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace admin\models\forms;
use admin\models\Admin;
use common\models\AdminAccessToken;
use Yii;
use common\core\BaseModel;
use common\validators\MobieValidator;
use yii\db\Exception;
/**
* register form
*/
class LoginForm extends BaseModel
{
public $mobile;
public $password;
public $rememberMe = true;
/**
* @var Admin
*/
private $_user;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['mobile', 'password'], 'required'],
['mobile', MobieValidator::class],
['password', 'validatePassword'],
['rememberMe', 'boolean'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect mobile or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
$adminAccessToken = new AdminAccessToken();
return $adminAccessToken->createToken($this->_user->uid,'admin');
} else {
throw new Exception($this->getErrorMsg());
}
}
/**
* Finds user by [[username]]
*
* @return Admin|null
*/
public function getUser()
{
if ($this->_user === null) {
$this->_user = Admin::findByMobile($this->mobile);
}
return $this->_user;
}
public function ResetPassword()
{
$admin=Admin::find()->where([
'mobile'=>$this->mobile
])->one();
if (!$admin) return ['账号不存在'];
$admin->password=(new Admin())->setPassword($this->password);
if (!$admin->saveOrFail())throw new Exception('重置密码或忘记密码失败');
return ['重置密码或忘记密码成功'];
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace admin\models\forms;
use admin\exceptions\ApiException;
use common\models\PostageRules;
use yii\base\Model;
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/23
* Time: 2:21 PM
*/
/**
* @property PostageRules $model
*/
class PostageRulesEditForm extends Model
{
public $name;
public $type;
public $detail;
public $model;
public function rules()
{
return [
[['name', 'type'], 'required'],
['type', 'integer'],
['detail', 'safe']
];
}
public function save()
{
if (!$this->validate()) {
return $this->getErrorResponse();
}
if (empty($this->detail)) {
throw new ApiException("请填写运费规则");
}
foreach ($this->detail as &$item) {
if (isset($item['first'])) {
if(!is_numeric($item['first'])) {
throw new ApiException("首件/首重必须是数字且不小于0");
}
} else {
$item['first'] = 0;
}
if (isset($item['firstPrice'])) {
if (!is_numeric($item['firstPrice']) || $item['firstPrice'] < 0) {
throw new ApiException("运费必须是数字且不小于0");
}
} else {
$item['firstPrice'] = 0;
}
if (isset($item['second'])) {
if (!is_numeric($item['second'])) {
throw new ApiException("续件/续重必须是数字且不小于0");
}
} else {
$item['second'] = 0;
}
if (isset($item['secondPrice'])) {
if (!is_numeric($item['secondPrice']) || $item['secondPrice'] < 0) {
throw new ApiException("运费必须是数字且不小于0");
}
} else {
$item['secondPrice'] = 0;
}
}
$this->detail = json_encode($this->detail);
$this->model->attributes = $this->attributes;
if ($this->model->save()) {
return [
];
} else {
return ['errors'=>$this->model->getErrors()];
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Created by PhpStorm.
* User: chatfeed
* Date: 2022/5/23
* Time: 7:14 PM
*/
namespace admin\models\forms;
use admin\exceptions\ApiException;
use common\models\DistrictArr;
use common\models\RefundAddress;
use yii\base\Model;
class RefundAddressEditForm extends RefundAddress
{
public $name;
public $addressId;
public $address_detail;
public $mobile;
public $remark;
public $id;
public function rules()
{
return [
[['name', 'addressId', 'mobile'], 'required'],
[['name', 'mobile', 'remark', 'address_detail'], 'string'],
[['id','addressId'], 'integer'],
];
}
public function attributeLabels()
{
return [
'name' => '收件人名称',
'address' => '省市区',
'address_detail' => '收件人详细地址',
'mobile' => '收件人手机号',
'remark' => '备注',
];
}
public function save($runValidation = true, $attributeNames = null)
{
if (!$this->validate()) {
return ['error'=>$this->getErrors()];
}
$addressArr = [];
$arr = DistrictArr::getArr();
$area = $arr[$this->addressId];
$city = $arr[$area['parent_id']];
$province = $arr[$city['parent_id']];
$this->address = json_encode([$province['name'],$city['name'],$area['name']]);
if (!parent::save($runValidation,$attributeNames)) {
throw new \Exception('保存失败');
}else{
return [];
}
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\BaseConfig;
use yii\db\Exception;
//协议Form
class AgreeForm extends BaseModel
{
public $id;
public $end;
public $desc;
public $type;
public $content;
public $status;
public $change_at;
public function rules()
{
return [
[['id', 'status', 'end', 'type', 'change_at','end'], 'integer'],
[['desc', 'content'], 'string'],
[['content', 'type'], 'required'],
];
}
public function save()
{
if (!$this->validate()) {
throw new Exception($this->getErrorMsg());
}
if (!$this->id) {
$BaseConfig = new BaseConfig();
} else {
$BaseConfig = BaseConfig::find()->where([
'id' => $this->id,
])->one();
if (!$BaseConfig) {
throw new Exception('协议不存在');
}
}
$BaseConfig->end = $this->end ?? $BaseConfig->end;
$BaseConfig->desc = $this->desc ?? $BaseConfig->desc;
$BaseConfig->type = $this->type ?? $BaseConfig->type;
$BaseConfig->content = $this->content ?? $BaseConfig->content;
$BaseConfig->change_at = time();
$BaseConfig->saveOrFail();
return ['success'];
}
public function del()
{
$BaseConfig = BaseConfig::find()->where([
'id' => $this->id
])->one();
if (!$BaseConfig) {
throw new Exception('协议不存在');
}
$BaseConfig->status = 1;
if (!$BaseConfig->saveOrFail()) {
throw new Exception('删除失败');
}
return ['已删除'];
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\DoctorArticle;
use yii\db\Exception;
//文章Form
class ArticleForm extends BaseModel
{
public $id;
public $type;
public $cid;
public $su_id;
public $cover;
public $title;
public $intro;
public $content;
public $video_url;
public $read_num;
public $collection;
public $is_draft;
public function rules()
{
return [
[['su_id','read_num','collection','is_draft','id'],'integer'],
[['cover','content','title','cid','type'],'required'],
[['video_url','content','cover','title','intro'],'string'],
['su_id','default','value'=>'0'],
['read_num','default','value'=>'0'],
['collection','default','value'=>'0'],
['is_draft','default','value'=>'0'],
];
}
public function attributeLabels()
{
return [
'type'=>'文章类型',
'cid'=>'分类id',
'cover'=>'封面',
'intro'=>'简介',
'content'=>'内容',
'title'=>'文章标题',
'video_url'=>'视频链接',
'is_draft'=>'是否是草稿0否1是',
'su_id'=>'医生id 0为后台发布',
];
}
public function save()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
if (!$this->id){
$DoctorArticle= new DoctorArticle();
}else{
$DoctorArticle= DoctorArticle::find()->where(['id'=>$this->id])->one();
if (!$DoctorArticle) throw new Exception('文章不存在');
}
$DoctorArticle->attributes=$this->attributes;
if (!$DoctorArticle->saveOrFail()){
throw new Exception('error');
};
return ['success'];
}
public function del()
{
$article= DoctorArticle::find()->where([
'id' => $this->id,
'is_delete'=>0
])->one();
if (!$article) throw new Exception('文章不存在');
$article->is_delete=1;
$article->saveOrFail();
return ['删除成功'];
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\Drug;
use yii\db\Exception;
//中药饮片form
class ChineseForm extends BaseModel
{
public $id;
public $drug_name;
public $drug_number;
public $drug_alias;
public $unit_id;
public $decotion;
public $place;
public $source;
public $instruction;
public $type;
public $drugstore;
public $pinyin_simple;
public $is_otc;
public $category_first;
public $category_second;
public $status;
public function rules()
{
return [
[['id','type','status','is_otc'],'integer'],
[['drug_name','drug_number','unit_id','pinyin_simple','status'],'required'],
[['place','source','instruction','drugstore','pinyin_simple','decotion','drug_alias'],'string'],
['type','default','value'=>'1'],
];
}
public function attributeLabels()
{
return [
'drug_name'=>'药名',
'drug_number'=>'药品编号',
'drug_alias'=>'药品别名',
'unit_id'=>'单位',
'pinyin_simple'=>'拼音首拼',
'status'=>'状态 1草稿 2下架 3上架',
'decotion'=>'煎法',
'is_otc'=>'是否处方药',
];
}
public function save()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$t = \Yii::$app->db->beginTransaction();
try {
$DRUG=new Drug();
$DRUG->attributes=$this->attributes;
$DRUG->created_at=time();
$DRUG->saveOrFail();
$t->commit();
return ['新增成功'];
}catch (\Exception $e){
$t->rollBack();
throw new Exception($e->getMessage());
}
}
public function update()
{
$drug=Drug::find()->where([
'id'=>$this->id,
'type'=>1,
])->one();
if (!$drug) throw new \yii\base\Exception('该药品不存在');
$drug->pinyin_simple=$this->pinyin_simple??$drug->pinyin_simple;
$drug->status=$this->status??$drug->status;
$drug->drug_name=$this->drug_name??$drug->drug_name;
$drug->drug_number=$this->drug_number??$drug->drug_number;
$drug->drug_alias=$this->drug_alias??$drug->drug_alias;
$drug->unit_id=$this->unit_id??$drug->unit_id;
$drug->place=$this->place??$drug->place;
$drug->source=$this->source??$drug->source;
$drug->instruction=$this->instruction??$drug->instruction;
$drug->saveOrFail();
return ['编辑成功'];
}
public function info()
{
$drug=Drug::find()->where([
'id'=>$this->id,
'type'=>1,
])->one();
if (!$drug) throw new Exception('该药品不存在');
return $drug;
}
}

View File

@@ -0,0 +1,218 @@
<?php
namespace admin\models\forms\drug;
use admin\controllers\StoreController;
use admin\models\Admin;
use common\core\BaseModel;
use common\enums\UserRoleEnum;
use common\models\CashAccount;
use common\models\Department;
use common\models\Hospital;
use common\models\Log;
use common\models\Store;
use common\services\WeappService;
use yii\db\Exception;
use yii\helpers\Json;
//科室form
class DepartForm extends BaseModel
{
public $hospital_id;
public $position;
public $depart_id;
public $yard_id;
public $name;
public $pid;
public $level;
public $feature;
public $logo;
public $image;
public $intro;
public $content;
public $id;
public $plate_id;
public $drugstore_id;
public $erp_id;
public $contact;
public $mobile;
public $offical_seal;
public $start_time;
public $end_time;
public $pic;
public $qr_code;
public $shouzimu;
public $store_name;
public $bank_user_name;
public $bank_card;
public $bank_name;
public $bank_account_type;
public $bank_no;
public $code;
public $province_id;
public $city_id;
public function rules()
{
return [
[['name','level','offical_seal','code'],'required'],
[['position','logo','offical_seal','image','intro','content','contact','mobile','start_time','end_time','pic','qr_code','shouzimu','store_name','bank_user_name','bank_card','bank_name','bank_no'],'string'],
[['depart_id','hospital_id','pid','yard_id','plate_id','drugstore_id','id','bank_account_type','province_id','city_id','erp_id'],'integer'],
[['feature','pid'],'default','value'=>0],
];
}
public function attributeLabels()
{
return [
'erp_id'=>'对接的erp_id',
'code'=>'推广码',
'level'=>'级别',
'offical_seal'=>'公章',
'name'=>'名字',
'shouzimu'=>'首字母',
'start_time'=>'开始营业时间',
'end_time'=>'结束营业时间',
'qr_code'=>'门店二维码',
];
}
//新增科室
public function SaveDepart()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$Department=Department::find()->where([
'name'=>$this->name
])->one();
if ($Department) throw new Exception('科室已存在');
if ($this->level != 1){
if (empty($this->pid)){
return ['pid不能为空'];
}
}
$department=new Department();
$department->attributes=$this->attributes;
$department->saveOrFail();
return ['添加成功'];
}
//新增门店
public function SaveStore()
{
$admin=Admin::find()->where(['code'=>$this->code,'role'=>UserRoleEnum::SUPPLY])->one();
if (!$admin)throw new Exception('推广码或业务员不存在');
if ($this->id){
$Store=Store::find()->where([
'plate_id'=>$this->plate_id,
'id'=>$this->id
])->one();
if (!$Store) throw new Exception('门店不存在');
if (!empty($this->bank_account_type)){
if ($this->bank_account_type== 1 || $this->bank_account_type == 5) {
if (empty($this->bank_no)) {
throw new Exception('bank_no不能为空');
}
} else {
if (substr($this->bank_card, 0, 2) != '62') {
if (empty($this->bank_no)) {
throw new Exception('bank_no不能为空');
}
}
}
}
$Store->plate_id=$this->plate_id;
$Store->drugstore_id=$this->drugstore_id;
$Store->name=$this->store_name;
if($this->erp_id){
$Store->erp_id=$this->erp_id;
}
$Store->shouzimu=$this->shouzimu;
$Store->contact=$this->contact;
$Store->offical_seal=$this->offical_seal??$Store->offical_seal;
$Store->province_id=$this->province_id;
$Store->city_id=$this->city_id;
$Store->position=$this->position;
$Store->mobile=$this->mobile;
$Store->uid=$admin->uid;
$Store->code=$this->code;
$Store->bank_user_name=$this->bank_user_name;
$Store->bank_card=$this->bank_card;
$Store->bank_name=$this->bank_name;
$Store->bank_account_type=$this->bank_account_type;
$Store->bank_no=$this->bank_no;
$Store->start_time=$this->start_time;
$Store->end_time=$this->end_time;
if(!$Store->qr_code){
$scene = 'STORE_QR_CODE'.'_'.$this->id;
$weappService = new WeappService();
$url= $weappService->getQrcode($scene);
$Store->qr_code = $url;
}
$Store->saveOrFail();
return ['编辑成功'];
}
$Store=Store::find()->where([
'plate_id'=>$this->plate_id,
'name'=>$this->name
])->one();
if ($Store) throw new Exception('门店已存在');
$t=\Yii::$app->db->beginTransaction();
try {
$Store=new Store();
$Store->plate_id=$this->plate_id;
$Store->drugstore_id=$this->drugstore_id;
$Store->erp_id=$this->erp_id;
$Store->name=$this->store_name;
$Store->contact=$this->contact;
$Store->offical_seal=$this->offical_seal??'';
$Store->province_id=$this->province_id;
$Store->city_id=$this->city_id;
$Store->position=$this->position;
$Store->mobile=$this->mobile;
$Store->uid=$admin->uid;
$Store->code=$this->code;
// $Store->bank_user_name=$this->bank_user_name;
// $Store->bank_card=$this->bank_card;
// $Store->bank_name=$this->bank_name;
// $Store->bank_account_type=$this->bank_account_type;
// $Store->bank_no=$this->bank_no;
$Store->start_time=$this->start_time;
$Store->end_time=$this->end_time;
$Store->shouzimu=$this->shouzimu;
$Store->saveOrFail();
$add_store = Store::find()->where([
'id' => $Store->id
])->one();
$scene = 'STORE_QR_CODE'.'_'.$add_store->id;
$weappService = new WeappService();
$url= $weappService->getQrcode($scene);
$add_store->qr_code=$url;
$add_store->saveOrFail();
// StoreController::actionQrcode($Store->id);
$t->commit();
return ['添加成功'];
}catch (\Exception $e){
$t->rollBack();
throw new Exception($e->getMessage());
}
}
}

View File

@@ -0,0 +1,104 @@
<?php
/*
* @author: liudiao
* @Date: 2023-04-18 11:05:02
* @Description:
*/
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\modelsgii\Disease;
use Overtrue\Pinyin\Pinyin;
use yii\db\Exception;
//症状诊断form
class DiagnoseForm extends BaseModel
{
public $id;
public $name;
public $diagnose_code;
public $major_number;
public $ref_number;
public function rules()
{
return [
['id','integer'],
['name','required'],
[['diagnose_code','major_number','ref_number'],'string']
];
}
//录入
public function save()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
if ($this->id){
$Disease=Disease::find()->where(['id'=>$this->id,'is_delete'=>0])->one();
$Disease->attributes=$this->attributes;
$Disease->saveOrFail();
return ['编辑成功'];
}
$is_disease=Disease::find()->where(['name'=>$this->name,'is_delete'=>0])->one();
if ($is_disease) throw new Exception('改症状已经存在,请勿重复添加');
$add_disease=new Disease();
$add_disease->attributes=$this->attributes;
$add_disease->pinyin = (new Pinyin())->abbr($this->name);
$add_disease->saveOrFail();
return ['添加成功'];
}
//导入
public function export($data)
{
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
foreach ($data as $item) {
try {
$Disease=Disease::find()->where(['diagnose_code'=>$item['编码'],'is_delete'=>0])->one();
if (!$Disease){
$model = new Disease();
$model->setAttribute('diagnose_code', trim($item['编码']));
$model->setAttribute('name', trim($item['名称']));
$model->setAttribute('pinyin', (new Pinyin())->abbr(trim($item['名称'])));
$model->setAttribute('major_number', trim($item['主编号']));
$model->setAttribute('ref_number',trim($item['次编号']) );
if (!$model->save()) {
$errorsMsg = array_values($model->getFirstErrors());
return [$errorsMsg[0]];
}
$success[] = '诊断症状导入成功';
}else{
$errors[]= '编码:'.$item['编码'].'导入失败,原因:重复导入';
}
} catch (\Exception $e) {
$errors[] = $e->getMessage();
continue;
}
}
return ['success'=> $success,'error'=>$errors];
}
}
public function del()
{
$Disease=Disease::find()->where([
'id'=>$this->id,
'is_delete'=>0
])->one();
if (!$Disease) throw new Exception('诊断症状不存在');
$Disease->is_delete=1;
$Disease->saveorFail();
return ['删除成功'];
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\DrugCategories;
use yii\db\Exception;
class DrugCategoryForm extends BaseModel
{
public $id;
public $category_name;
public $parent_id;
public $level;
public $sort;
public function rules()
{
return [
['id', 'integer'],
[['category_name', 'level', 'sort'], 'required'],
['parent_id', 'default','value'=>'0'],
['category_name', 'string'],
];
}
public function attributeLabels()
{
return [
'level'=>'等级',
'sort'=>'排序',
'parent_id'=>'父级ID',
];
}
public function save()
{
if (!$this->validate()) {
throw new Exception($this->getErrorMsg());
}
$DrugCategories = DrugCategories::find()->where([
'category_name' => $this->category_name,
'deleted_at' => null
])->one();
if ($DrugCategories) throw new Exception('药品分类已存在,请勿重复添加');
if ($this->level != 1){
if (empty($this->parent_id)){
return ['parent_id不能为空'];
}
}
if (!$this->id){
$DrugCategories=new DrugCategories();
}
$DrugCategories->category_name = $this->category_name;
$DrugCategories->parent_id = $this->parent_id;
$DrugCategories->level = $this->level;
$DrugCategories->sort = $this->sort;
$DrugCategories->created_at = date('Y-m-d H:i:s',time());
$DrugCategories->updated_at = date('Y-m-d H:i:s',time());
$DrugCategories->save();
return ['添加成功'];
}
public function update()
{
if (!$this->validate()) {
throw new Exception($this->getErrorMsg());
}
$DrugCategories = DrugCategories::find()->where([
'id' => $this->id,
'deleted_at' => null
])->one();
if (!$DrugCategories) throw new Exception('药品分类不存在');
$DrugCategories->category_name = $this->category_name;
$DrugCategories->parent_id = $this->parent_id;
$DrugCategories->level = $this->level;
$DrugCategories->sort = $this->sort;
$DrugCategories->created_at = date('Y-m-d H:i:s',time());
$DrugCategories->updated_at = date('Y-m-d H:i:s',time());
$DrugCategories->saveOrFail();
return ['编辑成功'];
}
public function del()
{
$DrugCategories = DrugCategories::find()->where([
'id' => $this->id,
'deleted_at' => null
])->one();
if (!$DrugCategories) throw new Exception('药品分类不存在');
$DrugCategories->deleted_at=date('Y-m-d H:i:s',time());
$DrugCategories->saveOrFail();
return ['删除成功'];
}
public function info()
{
$DrugCategories = DrugCategories::find()->where([
'id' => $this->id,
'deleted_at' => null
])->one();
if (!$DrugCategories) throw new Exception('药品分类不存在');
return $DrugCategories;
}
}

View File

@@ -0,0 +1,188 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\Drug;
use yii\db\Exception;
class DrugForm extends BaseModel
{
public $id;
public $drug_name;
public $is_otc;
public $pinyin_simple;
public $drug_number;
public $bar_code;
public $specification;
public $guozi_no;
public $function;
public $source;
public $place;
public $category_first;
public $category_second;
public $instruction;
public $image;
public $type;
public $status;
public $usage;
public $drugstore;
public $unit_id;
public $frequency_id;
public $type_id;
public $time_id;
public $drug_alias;
public function rules()
{
return [
[['id', 'type', 'unit_id', 'frequency_id', 'type_id', 'time_id'], 'integer'],
[['drugstore', 'place','drug_alias'], 'string'],
[['pinyin_simple', 'is_otc', 'drug_name', 'drug_number', 'bar_code', 'specification', 'guozi_no', 'function', 'source', 'instruction', 'type', 'usage', 'image', 'status', 'frequency_id', 'type_id'], 'required']
];
}
public function attributeLabels()
{
return [
'frequency_id'=>'使用频率',
'type_id'=>'使用方法',
'unit_id'=>'单位',
'time_id'=>'使用时间',
'drug_alias'=>'别名',
'place'=>'产地',
'drugstore'=>'仓库',
'pinyin_simple'=>'拼音首拼',
'is_otc'=>'是否处方药',
'drug_name'=>'药名',
'drug_number'=>'药品编号',
'usage'=>'用法',
'status'=>'状态 1草稿 2下架 3上架',
'image'=>'药品图片',
'instruction'=>'说明书图片',
'source'=>'货源(厂家)',
'function'=>'功能主治',
'guozi_no'=>'国字准号',
'specification'=>'规格',
'bar_code'=>'条形码',
];
}
public function save()
{
if (!$this->validate()) {
throw new Exception($this->getErrorMsg());
}
$Drug = new Drug();
$Drug->attributes = $this->attributes;
$Drug->created_at = time();
$Drug->updated_at = time();
if (!$Drug->saveOrFail()) {
throw new Exception('新增失败');
}
// $decode=json_decode($this->drugstore,true);
//
// foreach ($decode as $value){
// $DrugStoreDrug = DrugStoreDrug::find()->where([
// 'drugstore_id' => $value['drugstore_id'],
// 'drug_id' => $DRUG->id,
// 'is_delete' => 0
// ])->one();
// if ($DrugStoreDrug) {
// $DrugStoreDrug ->is_delete=1;
// $DrugStoreDrug->saveOrFail();
// }
//
// $drug = new DrugStoreDrug();
// $drug->drugstore_id = $value['drugstore_id'];
// $drug->drug_id = $DRUG->id;
// $drug->type = $value['type'];
// $drug->price = $value['price'];
// $drug->stock =$value['stock'];
// $drug->saveOrFail();
// }
return ['新增成功'];
}
public function update()
{
$drug = Drug::find()->where([
'id' => $this->id,
])->one();
if (!$drug) throw new Exception('该药品不存在');
$drug->type = $this->type ?? $drug->type;
$drug->drug_name = $this->drug_name ?? $drug->drug_name;
$drug->drug_number = $this->drug_number ?? $drug->drug_number;
$drug->bar_code = $this->bar_code ?? $drug->bar_code;
$drug->specification = $this->specification ?? $drug->specification;
$drug->guozi_no = $this->guozi_no ?? $drug->guozi_no;
$drug->source = $this->source ?? $drug->source;
$drug->function = $this->function ?? $drug->function;
$drug->image = $this->image ?? $drug->image;
$drug->usage = $this->usage ?? $drug->usage;
$drug->instruction = $this->instruction ?? $drug->instruction;
$drug->place = $this->place ?? $drug->place;
$drug->is_otc = $this->is_otc ?? $drug->is_otc;
$drug->status = $this->status ?? $drug->status;
$drug->place = $this->place ?? $drug->place;
$drug->time_id = $this->time_id ?? $drug->time_id;
$drug->type_id = $this->type_id ?? $drug->type_id;
$drug->frequency_id = $this->frequency_id ?? $drug->frequency_id;
$drug->unit_id = $this->unit_id ?? $drug->unit_id;
$drug->drug_alias = $this->drug_alias ?? $drug->drug_alias;
$drug->updated_at = time();
if (!$drug->saveOrFail()) {
throw new Exception('编辑失败');
}
return ['编辑成功'];
}
//上下架
public function IsSale()
{
$drug = Drug::find()->where([
'id' => $this->id,
'type' => $this->type,
])->one();
if (!$drug) throw new Exception('该药品不存在');
$drug->status = $this->status;
if (!$drug->saveOrFail()) throw new Exception('上下架失败');
return ['成功上下架'];
}
//基础药品-草稿
public function Draft()
{
$drug = Drug::find()->where([
'id' => $this->id,
'type' => $this->type,
])->one();
if (!$drug) throw new Exception('该药品不存在');
$drug->status = 1;
if (!$drug->saveOrFail()) throw new Exception('修改为草稿失败');
return ['成功修改为草稿'];
}
public function info()
{
$drug = Drug::find()->where([
'id' => $this->id,
'type' => $this->type,
])->one();
if (!$drug) throw new Exception('该药品不存在');
return $drug;
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\Drug;
use common\models\DrugStoreDrug;
use yii\db\Exception;
//颗粒配方form
class GranularForm extends BaseModel
{
public $id;
public $drug_name;
public $drug_number;
public $drug_alias;
public $unit_id;
public $place;
public $source;
public $instruction;
public $type;
public $drugstore;
public $pinyin_simple;
public $is_otc;
public $status;
public function rules()
{
return [
[['id','type','is_otc'],'integer'],
[['drug_name','drug_number','drug_alias','unit_id','pinyin_simple','status'],'required'],
[['place','source','instruction','drugstore','pinyin_simple'],'string'],
['type','default','value'=>'3'],
];
}
public function attributeLabels()
{
return [
'drug_name'=>'药名',
'drug_number'=>'药品编号',
'drug_alias'=>'药品别名',
'unit_id'=>'单位',
'pinyin_simple'=>'拼音首拼',
'status'=>'状态 1草稿 2下架 3上架',
];
}
public function save()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$t = \Yii::$app->db->beginTransaction();
try {
$drug=new Drug();
$drug->attributes=$this->attributes;
$drug->created_at=time();
$drug->saveOrFail();
$t->commit();
return ['新增成功'];
}catch (\Exception $e){
$t->rollBack();
throw new Exception($e->getMessage());
}
}
public function update()
{
$drug=Drug::find()->where([
'id'=>$this->id,
'type'=>3,
])->one();
if (!$drug) throw new Exception('该药品不存在');
$drug->pinyin_simple=$this->pinyin_simple??$drug->pinyin_simple;
$drug->status=$this->status??$drug->status;
$drug->drug_name=$this->drug_name??$drug->drug_name;
$drug->drug_number=$this->drug_number??$drug->drug_number;
$drug->drug_alias=$this->drug_alias??$drug->drug_alias;
$drug->unit_id=$this->unit_id??$drug->unit_id;
$drug->place=$this->place??$drug->place;
$drug->source=$this->source??$drug->source;
$drug->instruction=$this->instruction??$drug->instruction;
$drug->saveOrFail();
return ['编辑成功'];
}
public function info()
{
$drug= Drug::find()->where([
'id'=>$this->id,
'type'=>3,
])->one();
if (!$drug) throw new Exception('该药品不存在');
return $drug;
}
}

View File

@@ -0,0 +1,350 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\helpers\ArrayHelper;
use common\models\Drug;
use common\models\DrugStoreDrug;
use common\models\Platform;
use Overtrue\Pinyin\Pinyin;
use yii\db\Exception;
class ImportForm extends BaseModel
{
public $file;
public $status;
public function rules()
{
return [
['status', 'integer'],
[['file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xls,xlsx'],
];
}
public function attributeLabels()
{
return [
'file' => '文件上传'
];
}
//首拼
public function shoupin($name)
{
return ArrayHelper::shouzimu($name);
}
//西药导入
public function WestImport($data)
{
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($data as $item) {
if (empty($item['药名'])) {
throw new Exception('药名不能为空,导入失败');
}
$drug = Drug::find()->where([
'or',
['bar_code' => $item['条形码']],
['guozi_no' => $item['国字准号']]
])->one();
if (!$drug) {
$model = new Drug();
$model->setAttribute('drug_name', trim($item['药名']));
$model->setAttribute('drug_alias', trim($item['商品名']));
$model->setAttribute('pinyin_simple', (new Pinyin())->abbr(trim($item['药名'])));
$model->setAttribute('drug_number', trim($item['编号']));
$model->setAttribute('bar_code',trim( $item['条形码']));
$model->setAttribute('specification', trim($item['规格']));
$model->setAttribute('guozi_no', trim($item['国字准号']));
$model->setAttribute('status',trim( $item['药品状态']));
$model->setAttribute('function', trim($item['功能主治']));
$model->setAttribute('source', trim($item['厂家']));
$model->setAttribute('status', trim($item['状态']));
$model->setAttribute('is_otc', trim($item['是否处方药']));
$model->setAttribute('time_id', trim($item['服用时间']));
$model->setAttribute('type_id', trim($item['服用方法']));
$model->setAttribute('frequency_id',trim( $item['使用频率']));
$model->setAttribute('unit_id', trim($item['用量单位']));
$model->setAttribute('usage', trim($item['用法']));
$model->setAttribute('type', '2');
$model->setAttribute('created_at', time());
if (!$model->save()) {
$errorsMsg = array_values($model->getFirstErrors());
$errors[] = '条形码:' . $item['条形码'] . ',国子准号:' . $item['国字准号'] . '的西药导入失败,原因:保存失败;'.$errorsMsg[0];
}else{
$success[] = '条形码:' . $item['条形码'] . ',国子准号:' . $item['国字准号'] . '的西药导入成功';
}
} else {
$errors[] = '条形码:' . $item['条形码'] . ',国子准号:' . $item['国字准号'] . '的西药导入失败,原因:重复导入';
}
}
$t->commit();
} catch (\Exception $e) {
$t->rollBack();
$errors[] = $e->getMessage();
}
return ['success' => $success, 'error' => $errors];
}
}
//导入中药
public function ChineseImport($data)
{
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($data as $item) {
if (empty($item['药名'])) {
throw new Exception('药名不能为空,导入失败');
}
$drug = Drug::find()->where(['drug_number' => trim($item['编号'])])->one();
if (!$drug) {
$model = new Drug();
$model->setAttribute('drug_name', trim($item['药名']));
$model->setAttribute('pinyin_simple', (new Pinyin())->abbr(trim($item['药名'])));
$model->setAttribute('drug_number', trim($item['编号']));
$model->setAttribute('drug_alias', trim($item['别名']));
$model->setAttribute('unit_id', trim($item['单位']));
$model->setAttribute('status', trim($item['状态']));
$model->setAttribute('type', '1');
$model->setAttribute('created_at', time());
$model->setAttribute('updated_at', time());
if (!$model->saveOrFail()) {
$errorsMsg = array_values($model->getFirstErrors());
$errors[] = '编号:' . $item['编号'] . '的导入失败,原因:保存失败,' . $errorsMsg[0];
} else {
$success[] = '编号:' . $item['编号'] . '的中药导入成功';
}
} else {
$errors[] = '编号:' . $item['编号'] . '的中药导入失败,原因:重复导入';
}
}
$t->commit();
} catch (\Exception $e) {
$t->rollBack();
$errors[] = $e->getMessage();
}
return ['success' => $success, 'error' => $errors];
}
}
//颗粒配方
public function GranularImport($data)
{
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($data as $item) {
if (empty($item['药名'])) {
throw new Exception('药名不能为空,导入失败');
}
$drug = Drug::find()->where(['drug_number' => trim($item['编号'])])->one();
if (!$drug) {
$model = new Drug();
$model->setAttribute('drug_name', trim($item['药名']));
$model->setAttribute('pinyin_simple',(new Pinyin())->abbr(trim($item['药名'])));
$model->setAttribute('drug_number', trim($item['编号']));
$model->setAttribute('drug_alias', trim($item['别名']));
$model->setAttribute('place', trim($item['产地']));
$model->setAttribute('source',trim( $item['厂家']));
$model->setAttribute('status', trim($item['状态']));
$model->setAttribute('is_otc', trim($item['是否处方药']));
$model->setAttribute('type', '3');
$model->setAttribute('created_at', time());
if (!$model->save()) {
$errorsMsg = array_values($model->getFirstErrors());
$errors[] = '编号:' . $item['编号'] . '导入失败,原因:保存失败;'.$errorsMsg[0];
}else{
$success[] = '编号:' . $item['编号'] . '的颗粒配方导入成功';
}
} else {
$errors[] = '编号:' . $item['编号'] . '的颗粒配方导入失败,原因:重复导入';
}
}
$t->commit();
} catch (\Exception $e) {
$t->rollBack();
$errors[] = $e->getMessage();
}
return ['success' => $success, 'error' => $errors];
}
}
//中成药导入
public function ImportZhongcheng($data)
{
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
$t = \Yii::$app->db->beginTransaction();
try {
foreach ($data as $item) {
if (empty($item['药名'])) {
throw new Exception('药名不能为空,导入失败');
}
$drug = Drug::find()->where([
'or',
['bar_code' => trim($item['条形码'])],
['guozi_no' => trim($item['国字准号'])]
])->one();
if (!$drug) {
$model = new Drug();
$model->setAttribute('drug_name',trim( $item['药名']));
$model->setAttribute('drug_alias', trim($item['别名']));
$model->setAttribute('pinyin_simple', (new Pinyin())->abbr(trim($item['药名'])));
$model->setAttribute('drug_number', trim($item['编号']));
$model->setAttribute('bar_code', trim($item['条形码']));
$model->setAttribute('specification', trim($item['规格']));
$model->setAttribute('guozi_no',trim( $item['国字准号']));
$model->setAttribute('function', trim($item['功能主治']));
$model->setAttribute('source',trim( $item['厂家']));
$model->setAttribute('status', trim($item['状态']));
$model->setAttribute('is_otc',trim( $item['是否处方药']));
$model->setAttribute('time_id',trim( $item['服用时间']));
$model->setAttribute('type_id', trim($item['服用方法']));
$model->setAttribute('frequency_id', trim($item['使用频率']));
$model->setAttribute('unit_id', trim($item['用量单位']));
$model->setAttribute('usage', trim($item['用法']));
$model->setAttribute('type', '4');
$model->setAttribute('created_at', time());
if (!$model->save()) {
$errorsMsg = array_values($model->getFirstErrors());
$errors[] = '条形码:' . $item['条形码'] . ',国子准号:' . $item['国字准号'] . '的中成药导入失败,原因:保存失败;'.$errorsMsg[0];
}else{
$success[] = '条形码:' . $item['条形码'] . ',国子准号:' . $item['国字准号'] . '的中成药导入成功';
}
} else {
$errors[] = '条形码:' . $item['条形码'] . ',国子准号:' . $item['国字准号'] . '的中成药导入失败,原因:重复导入';
}
}
$t->commit();
} catch (\Exception $e) {
$t->rollBack();
$errors[] = $e->getMessage();
}
return ['success' => $success, 'error' => $errors];
}
}
public function DivisionImport($data)
{
$user = \Yii::$app->user->identity;
$Platform_id = Platform::find()->select('id')->where([
'drugstore_id' => $user->drugstore,
])->one();
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
foreach ($data as $item) {
$t = \Yii::$app->db->beginTransaction();
try {
$Is_PlatformDrug = PlatformDrug::find()->where([
'platform_id' => $Platform_id->id,
'drug_id' => $item['药品ID'],
'platform_drug_id' => $item['平台药品ID'],
'is_deleted' => 0
])->one();
if (!$Is_PlatformDrug) {
$PlatformDrug = new PlatformDrug();
$PlatformDrug->setAttribute('platform_drug_id', trim($item['平台药品ID']));
$PlatformDrug->setAttribute('drug_id', trim($item['药品ID']));
$PlatformDrug->setAttribute('platform_id', $Platform_id->id);
if (!$PlatformDrug->save()) {
$errorsMsg = array_values($PlatformDrug->getFirstErrors());
return [$errorsMsg[0]];
}
}
$Drug = Drug::find()->where([
'id' => $item['药品ID'],
'is_delete' => 0
])->one();
if (!$Drug) throw new Exception('该药品不存在');
$Is_DrugStoreDrug = DrugStoreDrug::find()->where([
'drug_id' => $item['药品ID'],
'drugstore_id' => $user->drugstore,
'is_delete' => 0
])->one();
if (!$Is_DrugStoreDrug) {
$model = new DrugStoreDrug();
$model->setAttribute('drugstore_id', $user->drugstore);
$model->setAttribute('drug_id', trim($item['药品ID']));
$model->setAttribute('type', $Drug->type);
$model->setAttribute('stock', $item['库存']);
$model->setAttribute('price', $item['价格']);
if (!$model->save()) {
$errorsMsg = array_values($model->getFirstErrors());
return [$errorsMsg[0]];
}
}
$t->commit();
$success[] = '分仓药品导入成功!';
} catch (\Exception $e) {
$t->rollBack();
$errors[] = $e->getMessage();
continue;
}
}
return ['success' => $success, 'error' => $errors];
}
}
public function ExportRealDrug($data)
{
if (empty($data)) {
throw new Exception('导入数据为空');
} else {
$t=\Yii::$app->db->beginTransaction();
try {
foreach ($data as $item) {
$DrugStoreDrug = DrugStoreDrug::find()->where(['drug_id' => trim($item['药品ID']), 'type' => trim($item['类别'])])->one();
if (!$DrugStoreDrug) {
$model = new DrugStoreDrug();
$model->setAttribute('drugstore_id', 1);
$model->setAttribute('drug_id', trim($item['药品ID']));
$model->setAttribute('type', trim($item['类别']));
$model->setAttribute('price', trim($item['销售价格']));
$model->setAttribute('market_price', trim($item['市场(指导价)价']) ?? '');
$model->setAttribute('stock', trim($item['库存']));
if (!$model->save()) {
$errorsMsg = array_values($model->getFirstErrors());
$errors[] = $item['药品ID'] . '导入失败,原因:保存失败;'.$errorsMsg[0];
}else{
$success[] = $item['药品ID'] . '导入成功!';
}
} else {
$errors[] = $item['药品ID'] . '导入失败,原因:重复导入';
}
}
$t->commit();
} catch (\Exception $e) {
$t->rollBack();
$errors[] = $e->getMessage();
}
return ['success' => $success, 'error' => $errors];
}
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace admin\models\forms\drug;
use common\core\BaseModel;
use common\models\Nav;
use yii\db\Exception;
class NavForm extends BaseModel
{
public $id;
public $store_id;
public $sort;
public $link_type;
public $pic;
public $external_link;
public $type;
public $is_home;
public function rules()
{
return [
['pic','required'],
['external_link','string'],
[['id','is_home','store_id','type','sort','link_type'],'integer'],
['external_link', 'url', 'defaultScheme' => 'http'],
['external_link', 'IsGet'], //定义验证方法
];
}
public function IsGet($attribute){
$temp = get_headers($this->external_link,true);
if(!preg_match('/200/',$temp[0])){
$this->addError($attribute,'该链接无效, 无法访问');
}else{
return true;
}
}
public function save()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$nav=new Nav();
$nav->pic=$this->pic;
$nav->external_link=$this->external_link;
$nav->type=$this->type;
$nav->store_id=$this->store_id;
$nav->sort=$this->sort;
$nav->link_type=$this->link_type;
if ($this->is_home==1){
$nav->is_home=$this->is_home;
$nav->home_time=date('Y-m-d H:i:s',time());
}
$nav->saveOrFail();
}
public function update()
{
$nav=Nav::find()->where([
'id'=>$this->id,
'is_delete'=>0
])->one();
if (!$nav) throw new Exception('轮播图不存在');
$nav->pic=$this->pic?? $nav->pic;
$nav->external_link=$this->external_link?? $nav->external_link;
$nav->type=$this->type?? $nav->type;
$nav->store_id=$this->store_id?? $nav->store_id;
$nav->sort=$this->sort?? $nav->sort;
$nav->link_type=$this->link_type?? $nav->link_type;
if ($this->is_home==1) {
$nav->home_time=date('Y-m-d H:i:s',time());
}
$nav->saveOrFail();
return ['编辑成功'];
}
public function del()
{
$nav=Nav::find()->where([
'id'=>$this->id,
'is_delete'=>0
])->one();
if (!$nav)throw new Exception('轮播图不存在');
$nav->is_delete=1;
$nav->saveOrFail();
return ['删除成功'];
}
}

View File

@@ -0,0 +1,343 @@
<?php
namespace admin\models\forms\statistics;
use admin\exceptions\ApiException;
use common\models\Goods;
use common\models\GoodsWarehouse;
use common\models\Order;
use common\models\OrderDetail;
use common\models\OrderRefund;
use common\models\User;
use yii\base\Model;
class DataForm extends Model
{
public $date_start;
public $date_end;
public $mch_id;
public $name;
public $goods_order;
public $user_order;
public $sign = 'all';//给默认值,后台统计没有传该值
public $status;
public $page;
public $limit;
public $flag;
public $fields;
public $type;
public function rules()
{
return [
[['flag', 'goods_order', 'user_order', 'name', 'sign', 'type'], 'string'],
[['page', 'limit'], 'integer'],
[['page',], 'default', 'value' => 1],
[['status',], 'default', 'value' => -1],
[['date_start', 'date_end', 'fields'], 'trim'],
// [['mch_per',], 'default', 'value' => false],
];
}
public function init()
{
parent::init(); // TODO: Change the autogenerated stub
}
protected function get_all_data()
{
//以下随时间查询改变
$order_query = Order::find()->alias('o')->where(['o.is_recycle' => 0, 'o.is_delete' => 0])
->andWhere(['not', ['o.cancel_status' => 1]]);
if(\Yii::$app->mallId){
$order_query->andWhere(['o.mall_id' => \Yii::$app->mallId]);
}
//插件分类查询
if ($this->sign == 'all') {
} else if ($this->sign == 'mall') {
$order_query->andWhere(['o.sign' => '']);
} else {
$order_query->andWhere(['o.sign' => $this->sign]);
}
$wait_query = clone $order_query;
$data_arr['wait_send_num'] = $wait_query->andWhere(['is_send' => 0])
->andWhere(['or', ['o.is_pay' => 1], ['o.pay_type' => 2]])
->andWhere(['o.cancel_status' => 0, 'o.sale_status' => 0])
->count();
$refund_query = OrderRefund::find()->where([
'status' => 1,
'is_delete' => 0
]);
if(\Yii::$app->mallId){
$refund_query->andWhere(['mall_id' => \Yii::$app->mallId,]);
}
$data_arr['wait_refund_num'] = $refund_query->count();
return $data_arr;
}
//经营概况
public function data_search()
{
if (!$this->validate()) {
throw new ApiException(implode(",",$this->getFirstErrors()));
}
$arr_list = [];
//订单数据
$arr_list['total_data'] = $this->today_order_data();
//wait数据
$arr_list['wait_data'] = $this->get_all_data();
return $arr_list;
}
/**
* 销量排行榜
*/
public function sales_top()
{
$this->goods_order = 'num DESC';
$goods_query = Order::find()->alias('o')
->where([ 'o.is_recycle' => 0, 'o.is_delete' => 0])->andWhere(['not', ['o.cancel_status' => 1]])
->leftJoin(['od' => OrderDetail::tableName()], 'od.order_id = o.id')
->leftJoin(['g' => Goods::tableName()], 'g.id = od.goods_id')
->leftJoin(['gw' => GoodsWarehouse::tableName()], 'g.goods_warehouse_id = gw.id');
if(\Yii::$app->mallId){
$goods_query->andWhere(['g.mall_id' => \Yii::$app->mallId,]);
}
//排序
$goods_query->orderBy('num DESC,g.goods_warehouse_id');
$goods_query->select("COALESCE(SUM(od.`num`),0) AS `num`,gw.brand,gw.name")
->groupBy('g.goods_warehouse_id');
$goods_query_2 = clone $goods_query;
$week_top_list = $goods_query
->andWhere(['>=', 'od.created_at', strtotime(date('Y-m-d',strtotime('-7 day')) . ' 00:00:00')])
->andWhere(['<=', 'od.created_at', strtotime(date('Y-m-d') . ' 23:59:59')])
->limit(10)
->asArray()
->all();
$mouth_top_list = $goods_query_2
->andWhere(['>=', 'od.created_at', strtotime(date('Y-m-d',strtotime('-30 day')) . ' 00:00:00')])
->andWhere(['<=', 'od.created_at', strtotime(date('Y-m-d') . ' 23:59:59')])
->limit(10)
->asArray()
->all();
return [
'week_top_list' => $week_top_list,
'mouth_top_list' => $mouth_top_list
];
}
public function table_search()
{
if (!$this->validate()) {
throw new ApiException(implode(",",$this->getFirstErrors()));
}
$query = $this->table_where();
$query->select("FROM_UNIXTIME(`o`.`created_at`, '%Y-%m-%d') AS `time`,
COALESCE(COUNT(DISTINCT `o`.`id`),0) AS `order_num`,SUM(`o`.`total_pay_price`) AS `total_pay_price`");
//时间查询
if ($this->date_start) {
$query->andWhere(['>=', 'o.created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$query->andWhere(['<=', 'o.created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$list = $query->groupBy('time')
->orderBy('time')->asArray()->all();
$day = floor((strtotime($this->date_end) - strtotime($this->date_start)) / 86400) + 1;
for ($i = 0; $i < $day; $i++) {
$date = date('Y-m-d', strtotime("-$i day",strtotime($this->date_end)));
$bool = false;
foreach ($list as $item) {
if ($date == $item['time']) {
$bool = true;
$arr[$i]['created_at'] = $item['time'];
$arr[$i]['order_num'] = $item['order_num'];
$arr[$i]['total_pay_price'] = $item['total_pay_price'];
}
}
if (!$bool) {
$arr[$i]['created_at'] = $date;
$arr[$i]['order_num'] = '0';
$arr[$i]['total_pay_price'] = '0.00';
}
}
$list = !empty($arr) ? array_reverse($arr) : [];
return $list;
}
protected function table_where()
{
$orderQuery = OrderDetail::find()->alias('od')->where(['is_delete' => 0])
->select(['od.order_id', 'SUM(`od`.`num`) num'])->groupBy('od.order_id');
//时间查询
if ($this->date_start) {
$orderQuery->andWhere(['>=', 'od.created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$orderQuery->andWhere(['<=', 'od.created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$query = Order::find()->alias('o')
->where(['o.is_recycle' => 0, 'o.is_pay' => 1])
->andWhere(['o.is_delete' => 0])->andWhere(['not', ['o.cancel_status' => 1]])
->leftJoin(['d' => $orderQuery], 'd.order_id = o.id');
// ->leftJoin(['d' => OrderDetail::tableName()], 'd.order_id = o.id');
if(\Yii::$app->mallId){
$query->andWhere(['o.mall_id' => \Yii::$app->mallId]);
}
//插件分类查询
if ($this->sign == 'all') {
} else if ($this->sign == 'mall') {
$query->andWhere(['o.sign' => '']);
} else {
$query->andWhere(['o.sign' => $this->sign]);
}
return $query;
}
protected function goods_where()
{
$query = Order::find()->alias('o')
->where(['o.is_recycle' => 0, 'o.is_delete' => 0])->andWhere(['not', ['o.cancel_status' => 1]])
->leftJoin(['od' => OrderDetail::tableName()], 'od.order_id = o.id and od.is_refund = 0')//过滤退款
->leftJoin(['g' => Goods::tableName()], 'g.id = od.goods_id');
//时间查询
if ($this->date_start) {
$query->andWhere(['>=', 'od.created_at', $this->date_start . ' 00:00:00']);
}
if ($this->date_end) {
$query->andWhere(['<=', 'od.created_at', $this->date_end . ' 23:59:59']);
}
if(\Yii::$app->mallId){
$query->andWhere(['g.mall_id' => \Yii::$app->mallId, ]);
}
//排序
$query->orderBy((!empty($this->goods_order) ? $this->goods_order : 'total_price DESC') . ',g.goods_warehouse_id');
return $query;
}
public function today_order_data()
{
$this->date_start = date('Y-m-d',time());
$this->date_end = date('Y-m-d',time());
$order_query = $this->table_where();
$order_query->select("COALESCE(COUNT(DISTINCT `o`.`id`),0) AS `order_num`,
COALESCE(SUM(`o`.`total_pay_price`),0) AS `total_pay_price`");
//比较昨日
$list_1 = [
'order_num' => 0,
'total_pay_price' => 0,
];
$order_query_1 = clone $order_query;
$order_query_1->andWhere(['>=', 'o.created_at', strtotime(date('Y-m-d', strtotime('-1 day')) . ' 00:00:00')]);
$order_query_1->andWhere(['<=', 'o.created_at', strtotime(date('Y-m-d', strtotime('-1 day')) . ' 23:59:59')]);
$list_1 = $order_query_1->asArray()->one();
//比较上周的这一日
$list_2 = [
'order_num' => 0,
'total_pay_price' => 0,
];
$order_query_2 = clone $order_query;
$order_query_2->andWhere(['>=', 'o.created_at', strtotime(date('Y-m-d', strtotime('-7 day')) . ' 00:00:00')]);
$order_query_2->andWhere(['<=', 'o.created_at', strtotime(date('Y-m-d', strtotime('-7 day')) . ' 23:59:59')]);
$list_2 = $order_query_2->asArray()->one();
//时间查询
if ($this->date_start) {
$order_query->andWhere(['>=', 'o.created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$order_query->andWhere(['<=', 'o.created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$list = $order_query->asArray()->one();
//------------------------------------------------------------------------
$user_query = User::find();
//比较昨日
$user_num_1 = 0;
$user_query_1 = clone $user_query;
$user_query_1->andWhere(['>=', 'created_at', strtotime(date('Y-m-d', strtotime('-1 day')) . ' 00:00:00')]);
$user_query_1->andWhere(['<=', 'created_at', strtotime(date('Y-m-d', strtotime('-1 day')) . ' 23:59:59')]);
$user_num_1 = $user_query_1->count();
//比较上周的这一日
$user_num_2 = 0;
$user_query_2 = clone $user_query;
$user_query_2->andWhere(['>=', 'created_at', strtotime(date('Y-m-d', strtotime('-7 day')) . ' 00:00:00')]);
$user_query_2->andWhere(['<=', 'created_at', strtotime(date('Y-m-d', strtotime('-7 day')) . ' 23:59:59')]);
$user_num_2 = $user_query_2->count();
if ($this->date_start) {
$user_query->andWhere(['>=', 'created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$user_query->andWhere(['<=', 'created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$user_num = $user_query->count();
//------------------------------------------------------------------------
$yestoday = [];
$yestoday['order_num_status'] = empty($list_1) || $list['order_num'] > $list_1['order_num'] ? 'up' : ($list['order_num'] < $list_1['order_num'] ? 'down' : 'equal');
$yestoday['order_num_abs'] = abs($list['order_num']-$list_1['order_num']);
$yestoday['total_pay_price_status'] = empty($list_1) || $list['total_pay_price'] > $list_1['total_pay_price'] ? 'up' : ($list['total_pay_price'] < $list_1['total_pay_price'] ? 'down' : 'equal');
$yestoday['total_pay_price_abs'] = abs($list['total_pay_price']-$list_1['total_pay_price']);
$yestoday['user_num_status'] = $user_num > $user_num_1 ? 'up' : ($user_num < $user_num_1 ? 'down' : 'equal');
$yestoday['user_num_abs'] = abs($user_num-$user_num_1);
$lastweek = [];
$lastweek['order_num_status'] = empty($list_2) || $list['order_num'] > $list_2['order_num'] ? 'up' : ($list['order_num'] < $list_2['order_num'] ? 'down' : 'equal');
$lastweek['order_num_abs'] = abs($list['order_num']-$list_2['order_num']);
$lastweek['total_pay_price_status'] = empty($list_2) || $list['total_pay_price'] > $list_2['total_pay_price'] ? 'up' : ($list['total_pay_price'] < $list_2['total_pay_price'] ? 'down' : 'equal');
$lastweek['total_pay_price_abs'] = abs(bcsub($list['total_pay_price'],$list_2['total_pay_price'],2));
$lastweek['user_num_status'] = $user_num > $user_num_2 ? 'up' : ($user_num < $user_num_2 ? 'down' : 'equal');
$lastweek['user_num_abs'] = abs($user_num-$user_num_2);
$list['user_num'] = $user_num;
return [
'today' => $list,
'yestoday' => $yestoday,
'lastweek' => $lastweek
];
}
}

View File

@@ -0,0 +1,174 @@
<?php
namespace admin\models\forms\statistics;
use admin\exceptions\ApiException;
use admin\models\forms\export\CommonExport;
use common\models\Goods;
use common\models\GoodsWarehouse;
use common\models\ImMessage;
use common\models\ImMessageSession;
use common\models\Order;
use common\models\OrderDetail;
use common\models\OrderRefund;
use common\models\User;
use yii\base\Model;
use yii\data\ActiveDataProvider;
class ServiceDataForm extends Model
{
public $date_start;
public $date_end;
public $page;
public $limit;
public $is_export;
public function rules()
{
return [
[['page', 'limit'], 'integer'],
[['page',], 'default', 'value' => 1],
[['limit'], 'default', 'value' => 20],
[['date_start', 'date_end'], 'trim'],
['is_export','default','value'=> 0]
];
}
public function init()
{
parent::init(); // TODO: Change the autogenerated stub
}
public function head_search()
{
if (!$this->validate()) {
throw new ApiException(implode(",",$this->getFirstErrors()));
}
if(!$this->date_start){
$this->date_start = date('Y-m').'-01';
}
if(!$this->date_end){
$this->date_end = date('Y-m-t');
}
$query = ImMessageSession::find()->alias('i')->where([
'i.mall_id' => \Yii::$app->mallId,
'i.type' => 0,
])->andWhere(['<>','i.imuser_id',0])->joinWith(['imUser u'=>function($q){
$q->andWhere(['not', ['u.id' => null]]);
}]);
if ($this->date_start) {
$query->andWhere(['>=', 'i.created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$query->andWhere(['<=', 'i.created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$query->select("count(i.user_id) as `times`,count(distinct(i.user_id)) as `peoples`");
$data = $query->all();
$query2 = ImMessageSession::find()->alias('i')->where([
'i.mall_id' => \Yii::$app->mallId,
'i.type' => 0,
])->andWhere(['<>','i.imuser_id',0])->joinWith(['imUser u'=>function($q){
$q->andWhere(['not', ['u.id' => null]]);
}]);
if ($this->date_start) {
$query2->andWhere(['>=', 'i.created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$query2->andWhere(['<=', 'i.created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$query2->select("FROM_UNIXTIME(i.`created_at`, '%Y-%m-%d') AS `time`,count(i.user_id) as `times`,count(distinct(i.user_id)) as `peoples`");
$list= $query2->groupBy('time')->orderBy('time')->asArray()->all();
$day = floor((strtotime($this->date_end) - strtotime($this->date_start)) / 86400) + 1;
for ($i = 0; $i < $day; $i++) {
$date = date('Y-m-d', strtotime("-$i day",strtotime($this->date_end)));
$bool = false;
foreach ($list as $item) {
if ($date == $item['time']) {
$bool = true;
$arr[$i]['created_at'] = $item['time'];
$arr[$i]['times'] = $item['times'];
$arr[$i]['peoples'] = $item['peoples'];
}
}
if (!$bool) {
$arr[$i]['created_at'] = $date;
$arr[$i]['times'] = 0;
$arr[$i]['peoples'] = 0;
}
}
$list = !empty($arr) ? array_reverse($arr) : [];
return [
'data' => $data[0],
'table' => $list
];
}
public function bottom_query()
{
if(!$this->date_start){
$this->date_start = date('Y-m').'-01';
}
if(!$this->date_end){
$this->date_end = date('Y-m-t');
}
$query = ImMessageSession::find()->alias('i')->where([
'i.mall_id' => \Yii::$app->mallId,
'i.type' => 0,
])->andWhere(['<>','i.imuser_id',0]);
if ($this->date_start) {
$query->andWhere(['>=', 'i.created_at', strtotime($this->date_start . ' 00:00:00')]);
}
if ($this->date_end) {
$query->andWhere(['<=', 'i.created_at', strtotime($this->date_end . ' 23:59:59')]);
}
$query->joinWith(['imUser u'=>function($q){
$q->andWhere(['not', ['u.id' => null]]);
}])->select(['i.imuser_id,COUNT(i.user_id) AS `times`,COUNT(distinct(i.user_id)) AS `peoples`'])->groupBy('i.imuser_id')->orderBy('i.imuser_id desc');
return $query;
}
public function bottom_search()
{
if (!$this->validate()) {
throw new ApiException(implode(",",$this->getFirstErrors()));
}
$query = $this->bottom_query();
if ($this->is_export) {
$fields = [
'imuser_name','times','peoples'
];
$queueId = CommonExport::handle([
'export_class' => 'backend\\models\\forms\\export\\ServiceExport',
'params' => [
'fieldsKeyList' => $fields,
],
'model_class' => 'backend\\models\\forms\\statistics\\ServiceDataForm',
'model_params' => $this->attributes,
'function_name' => 'bottom_query'
]);
return [
'queue_id' => $queueId
];
}
$data = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'defaultPageSize' => $this->limit,
'params' => [
'page' => $this->page
]
]
]);
return $data;
}
}