Files
ctms-yii/ctms-api/controllers/gm/v1/CarownerController.php
T
fm453 270b881437 ADD:添加后台管理端接口;
DEL:删除不必要的头部注释;
FIX:修正若干已知错误;
2025-07-13 19:40:10 +08:00

524 lines
16 KiB
PHP
Executable File

<?php
namespace api\controllers\gm\v1;
use Yii;
use yii\data\Pagination;
use addons\models\AcCar;
use addons\models\AcCarOwner;
use addons\models\AcStore;
use addons\models\AcEmployee;
use addons\functions\FmFunc;
use common\models\Member as User;
use addons\models\AcUserExt;
use common\models\CSms;
use common\models\CVcode;
use vendor\aliyun\dysms\Sms;
use function addons\functions\isMobile;
class CarownerController extends Common
{
public function beforeAction($action)
{
if (!$this->pid) {
$this->result('您正使用本系统内部接口,禁止非法链接使用!');
}
return parent::beforeAction($action);
}
//主界面
public function actionIndex()
{
$apis = [
'list'=>'车主列表',
'detail'=>'详情',
'add'=>'添加',
'edit'=>'编辑',
'delete'=>'删除',
'show'=>'显示',
'hide'=>'隐藏',
'ajax'=>'ajax操作'
];
$this->result('您正使用CMTS-GM系统车主管理接口!', $apis, 200);
}
//车主用户列表
public function actionList()
{
$s = $this->search();
$res = $s['res'];
if (!$res) {
$this->result('没有查询到相应的数据!', [], 0);
}
$return = [];
$return['code'] = 200;
$return['msg'] = '车主查询成功!';
$return['data']= [
'total'=>$s['query']->count(),
'owners' => $res,
'users' => $s['users'],
'exts' => $s['exts'],
'employees' => $s['employees'],
'stores' => $s['stores'],
'page'=>$this->page
];
$this->result($return['msg'], $return['data'], $return['code']);
}
public function actionDetail()
{
$id = (int)Yii::$app->request->get('id');
if(!$id) $this->result('请求错误,未携带ID参数');
$model = new AcCarOwner();
$res = $model->findOne($id)->toArray();
if(!$res) $this->result('未查询到相应数据');
$owner = $this->showCarOwner($res);
$this->result('车主信息查询完成', $owner, 200);
}
//新增车主
public function actionAdd()
{
//数据预检查、编排
$data = $this->preSave('add');
if(!$data) $this->result('数据预检查未通过,保存失败', $data, 100);
//保存资料
$model = new AcCarOwner();
foreach ($data as $key=>$val) {
$model->$key = $val;
}
$res = $model->save();
$msg = '数据保存失败!';
if(!$res) $this->result($msg, [], 100);
//保存扩展资料
$post = $this->postdata;
$this->saveUserExt($post,$data['mid'],trim($post['mobile']));
$msg = '数据保存成功!';
$return = [];
$return['id']= $model->attributes['id']; //获取插入后id;
$this->result($msg,$return, 200);
}
//更新车主
public function actionEdit()
{
$detail = $this->preUpdate();
//数据预检查、编排
$data = $this->preSave('edit');
if(!$data) $this->result('数据预检查未通过,保存失败', $data, 100);
//保存资料
foreach ($data as $key=>$val) {
$detail->$key = $val;
}
$res = $detail->save();
$msg = '数据编辑失败!';
if(!$res) $this->result($msg, [], 100);
//保存扩展资料
$post = $this->postdata;
$this->saveUserExt($post,$data['mid'],trim($post['mobile']));
$msg = '数据编辑成功!';
$return = [];
$return['data']= $detail;
$this->result($msg,$return, 200);
}
//删除用户
public function actionDelete($id)
{
$detail = $this->preUpdate();
$data = [];
$data['update_at'] = time();
$data['deleted'] = $detail->deleted + 1;
//保存资料
foreach ($data as $key=>$val) {
$detail->$key = $val;
}
$res = $detail->save();
$msg = '车主数据删除失败!';
if(!$res) $this->result($msg, [], 100);
$msg = '车主数据删除成功!';
$this->result($msg,[], 200);
}
public function actionAjax()
{
$detail = $this->preUpdate();
$get = Yii::$app->request->get();
$msg = '';
$errorCode = 0;
$detail->update_at = time();
switch ($get['do']) {
case 'hide':
$detail->status_code = 0;
$res = $detail->save();
if ($res) {
$msg = '车主隐藏标记成功';
$errorCode = 200;
} else {
$msg = '车主隐藏标记失败';
}
break;
case 'show':
$detail->status_code = 1;
$res = $detail->save();
if ($res) {
$msg = '车主显示标记成功';
$errorCode = 200;
} else {
$msg = '车主显示标记失败';
}
break;
default:
break;
}
$this->result($msg,[], $errorCode);
}
//短信营销
public function actionMsg()
{
$op = Yii::$app->request->get('op');
$id = (int)Yii::$app->request->get('id');
$detail = $this->preUpdate();
$msg = '';
$errorCode = 0;
$detail->update_at = time();
$owner = $detail->toArray();
//短信接口配置
$option = [];
$config = [];
$config['accessKeyId'] = Yii::$app->params['aliDySms']['accessKeyId'];
$config['accessKeySecret'] = Yii::$app->params['aliDySms']['accessKeySecret'];
$config['sign'] = Yii::$app->params['aliDySms']['sign'];
$sms = new Sms($option, $config);
//获取手机号
$phone = '';
$user = User::findOne($detail->mid);
if ($user) {
$phone = $owner['mobile'] = $user->mobile;
}
//格式化内容
$content = [];
switch ($op) {
case 'vcode': //发送验证码
$code = mt_rand(1000, 9999);
$content['code'] = $code;
$tmpl = Yii::$app->params['aliDySms']['tmpl']['vcode'];
//验证码入库
$vcodeModel = new CVcode();
$vcode = [];
$vcode['code'] = $code;
$vcode['mobile'] = $phone;
$vcode['create_at'] = time();
foreach ($vcode as $key => $val) {
$vcodeModel->$key = $val;
}
$vcodeModel->save();
break;
case 'birthday': //发送生日祝福
$realname = $owner['realname'] ?? 'VIP';
$content['name'] = $realname;
$content['company'] = Yii::$app->request->post('company');
$content['company'] = $content['company'] ?? '安邮运车';
$tmpl = Yii::$app->params['aliDySms']['tmpl']['acBirthday'];
break;
}
$result = $sms->send($phone, $tmpl, $content);
//保存发送记录
$smsModel = new CSms();
$smsdata = [];
$smsdata['sid'] = $this->site_id;
$smsdata['pid'] = $this->pid;
$smsdata['uid'] = $this->user_id;
$smsdata['mobile'] = $phone;
$smsdata['content'] = json_encode($content, JSON_UNESCAPED_UNICODE);
$smsdata['create_at'] = time();
foreach ($smsdata as $key => $val) {
$smsModel->$key = $val;
}
$smsModel->save();
if (!$result) {
$msg .= "【" . $phone . "】发送失败,接口提示:" . $sms->errors . "\r\n";
} else if (is_array($result) && $result['Code'] != 'OK') {
$msg .= "【" . $phone . "】发送失败,接口提示:" . $result['Message'] . "\r\n";
} else {
$msg .= "【" . $phone . "】发送成功" . "\r\n";
}
//更新车主数据
$detail->last_send = time();
$detail->save();
$this->result($msg, [], $errorCode);
}
private function search(){
$pid = $this->pid;
$return = [];
$model = new AcCarOwner();
$where = $where2 = [];
$where2[] = 'and';
$where['pid'] = $pid;
$post = $this->postdata;
$search = $post['search'] ?? [];
$search['title'] = isset($search['title']) ? trim(htmlspecialchars_decode($search['title'])) : '';
if (!empty($search['title'])) {
$where2[] = ['LIKE', 'nickname', $search['title']];
}
$where['deleted'] = 0;
$data = $model->find()->where($where);
if ($search['title']) {
$data = $data->andwhere($where2);
}
$pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $this->pageSize]);
$res = $data->offset($pages->offset)->limit($pages->limit)->indexBy('mid')->all();
$gender = Yii::$app->params['gender'];
$mids = $bids = $sids = [];
if ($res) {
foreach ($res as $r) {
$mids[] = $r->mid;
$eids[] = $r->employee_id;
$sids[] = $r->store_id;
}
}
$AcStore = new AcStore();
$where = [];
$where['pid'] = $pid;
$_stores = $AcStore->find()->where($where)->andwhere(['in', 'id', $sids])->all();
$stores = [];
foreach ($_stores as $s) {
$stores[$s->id] = $s->toArray();
}
$AcEmployee = new AcEmployee();
$where = [];
$where['pid'] = $pid;
$_employees = $AcEmployee->find()->where($where)->andwhere(['in', 'id', $eids])->all();
$employees = [];
if ($_employees) {
foreach ($_employees as $r) {
$employees[$r->id] = $r->toArray();
}
}
$User = new User();
$where = [];
$where['pid'] = $pid;
$_users = $User->find()->where($where)->andwhere(['in', 'id', $mids])->all();
$users = [];
foreach ($_users as $s) {
$users[$s->id] = $s->toArray();
}
$AcUserExt = new AcUserExt();
$userExts = $AcUserExt->find()->where(['pid' => $pid, 'deleted' => 0])->andWhere(['in', 'mid', $mids])->all();
$exts = [];
if ($userExts) {
foreach ($userExts as $ext) {
$ext = $ext->toArray();
if (isset($users[$ext['mid']])) {
if ($ext['mobile'] == $users[$ext['mid']]['mobile']) {
$exts[$ext['mid']][$ext['key']] = $ext['value'];
}
}
}
}
$owners = [];
foreach ($res as $s) {
$s = $s->toArray();
if (isset($exts[$s['mid']])) {
foreach ($exts[$s['mid']] as $col => $val) {
$s[$col] = $val;
}
}
$owners[$s['id']] = $s;
}
return ['res'=>$owners,'query'=>$data,'employees' => $employees,'users'=>$users,'stores' => $stores,'exts' => $exts,];
}
/*
* 数据更新前的预检查,返回对应关联数据
* 必须确保get与post数据中均包含需更新的数据id且一致
* */
private function preUpdate()
{
$id = (int)Yii::$app->request->get('id');
if(!$id) $this->result('请求错误,未携带ID参数');
$post = $this->postdata;
if($post['id'] != $id) $this->result('传参id与请求数据不匹配',[],403);
$model = new AcCarOwner();
$res = $model->findOne($id);
if(!$res) $this->result('未查询到相应数据',[],404);
return $res;
}
/*
* 数据保存前的预检查(查重、参数校验等)
* 要保存的数据[],直接从post中取出
* @op,操作类型(add,edit……)
* 校验机制:
* 编辑数据时,必须用get方式传入参数id,并与post进来的数据id进行比对,只有一致时才能继续;
* 查重:禁止录入重复数据
* 返回:校验重组后的数据
* */
private function preSave($op)
{
$post = $this->postdata;
$user_id = (int)$post['mid'];//已传入会员ID时则不需录入主手机号等
$userModel = new User();
$errorMsg = '';
if(!$user_id){
if (!$post['mobile']) $this->result('请传入车主主手机号');
$mobile = trim($post['mobile']);
if(!isMobile($mobile)) $this->result('车主主手机号无效,请检查');
//查询对应的系统用户
$user = User::find()->where(['mobile' => $mobile])->one();
if (!$user) {
$pwd = isset($post['password']) ? trim($post['password']) : Yii::$app->params['defaultUserPassword'];
$username = isset($post['realname']) ? trim($post['realname']) : (isset($post['nickname']) ? trim($post['nickname']) : $mobile);
//检测字符串长度值,以匹配数据源字段长度限制
if(strLen($username)>$userModel->lenthUsername()){
$username = $mobile;
$errorMsg = '用户名过长,系统自动替换为手机号';
}
$userModel->mobile = $mobile;
$userModel->username = $username;
$userModel->email = $mobile . '@hiluker.com';
$userModel->setPassword($pwd);
$userModel->generateAuthKey();
$userModel->avatar = Yii::$app->params['defaultUserAvatar'];
$userModel->created_at = time();
$userModel->status = 1;
$userModel->save();
$user_id = $userModel->attributes['id']; //获取插入后id
} else {
$user_id = $user->id;
}
}
//格式化数据
$data = [];
//判断车主数据是否在库:新增时,手机号找会员-》会员ID找车主;更新时,手机号找会员=》与传入的会员ID比对
//查询该车主是否在库
$_id = 0;
$carOwner = AcCarOwner::find()->where(['pid' => $this->pid, 'mid' => $user_id])->one();
if ($carOwner) {
$_id = $carOwner->id;
}
$model = new AcCarOwner();
switch ($op) {
case 'add':
if($_id) $this->result('指定会员或手机号关联的车主资料已在库,拒绝重复录入',[],403);
$data['create_at'] = time();
$data['update_at'] = $data['create_at'];
break;
case 'edit':
$id = (int)Yii::$app->request->get('id');
if(!$id != $_id) $this->result('id参数不匹配,请检查');
$data['update_at'] = time();
break;
}
//目标键=》POST键
$cols = ['gender' => 'gender', 'total_fee' => 'total_fee', 'level' => 'level', 'score' => 'score', 'store_id' => 'store_id', 'employee_id' => 'employee_id', 'status_code' => 'status_code', 'deleted' => 'deleted'];
foreach ($cols as $col => $key) {
$data[$col] = isset($post[$key]) ? (int)$post[$key] : 0;
}
$cols = ['last_send' => 'last_send', 'last_contact' => 'last_contact'];
foreach ($cols as $col => $key) {
$data[$col] = isset($post[$key]) ? strtotime($post[$key]) : 0;
}
$cols = ['remark' => 'editor'];
foreach ($cols as $col => $key) {
$data[$col] = isset($post[$key]) ? htmlspecialchars($post[$key]) : '';
}
$data['pid'] = $this->pid;
$data['mid'] = $user_id;
return $data;
}
//保存用户扩展资料
private function saveUserExt($post,$mid,$mobile){
$AcUserExt = new AcUserExt();
$datas = [];
$cols = ['realname' => 'realname', 'nickname' => 'nickname', 'title' => 'title', 'password' => 'password', 'mobiles' => 'mobiles', 'thumb' => 'thumb', 'province' => 'province', 'idcard' => 'idcard'];
foreach ($cols as $col => $key) {
$data = [];
$data['pid'] = $this->pid;
$data['mid'] = $mid;
$data['key'] = $col;
$data['mobile'] = $mobile;
$data['value'] = isset($post[$key]) ? trim($post[$key]) : '';
$datas[] = $data;
}
//批量硬删及软删
// $AcUserExt->updateAll(['deleted'=>1],['deleted'=>0,'pid'=>$pid,'mid'=>$user_id]);
$AcUserExt->deleteAll(['deleted' => 9, 'pid' => $this->pid, 'mid' => $mid]); //硬删,变更历史8次的
$AcUserExt->updateAllCounters(['deleted' => 1], ['pid' => $this->pid, 'mid' => $mid]); //更新已有数据
//批量插入
$model = clone $AcUserExt;
foreach ($datas as $attributes) {
$model->isNewRecord = TRUE;
$model->setAttributes($attributes, FALSE);
$model->save() && $model->id = 0;
}
}
//格式化显示车辆信息 @owner 车主信息原始数据 []
private function showCarOwner($owner){
$owner['last_send_time'] = $owner['last_send'] ? date('Y-m-d H:i:s', $owner['last_send']) : '';
$owner['last_contact_time'] = $owner['last_contact'] ? date('Y-m-d H:i:s', $owner['last_contact']) : '';
$store = AcStore::findOne($owner['store_id']);
if ($store) {
$owner['store_title'] = $store->title;
}
$employee = AcEmployee::findOne($owner['employee_id']);
if ($employee) {
$owner['employee_title'] = $employee->name;
}
$user = User::findOne($owner['mid']);
if ($user) {
$owner['mobile'] = $user->mobile;
}
$exts = AcUserExt::find()->where(['mid' => $owner['mid'], 'mobile' => $owner['mobile'], 'pid' => $this->pid, 'deleted' => 0])->all();
if ($exts) {
foreach ($exts as $ext) {
$owner[$ext['key']] = $ext['value'];
}
}
return $owner;
}
}