v11.1.0-20210625

pull/1/head
Michael_xu 3 years ago
parent 5949f1d4f8
commit 26b0e8466b

@ -28,8 +28,6 @@ class ApiCommon extends Common
$paramArr = $request->param(); $paramArr = $request->param();
$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding) $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
$cache = Cache::get('Auth_'.$authKey.$platform); $cache = Cache::get('Auth_'.$authKey.$platform);
// $cache = cache('Auth_'.$authKey.$platform);
// dump($request->action());die;
// 校验sessionid和authKey // 校验sessionid和authKey
if (empty($sessionId) || empty($authKey) || empty($cache)) { if (empty($sessionId) || empty($authKey) || empty($cache)) {
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');

@ -32,52 +32,9 @@ class Base extends Common
return resultArray(['error' => $userModel->getError()]); return resultArray(['error' => $userModel->getError()]);
} }
# 数据库更新 todo 在线升级正常使用后删除
$updateStatus = $this->executeUpdateSql();
if (empty($updateStatus['status'])) return resultArray(['error' => $updateStatus['message']]);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/**
* 更新SQL
*
* @author fanqi
* @since 2021-05-08
*/
public function executeUpdateSql()
{
# 表前缀
$prefix = config('database.prefix');
# 检查更新记录表是否存在
if (!db()->query("SHOW TABLES LIKE '".$prefix."admin_upgrade_record'")) {
db()->query("
CREATE TABLE `".$prefix."admin_upgrade_record` (
`version` int(10) unsigned DEFAULT NULL COMMENT '版本号',
UNIQUE KEY `version` (`version`) USING BTREE
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT = 'SQL更新记录用于防止重复执行更新。'
");
}
# 检查是否执行过11.0.3版本的更新
if (!db('admin_upgrade_record')->where('version', 1103)->value('version')) {
# 添加跟进记录导入导出权限数据
UpdateSql::addFollowRuleData();
# 添加公海默认数据
$poolStatus = UpdateSql::addPoolDefaultData();
if (!$poolStatus) return ['status' => false, 'message' => '添加公海默认配置失败,请在后台手动添加!'];
# 添加此次升级标记
db('admin_upgrade_record')->insert(['version' => 1103]);
return ['status' => true, 'message' => '更新完成!'];
}
return ['status' => true, 'message' => '没有可用更新!'];
}
//退出登录 //退出登录
public function logout() public function logout()
{ {

@ -259,7 +259,6 @@ class ExamineFlow extends ApiCommon
$content='启用了:'; $content='启用了:';
} }
$dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find(); $dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find();
// p(3333);
SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']); SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']);
return resultArray(['data' => '操作成功']); return resultArray(['data' => '操作成功']);
} }

@ -56,14 +56,16 @@ class Field extends ApiCommon
} }
$param = $this->param; $param = $this->param;
$types_arr = [ $types_arr = [
['types' => 'crm_leads','name' => '线索管理'], ['types' => 'crm_leads', 'name' => '线索管理'],
['types' => 'crm_customer','name' => '客户管理'], ['types' => 'crm_customer', 'name' => '客户管理'],
['types' => 'crm_contacts','name' => '联系人管理'], ['types' => 'crm_contacts', 'name' => '联系人管理'],
['types' => 'crm_product','name' => '产品管理'], ['types' => 'crm_business', 'name' => '商机管理'],
['types' => 'crm_business','name' => '商机管理'], ['types' => 'crm_contract', 'name' => '合同管理'],
['types' => 'crm_contract','name' => '合同管理'], ['types' => 'crm_receivables', 'name' => '回款管理'],
['types' => 'crm_receivables','name' => '回款管理'], ['types' => 'crm_receivables_plan', 'name' => '回款计划管理'],
['types' => 'crm_visit','name' => '客户回访管理'], ['types' => 'crm_invoice', 'name' => '发票管理'],
['types' => 'crm_visit', 'name' => '回访管理'],
['types' => 'crm_product', 'name' => '产品管理'],
]; ];
$examine_types_arr = []; $examine_types_arr = [];
switch ($param['type']) { switch ($param['type']) {
@ -99,11 +101,6 @@ class Field extends ApiCommon
*/ */
public function update() public function update()
{ {
# 权限判断 todo 允许有相应权限的普通员工操作,暂时注释代码,后期修改权限验证。
// if (!checkPerByAction('admin', 'crm', 'field')) {
// header('Content-Type:application/json; charset=utf-8');
// exit(json_encode(['code'=>102,'error'=>'无权操作']));
// }
# 系统审批类型暂不支持编辑 # 系统审批类型暂不支持编辑
if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) { if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) {
return resultArray(['error' => '系统审批类型暂不支持编辑']); return resultArray(['error' => '系统审批类型暂不支持编辑']);
@ -114,7 +111,6 @@ class Field extends ApiCommon
$param = $this->param; $param = $this->param;
$types = $param['types']; $types = $param['types'];
$types_id = $param['types_id'] ? : 0; $types_id = $param['types_id'] ? : 0;
// $data['types'] = $param['types'];
$data = $param['data']; $data = $param['data'];
$saveParam = []; # 新增数据 $saveParam = []; # 新增数据
@ -132,6 +128,24 @@ class Field extends ApiCommon
break; break;
} }
# 验证数字范围
if (!empty($v['max_num_restrict']) && !empty($v['min_num_restrict']) && $v['min_num_restrict'] > $v['max_num_restrict']) {
$errorMessage = '数字范围错误!';
break;
}
# 验证百分数小数位
if ($v['form_type'] == 'percent' && !empty($v['precisions']) && ($v['precisions'] < 1 || $v['precisions'] > 5)) {
$errorMessage = '百分数字段类型的小数配置错误!';
break;
}
# 验证数字小数位
if ($v['form_type'] == 'number' && !empty($v['precisions']) && ($v['precisions'] < 1 || $v['precisions'] > 14)) {
$errorMessage = '数字字段类型的小数配置错误!';
break;
}
if ($v['field_id']) { if ($v['field_id']) {
if (isset($v['is_deleted']) && $v['is_deleted'] == '1') { if (isset($v['is_deleted']) && $v['is_deleted'] == '1') {
# 删除 # 删除
@ -160,26 +174,14 @@ class Field extends ApiCommon
foreach ($deleteIds AS $key => $value) { foreach ($deleteIds AS $key => $value) {
if (!in_array($value, $delParam)) $delParam[] = $value; if (!in_array($value, $delParam)) $delParam[] = $value;
} }
$recordModules = [
'crm_leads' => '线索',
'crm_customer' => '客户',
'crm_pool' => '客户公海',
'crm_contacts' => '联系人',
'crm_product' => '产品',
'crm_business' => '商机',
'crm_contract' => '合同',
'crm_receivables' => '回款',
'crm_visit' => '回访',
'crm_invoice' => '回款',
'oa_log' => '办公日志',
'oa_examine' => '办公审批',
];
# 新增 # 新增
if (!empty($saveParam)) { if (!empty($saveParam)) {
if (!$data = $fieldModel->createData($types, $saveParam)) { if (!$data = $fieldModel->createData($types, $saveParam)) {
$errorMessage[] = $fieldModel->getError(); $errorMessage[] = $fieldModel->getError();
} }
} }
# 编辑 # 编辑
if (!empty($updateParam)) { if (!empty($updateParam)) {
if (!$data = $fieldModel->updateDataById($updateParam, $types)) { if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
@ -215,10 +217,10 @@ class Field extends ApiCommon
'oa_log' => '办公日志', 'oa_log' => '办公日志',
'oa_examine' => '办公审批', 'oa_examine' => '办公审批',
]; ];
if($types !== 'oa_examine'){ if ($types !== 'oa_examine') {
$systemModules='customer'; $systemModules = 'customer';
}else{ } else {
$systemModules='approval'; $systemModules = 'approval';
} }
SystemActionLog($userInfo['id'], $types,$systemModules, 1, 'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]); SystemActionLog($userInfo['id'], $types,$systemModules, 1, 'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]);
return resultArray(['data' => '修改成功']); return resultArray(['data' => '修改成功']);
@ -242,6 +244,7 @@ class Field extends ApiCommon
$controller = trim($param['controller']); $controller = trim($param['controller']);
$action = trim($param['action']); $action = trim($param['action']);
$system = !empty($param['system']) ? $param['system'] : 0; $system = !empty($param['system']) ? $param['system'] : 0;
$format = !empty($param['format']) ? $param['format'] : 1; // 设置返回数据的格式类型1 还是之前的二维数组格式,兼容移动端、 2 三维数组,新版自定义字段的分组排序。
unset($param['system']); unset($param['system']);
if (!$module || !$controller || !$action) { if (!$module || !$controller || !$action) {
@ -260,11 +263,6 @@ class Field extends ApiCommon
case 'crm_customer' : case 'crm_customer' :
$customerModel = new \app\crm\model\Customer(); $customerModel = new \app\crm\model\Customer();
$dataInfo = $customerModel->getDataById(intval($param['action_id'])); $dataInfo = $customerModel->getDataById(intval($param['action_id']));
// 公海
if (!empty($param['pool_id'])) {
$data = $fieldModel->getPoolFieldData($param['pool_id'], $dataInfo);
return resultArray(['data' => $data]);
}
//判断权限 //判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'customer', $param['action']); $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $param['action']);
//读写权限 //读写权限
@ -327,6 +325,13 @@ class Field extends ApiCommon
case 'crm_product' : case 'crm_product' :
$productModel = new \app\crm\model\Product(); $productModel = new \app\crm\model\Product();
$dataInfo = $productModel->getDataById(intval($param['action_id'])); $dataInfo = $productModel->getDataById(intval($param['action_id']));
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'product', $param['action']);
if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
break; break;
case 'crm_receivables' : case 'crm_receivables' :
$receivablesModel = new \app\crm\model\Receivables(); $receivablesModel = new \app\crm\model\Receivables();
@ -368,7 +373,23 @@ class Field extends ApiCommon
//读写权限 //读写权限
$roPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'read'); $roPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'read');
$rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update'); $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
if (!in_array($user_id, stringToArray($dataInfo['owner_user_id'])) && !in_array($user_id,$auth_user_ids) && !$roPre && !$rwPre) { if (!in_array($dataInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
break;
case 'crm_invoice' :
$visit = new \app\crm\model\Invoice();
$dataInfo = $visit->getDataById(intval($param['action_id']));
$fieldModel = new \app\admin\model\Field();
$datetimeField = $fieldModel->getFieldByFormType('crm_invoice', 'datetime'); //日期时间类型
foreach ($datetimeField as $key => $val) {
$dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
}
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'invoice', $param['action']);
if (!in_array($user_id, stringToArray($dataInfo['owner_user_id'])) && !in_array($user_id,$auth_user_ids) ) {
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作'])); exit(json_encode(['code'=>102,'error'=>'无权操作']));
} }
@ -380,6 +401,11 @@ class Field extends ApiCommon
$action_id = $param['action_id'] ? : ''; $action_id = $param['action_id'] ? : '';
$data = $fieldModel->field($param, $dataInfo) ? : []; $data = $fieldModel->field($param, $dataInfo) ? : [];
# 多公海数据详情
if (!empty($param['pool_id']) && $param['action'] == 'read') {
$data = $this->setPoolDetailData($data, $param['pool_id'], $param['action_id']);
}
# 回访模块下,负责人名称变更为回访人 # 回访模块下,负责人名称变更为回访人
if ($param['types'] == 'crm_visit') { if ($param['types'] == 'crm_visit') {
foreach ($data AS $key => $value) { foreach ($data AS $key => $value) {
@ -446,6 +472,18 @@ class Field extends ApiCommon
} }
} }
} }
# 发票自动编号设置
if ($param['types'] == 'crm_invoice') {
foreach ($data AS $key => $value) {
if ($value['field'] == 'invoice_apple_number') {
if ($this->getAutoNumberStatus(4)) {
$data[$key]['is_null'] = 0;
$data[$key]['is_unique'] = 0;
}
$data[$key]['autoGeneNumber'] = $this->getAutoNumberStatus(4) ? 1 : 0;
}
}
}
# 隐藏回款计划中的附件 # 隐藏回款计划中的附件
if ($param['types'] == 'crm_receivables_plan') { if ($param['types'] == 'crm_receivables_plan') {
@ -490,10 +528,10 @@ class Field extends ApiCommon
case 'crm_customer' : case 'crm_customer' :
$customerModel = new Customer(); $customerModel = new Customer();
$customerData = $customerModel->getSystemInfo($action_id); $customerData = $customerModel->getSystemInfo($action_id);
$customerArray = ['obtain_time' => '负责人获取客户时间', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'last_record' => '最后跟进记录', 'deal_status' => '成交状态']; $customerArray = ['obtain_time' => '负责人获取客户时间', 'owner_user_id' => '负责人', 'create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'last_record' => '最后跟进记录', 'deal_status' => '成交状态'];
foreach ($customerData AS $key => $value) { foreach ($customerData AS $key => $value) {
if (empty($customerArray[$key])) continue; if (empty($customerArray[$key]) || (!empty($param['pool_id']) && in_array($key, ['obtain_time', 'owner_user_id']))) continue;
$data[] = [ $data[] = [
'field' => $key, 'field' => $key,
@ -606,11 +644,23 @@ class Field extends ApiCommon
]; ];
} }
break; break;
case 'crm_invoice' :
$invoiceData = db('crm_invoice')->field(['create_user_id', 'owner_user_id', 'create_time', 'update_time'])->where('invoice_id', $action_id)->find();
$createUserName = db('admin_user')->where('id', $invoiceData['create_user_id'])->value('realname');
$ownerUserName = db('admin_user')->where('id', $invoiceData['owner_user_id'])->value('realname');
$data[] = ['field' => 'create_user_id', 'name' => '创建人', 'form_type' => 'user', 'value' => $createUserName, 'system' => 1];
$data[] = ['field' => 'create_user_id', 'name' => '负责人', 'form_type' => 'user', 'value' => $ownerUserName, 'system' => 1];
$data[] = ['field' => 'create_time', 'name' => '创建时间', 'form_type' => 'datetime', 'value' => date('Y-m-d H:i:s', $invoiceData['create_time']), 'system' => 1];
$data[] = ['field' => 'update_time', 'name' => '更新时间', 'form_type' => 'datetime', 'value' => date('Y-m-d H:i:s', $invoiceData['update_time']), 'system' => 1];
} }
} }
# 处理自定义字段别名、权限
$data = $fieldModel->resetField($user_id, $param['types'], $param['action'], $data); $data = $fieldModel->resetField($user_id, $param['types'], $param['action'], $data);
# 处理自定义字段分组排序
if (in_array($param['action'], ['save', 'update', 'relative']) && $format == 2) $data = getFieldGroupOrderData($data);
return resultArray(['data' => array_values($data)]); return resultArray(['data' => array_values($data)]);
} }
@ -623,11 +673,7 @@ class Field extends ApiCommon
{ {
$param = $this->param; $param = $this->param;
$fieldModel = model('Field'); $fieldModel = model('Field');
if (is_array($param['val'])) { $res = $fieldModel->getValidate(trim($param['field']), $param['val'], intval($param['id']), trim($param['types']));
//多选类型暂不验证
return resultArray(['data' => '验证通过']);
}
$res = $fieldModel->getValidate(trim($param['field']), trim($param['val']), intval($param['id']), trim($param['types']));
if (!$res) { if (!$res) {
return resultArray(['error' => $fieldModel->getError()]); return resultArray(['error' => $fieldModel->getError()]);
} }
@ -725,4 +771,58 @@ class Field extends ApiCommon
{ {
return Db::name('crm_number_sequence')->where('number_type', $type)->where('status', 0)->value('number_sequence_id'); return Db::name('crm_number_sequence')->where('number_type', $type)->where('status', 0)->value('number_sequence_id');
} }
/**
* 处理公海详情数据
*
* @param $data array 公海数据
* @param $poolId int 公海ID
* @param $actionId int 数据ID
* @author fanqi
* @since 2021-06-21
* @return array
*/
private function setPoolDetailData($data, $poolId, $actionId)
{
$poolData = [];
$poolList = db('crm_customer_pool_field_setting')->field(['field_name', 'is_hidden'])->where('pool_id', $poolId)->select();
// 组装字段数据
foreach ($poolList AS $key => $value) {
$poolData[$value['field_name']] = $value['is_hidden'];
}
// 处理公海数据
foreach ($data AS $key => $value) {
if (!empty($poolData[$value['field']]) || $value['field'] == 'owner_user_id') {
unset($data[(int)$key]);
continue;
}
}
// 前负责人
$beforeUser = db('crm_customer')->alias('customer')
->join('__ADMIN_USER__ user', 'user.id = customer.before_owner_user_id', 'left')
->field(['user.id', 'user.username', 'user.realname', 'user.thumb_img'])
->where('customer_id', $actionId)
->find();
if (!empty($beforeUser['thumb_img'])) $beforeUser['thumb_img'] = getFullPath($beforeUser['thumb_img']);
$data[] = [
'field' => 'before_owner_user_id',
'name' => '前负责人',
'form_type' => 'user',
'writeStatus' => 0,
'fieldName' => 'before_owner_user_id',
'value' => [$beforeUser],
'setting' => [],
'default_value' => [],
'options' => '',
'optionsData' => ''
];
return array_values($data);
}
} }

@ -107,6 +107,8 @@ class Groups extends ApiCommon
{ {
$groupModel = model('Group'); $groupModel = model('Group');
$param = $this->param; $param = $this->param;
$userInfo=$this->userInfo;
$param['user_id']=$userInfo['id'];
$dataInfo = $groupModel->getDataById($param['id']); $dataInfo = $groupModel->getDataById($param['id']);
if (!$dataInfo) { if (!$dataInfo) {
return resultArray(['error' => '参数错误']); return resultArray(['error' => '参数错误']);
@ -130,6 +132,7 @@ class Groups extends ApiCommon
{ {
$groupModel = model('Group'); $groupModel = model('Group');
$param = $this->param; $param = $this->param;
$userInfo=$this->userInfo;
$dataInfo = $groupModel->getDataById($param['id']); $dataInfo = $groupModel->getDataById($param['id']);
if (!$dataInfo) { if (!$dataInfo) {
return resultArray(['error' => '参数错误']); return resultArray(['error' => '参数错误']);
@ -137,7 +140,7 @@ class Groups extends ApiCommon
if ($dataInfo['types']) { if ($dataInfo['types']) {
return resultArray(['error' => '系统角色,不能删除']); return resultArray(['error' => '系统角色,不能删除']);
} }
$data = $groupModel->delGroupById($param['id']); $data = $groupModel->delGroupById($param['id'],$userInfo['id']);
if (!$data) { if (!$data) {
return resultArray(['error' => $groupModel->getError()]); return resultArray(['error' => $groupModel->getError()]);
} }

@ -62,7 +62,10 @@ class Index extends ApiCommon
if ($value['field'] == 'check_status') $field_arr[$key]['form_type'] = 'check_status'; if ($value['field'] == 'check_status') $field_arr[$key]['form_type'] = 'check_status';
if ($param['types'] == 'crm_visit' && $value['field'] == 'owner_user_id') $field_arr[$key]['name'] = '回访人'; if ($param['types'] == 'crm_visit' && $value['field'] == 'owner_user_id') $field_arr[$key]['name'] = '回访人';
} }
if(in_array($param['types'],['crm_customer','crm_customer_pool','crm_contacts','crm_business','crm_contract','crm_receivables'])){
$field=[['field'=>'team_id','name'=>'相关团队','form_type'=>'user','setting'=>[]]];
$field_arr=array_merge($field_arr,$field);
}
return resultArray(['data' => $field_arr]); return resultArray(['data' => $field_arr]);
} }

@ -47,7 +47,7 @@ class Install extends Controller
*/ */
public function index() public function index()
{ {
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https'; $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
if (strpos(request()->url(), "index.php") === false) { if (strpos(request()->url(), "index.php") === false) {
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url(); $url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
@ -70,7 +70,7 @@ class Install extends Controller
public function step1() public function step1()
{ {
if (strpos(request()->url(), "index.php") === false) { if (strpos(request()->url(), "index.php") === false) {
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https'; $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url(); $url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
header("Location:" . $url); header("Location:" . $url);
} }
@ -97,7 +97,7 @@ class Install extends Controller
die(); die();
} }
if (strpos(request()->url(), "index.php") === false) { if (strpos(request()->url(), "index.php") === false) {
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https'; $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url(); $url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
header("Location:" . $url); header("Location:" . $url);
} }
@ -377,6 +377,10 @@ INFO;
'openssl' => ['openssl', '开启', '开启', 'ok'], 'openssl' => ['openssl', '开启', '开启', 'ok'],
'pdo' => ['pdo', '开启', '开启', 'ok'], 'pdo' => ['pdo', '开启', '开启', 'ok'],
]; ];
// linux系统下需要posix扩展
if (in_array(PHP_OS, ['Linux', 'centos', 'Centos', 'ubuntu', 'Ubuntu'])) {
$items['posix'] = ['posix', '开启', '开启', 'ok'];
}
session('install_error',''); session('install_error','');
if (substr($items['php'][1],0,3) < '7.0') { if (substr($items['php'][1],0,3) < '7.0') {
$items['php'][3] = 'error'; $items['php'][3] = 'error';
@ -388,6 +392,7 @@ INFO;
$items['gd'][3] = 'error'; $items['gd'][3] = 'error';
session('install_error', true); session('install_error', true);
} }
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
$items['openssl'][1] = '未开启'; $items['openssl'][1] = '未开启';
$items['openssl'][3] = 'error'; $items['openssl'][3] = 'error';
@ -398,7 +403,12 @@ INFO;
$items['pdo'][3] = 'error'; $items['pdo'][3] = 'error';
session('install_error', true); session('install_error', true);
} }
// dump($items);die; // linux系统下检查是否加载了posix扩展
if (in_array(PHP_OS, ['Linux', 'centos', 'Centos', 'ubuntu', 'Ubuntu']) && !extension_loaded('posix')) {
$items['posix'][1] = '未开启';
$items['posix'][3] = 'error';
session('install_error', true);
}
return $items; return $items;
} }

@ -9,6 +9,7 @@ namespace app\admin\controller;
use think\Hook; use think\Hook;
use think\Request; use think\Request;
use think\Db;
class Rules extends ApiCommon class Rules extends ApiCommon
{ {
@ -22,7 +23,7 @@ class Rules extends ApiCommon
{ {
$action = [ $action = [
'permission'=>[''], 'permission'=>[''],
'allow'=>['index'] 'allow'=>['index','groupauth','upgroupauth','getgroupauth','groupauthid']
]; ];
Hook::listen('check_auth',$action); Hook::listen('check_auth',$action);
$request = Request::instance(); $request = Request::instance();
@ -75,5 +76,134 @@ class Rules extends ApiCommon
} }
return resultArray(['data' => '编辑成功']); return resultArray(['data' => '编辑成功']);
} }
/**
* 配置角色查看范围列表
* @author zjf
*/
public function groupauth()
{
$param = $this->param;
$data = ['0' => ['name' => '系统管理角色','pid' => 1],'1' => ['name' => '办公管理角色','pid' => 6],'2' => ['name' => '客户管理角色','pid' => 2],'3' => ['name' => '项目管理角色','pid' => '9']];
$list = db('admin_group')->field('id, pid, title')->select();
$authList = db('admin_group_auth')->where('group_id', $param['group_id'])->column('auth_group_id');
foreach ($data as $key => $value) {
foreach ($list as $k => $v) {
$v['is_true'] = in_array($v['id'], $authList) ? 1 : 0;
if($v['pid'] == $value['pid']){
$data[$key]['item'][] = $v;
}
}
}
return resultArray(['data' => $data]);
}
/**
* 配置角色查看范围列表
* @author zjf
*/
public function groupauthid()
{
$param = $this->param;
$authList = db('admin_group_auth')->where('group_id', $param['group_id'])->column('auth_group_id');
return resultArray(['data' => array_map('intval', $authList)]);
}
/**
* 编辑配置角色查看范围
*/
public function upgroupauth()
{
$param = $this->param;
$group_id = $param['group_id'];
$auth_group_id = $param['auth_group_id'];
$data = [];
foreach ($auth_group_id as $key => $value) {
$data[] = [
'group_id' => $param['group_id'],
'auth_group_id' => $value
];
}
// 启动事务
Db::startTrans();
try{
db('admin_group_auth')->where('group_id', $param['group_id'])->delete();
db('admin_group_auth')->insertAll($data);
// 提交事务
Db::commit();
return resultArray(['data' => '编辑成功']);
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
return resultArray(['data' => '编辑失败']);
}
}
/**
* 配置角色查看范围列表
* @author zjf
*/
public function getgroupauth()
{
$userInfo = $this->userInfo;
$userId = $userInfo['id'];
$groupIds = db('admin_access')->where('user_id', $userId)->column('group_id');
$rules = db('admin_group')->where('id', 'in', $groupIds)->column('rules');
$arr = [];
foreach ($rules as $key => $value) {
if($arr){
$arr = array_merge(explode(",", trim($value, ",")), $arr);
}else{
$arr = explode(",", trim($value, ","));
}
}
$data = ['0' => ['name' => '系统管理角色','pid' => 1],'1' => ['name' => '办公管理角色','pid' => 6],'2' => ['name' => '客户管理角色','pid' => 2],'3' => ['name' => '项目管理角色','pid' => '9']];
# 角色权限查看 配置范围对应id
$rule_authority_id = db('admin_rule')->where(['title' => '角色权限设置', 'name' => 'update'])->value('id');
if(!in_array($rule_authority_id, $arr) && $userId != 1){
$auth_group_ids = db('admin_group_auth')->where('group_id', 'in', $groupIds)->column('auth_group_id');
$list = db('admin_group')->where('id', 'in', $auth_group_ids)->select();
$arrData = [];
foreach ($data as $key => $value) {
$item = [];
foreach ($list as $k => $v) {
if($v['pid'] == $value['pid']){
$item[] = $v;
}
}
$items = [];
if(!empty($item)){
$items = [
'name' => $value['name'],
'pid' => $value['pid'],
'list' => $item,
];
$arrData[] = $items;
}
}
return resultArray(['data' => $arrData]);
}else{
$list = db('admin_group')->select();
foreach ($data as $key => $value) {
foreach ($list as $k => $v) {
if($v['pid'] == $value['pid']){
$data[$key]['list'][] = $v;
}
}
}
return resultArray(['data' => $data]);
}
}
} }

@ -176,4 +176,20 @@ class Setting extends ApiCommon
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/**
* 设置顶部导航信息
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 11:28
*/
public function appMenuConfig()
{
$param=$this->param;
$userId=$this->userInfo['id'];
$settingModel = new \app\crm\model\Setting();
$data=$settingModel->setMenuConfig($param,$userId);
return resultArray(['data'=>'操作成功']);
}
} }

@ -195,7 +195,8 @@ class Structures extends ApiCommon
} }
$structureModel = model('Structure'); $structureModel = model('Structure');
$param = $this->param; $param = $this->param;
$data = $structureModel->delStrById($param['id']); $userInfo=$this->userInfo;
$data = $structureModel->delStrById($param['id'],$userInfo['id']);
if (!$data) { if (!$data) {
return resultArray(['error' => $structureModel->getError()]); return resultArray(['error' => $structureModel->getError()]);
} }

@ -16,10 +16,10 @@ class System extends ApiCommon
public function _initialize() public function _initialize()
{ {
$action = [ $action = [
'permission'=>['index'], 'permission' => ['index'],
'allow'=>[''] 'allow' => ['']
]; ];
Hook::listen('check_auth',$action); Hook::listen('check_auth', $action);
$request = Request::instance(); $request = Request::instance();
$a = strtolower($request->action()); $a = strtolower($request->action());
if (!in_array($a, $action['permission'])) { if (!in_array($a, $action['permission'])) {
@ -39,23 +39,26 @@ class System extends ApiCommon
public function save() public function save()
{ {
$param = $this->param; $param = $this->param;
$userInfo=$this->userInfo; $userInfo = $this->userInfo;
$field_name=''; $field_name = '';
$dataInfo=[]; $dataInfo = [];
if (isset($param['logo'])) { if (isset($param['logo'])) {
$system_id=2; $system_id = 2;
$field_name='企业logo'; $field_name = '企业logo';
$logo = !empty($param['logo']) ? './public/uploads/'.$param['logo'] : ''; $logo = !empty($param['logo']) ? './public/uploads/' . $param['logo'] : '';
$dataInfo = db('admin_system')->where('id', $system_id)->column('name,value'); $dataInfo = db('admin_system')->where('id', $system_id)->column('name,value');
db('admin_system')->where('name', 'logo')->update(['value' => $logo]); db('admin_system')->where('name', 'logo')->update(['value' => $logo]);
}elseif (isset($param['name'])) { # 修改记录
$system_id=1; SystemActionLog($userInfo['id'], 'admin_system', 'company', 1, 'update', '企业基本信息设置', '', '', '编辑了:' . $field_name);
$field_name='企业名称'; }
if (isset($param['name'])) {
$system_id = 1;
$field_name = '企业名称';
$dataInfo = db('admin_system')->where('id', $system_id)->column('name,value'); $dataInfo = db('admin_system')->where('id', $system_id)->column('name,value');
db('admin_system')->where('name', 'name')->update(['value' => $param['name']]); db('admin_system')->where('name', 'name')->update(['value' => $param['name']]);
}
# 修改记录 # 修改记录
SystemActionLog($userInfo['id'],'admin_system','company',1,'update','企业基本信息设置','','','编辑了:'.$field_name); SystemActionLog($userInfo['id'], 'admin_system', 'company', 1, 'update', '企业基本信息设置', '', '', '编辑了:' . $field_name);
}
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
} }

@ -21,10 +21,10 @@ class UpdateSql
*/ */
static public function addPoolDefaultData() static public function addPoolDefaultData()
{ {
# 员工ID // 员工ID
$userIds = db('admin_user')->column('id'); $userIds = db('admin_user')->column('id');
# 公海主数据 // 公海主数据
$poolData = [ $poolData = [
'pool_name' => '系统默认公海', 'pool_name' => '系统默认公海',
'admin_user_ids' => ',1,', 'admin_user_ids' => ',1,',
@ -42,7 +42,7 @@ class UpdateSql
'create_time' => time() 'create_time' => time()
]; ];
# 公海规则数据 // 公海规则数据
$poolRuleData = [ $poolRuleData = [
'pool_id' => 0, 'pool_id' => 0,
'type' => 1, 'type' => 1,
@ -53,7 +53,7 @@ class UpdateSql
'limit_day' => 0 'limit_day' => 0
]; ];
# 公海字段数据 // 公海字段数据
$poolFieldData = []; $poolFieldData = [];
$fields = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select(); $fields = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
foreach ($fields AS $key => $value) { foreach ($fields AS $key => $value) {
@ -76,14 +76,14 @@ class UpdateSql
Db::startTrans(); Db::startTrans();
try { try {
# 添加公海主数据 // 添加公海主数据
$poolId = Db::name('crm_customer_pool')->insert($poolData, false, true); $poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
# 添加公海规则数据 // 添加公海规则数据
$poolRuleData['pool_id'] = $poolId; $poolRuleData['pool_id'] = $poolId;
Db::name('crm_customer_pool_rule')->insert($poolRuleData); Db::name('crm_customer_pool_rule')->insert($poolRuleData);
# 添加公海字段数据 // 添加公海字段数据
array_walk($poolFieldData, function (&$val) use ($poolId) { array_walk($poolFieldData, function (&$val) use ($poolId) {
$val['pool_id'] = $poolId; $val['pool_id'] = $poolId;
}); });
@ -107,10 +107,10 @@ class UpdateSql
*/ */
static public function addFollowRuleData() static public function addFollowRuleData()
{ {
# 删除旧版的跟进记录权限规则数据 // 删除旧版的跟进记录权限规则数据
db('admin_rule')->where(['types' => 2, 'title' => '跟进记录管理', 'name' => 'record', 'level' => 2, 'pid' => 1])->delete(); db('admin_rule')->where(['types' => 2, 'title' => '跟进记录管理', 'name' => 'record', 'level' => 2, 'pid' => 1])->delete();
# 新版跟进记录权限规则增加导入导出 // 新版跟进记录权限规则增加导入导出
$activityPid = db('admin_rule')->where(['types' => 2, 'title' => '跟进记录', 'name' => 'activity', 'level' => 2])->value('id'); $activityPid = db('admin_rule')->where(['types' => 2, 'title' => '跟进记录', 'name' => 'activity', 'level' => 2])->value('id');
if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelImport'])->value('id')) { if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelImport'])->value('id')) {
db('admin_rule')->insert(['types' => 2, 'title' => '导入', 'name' => 'excelImport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]); db('admin_rule')->insert(['types' => 2, 'title' => '导入', 'name' => 'excelImport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
@ -119,4 +119,110 @@ class UpdateSql
db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]); db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
} }
} }
/**
* 处理11.0.3升级时,没有处理旧公海数据的问题
*
* @author fanqi
* @since 2021-06-23
*/
static public function SynchronizationCustomerToPool()
{
$poolData = [];
$installData = [];
$updateData = [];
// 公海数据
$poolList = db('crm_customer_pool')->alias('pool')
->join('__CRM_CUSTOMER_POOL_RELATION__ relation', 'pool.pool_id = relation.pool_id', 'INNER')
->field(['relation.pool_id', 'relation.customer_id'])->select();
// 整理公海数据
foreach ($poolList AS $key => $value) {
$poolData[$value['pool_id']][] = $value['customer_id'];
}
// 没有负责人和没有进入公海时间的客户
$customerIds = db('crm_customer')->where(['owner_user_id' => 0, 'into_pool_time' => 0])->column('customer_id');
// 整理要添加(公海客户管理表)和要编辑的数据(修改客户的进入公海时间)
foreach ($customerIds AS $key => $value) {
foreach ($poolData AS $k => $v) {
if (!in_array($value, $v)) {
$installData[] = [
'pool_id' => $k,
'customer_id' => $value
];
$updateData[] = $value;
}
}
}
// 添加至公海客户关联表
if (!empty($installData)) {
db('crm_customer_pool_relation')->insertAll($installData);
}
// 更新客户的进入公海时间
if (!empty($updateData)) {
db('crm_customer')->whereIn('customer_id', array_unique($updateData))->exp('before_owner_user_id', 'create_user_id')->update(['into_pool_time' => time()]);
}
}
/**
* 发票导出权限
*
* @author fanqi
* @since 2021-06-24
*/
static public function createInvoiceExportRule()
{
// 发票导出权限
$invoiceId = db('admin_rule')->where(['types' => 2, 'title' => '发票管理', 'name' => 'invoice', 'level' => 2, 'pid' => 1])->value('id');
if (!empty($invoiceId)) {
db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $invoiceId, 'status' => 1]);
}
}
/**
* 修改数字字段类型
*
* @author fanqi
* @since 2021-06-24
*/
static public function updateFieldNumberType()
{
$leadsList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_leads', 'form_type' => 'number'])->select();
foreach ($leadsList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_leads` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$customerList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_customer', 'form_type' => 'number'])->select();
foreach ($customerList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_customer` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$contactsList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_contacts', 'form_type' => 'number'])->select();
foreach ($contactsList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_contacts` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$businessList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_business', 'form_type' => 'number'])->select();
foreach ($businessList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_business` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$contractList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_contract', 'form_type' => 'number'])->select();
foreach ($contractList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_contract` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$receivablesList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_receivables', 'form_type' => 'number'])->select();
foreach ($receivablesList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_receivables` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$visitList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_visit', 'form_type' => 'number'])->select();
foreach ($visitList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_visit` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
$productList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_product', 'form_type' => 'number'])->select();
foreach ($productList AS $key => $value) {
Db::execute("ALTER TABLE `5kcrm_crm_product` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
}
}
} }

@ -98,9 +98,72 @@ class Users extends ApiCommon
} }
$serverUserInfo = $this->queryLoginUser(); $serverUserInfo = $this->queryLoginUser();
if (!empty($serverUserInfo)) $data['serverUserInfo'] = $serverUserInfo; if (!empty($serverUserInfo)) $data['serverUserInfo'] = $serverUserInfo;
# 角色权限查看 配置范围对应id
$rule_authority_id = db('admin_rule')->where(['title' => '角色权限查看', 'name' => 'ruleList'])->value('id');
$data['rule_authority_id'] = $rule_authority_id;
# 数据库更新 todo 在线升级正常使用后删除
$updateStatus = $this->executeUpdateSql();
if (empty($updateStatus['status'])) return resultArray(['error' => $updateStatus['message']]);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/**
* 更新SQL
*
* @author fanqi
* @since 2021-05-08
*/
public function executeUpdateSql()
{
// 表前缀
$prefix = config('database.prefix');
// 检查更新记录表是否存在
if (!db()->query("SHOW TABLES LIKE '".$prefix."admin_upgrade_record'")) {
db()->query("
CREATE TABLE `".$prefix."admin_upgrade_record` (
`version` int(10) unsigned DEFAULT NULL COMMENT '版本号',
UNIQUE KEY `version` (`version`) USING BTREE
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT = 'SQL更新记录用于防止重复执行更新。'
");
}
// 检查是否执行过11.0.3版本的更新
if (!db('admin_upgrade_record')->where('version', 1103)->value('version')) {
// 添加跟进记录导入导出权限数据
UpdateSql::addFollowRuleData();
// 添加公海默认数据
$poolStatus = UpdateSql::addPoolDefaultData();
if (!$poolStatus) return ['status' => false, 'message' => '添加公海默认配置失败,请在后台手动添加!'];
// 添加此次升级标记
db('admin_upgrade_record')->insert(['version' => 1103]);
return ['status' => true, 'message' => '更新完成!'];
}
// 检查是否执行过11.0.4版本的更新
if (!db('admin_upgrade_record')->where('version', 1104)->value('version')) {
// 处理11.0.3升级时,没有处理旧公海数据的问题
UpdateSql::SynchronizationCustomerToPool();
// 发票导出权限
UpdateSql::createInvoiceExportRule();
// 修改数字字段类型
UpdateSql::updateFieldNumberType();
// 添加此次升级标记
db('admin_upgrade_record')->insert(['version' => 1104]);
}
return ['status' => true, 'message' => '没有可用更新!'];
}
/** /**
* 员工创建 * 员工创建
* @param * @param
@ -111,6 +174,7 @@ class Users extends ApiCommon
$userModel = model('User'); $userModel = model('User');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['userId']=$userInfo['id'];
$data = $userModel->createData($param); $data = $userModel->createData($param);
if (!$data) { if (!$data) {
return resultArray(['error' => $userModel->getError()]); return resultArray(['error' => $userModel->getError()]);
@ -138,6 +202,7 @@ class Users extends ApiCommon
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code' => 102, 'error' => '无权操作'])); exit(json_encode(['code' => 102, 'error' => '无权操作']));
} }
$param['userId']=$userInfo['id'];
} }
unset($param['username']); unset($param['username']);
$data = $userModel->updateDataById($param, $param['id']); $data = $userModel->updateDataById($param, $param['id']);
@ -158,6 +223,8 @@ class Users extends ApiCommon
exit(json_encode(['code' => 102, 'error' => '无权操作'])); exit(json_encode(['code' => 102, 'error' => '无权操作']));
} }
$param = $this->param; $param = $this->param;
$userInfo=$this->userInfo;
$param['user_id']=$userInfo['id'];
if ($param['password'] && is_array($param['id'])) { if ($param['password'] && is_array($param['id'])) {
$userModel = model('User'); $userModel = model('User');
$ret = $userModel->updatePwdById($param); $ret = $userModel->updatePwdById($param);
@ -322,7 +389,7 @@ class Users extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$userModel = model('User'); $userModel = model('User');
$userId=$userInfo['id'];
if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']); if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
if ($param['id'] && (int)$param['id'] !== $userInfo['id']) { if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
@ -359,7 +426,7 @@ class Users extends ApiCommon
$userModel = model('User'); $userModel = model('User');
$old_pwd = $param['old_pwd']; $old_pwd = $param['old_pwd'];
$new_pwd = $param['new_pwd']; $new_pwd = $param['new_pwd'];
$data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd); $data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd,$userId);
if (!$data) { if (!$data) {
return resultArray(['error' => $userModel->getError()]); return resultArray(['error' => $userModel->getError()]);
} }
@ -721,7 +788,8 @@ class Users extends ApiCommon
if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']); if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']);
$userModel = new User(); $userModel = new User();
$userInfo=$this->userInfo;
$param['userId']=$userInfo['id'];
if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']); if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);

@ -125,10 +125,11 @@ class Work extends ApiCommon
{ {
if (empty($this->param['id'])) return resultArray(['error' => '请选择要编辑的权限角色!']); if (empty($this->param['id'])) return resultArray(['error' => '请选择要编辑的权限角色!']);
if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']); if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']);
$userInfo=$this->userInfo;
$this->param['user_id']=$userInfo['id'];
$data=$workLogic->updateRole($this->param); $data=$workLogic->updateRole($this->param);
if (empty($data)) return resultArray(['error' => '操作失败!']); if ($data!==false)return resultArray(['data' => '操作成功!']);
return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
} }
/** /**
@ -142,8 +143,8 @@ class Work extends ApiCommon
public function deleteRole(WorkLogic $workLogic) public function deleteRole(WorkLogic $workLogic)
{ {
if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的权限角色!']); if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的权限角色!']);
$userInfo=$this->userInfo;
$result = $workLogic->deleteRole($this->param['id']); $result = $workLogic->deleteRole($this->param['id'],$userInfo['id']);
if (empty($result['status'])) return resultArray(['error' => $result['error']]); if (empty($result['status'])) return resultArray(['error' => $result['error']]);

@ -46,7 +46,10 @@ class FieldGrantLogic
'visit' => [ 'visit' => [
'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction', 'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
'feedback', 'create_user_id', 'create_time', 'update_time' 'feedback', 'create_user_id', 'create_time', 'update_time'
] ],
'invoice' => [
'invoice_apple_number', 'customer_id', 'contract_id', 'contract_money', 'invoice_date', 'invoice_money', 'invoice_type', 'remark'
],
]; ];
/** /**
@ -90,6 +93,8 @@ class FieldGrantLogic
*/ */
public function createCrmFieldGrant($roleId) public function createCrmFieldGrant($roleId)
{ {
# 防止重复,先删除一下
$this->deleteCrmFieldGrant($roleId);
# 添加线索字段授权数据 # 添加线索字段授权数据
$this->createLeadsFieldGrant($roleId); $this->createLeadsFieldGrant($roleId);
# 添加客户字段授权数据 # 添加客户字段授权数据
@ -106,6 +111,8 @@ class FieldGrantLogic
$this->createProductFieldGrant($roleId); $this->createProductFieldGrant($roleId);
# 添加回访字段授权信息 # 添加回访字段授权信息
$this->createVisitFieldGrant($roleId); $this->createVisitFieldGrant($roleId);
# 添加发票字段授权信息
$this->createInvoiceFieldGrant($roleId);
} }
/** /**
@ -678,4 +685,51 @@ class FieldGrantLogic
'update_time' => time() 'update_time' => time()
]); ]);
} }
/**
* 处理回访字段授权信息
*
* @param $roleId
* @author fanqi
* @since 2021-06-25
*/
private function createInvoiceFieldGrant($roleId)
{
$content = [
['field' => 'invoice_apple_number', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '发票申请编号'],
['field' => 'customer_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '客户名称'],
['field' => 'contract_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同编号'],
['field' => 'contract_money', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同金额'],
['field' => 'invoice_money', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '开票金额'],
['field' => 'invoice_date', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '开票日期'],
['field' => 'invoice_type', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '开票类型'],
['field' => 'remark', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
];
$invoiceList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_invoice')->select();
# 处理自定义字段
foreach ($invoiceList AS $key => $value) {
if (in_array($value['field'], $this->except['invoice'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => 1,
'write' => 1,
'write_operation' => 1,
'is_diy' => 1
];
}
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
'column' => 'invoice',
'content' => serialize($content),
'create_time' => time(),
'update_time' => time()
]);
}
} }

@ -440,6 +440,25 @@ class InitializeLogic
# ------ 重置自动编号数据 END ------ # # ------ 重置自动编号数据 END ------ #
# ------ 重置扩展数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."crm_leads_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_contacts_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_business_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_contract_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_receivables_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_receivables_plan_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_invoice_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_visit_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_product_data");
# ------ 重置扩展数据 END ------ #
# ------ 清除待办事项关联数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."crm_dealt_relation");
# ------ 清除待办事项关联数据 END ------ #
# ------ 设置跟进记录常用语 START ------ # # ------ 设置跟进记录常用语 START ------ #
$phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大']; $phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大'];
$phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id'); $phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id');
@ -515,44 +534,6 @@ class InitializeLogic
# 启动事务 # 启动事务
Db::startTrans(); Db::startTrans();
try { try {
# ------ 清除任务数据 START ------ #
// # 获取任务ID
// $taskIds = Db::name('task')->where(['work_id' => ['eq', 0]])->column('task_id');
//
// # 获取任务下关联的附件ID
// $taskFieldIds = Db::name('work_task_file')->whereIn('task_id', $taskIds)->column('file_id');
//
// # 查询活动附件数据
// $taskFileInfo = $this->getFileList($taskFieldIds);
//
// # 合并附件数据
// $files = array_merge($files, $taskFileInfo);
//
// # 删除任务附件关联表
// Db::name('work_task_file')->whereIn('task_id', $taskIds)->delete();
// # 重置自增ID
// Db::query("ALTER TABLE ".$prefix."work_task_file AUTO_INCREMENT = 1");
//
// # 删除附件
// Db::name('admin_file')->whereIn('file_id', $taskFieldIds)->delete();
//
// # 清除任务关联的客户模块数据数据并重置自增ID
// Db::query("TRUNCATE TABLE ".$prefix."task_relation");
//
// # 删除任务log
// Db::name('work_task_log')->whereIn('task_id', $taskIds)->delete();
// # 重置任务log自增ID
// Db::query("ALTER TABLE ".$prefix."work_task_log AUTO_INCREMENT = 1");
//
// # 删除任务
// Db::name('task')->where(['work_id' => ['eq', 0]])->delete();
// # 重置任务自增ID
// Db::query("ALTER TABLE ".$prefix."task AUTO_INCREMENT = 1");
# ------ 清除任务数据 END ------ #
# ------ 清除审批数据 START ------ # # ------ 清除审批数据 START ------ #
# 获取审批下关联的附件ID # 获取审批下关联的附件ID
@ -595,6 +576,11 @@ class InitializeLogic
# ------ 清除审批数据 END ------ # # ------ 清除审批数据 END ------ #
# ------ 重置扩展数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."oa_examine_data");
# ------ 重置扩展数据 END ------ #
# ------ 清除活动中有关审批的数据 START ------ # # ------ 清除活动中有关审批的数据 START ------ #
# 获取有关审批的活动ID # 获取有关审批的活动ID

@ -245,7 +245,7 @@ class LogLogic
'action' => in_array('crm',explode('_',$value['module']))==1? 'action' => in_array('crm',explode('_',$value['module']))==1?
'客户管理':(in_array('oa',explode('_',$value['module']))==1?'办公管理':'项目管理'), '客户管理':(in_array('oa',explode('_',$value['module']))==1?'办公管理':'项目管理'),
'content' => $value['content'], 'content' => $value['content'],
'user_name' => $value['realname'], 'user_name' => $value['realname']?:'系统',
'action_name' => $this->action[$value['action_name']], 'action_name' => $this->action[$value['action_name']],
]; ];
} }
@ -270,7 +270,7 @@ class LogLogic
'ip' => $value['client_ip'], 'ip' => $value['client_ip'],
'action' => $this->systemModules[$value['module_name']], 'action' => $this->systemModules[$value['module_name']],
'content' => $value['content'], 'content' => $value['content'],
'user_name' => $value['realname'], 'user_name' => $value['realname']?:'系统',
'action_name' => $this->action[$value['action_name']], 'action_name' => $this->action[$value['action_name']],
'module' => '后台管理', 'module' => '后台管理',
'action_down' => $this->recordModules[$value['controller_name']]?:'', 'action_down' => $this->recordModules[$value['controller_name']]?:'',

@ -245,7 +245,7 @@ class MessageLogic
$where['is_delete'] = ['eq', 1]; $where['is_delete'] = ['eq', 1];
$where['type'] = $this->label(''); $where['type'] = $this->label('');
$allCount = db('admin_message')->where($where)->count(); $allCount = db('admin_message')->where($where)->where(['advance_time'=>['<', time()]])->count();
$where['type'] = $this->label(1); $where['type'] = $this->label(1);
$taskCount = db('admin_message')->where($where)->count(); $taskCount = db('admin_message')->where($where)->count();
$where['type'] = $this->label(2); $where['type'] = $this->label(2);
@ -255,7 +255,7 @@ class MessageLogic
$where['type'] = 9; $where['type'] = 9;
$announceCount = db('admin_message')->where($where)->count(); $announceCount = db('admin_message')->where($where)->count();
$where['type'] = $this->label(5); $where['type'] = $this->label(5);
$eventCount = db('admin_message')->where($where)->where(['advance_time'=>['<', time()],'advance_time'=>['<>',0]])->count(); $eventCount = db('admin_message')->where($where)->where(['advance_time'=>['<', time()]])->count();
$where['type'] = $this->label(6); $where['type'] = $this->label(6);
$crmCount = db('admin_message')->where($where)->count(); $crmCount = db('admin_message')->where($where)->count();

@ -273,6 +273,9 @@ class PoolConfigLogic
# 删除用户保存的公海字段数据 # 删除用户保存的公海字段数据
Db::name('crm_customer_pool_field_style')->where('pool_id', $poolId)->delete(); Db::name('crm_customer_pool_field_style')->where('pool_id', $poolId)->delete();
# 删除公海操作记录数据
Db::name('crm_customer_pool_record')->where('pool_id', $poolId)->delete();
# 删除公海数据 # 删除公海数据
Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete(); Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete();
@ -361,63 +364,81 @@ class PoolConfigLogic
public function getPoolFieldList($param) public function getPoolFieldList($param)
{ {
if (!empty($param['pool_id'])) { if (!empty($param['pool_id'])) {
return db('crm_customer_pool_field_setting')->field(['field_name AS field', 'name', 'form_type', 'is_hidden'])->where('pool_id', $param['pool_id'])->select(); return db('crm_customer_pool_field_setting')->field(['field_name AS field', 'name', 'form_type', 'is_hidden', 'is_null', 'is_unique'])->where('pool_id', $param['pool_id'])->select();
} else { } else {
$data = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select(); $data = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden', 'is_null', 'is_unique'])->where(['types' => 'crm_customer'])->select();
$address = [ $address = [
'field' => 'address', 'field' => 'address',
'name' => '省、市、区/县', 'name' => '省、市、区/县',
'form_type' => 'customer_address', 'form_type' => 'customer_address',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$detailAddress = [ $detailAddress = [
'field' => 'detail_address', 'field' => 'detail_address',
'name' => '详细地址', 'name' => '详细地址',
'form_type' => 'text', 'form_type' => 'text',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$lastRecord = [ $lastRecord = [
'field' => 'last_record', 'field' => 'last_record',
'name' => '最后跟进记录', 'name' => '最后跟进记录',
'form_type' => 'text', 'form_type' => 'text',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$lastTime = [ $lastTime = [
'field' => 'last_time', 'field' => 'last_time',
'name' => '最后跟进时间', 'name' => '最后跟进时间',
'form_type' => 'datetime', 'form_type' => 'datetime',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$beforeOwnerUser = [ $beforeOwnerUser = [
'field' => 'before_owner_user_id', 'field' => 'before_owner_user_id',
'name' => '前负责人', 'name' => '前负责人',
'form_type' => 'user', 'form_type' => 'user',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$intoPoolTime = [ $intoPoolTime = [
'field' => 'into_pool_time', 'field' => 'into_pool_time',
'name' => '进入公海时间', 'name' => '进入公海时间',
'form_type' => 'datetime', 'form_type' => 'datetime',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$createTime = [ $createTime = [
'field' => 'create_time', 'field' => 'create_time',
'name' => '创建时间', 'name' => '创建时间',
'form_type' => 'datetime', 'form_type' => 'datetime',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$updateTime = [ $updateTime = [
'field' => 'update_time', 'field' => 'update_time',
'name' => '更新时间', 'name' => '更新时间',
'form_type' => 'datetime', 'form_type' => 'datetime',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
$createUser = [ $createUser = [
'field' => 'create_user_id', 'field' => 'create_user_id',
'name' => '创建人', 'name' => '创建人',
'form_type' => 'user', 'form_type' => 'user',
'is_hidden' => 0 'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
]; ];
array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime); array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime);
@ -472,7 +493,9 @@ class PoolConfigLogic
'name' => $value['name'], 'name' => $value['name'],
'field_name' => $value['field'], 'field_name' => $value['field'],
'form_type' => $value['form_type'], 'form_type' => $value['form_type'],
'is_hidden' => $value['is_hidden'] 'is_hidden' => $value['is_hidden'],
'is_null' => $value['is_null'],
'is_unique' => $value['is_unique']
]; ];
} }

@ -92,14 +92,14 @@ class WorkLogic
public function updateRole($param) public function updateRole($param)
{ {
$res=Db::name('admin_group')->where('id',$param['id'])->find(); $res=Db::name('admin_group')->where('id',$param['id'])->find();
$userInd=$param['user_id'];
unset($param['user_id']);
if(!$res){ if(!$res){
return false; return false;
}else{ }else{
$data=Db::name('admin_group')->update($param); $data=Db::name('admin_group')->update($param);
# 添加系统操作日志 # 添加系统操作日志
$user=new ApiCommon(); SystemActionLog($userInd, 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
return $data; return $data;
} }
@ -113,7 +113,7 @@ class WorkLogic
* @throws \think\Exception * @throws \think\Exception
* @throws \think\exception\PDOException * @throws \think\exception\PDOException
*/ */
public function deleteRole($id) public function deleteRole($id,$userId)
{ {
$system = Db::name('admin_group')->where('id', $id)->find(); $system = Db::name('admin_group')->where('id', $id)->find();
@ -128,9 +128,7 @@ class WorkLogic
db('work_user')->where('group_id', $id)->update(['group_id' => $readOnlyId]); # 处理私有项目的权限 db('work_user')->where('group_id', $id)->update(['group_id' => $readOnlyId]); # 处理私有项目的权限
} }
# 添加系统操作日志 # 添加系统操作日志
$user=new ApiCommon(); SystemActionLog($userId, 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
return ['status' => true]; return ['status' => true];
} }
} }

@ -43,7 +43,7 @@ class ActionRecord extends Common
} }
$userModel = model('User'); $userModel = model('User');
foreach ($dataList as $k=>$v) { foreach ($dataList as $k=>$v) {
$dataList[$k]['user_id_info'] = isset($v['user_id']) ? $userModel->getUserById($v['user_id']) : []; $dataList[$k]['user_id_info'] = $v['user_id']!=0 ? $userModel->getUserById($v['user_id']) : '系统';
$dataList[$k]['content'] = explode('.|.', $v['content']); $dataList[$k]['content'] = explode('.|.', $v['content']);
} }
return $dataList; return $dataList;

@ -36,16 +36,16 @@ class Common extends Model
* @param [array] $request [参数] * @param [array] $request [参数]
* @return [array] * @return [array]
*/ */
public function fmtRequest( $request = [] ) public function fmtRequest($request = [])
{ {
$pageType = $request['pageType'] ? 'all' : ''; //all全部不分页 $pageType = $request['pageType'] ? 'all' : ''; //all全部不分页
$page = 1; $page = 1;
if (isset($request['page']) && is_numeric($request['page']) ) { if (isset($request['page']) && is_numeric($request['page'])) {
$page = $request['page']; $page = $request['page'];
unset($request['page']); unset($request['page']);
} }
$limit = 15; $limit = 15;
if (isset($request['limit']) && is_numeric($request['limit']) ) { if (isset($request['limit']) && is_numeric($request['limit'])) {
$limit = $request['limit']; $limit = $request['limit'];
unset($request['limit']); unset($request['limit']);
} }
@ -118,7 +118,7 @@ class Common extends Model
try { try {
$this->data($param)->allowField(true)->save(); $this->data($param)->allowField(true)->save();
return true; return true;
} catch(\Exception $e) { } catch (\Exception $e) {
$this->error = '添加失败'; $this->error = '添加失败';
return false; return false;
} }
@ -148,7 +148,7 @@ class Common extends Model
try { try {
$this->allowField(true)->save($param, [$this->getPk() => $id]); $this->allowField(true)->save($param, [$this->getPk() => $id]);
return true; return true;
} catch(\Exception $e) { } catch (\Exception $e) {
$this->error = '编辑失败'; $this->error = '编辑失败';
return false; return false;
} }
@ -172,13 +172,13 @@ class Common extends Model
if ($delSon && is_numeric($id)) { if ($delSon && is_numeric($id)) {
// 删除子孙 // 删除子孙
$childIds = $this->getAllChild($id); $childIds = $this->getAllChild($id);
if($childIds){ if ($childIds) {
$this->where($this->getPk(), 'in', $childIds)->delete(); $this->where($this->getPk(), 'in', $childIds)->delete();
} }
} }
$this->commit(); $this->commit();
return true; return true;
} catch(\Exception $e) { } catch (\Exception $e) {
$this->error = '删除失败'; $this->error = '删除失败';
$this->rollback(); $this->rollback();
return false; return false;
@ -241,7 +241,7 @@ class Common extends Model
$ids = array_unique($ids); $ids = array_unique($ids);
} }
try { try {
$this->where($this->getPk(),'in',$ids)->setField('status', $status); $this->where($this->getPk(), 'in', $ids)->setField('status', $status);
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error = '操作失败'; $this->error = '操作失败';
@ -282,7 +282,7 @@ class Common extends Model
$this->allowField(true)->save($data, [$this->getPk() => $id]); $this->allowField(true)->save($data, [$this->getPk() => $id]);
$this->commit(); $this->commit();
return true; return true;
} catch(\Exception $e) { } catch (\Exception $e) {
$this->error = '删除失败'; $this->error = '删除失败';
$this->rollback(); $this->rollback();
return false; return false;
@ -303,9 +303,9 @@ class Common extends Model
if (isset($val[$field['field'] . 'name'])) { if (isset($val[$field['field'] . 'name'])) {
$val[$field['field']] = $val[$field['field'] . 'name']; $val[$field['field']] = $val[$field['field'] . 'name'];
} }
// else { if ($field['field'] == 'order_user_id') {
// $val[$field['field']] = implode(',', array_column($val[$field['field'] . '_info'], 'realname')); $val[$field['field']] = $val[$field['field'] . '_name'];
// } }
break; break;
case 'structure': case 'structure':
// $temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']); // $temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']);
@ -317,22 +317,26 @@ class Common extends Model
break; break;
case 'customer':break; case 'customer':break;
case 'business':break; case 'business':break;
case 'contacts':break; case 'contacts':
$val[$field['field']] = $val[$field['field'] . '_info']['name']; $val[$field['field']] = $val[$field['field'] . '_info']['name'];
break; break;
default : default :
switch ($field['field']) { switch ($field['field']) {
// 商机销售阶段、商机状态组 // 商机销售阶段、商机状态组
case 'status_id': case 'status_id':
if($val['is_end']!=0){ if ($val['is_end'] != 0) {
$val[$field['field']]= $val['is_end']; $val[$field['field']] = $val['is_end'];
} }
break; break;
case 'type_id':break; case 'type_id':
break;
// $val[$field['field']] = $val[$field['field'] . '_info']; // $val[$field['field']] = $val[$field['field'] . '_info'];
case 'check_status' : case 'check_status' :
$val[$field['field']] = $val[$field['field'] . '_info']; $val[$field['field']] = $val[$field['field'] . '_info'];
break; break;
case 'plan_id' :
$val[$field['field']] = $val[$field['field'] . '_info'];
break;
} }
} }
} }

@ -14,6 +14,7 @@ use com\PseudoQueue as Queue;
use think\Cache; use think\Cache;
use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\cache\driver\Redis; use think\cache\driver\Redis;
class Excel extends Common class Excel extends Common
{ {
/** /**
@ -26,6 +27,8 @@ class Excel extends Common
'crm_customer', 'crm_customer',
'crm_contacts', 'crm_contacts',
'crm_product', 'crm_product',
'crm_contract',
'crm_business',
'admin_user', 'admin_user',
'task' 'task'
]; ];
@ -111,6 +114,7 @@ class Excel extends Common
} else { } else {
$k = 0; $k = 0;
} }
$objActSheet->getColumnDimension('A1')->setWidth(70);
foreach ($field_list as $field) { foreach ($field_list as $field) {
if ($field['form_type'] == 'map_address' && $types == 'crm_customer') { if ($field['form_type'] == 'map_address' && $types == 'crm_customer') {
for ($a = 0; $a <= 3; $a++) { for ($a = 0; $a <= 3; $a++) {
@ -121,13 +125,13 @@ class Excel extends Common
} }
} else { } else {
$objActSheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(20); //设置单元格宽度 $objActSheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(20); //设置单元格宽度
if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category' || $field['form_type']=='user') { if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category' || $field['form_type'] == 'user') {
//产品类别 //产品类别
if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') { if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
$setting = db('crm_product_category')->order('pid asc')->column('name'); $setting = db('crm_product_category')->order('pid asc')->column('name');
} elseif($field['form_type']=='user' && $field['field'] == 'owner_user_id') { } elseif ($field['form_type'] == 'user' && ($field['field'] == 'owner_user_id' || $field['field'] == 'create_user_id' || $field['field'] == 'before_owner_user_id')) {
$setting = db('admin_user')->order('id asc')->column('realname'); $setting = db('admin_user')->order('id asc')->column('realname');
}else{ } else {
$setting = $field['setting'] ?: []; $setting = $field['setting'] ?: [];
} }
$select_value = implode(',', $setting); $select_value = implode(',', $setting);
@ -146,6 +150,7 @@ class Excel extends Common
$endcell = $c; $endcell = $c;
} }
for ($j = 3; $j <= 70; $j++) { for ($j = 3; $j <= 70; $j++) {
$objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
$objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本) $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
//数据有效性 start //数据有效性 start
$objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation(); $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
@ -164,6 +169,7 @@ class Excel extends Common
} else { } else {
if ($select_value) { if ($select_value) {
for ($j = 3; $j <= 70; $j++) { for ($j = 3; $j <= 70; $j++) {
$objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
$objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本) $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
//数据有效性 start //数据有效性 start
$objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation(); $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
@ -182,10 +188,14 @@ class Excel extends Common
} }
} }
} }
$objActSheet->getStyle($this->stringFromColumnIndex($k))->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本) $objActSheet->getStyle($this->stringFromColumnIndex($k))->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
//检查该字段若必填,加上"*" //检查该字段若必填,加上"*"
$field['name'] = sign_required($field['is_null'], $field['name']); $field['name'] = sign_required($field['is_null'], $field['name']);
$objActSheet->setCellValue($this->stringFromColumnIndex($k) . '2', $field['name']); $objActSheet->setCellValue($this->stringFromColumnIndex($k) . '2', $field['name']);
if (strstr($field['name'], '*')) {
$objActSheet->getStyle($this->stringFromColumnIndex($k) . '2')->getFont()->getColor()->setARGB('#FF0000');
}
$k++; $k++;
} }
} }
@ -193,19 +203,17 @@ class Excel extends Common
$mark_row = $this->stringFromColumnIndex($k); $mark_row = $this->stringFromColumnIndex($k);
$objActSheet->mergeCells('A1:' . $max_row . '1'); $objActSheet->mergeCells('A1:' . $max_row . '1');
$objActSheet->getStyle('A1:' . $mark_row . '1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); //水平居中
$objActSheet->getStyle('A1:' . $mark_row . '1')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); //垂直居中
$objActSheet->getRowDimension(1)->setRowHeight(28); //设置行高
$objActSheet->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000'); $objActSheet->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000');
$objActSheet->getStyle('A1')->getAlignment()->setWrapText(true); $objActSheet->getStyle('A2:' . $max_row . '2')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); //
$objActSheet->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000');
$objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);
//设置单元格格式范围的字体、字体大小、加粗 //设置单元格格式范围的字体、字体大小、加粗
$objActSheet->getStyle('A1:' . $max_row . '1')->getFont()->setName("微软雅黑")->setSize(13)->getColor()->setARGB('#00000000'); $objActSheet->getStyle('A1:' . $max_row . '1')->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
//给单元格填充背景色 //给单元格填充背景色
$objActSheet->getStyle('A1:' . $max_row . '1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('#ff9900'); // $objActSheet->getStyle('A1:' . $max_row . '1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('#ff9900');
$objActSheet->getStyle('A1:' . $max_row . '1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT); //水平居中
$objActSheet->getStyle('A1:' . $max_row . '1')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT); //垂直居中
$objActSheet->getRowDimension(1)->setRowHeight(100); //设置行高
$objActSheet->getRowDimension(2)->setRowHeight(30); //设置行高
$objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);
switch ($types) { switch ($types) {
case 'crm_leads' : case 'crm_leads' :
$types_name = '线索信息'; $types_name = '线索信息';
@ -243,13 +251,34 @@ class Excel extends Common
$types_name = '任务信息'; $types_name = '任务信息';
$type_name = 'task'; $type_name = 'task';
break; break;
case 'crm_pool' :
$types_name = '公海信息';
$type_name = 'pool';
break;
case 'crm_activity' :
$types_name = '跟进记录';
$type_name = 'activity';
break;
default : default :
$types_name = '悟空软件'; $types_name = '悟空软件';
$type_name = 'WuKong'; $type_name = 'WuKong';
break; break;
} }
$content = $types_name . '*代表必填项;时间格式:' . date('Y-m-d H:i:s') . '';
//内容设置
$content='';
if ($types == 'admin_user') {
$content ="注意事项:\n1、表头标“*”的红色字体为必填项\n2、手机号目前只支持中国大陆的11位手机号码且手机号不允许重复\n3、登录密码密码由6-20位字母、数字组成\n4、部门上下级部门间用“/”隔开,且从最上级部门开始,例如“上海分公司/市场部/市场一部”。如出现相同的部门,则默认导入组织架构中顺序靠前的部门";
} elseif($types == 'crm_activity'){
$content = "注意事项:\n1、表头标“*”的红色字体为必填项\n2、跟进时间推荐格式为2020-2-1\n3、若相关数据有多条时用“/”区分例如:杭州科技有限公司/卡卡罗特软件科技有限公司\n4、所属客户中的客户需要存在系统中且填写的所属客户名称与系统中的客户名称必须保持一致否则会导入失败\n5、创建人为系统员工请填写系统员工“姓名”若匹配不到系统员工则会导致导入失败\n6、如果系统中存在多个名称重复的情况会默认导入到最新的数据中";
}elseif($types == 'crm_pool'){
$content = "注意事项:\n1、表头标“*”的红色字体为必填项\n2、日期时间推荐格式为2020-02-02 13:13:13\n3、日期推荐格式为2020-02-02\n4、手机号支持6-15位数字包含国外手机号格式\n5、邮箱只支持邮箱格式\n6、多行文本字数限制为800字\n7、负责人不必填若填写负责人则数据将进入客户模块否则进入公海模块";
}else{
$content = "注意事项:\n1、表头标“*”的红色字体为必填项\n2、日期时间推荐格式为2020-02-02 13:13:13\n3、日期推荐格式为2020-02-02\n4、手机号支持6-15位数字包含国外手机号格式\n5、邮箱只支持邮箱格式\n6、多行文本字数限制为800字";
}
$objActSheet->setCellValue('A1', $content); $objActSheet->setCellValue('A1', $content);
//设置A1单元格内容为
$objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls'); $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
ob_end_clean(); ob_end_clean();
if ($save_path) { if ($save_path) {
@ -432,11 +461,13 @@ class Excel extends Common
foreach ($field_list as $rule) { foreach ($field_list as $rule) {
if ($rule['form_type'] == 'customer_address') { if ($rule['form_type'] == 'customer_address') {
$address_arr = explode(chr(10), $val['address']); $address_arr = explode(chr(10), $val['address']);
$rows[] = $address_arr[0] ?: ''; $rows[] = $address_arr[0] ?: '';
$rows[] = $address_arr[1] ?: ''; $rows[] = $address_arr[1] ?: '';
$rows[] = $address_arr[2] ?: ''; $rows[] = $address_arr[2] ?: '';
} else { } else {
if (is_numeric($val[$rule['field']]) && strlen($val[$rule['field']]) > 15) {
$val[$rule['field']] = "\t" . $val[$rule['field']] . "\t";
}
$rows[] = $fieldModel->getValueByFormtype($val[$rule['field']], $rule['form_type']); $rows[] = $fieldModel->getValueByFormtype($val[$rule['field']], $rule['form_type']);
} }
} }
@ -488,8 +519,11 @@ class Excel extends Common
$queue->dequeue(); $queue->dequeue();
return false; return false;
} }
if (!empty($param['pool_id'])) {
$user_id = $param['create_user_id'];
} else {
$user_id = $param['owner_user_id']; $user_id = $param['owner_user_id'];
}
// 采用伪队列 允许三人同时导入数据 // 采用伪队列 允许三人同时导入数据
$queue = new Queue(self::IMPORT_QUEUE, 50000000); $queue = new Queue(self::IMPORT_QUEUE, 50000000);
$import_queue_index = input('import_queue_index'); $import_queue_index = input('import_queue_index');
@ -556,15 +590,15 @@ class Excel extends Common
$save_path = UPLOAD_PATH . $save_name; $save_path = UPLOAD_PATH . $save_name;
// 队列-判断是否需要排队 // 队列-判断是否需要排队
// if (!$queue->canExec()) { if (!$queue->canExec()) {
// $this->error = [ $this->error = [
// 'temp_file' => $save_name, 'temp_file' => $save_name,
// 'page' => -2, 'page' => -2,
// 'import_queue_index' => $import_queue_index, 'import_queue_index' => $import_queue_index,
// 'info' => $queue->error 'info' => $queue->error
// ]; ];
// return true; return true;
// } }
// 加载类库 // 加载类库
vendor("phpexcel.PHPExcel"); vendor("phpexcel.PHPExcel");
@ -649,15 +683,43 @@ class Excel extends Common
break; break;
} }
// 字段 // 字段
# 下次升级
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$fieldParam['types'] = $types; $fieldParam['types'] = $types;
$fieldParam['action'] = 'excel'; $fieldParam['action'] = 'excel';
if (!empty($param['pool_id'])) {
$list = [];
$field_list = db('crm_customer_pool_field_setting')->where(['pool_id' => $param['pool_id'], 'is_hidden' => 0,
'field_name' => ['not in', ['deal_status', 'create_user_id']]])->field('field_name as field,form_type,name')->select();
foreach ($field_list as $k => &$v) {
if ($v['field'] == 'address') {
$v['field'] = 'customer_address';
$v['form_type'] = 'map_address';
$list[] = $v;
unset($field_list[$k]);
} elseif ($v['field'] == 'detail_address') {
unset($field_list[$k]);
}
}
$field_list = array_merge($field_list, $list);
} else {
$field_list = $fieldModel->field($fieldParam); $field_list = $fieldModel->field($fieldParam);
if(!empty($param['pool_id'])){ }
$pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select(); if ($types != 'admin_user' && empty($param['pool_id'])) {
$merge_list = $fieldModel->field($fieldParam); $field = [1 => [
$field_list=array_intersect($merge_list,$pool_list); 'field' => 'owner_user_id',
'types' => 'crm_leads',
'name' => '负责人',
'form_type' => 'user',
'default_value' => '',
'is_null' => 1,
'input_tips' => '',
'setting' => array(),
'is_hidden' => 0,
'writeStatus' => 1,
'value' => '']
];
$first_array = array_splice($field_list, 2, 0, $field);
} }
$field_list = array_map(function ($val) { $field_list = array_map(function ($val) {
if (method_exists($val, 'toArray')) { if (method_exists($val, 'toArray')) {
@ -667,40 +729,6 @@ class Excel extends Common
} }
}, $field_list); }, $field_list);
$field_key_name_list = array_column($field_list, 'name', 'field'); $field_key_name_list = array_column($field_list, 'name', 'field');
# 下次升级
// $fieldModel = new \app\admin\model\Field();
// $fieldParam['types'] = $types;
// $fieldParam['action'] = 'excel';
// if(!empty($param['pool_id'])){
// $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
// $merge_list = $fieldModel->field($fieldParam);
// $field_list=array_intersect($merge_list,$pool_list);
// }else{
// $field_list = $fieldModel->field($fieldParam);
// $field=[1=>[
// 'field'=>'owner_user_id',
// 'types'=>'crm_leads',
// 'name'=>'负责人',
// 'form_type'=>'user',
// 'default_value'=>'',
// 'is_unique' => 1,
// 'is_null' => 1,
// 'input_tips' =>'',
// 'setting' => Array(),
// 'is_hidden'=>0,
// 'writeStatus' => 1,
// 'value' => '']
// ];
// $first_array = array_splice($field_list, 0, 2);
// }
// $field_list = array_map(function ($val) {
// if (method_exists($val, 'toArray')) {
// return $val->toArray();
// } else {
// return $val;
// }
// }, $field_list);
// $field_key_name_list = array_column($field_list, 'name', 'field');
// 加载导入数据文件 // 加载导入数据文件
$objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls'); $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
$objRender->setReadDataOnly(true); $objRender->setReadDataOnly(true);
@ -717,12 +745,12 @@ class Excel extends Common
// 检测导入文件是否使用最新模板 // 检测导入文件是否使用最新模板
$header = $sheet->rangeToArray("A2:{$max_col}2")[0]; $header = $sheet->rangeToArray("A2:{$max_col}2")[0];
$temp = 0; $temp = 0;
for ($i = 0; $i < count($field_list); $i++) { for ($i = 0; $i < count($field_list); $i++) {
if ( if (
$header[$i] == $field_list[$i]['name'] $header[$i] == $field_list[$i]['name']
|| $header[$i] == '*' . $field_list[$i]['name'] || $header[$i] == '*' . $field_list[$i]['name']
) { ) {
$res[] = $header[$i];
$temp++; $temp++;
// 字段为地址时,占四列 // 字段为地址时,占四列
} elseif ($field_list[$i]['form_type'] == 'map_address') { } elseif ($field_list[$i]['form_type'] == 'map_address') {
@ -732,12 +760,11 @@ class Excel extends Common
&& $header[$i + 2] == $this->map_address[2] && $header[$i + 2] == $this->map_address[2]
&& $header[$i + 3] == $this->map_address[3] && $header[$i + 3] == $this->map_address[3]
) { ) {
$ress[] = $header[$i];
$temp++; $temp++;
} }
} }
} }
// 每次导入条数 // 每次导入条数
$page_size = 100; $page_size = 100;
@ -768,31 +795,28 @@ class Excel extends Common
// 数据重复时的处理方式 0跳过 1覆盖 // 数据重复时的处理方式 0跳过 1覆盖
$config = $param['config'] ?: 0; $config = $param['config'] ?: 0;
// 默认数据 // 默认数据
if(!empty($param['pool_id'])){ if (!empty($param['pool_id'])) {
//公海导入 //公海导入
$default_data = [ $default_data = [
'create_user_id' => $param['create_user_id'], 'create_user_id' => $param['create_user_id'],
'create_time' => time(), 'create_time' => time(),
'update_time' => time(), 'update_time' => time(),
'owner_user_id' => 0, 'owner_user_id' => 0,
'before_owner_user_id'=>$param['create_user_id'], 'into_pool_time' => time(),
'into_pool_time'=>time(),
'pool_id' => $param['pool_id'], 'pool_id' => $param['pool_id'],
]; ];
}else{ } else {
$default_data = [ $default_data = [
'create_user_id' => $param['create_user_id'], 'create_user_id' => $param['create_user_id'],
'owner_user_id' => $param['owner_user_id'],
'create_time' => time(), 'create_time' => time(),
'update_time' => time(), 'update_time' => time(),
]; ];
} }
if ($temp !== count($field_list)) { if ($temp !== count($field_list)) {
// $this->error = '请使用最新导入模板';
@unlink($save_path); @unlink($save_path);
$queue->dequeue(); $queue->dequeue();
foreach ($dataList as $val) { foreach ($dataList as $val) {
$error_data_func($val, '请使用最新导入模板1'); $error_data_func($val, '请使用最新导入模板');
} }
$objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5'); $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
$objWriter->save($error_path); $objWriter->save($error_path);
@ -871,7 +895,7 @@ class Excel extends Common
} }
$fk++; $fk++;
} }
if (!empty($not_null_field)) { if (!empty($not_null_field) && empty($param['pool_id'])) {
$error_data_func($val, implode(', ', $not_null_field) . '不能为空'); $error_data_func($val, implode(', ', $not_null_field) . '不能为空');
continue; continue;
} }
@ -887,15 +911,19 @@ class Excel extends Common
$old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id); $old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
} }
} }
$userId = '';
#下次升级 #下次升级
// if(empty($param['pool_id'])){ if ($param['pool_id']) {
// $user_id=db('admin_user')->where('realname',$val[2])->value('id'); $userId = db('admin_user')->where('realname', $val[2])->value('id');
// $data['owner_user_id']=$user_id?:0; $data['before_owner_user_id'] = 0;
// } } else {
$userId = db('admin_user')->where('realname', $val[2])->value('id');
$data['owner_user_id'] = $userId ?: 0;
}
$owner = db('crm_customer_pool')->where(['pool_id' => $param['pool_id']])->value('admin_user_ids'); $owner = db('crm_customer_pool')->where(['pool_id' => $param['pool_id']])->value('admin_user_ids');
$auth=db('admin_access')->where('user_id',$param['create_user_id'])->column('group_id'); $auth = db('admin_access')->where('user_id', $param['create_user_id'])->column('group_id');
// 数据重复时 // 数据重复时
if (!empty($old_data_id_list) && empty($param['pool_id'])) { if ($old_data_id_list) {
if ($config) { if ($config) {
$data = array_merge($data, $default_data); $data = array_merge($data, $default_data);
$data['create_user_id'] = $param['create_user_id']; $data['create_user_id'] = $param['create_user_id'];
@ -904,13 +932,23 @@ class Excel extends Common
try { try {
$up_success_count = 0; $up_success_count = 0;
foreach ($old_data_id_list as $id) { foreach ($old_data_id_list as $id) {
if ($types == 'crm_customer') { if ($types == 'crm_customer' && !empty($param['pool_id'])) {
if (!in_array($param['create_user_id'],trim(stringToArray($owner),',')) && !in_array(1, $auth) && $param['create_user_id']!=1) { if (!in_array($param['create_user_id'], trim(stringToArray($owner), ',')) && !in_array(1, $auth) && $param['create_user_id'] != 1) {
$temp_error ='当前导入人员对该公海数据,无导入权限'; $temp_error = '当前导入人员对该公海数据,无导入权限';
$error_data_func($val, $temp_error); $error_data_func($val, $temp_error);
break; break;
} else {
if (!$dataModel->updateDataById($data, $id)) {
$temp_error = $dataModel->getError();
if ($temp_error == '无权操作') {
$temp_error = '当前导入人员对该数据无写入权限';
}
$error_data_func($val, $temp_error);
$dataModel->rollback();
break;
} }
} }
} else {
if (!$dataModel->updateDataById($data, $id)) { if (!$dataModel->updateDataById($data, $id)) {
$temp_error = $dataModel->getError(); $temp_error = $dataModel->getError();
if ($temp_error == '无权操作') { if ($temp_error == '无权操作') {
@ -920,6 +958,7 @@ class Excel extends Common
$dataModel->rollback(); $dataModel->rollback();
break; break;
} }
}
$up_success_count++; $up_success_count++;
} }
// 全部更新完成 // 全部更新完成
@ -944,16 +983,23 @@ class Excel extends Common
$unique_field = array_unique($unique_field); $unique_field = array_unique($unique_field);
$error_data_func($val, implode(', ', $unique_field) . ' 根据查重规则,该条数据重复'); $error_data_func($val, implode(', ', $unique_field) . ' 根据查重规则,该条数据重复');
} }
}elseif(!empty($old_data_id_list) && !empty($param['pool_id'])){
$error_data_func($val, ' 重复数据不在当前公海,无权覆盖');
} else { } else {
if ($types == 'crm_customer') { if ($types == 'crm_customer' && !empty($param['pool_id'])) {
if (!in_array($param['create_user_id'],trim(stringToArray($owner),',')) && !in_array(1, $auth) && $param['create_user_id']!=1) { if (!in_array($param['create_user_id'], trim(stringToArray($owner), ',')) && !in_array(1, $auth) && $param['create_user_id'] != 1) {
$temp_error = '当前导入人员对该公海数据,无导入权限'; $temp_error = '当前导入人员对该公海数据,无导入权限';
$error_data_func($val, $temp_error); $error_data_func($val, $temp_error);
} else {
$data = array_merge($data, $default_data);
$data['excel'] = 1;
if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError());
} }
}else{ }
} else {
$data = array_merge($data, $default_data); $data = array_merge($data, $default_data);
if ($types != 'admin_user') {
$data['excel'] = 1;
}
if (!$resData = $dataModel->createData($data)) { if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError()); $error_data_func($val, $dataModel->getError());
} }
@ -1001,7 +1047,7 @@ class Excel extends Common
'error' => $error 'error' => $error
]); ]);
// 执行完成 // 执行完成
$redis= new Redis(); $redis = new Redis();
if ($done >= $total) { if ($done >= $total) {
// 出队 // 出队
$queue->dequeue(); $queue->dequeue();
@ -2154,8 +2200,8 @@ class Excel extends Common
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度 $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11); $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000'); $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000');
$objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF'); $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
@ -2168,7 +2214,7 @@ class Excel extends Common
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗 $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中 $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
if ($v[3] > 0)//大于0表示需要设置宽度 if ($v[3] > 0)//大于0表示需要设置宽度
{ {
$objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度 $objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度
@ -2176,17 +2222,18 @@ class Excel extends Common
} }
$objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFont()->getColor()->setARGB('FF000000'); $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFont()->getColor()->setARGB('FF000000');
$objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF'); $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
$callCount = count($callback) + 2; //边框
$style_array = array( // $callCount = count($callback) + 2;
'borders' => array( // $style_array = array(
'allborders' => array( // 'borders' => array(
'style' => \PHPExcel_Style_Border::BORDER_THIN // 'allborders' => array(
) // 'style' => \PHPExcel_Style_Border::BORDER_THIN
)); // )
$objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array); // ));
// $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array);
foreach ($callback as $k => $item) { foreach ($callback as $k => $item) {
foreach ($field_list as $key => $rule) { foreach ($field_list as $key => $rule) {
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]); $objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]);
} }
@ -2249,7 +2296,7 @@ class Excel extends Common
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11); $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中 $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
if ($v[3] > 0)//大于0表示需要设置宽度 if ($v[3] > 0)//大于0表示需要设置宽度
@ -2394,9 +2441,11 @@ class Excel extends Common
$excelData = Cache::pull('excel'); $excelData = Cache::pull('excel');
$base = $excelData['base']; $base = $excelData['base'];
if ($param == 0) { if ($param == 0) {
if($base=='batchTaskImportData'){ if ($base == 'batchTaskImportData') {
$this->batchTaskImportData('', $excelData); $this->batchTaskImportData('', $excelData);
}else{ } elseif ($base == 'ActivityImport') {
$this->ActivityImport('', $excelData);
} else {
$this->batchImportData('', $excelData); $this->batchImportData('', $excelData);
} }
$data = 0; $data = 0;
@ -2454,7 +2503,7 @@ class Excel extends Common
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) { } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false; $data['firstPage'] = false;
$data['lastPage'] = false; $data['lastPage'] = false;
} else if ($param['page'] == 1) { } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = true; $data['firstPage'] = true;
$data['lastPage'] = false; $data['lastPage'] = false;
} }
@ -2471,7 +2520,7 @@ class Excel extends Common
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/9 0009 16:31 * @since 2021/4/9 0009 16:31
*/ */
public function ActivityImport($file,$field_list,$param,$controller = null) public function ActivityImport($file, $field_list, $param, $controller = null)
{ {
// 导入模块 // 导入模块
$types = $param['types']; $types = $param['types'];
@ -2480,7 +2529,7 @@ class Excel extends Common
$queue->dequeue(); $queue->dequeue();
return false; return false;
} }
$user_id = $param['user_id'];
// 采用伪队列 允许三人同时导入数据 // 采用伪队列 允许三人同时导入数据
$queue = new Queue(self::IMPORT_QUEUE, 30000); $queue = new Queue(self::IMPORT_QUEUE, 30000);
$import_queue_index = input('import_queue_index'); $import_queue_index = input('import_queue_index');
@ -2522,6 +2571,7 @@ class Excel extends Common
'done' => $temp['done'], 'done' => $temp['done'],
'cover' => $temp['cover'], 'cover' => $temp['cover'],
'error' => $temp['error'], 'error' => $temp['error'],
'user_id' => $user_id,
'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : '' 'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
]); ]);
$queue->dequeue(); $queue->dequeue();
@ -2642,39 +2692,41 @@ class Excel extends Common
} }
// 读取数据 // 读取数据
$dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}"); $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
// 默认数据 switch ($types) {
$default_data = [
];
switch ($types){
case 'crm_business': case 'crm_business':
$dataModel = new \app\crm\model\Business(); $dataModel = new \app\crm\model\Business();
$db = db('crm_business'); $db = db('crm_business');
$db_id = 'business_id'; $db_id = 'business_id';
$activity_type=5; $activity_type = 5;
$activity_name='所属商机';
break; break;
case 'crm_contract': case 'crm_contract':
$db = db('crm_contract'); $db = db('crm_contract');
$db_id = 'contract_id'; $db_id = 'contract_id';
$activity_type=6; $activity_type = 6;
$activity_name='所属合同';
break; break;
case 'crm_leads' : case 'crm_leads' :
$dataModel = new \app\crm\model\Leads(); $dataModel = new \app\crm\model\Leads();
$db = db('crm_leads'); $db = db('crm_leads');
$db_id = 'leads_id'; $db_id = 'leads_id';
$activity_type=1; $activity_type = 1;
$activity_name='所属线索';
break; break;
case 'crm_customer' : case 'crm_customer' :
$dataModel = new \app\crm\model\Customer(); $dataModel = new \app\crm\model\Customer();
$db = db('crm_customer'); $db = db('crm_customer');
$db_id = 'customer_id'; $db_id = 'customer_id';
$fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']]; $fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
$activity_type=2; $activity_type = 2;
$activity_name='所属客户';
break; break;
case 'crm_contacts' : case 'crm_contacts' :
$dataModel = new \app\crm\model\Contacts(); $dataModel = new \app\crm\model\Contacts();
$db = db('crm_contacts'); $db = db('crm_contacts');
$db_id = 'contacts_id'; $db_id = 'contacts_id';
$activity_type=3; $activity_type = 3;
$activity_name='所属联系人';
break; break;
} }
@ -2704,45 +2756,47 @@ class Excel extends Common
continue; continue;
} }
$activityLogic = new \app\crm\logic\ActivityLogic(); $activityLogic = new \app\crm\logic\ActivityLogic();
$userData=db('admin_user')->where(['realname'=>$val[1],'status'=>['neq',0]])->value('id'); $userData = db('admin_user')->where(['realname' => $val[1], 'status' => ['neq', 0]])->value('id');
$customerData=$db->where('name',$val[2])->value($db_id); $customerData = $db->where('name', $val[2])->value($db_id);
$classData = db('crm_activity')->where(['content' => $val[0], 'activity_type' => $param['activity_type'],'activity_type_id'=>$customerData])->order('activity_id', 'asc')->select(); $classData = db('crm_activity')->where(['content' => $val[0], 'activity_type' => $param['activity_type'], 'activity_type_id' => $customerData])->order('activity_id', 'asc')->select();
if (empty($customerData)) { if (empty($customerData)) {
$error_data_func($val, '所属客户'.$val[2].'不存在'); $error_data_func($val, $activity_name . $val[2] . '不存在');
continue; continue;
} }
if (empty($userData)) { if (empty($userData)) {
$error_data_func($val, '管理员'.$val[1].'不存在'); $error_data_func($val, '管理员' . $val[1] . '不存在');
continue; continue;
} }
if($types=='crm_customer' && (!empty($val[5]) || !empty($val[6]))){ if ($types == 'crm_customer' && (!empty($val[5]) || !empty($val[6]))) {
$contactsData=db('crm_contacts')->where('name',$val[5])->value($db_id); if(strstr($val[5], '/')||strstr($val[6], '/')){
$businessData=$db->where('crm_business',$val[6])->value($db_id); $val[5]= explode ( '/' , $val[5]);
if (empty($contactsData)&&eempty($businessData)) { $val[6]= explode ( '/' , $val[6]);
$error_data_func($val, '联系人'.$val[5].'不存在或商机'.$val[6].'不存在'); }
continue; $contactsData = db('crm_contacts')->where('name', ['in',arrayToString($val[5])])->column('contacts_id');
} $businessData = db('crm_business')->where('name', ['in',arrayToString($val[6])] )->column('business_id');
} $data['business_ids']=arrayToString($businessData);
if ($classData[0]['activity_id'] != '') { $data['contacts_ids']=arrayToString($contactsData);
}
$data['activity_id'] = $classData[0]['activity_id']; // if ($classData && $classData[0]['activity_id'] != '') {
$data = array_merge($data, $default_data); // $data['activity_id'] = $classData[0]['activity_id'];
$data['create_user_id'] = $userData; // $data['activity_type_id'] = $customerData;
$data['activity_type_id'] = $customerData; // $data['activity_type'] = $activity_type;
$data['activity_type'] = $activity_type; // $data['create_user_id'] = $user_id;
if (!$resData = $activityLogic->update($data)) { // if (!$resData = $activityLogic->update($data)) {
$error_data_func($val, $dataModel->getError()); // $error_data_func($val, $dataModel->getError());
} // }
}else{ // } else { }
$data = array_merge($data, $default_data); $data['user_id'] = $userData;
$data['user_id']=$userData;
$data['activity_type_id'] = $customerData; $data['activity_type_id'] = $customerData;
$data['activity_type'] = $activity_type; $data['activity_type'] = $activity_type;
$data['excel'] = 1;
$data['create_user_id'] = $user_id;
unset($data['create_user_id']); unset($data['create_user_id']);
if (!$resData = $activityLogic->save($data)) { if (!$resData = $activityLogic->save($data)) {
$error_data_func($val, $dataModel->getError()); $error_data_func($val, $dataModel->getError());
} }
}
} }
// 完成数(已导入数) // 完成数(已导入数)
$done = ($page - 1) * $page_size + count($dataList); $done = ($page - 1) * $page_size + count($dataList);
@ -2800,6 +2854,7 @@ class Excel extends Common
'done' => $done, 'done' => $done,
'cover' => $cover, 'cover' => $cover,
'error' => $error, 'error' => $error,
'user_id' => $user_id,
'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : '' 'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
]); ]);
Cache::set('item', 1, config('import_cache_time')); Cache::set('item', 1, config('import_cache_time'));
@ -2826,101 +2881,4 @@ class Excel extends Common
return false; return false;
} }
} }
/**
* 自定义excel导入样式
* @param $field_list
* @param $param
* @param $types
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/10 0010 09:27
*/
public function importDown($field_list,$types,$save_path='')
{
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); //创建一个新的工作表
//实例化主文件
$objPHPExcel = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
if ($save_path) {
$worksheet->setCellValue('A2', '错误原因(导入时需删除本列)');
$worksheet->getColumnDimension('A')->setWidth(40); //设置单元格宽度
$k = 1;
} else {
$k = 0;
}
$worksheet->getColumnDimension('A1')->setWidth(70); //设置A列宽度为30
foreach ($field_list as $v) {
for ($j = 3; $j <= 70; $j++) {
$worksheet->getStyle($this->stringFromColumnIndex($k).$j)->getNumberFormat()
->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
}
$worksheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(40); //自动设置B列宽度
//检查该字段若必填,加上"*"
$v['name'] = sign_required($v['is_null'], $v['name']);
$worksheet->setCellValue($this->stringFromColumnIndex($k) . '2', $v['name']);
$k++;
}
//加上"*"颜色变红
$worksheet -> getStyle('A2:C2') -> getFont()
-> getColor() -> setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
$max_row = $this->stringFromColumnIndex($k-1);//列
$mark_row = $this->stringFromColumnIndex($k);
//样式设置 - 字体
$worksheet->getStyle('A1:' . $max_row . '1')->getFont()
->setBold(true)->setName('宋体')
->setSize(11); //设置单元格A7:G10的字体样式
$worksheet->getStyle('A2:' . $max_row . '2')->getFont()
->setBold(true)->setName('宋体')
->setSize(11); //设置单元格A7:G10的字体样式; //设置单元格A1的字体颜色
//样式设置 - 行高
$worksheet->getRowDimension('1')->setRowHeight(200); //设置第10行高度为100
//样式设置 - 水平、垂直居中
$styleArray = [
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT,
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT
],
];
$worksheet->getStyle('A1:'.$max_row.'1')->applyFromArray($styleArray);
//样式设置 - 边框
$styleArray = [
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
]
],
];
$worksheet->getStyle('A1:'.$max_row.'1')->applyFromArray($styleArray);
//样式设置 - 合并和拆分
$worksheet->mergeCells('A1:'.$max_row.'1'); //合并单元格
//内容设置
$worksheet->setCellValue('A1', "
注意事项:\n
1、表头标“*”的红色字体为必填项\n
2、跟进时间推荐格式为2020-2-1\n
3、若相关数据有多条时用“/”区分例如:杭州科技有限公司/卡卡罗特软件科技有限公司\n
4、所属客户中的客户需要存在系统中且填写的所属客户名称与系统中的客户名称必须保持一致否则会导入失败\n
5、创建人为系统员工请填写系统员工“姓名”若匹配不到系统员工则会导致导入失败\n
6、如果系统中存在多个名称重复的情况会默认导入到最新的数据中"
); //设置A1单元格内容为
$worksheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
//下载工作表
ob_end_clean();
if ($save_path) {
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer -> save($save_path);
} else {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="1.xls"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
}
}
} }

File diff suppressed because it is too large Load Diff

@ -100,12 +100,14 @@ class Group extends Common
//编辑角色 //编辑角色
public function updateDataById($param,$group_id) public function updateDataById($param,$group_id)
{ {
$userId = $param['user_id'];
$dataInfo = $this->get($group_id); $dataInfo = $this->get($group_id);
if(!$dataInfo){ if(!$dataInfo){
$this->error = '该角色不存在或已删除'; $this->error = '该角色不存在或已删除';
return false; return false;
} }
unset($param['types']); unset($param['types']);
unset($param['user_id']);
# 处理编辑时前端可能不传父id的问题admin_rule表level为1的主键 # 处理编辑时前端可能不传父id的问题admin_rule表level为1的主键
if (!empty($param['rules'])) { if (!empty($param['rules'])) {
@ -125,9 +127,7 @@ class Group extends Common
} }
$flag = $this->where('id = '.$group_id)->update($param); $flag = $this->where('id = '.$group_id)->update($param);
if ($flag) { if ($flag) {
$user=new ApiCommon(); SystemActionLog($userId, 'admin_group','role', $group_id, 'update', $dataInfo['title'], '', '','编辑了:'.$dataInfo['title']);
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_group','role', $group_id, 'update', $dataInfo['title'], '', '','编辑了:'.$dataInfo['title']);
return true; return true;
} else { } else {
$this->error = '操作失败'; $this->error = '操作失败';
@ -136,7 +136,7 @@ class Group extends Common
} }
//删除角色 //删除角色
public function delGroupById($group_id = '') public function delGroupById($group_id = '',$userId)
{ {
$dataInfo = $this->get($group_id); $dataInfo = $this->get($group_id);
if(!$dataInfo){ if(!$dataInfo){
@ -150,9 +150,7 @@ class Group extends Common
$flag = $this->where('id = '.$group_id)->delete(); $flag = $this->where('id = '.$group_id)->delete();
if ($flag) { if ($flag) {
# 系统操作记录 # 系统操作记录
$user=new ApiCommon(); SystemActionLog($userId, 'admin_group','role', $group_id, 'update', $dataInfo['title'], '', '','删除了角色:'.$dataInfo['title']);
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_group','role', $group_id, 'update', $dataInfo['title'], '', '','删除了角色:'.$dataInfo['title']);
return true; return true;
} else { } else {
$this->error = '删除失败'; $this->error = '删除失败';

@ -165,7 +165,10 @@ class Message extends Common
* 移除团队成员 * 移除团队成员
*/ */
const TEAM_END = 31; const TEAM_END = 31;
/**
* 移除队成员
*/
const TEAM_LEADS = 32;
/** /**
* 消息类型 * 消息类型
* *
@ -273,6 +276,9 @@ class Message extends Common
31 => [ 31 => [
'template' => '将{from_user} 移除了您 {title} 的团队。', 'template' => '将{from_user} 移除了您 {title} 的团队。',
], ],
32 => [
'template' => '{from_user} 将您添加为线索 {title} 的成员。',
],
]; ];
/** /**

@ -150,7 +150,6 @@ class Scene extends Common
{ {
$where = []; $where = [];
$where['scene_id'] = $id; $where['scene_id'] = $id;
// $where['user_id'] = [['=',$user_id],['=',0],'or'];
$data = db('admin_scene')->where($where)->find(); $data = db('admin_scene')->where($where)->find();
if (!$types) { if (!$types) {
$types = $data['types'] ? : ''; $types = $data['types'] ? : '';
@ -407,7 +406,7 @@ class Scene extends Common
$where['types'] = $types; $where['types'] = $types;
$where['user_id'] = $user_id; $where['user_id'] = $user_id;
$scene_id = db('admin_scene_default')->where($where)->value('scene_id'); $scene_id = db('admin_scene_default')->where($where)->value('scene_id');
if (!$scene_id && in_array($types,['crm_leads','crm_customer','crm_business','crm_contacts','crm_contract','crm_receivables','crm_visit'])) { if (!$scene_id && in_array($types,['crm_leads','crm_customer','crm_business','crm_contacts','crm_contract','crm_receivables','crm_visit','crm_invoice'])) {
$resData['bydata'] = 'all'; $resData['bydata'] = 'all';
} else { } else {
$resData = db('admin_scene')->where(['scene_id' => $scene_id])->find(); $resData = db('admin_scene')->where(['scene_id' => $scene_id])->find();
@ -429,10 +428,6 @@ class Scene extends Common
*/ */
public function getByData($types, $bydata, $user_id) public function getByData($types, $bydata, $user_id)
{ {
// print_r($types . '--');
// print_r($bydata . '--');
// print_r($user_id);
// exit;
$map = []; $map = [];
$auth_user_ids = []; $auth_user_ids = [];
$part_user_ids = []; $part_user_ids = [];
@ -448,7 +443,7 @@ class Scene extends Common
break; break;
case 'sub' : case 'sub' :
# 下属负责的 # 下属负责的
$auth_user_ids = getSubUserId(false) ? : ['-1']; $auth_user_ids = getSubUserId(false, 0, $user_id) ? : ['-1'];
break; break;
case 'all' : case 'all' :
# 全部 # 全部
@ -456,7 +451,7 @@ class Scene extends Common
break; break;
case 'is_transform' : case 'is_transform' :
# 已转化线索 # 已转化线索
$map['is_transform'] = ['condition' => 'eq', 'value' => 1, 'form_type' => 'text', 'name' => '']; $map['is_transform'] = ['condition' => 'is', 'value' => [1], 'form_type' => 'text', 'name' => ''];
break; break;
case 'pool' : case 'pool' :
# 今日进入公海的客户 # 今日进入公海的客户
@ -465,16 +460,28 @@ class Scene extends Common
break; break;
case 'win_business' : case 'win_business' :
# 赢单的商机 # 赢单的商机
$map['is_end'] = ['condition' => 'eq', 'value' => 1]; $map['is_end'] = ['condition' => 'is', 'value' => [1], 'form_type' => 'text'];
break; break;
case 'fail_business' : case 'fail_business' :
# 输单的商机 # 输单的商机
$map['is_end'] = ['condition' => 'eq', 'value' => 2]; $map['is_end'] = ['condition' => 'is', 'value' => [2], 'form_type' => 'text'];
break; break;
case 'star' : case 'star' :
$where = $this->getStarParam($types, $user_id); $where = $this->getStarParam($types, $user_id);
if (!empty($where)) $map = $where; if (!empty($where)) $map = $where;
break; break;
case 'go_business' :
# 进行中的商机
$map['is_end'] = ['condition' => 'is', 'value' => ['0'], 'form_type' => 'text'];
break;
case 'put_on_shelves' :
# 上架的产品
$map['status'] = ['condition' => 'is', 'value' => ['上架'], 'form_type' => 'select', 'name' => '是否上架', 'type' => 'status'];
break;
case 'pull_off_shelves' :
# 下架的产品
$map['status'] = ['condition' => 'is', 'value' => ['下架'], 'form_type' => 'select', 'name' => '是否上架', 'type' => 'status'];
break;
default : default :
# 全部 # 全部
$auth_user_ids = ''; $auth_user_ids = '';
@ -483,12 +490,12 @@ class Scene extends Common
$auth_user_ids = $auth_user_ids ? : []; $auth_user_ids = $auth_user_ids ? : [];
if ($auth_user_ids) { if ($auth_user_ids) {
$map['owner_user_id'] = ['condition' => 'in','value' => $auth_user_ids,'form_type' => 'text','name' => '']; $map['owner_user_id'] = ['condition' => 'in', 'value' => $auth_user_ids, 'form_type' => 'user', 'name' => ''];
} }
if ($part_user_ids) { if ($part_user_ids) {
$map['ro_user_id'] = $part_user_ids ? : ''; $map['ro_user_id'] = $part_user_ids;
$map['rw_user_id'] = $part_user_ids ? : ''; $map['rw_user_id'] = $part_user_ids;
} }
return $map; return $map;
@ -505,17 +512,11 @@ class Scene extends Common
*/ */
public function getStarParam($types, $user_id) public function getStarParam($types, $user_id)
{ {
$where = []; $primaryKey = getPrimaryKeyName('crm_' . $types);
$result = [];
$data = Db::name('crm_star')->field(['target_id'])->where(['user_id' => $user_id, 'type' => 'crm_' . $types])->select();
foreach ($data AS $key => $value) $result[] = $value['target_id']; $targetIds = Db::name('crm_star')->where(['user_id' => $user_id, 'type' => 'crm_' . $types])->column('target_id');
if ($types == 'leads') $where['leads_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0; $where[$primaryKey] = ['condition' => 'in', 'value' => !empty($targetIds) ? $targetIds : [-1], 'form_type' => 'user'];
if ($types == 'customer') $where['customer_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
if ($types == 'contacts') $where['contacts_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
if ($types == 'business') $where['business_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
return $where; return $where;
} }

@ -64,7 +64,7 @@ class Structure extends Common
return $det; return $det;
} }
public function delStrById($id) public function delStrById($id,$userId)
{ {
if (!$id) { if (!$id) {
$this->error = '删除失败'; $this->error = '删除失败';
@ -90,11 +90,9 @@ class Structure extends Common
$this->error = '删除失败'; $this->error = '删除失败';
return false; return false;
} else { } else {
$apiCommon = new ApiCommon();
$userInfo = $apiCommon->userInfo;
$content='删除了部门:'.$dataInfo['name']; $content='删除了部门:'.$dataInfo['name'];
# 添加记录 # 添加记录
SystemActionLog($userInfo['id'], 'admin_structure','structures', $id,'delete', $dataInfo['name'], '', '', $content); SystemActionLog($userId, 'admin_structure','structures', $id,'delete', $dataInfo['name'], '', '', $content);
return true; return true;
} }
} }

@ -27,7 +27,7 @@ class User extends Common
protected $insert = [ protected $insert = [
'status' => 2, 'status' => 2,
]; ];
protected $statusArr = ['禁用','启用','未激活']; protected $statusArr = ['禁用', '启用', '未激活'];
protected $dateFormat = 'Y-m-d'; protected $dateFormat = 'Y-m-d';
protected $type = [ protected $type = [
@ -48,7 +48,7 @@ class User extends Common
'name' => '手机号(登录名)', 'name' => '手机号(登录名)',
'form_type' => 'mobile', 'form_type' => 'mobile',
'is_null' => 1, 'is_null' => 1,
// 'is_unique' => 1 //guogaobo 导入此字段会进行验重查询调用修改用户方法 'is_unique' => 1
], ],
[ [
'field' => 'password', 'field' => 'password',
@ -92,9 +92,9 @@ class User extends Common
return $this->belongsToMany('group', 'admin_access', 'group_id', 'user_id'); return $this->belongsToMany('group', 'admin_access', 'group_id', 'user_id');
} }
public function structureList($structure_id,$str) public function structureList($structure_id, $str)
{ {
$str_ids = structureList($structure_id,$str); $str_ids = structureList($structure_id, $str);
return $str_ids; return $str_ids;
} }
@ -108,13 +108,13 @@ class User extends Common
*/ */
public function getDataList($request) public function getDataList($request)
{ {
$structure_status=$request['isNeedChild']; $structure_status = $request['isNeedChild'];
unset($request['isNeedChild']); unset($request['isNeedChild']);
$request = $this->fmtRequest( $request ); $request = $this->fmtRequest($request);
$fieldarray = ['search','group_id','structure_id','status','type','page','limit','pageType']; $fieldarray = ['search', 'group_id', 'structure_id', 'status', 'type', 'page', 'limit', 'pageType'];
$map = $request['map'] ? : []; $map = $request['map'] ?: [];
if (isset($map['search']) && $map['search']) { if (isset($map['search']) && $map['search']) {
$map['user.username|user.realname'] = ['like', '%'.$map['search'].'%']; $map['user.username|user.realname'] = ['like', '%' . $map['search'] . '%'];
} }
unset($map['search']); unset($map['search']);
//角色员工 //角色员工
@ -123,26 +123,26 @@ class User extends Common
if ($map['group_id'] == 1 && !$group_user_ids) { if ($map['group_id'] == 1 && !$group_user_ids) {
$group_user_ids = ['1']; $group_user_ids = ['1'];
} }
$map['user.id'] = array('in',$group_user_ids); $map['user.id'] = array('in', $group_user_ids);
} }
$exp = new \think\db\Expression('field(user.status,1,2,0)'); $exp = new \think\db\Expression('field(user.status,1,2,0)');
// 默认除去超级管理员 // 默认除去超级管理员
// $map['user.id'] = array('neq', 1); // $map['user.id'] = array('neq', 1);
if($map['structure_id']){ if ($map['structure_id']) {
//获取部门下员工列表 //获取部门下员工列表
if($structure_status==1){ if ($structure_status == 1) {
$str_ids = structureList($map['structure_id'],''); $str_ids = structureList($map['structure_id'], '');
$new_str_ids = rtrim($str_ids,','); $new_str_ids = rtrim($str_ids, ',');
$map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id']; $map['user.structure_id'] = ['in', $new_str_ids]; //$map['structure_id'];
}else{ } else {
$map['user.structure_id']=['in',$map['structure_id']]; $map['user.structure_id'] = ['in', $map['structure_id']];
} }
} }
$structureData=db('admin_structure')->where('id',$map['structure_id'])->value('owner_user_id'); $structureData = db('admin_structure')->where('id', $map['structure_id'])->value('owner_user_id');
unset($map['structure_id']); unset($map['structure_id']);
if ($map['status'] || $map['group_id']) { if ($map['status'] || $map['group_id']) {
if ($map['status'] != 3) { if ($map['status'] != 3) {
$map['user.status'] = ($map['status'] !== 'all') ? ($map['status'] ? : ['gt',0]) : ['egt',0]; $map['user.status'] = ($map['status'] !== 'all') ? ($map['status'] ?: ['gt', 0]) : ['egt', 0];
} else { } else {
$map['user.create_time'] = ['gt', time() - 86400 * 7]; $map['user.create_time'] = ['gt', time() - 86400 * 7];
} }
@ -151,9 +151,9 @@ class User extends Common
} }
unset($map['status']); unset($map['status']);
$map['user.type'] = 1; $map['user.type'] = 1;
if(isset($map['type'])) $map['user.type'] == ($map['type'] == '0') ? 0 : 1; if (isset($map['type'])) $map['user.type'] == ($map['type'] == '0') ? 0 : 1;
//过滤字段 //过滤字段
foreach($fieldarray as $value){ foreach ($fieldarray as $value) {
unset($map[$value]); unset($map[$value]);
} }
//获取列表 //获取列表
@ -167,15 +167,15 @@ class User extends Common
->alias('user') ->alias('user')
->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT') ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
// ->join('HrmUserDet hud','hud.user_id = user.id','LEFT') // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
->limit(($request['page']-1)*$request['limit'], $request['limit']) ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
->where($map) ->where($map)
->field('user.id,user.username,user.img,user.thumb_img,user.realname,user.num,user.email,user.mobile,user.sex,user.structure_id,user.post,user.status,user.parent_id,user.type,user.create_time,structure.name as s_name') ->field('user.id,user.username,user.img,user.thumb_img,user.realname,user.num,user.email,user.mobile,user.sex,user.structure_id,user.post,user.status,user.parent_id,user.type,user.create_time,structure.name as s_name')
->order($exp) ->order($exp)
->order('user.id asc') ->order('user.id asc')
->select(); ->select();
foreach ($list as $k=>$v) { foreach ($list as $k => $v) {
//直属上级 //直属上级
$list[$k]['status_name'] = $v['status']=='1'?'启用':'禁用'; $list[$k]['status_name'] = $v['status'] == '1' ? '启用' : '禁用';
$parentInfo = []; $parentInfo = [];
$parentInfo = $this->getUserById($v['parent_id']); $parentInfo = $this->getUserById($v['parent_id']);
$list[$k]['parent_name'] = $v['parent_id'] ? $parentInfo['realname'] : ''; $list[$k]['parent_name'] = $v['parent_id'] ? $parentInfo['realname'] : '';
@ -184,28 +184,28 @@ class User extends Common
$groupsArr = $this->get($v['id'])->groups; $groupsArr = $this->get($v['id'])->groups;
$groups = []; $groups = [];
$groupids = []; $groupids = [];
foreach ($groupsArr as $key=>$val) { foreach ($groupsArr as $key => $val) {
$groups[] = $val['title']; $groups[] = $val['title'];
$groupids[] = $val['id']; $groupids[] = $val['id'];
} }
$list[$k]['groups'] = $groups ? implode(',',$groups) : ''; $list[$k]['groups'] = $groups ? implode(',', $groups) : '';
$list[$k]['groupids'] = $groupids ? implode(',',$groupids) : ''; $list[$k]['groupids'] = $groupids ? implode(',', $groupids) : '';
$list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : ''; $list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : '';
$list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : ''; $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
$list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : ''; $list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
$list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : ''; $list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : '';
$list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : ''; $list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : '';
if($v['id']==1){ if ($v['id'] == 1) {
$list[$k]['userIdentity']=0; $list[$k]['userIdentity'] = 0;
}elseif($v['id']==$structureData){ } elseif ($v['id'] == $structureData) {
$list[$k]['userIdentity']=1; $list[$k]['userIdentity'] = 1;
}else{ } else {
$list[$k]['userIdentity']=2; $list[$k]['userIdentity'] = 2;
} }
} }
//二位数组排序 //二位数组排序
$last_names = array_column($list,'userIdentity'); $last_names = array_column($list, 'userIdentity');
array_multisort($last_names,SORT_ASC,$list); array_multisort($last_names, SORT_ASC, $list);
$data = []; $data = [];
$data['list'] = $list; $data['list'] = $list;
$data['dataCount'] = $dataCount; $data['dataCount'] = $dataCount;
@ -221,9 +221,9 @@ class User extends Common
if (!$idArr) { if (!$idArr) {
return []; return [];
} }
$list = $this->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select(); $list = $this->field('id,username,realname,thumb_img')->where(['id' => ['in', $idArr]])->select();
foreach($list as $key=>$value){ foreach ($list as $key => $value) {
$list[$key]['thumb_img'] = $value['thumb_img']?getFullPath($value['thumb_img']):''; $list[$key]['thumb_img'] = $value['thumb_img'] ? getFullPath($value['thumb_img']) : '';
} }
return $list; return $list;
} }
@ -243,14 +243,14 @@ class User extends Common
unset($data['password']); unset($data['password']);
unset($data['authkey']); unset($data['authkey']);
if($data['structure_id']) { if ($data['structure_id']) {
$structureDet = Db::name('AdminStructure')->field('id,name')->where('id = '.$data['structure_id'].'')->find(); $structureDet = Db::name('AdminStructure')->field('id,name')->where('id = ' . $data['structure_id'] . '')->find();
$data['structure_name'] = $structureDet['name']; $data['structure_name'] = $structureDet['name'];
} else { } else {
$data['structure_name'] = '暂无'; $data['structure_name'] = '暂无';
} }
if($data['parent_id']) { if ($data['parent_id']) {
$parentDet = Db::name('AdminUser')->field('id,realname')->where('id = '.$data['parent_id'].'')->find(); $parentDet = Db::name('AdminUser')->field('id,realname')->where('id = ' . $data['parent_id'] . '')->find();
$data['parent_name'] = $parentDet['realname']; $data['parent_name'] = $parentDet['realname'];
} else { } else {
$data['parent_name'] = '暂无'; $data['parent_name'] = '暂无';
@ -275,34 +275,36 @@ class User extends Common
} }
$param = $temp; $param = $temp;
$param['structure_id'] = 0; $param['structure_id'] = 0;
if(db('admin_user')->where('username',$param['username'])->find()){ if (db('admin_user')->where('username', $param['username'])->find()) {
$this->error = '手机号已存在'; $this->error = '手机号已存在';
return false; return false;
} }
if(db('admin_user')->where('realname',$param['realname'])->find()){
$this->error = '姓名已存在'; $nameData = db('admin_user')->where('realname', 'like', '%' . $param['realname'] . '%')->column('realname');
return false; if (in_array($param['realname'], $nameData)) {
for ($j = 1; $j < 100; $j++) {
$name = $param['realname'] . '-' . $j;
if (in_array($name, $nameData)) {
continue;
} else {
$name = $param['realname'] . '-' . $j;
break;
}
} }
$param['realname'] = $name;
}
// if(db('admin_user')->where('realname',$param['realname'])->find()){
// $this->error = '姓名已存在';
// return false;
// }
} else { } else {
if (empty($param['group_id']) || !is_array($param['group_id'])) { if (empty($param['group_id']) || !is_array($param['group_id'])) {
$this->error = '请至少勾选一个用户组'; $this->error = '请至少勾选一个用户组';
return false; return false;
} }
} }
$nameData=db('admin_user')->where('realname','like','%'.$param['realname'].'%')->column('realname'); $userId=$param['userId'];
if(in_array($param['realname'],$nameData)){ unset($param['userId']);
for($j=1;$j<100;$j++){
$name=$param['realname'].$j;
if(in_array($name,$nameData)){
}else{
$name= $param['realname'].$j;
break ;
}
}
$param['realname']= $name;
}else{
$param['realname']= $param['realname'];
}
// 验证 // 验证
$validate = validate($this->name); $validate = validate($this->name);
if (!$validate->check($param)) { if (!$validate->check($param)) {
@ -312,7 +314,7 @@ class User extends Common
$syncModel = new \app\admin\model\Sync(); $syncModel = new \app\admin\model\Sync();
$this->startTrans(); $this->startTrans();
try { try {
$salt = substr(md5(time()),0,4); $salt = substr(md5(time()), 0, 4);
$param['salt'] = $salt; $param['salt'] = $salt;
if (!$param['password']) { if (!$param['password']) {
$password = $param['username']; $password = $param['username'];
@ -322,15 +324,16 @@ class User extends Common
$param['password'] = user_md5($password, $salt, $param['username']); $param['password'] = user_md5($password, $salt, $param['username']);
$param['type'] = 1; $param['type'] = 1;
$param['mobile'] = $param['username']; $param['mobile'] = $param['username'];
$this->data($param)->allowField(true)->isUpdate(false)->save(); $this->data($param)->allowField(true)->isUpdate(false)->save();
$user_id = (int) $this->getLastInsId(); $user_id = (int)$this->getLastInsId();
//员工档案 //员工档案
$data['user_id'] = $param['user_id']; $data['user_id'] = $param['user_id'];
unset($param['user_id']); unset($param['user_id']);
$data['user_id'] = $user_id; $data['user_id'] = $user_id;
$data['mobile'] = $param['username']; $data['mobile'] = $param['username'];
$data['email'] = $param['email'] ? : ''; $data['email'] = $param['email'] ?: '';
$data['sex'] = $param['sex'] ? : ''; $data['sex'] = $param['sex'] ?: '';
$data['create_time'] = time(); $data['create_time'] = time();
Db::name('HrmUserDet')->insert($data); Db::name('HrmUserDet')->insert($data);
@ -343,16 +346,15 @@ class User extends Common
if ($userGroups) { if ($userGroups) {
Db::name('admin_access')->insertAll($userGroups); Db::name('admin_access')->insertAll($userGroups);
} }
$this->commit(); $this->commit();
$param['user_id'] = $data['user_id']; $param['user_id'] = $data['user_id'];
$resSync = $syncModel->syncData($param); $resSync = $syncModel->syncData($param);
# 添加记录 # 添加记录
$user=new ApiCommon(); if (request()->action() != 'import') {
$userInfo=$user->userInfo; SystemActionLog($userId, 'admin_user', 'employee', $user_id, 'save', $param['realname'], '', '', '新增用户:' . $param['realname']);
SystemActionLog($userInfo['id'], 'admin_user','employee', $user_id, 'save', $param['realname'], '', '','新增用户:'.$param['realname']); }
return true; return true;
} catch(\Exception $e) { } catch (\Exception $e) {
$this->rollback(); $this->rollback();
$this->error = '添加失败'; $this->error = '添加失败';
return false; return false;
@ -362,19 +364,19 @@ class User extends Common
//导入成为正式用户 //导入成为正式用户
public function beusers($request) public function beusers($request)
{ {
if ($request['userlist']&&is_array($request['userlist'])) { if ($request['userlist'] && is_array($request['userlist'])) {
$flag = true; $flag = true;
foreach ($request['userlist'] as $value) { foreach ($request['userlist'] as $value) {
$userInfo = Db::name('AdminUser')->where('id = '.$value.'')->find(); $userInfo = Db::name('AdminUser')->where('id = ' . $value . '')->find();
$userDet = Db::name('HrmUserDet')->where('user_id = '.$value.'')->find(); $userDet = Db::name('HrmUserDet')->where('user_id = ' . $value . '')->find();
$temp['status'] = 1; $temp['status'] = 1;
$temp['type'] = 1; $temp['type'] = 1;
$temp['username'] = $userDet['mobile']; $temp['username'] = $userDet['mobile'];
$salt = substr(md5(time()),0,4); $salt = substr(md5(time()), 0, 4);
$temp['salt'] = $salt; $temp['salt'] = $salt;
$password = $userDet['mobile']; $password = $userDet['mobile'];
$temp['password'] = user_md5($password, $salt, $temp['username']); $temp['password'] = user_md5($password, $salt, $temp['username']);
$flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp); $flag = $flag && Db::name('AdminUser')->where('id =' . $value)->update($temp);
} }
if ($flag) { if ($flag) {
return true; return true;
@ -394,24 +396,35 @@ class User extends Common
*/ */
public function updateDataById($param, $id) public function updateDataById($param, $id)
{ {
$user=new ApiCommon();
$user_id=$user->userInfo;
if ($param['user_id']) { if ($param['user_id']) {
//修改个人信息 //修改个人信息
$data['email'] = $param['email']; $data['email'] = $param['email'];
$data['sex'] = $param['sex']; $data['sex'] = $param['sex'];
// $data['mobile'] = $param['username']; // $data['mobile'] = $param['username'];
$userInfo=db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find(); $userInfo = db('admin_user')->where(['username' => $param['username'], 'id' => ['neq', $param['user_id']]])->find();
if ($userInfo) { if ($userInfo) {
$this->error = '手机号已存在'; $this->error = '手机号已存在';
return false; return false;
} }
$nameData = db('admin_user')->where(['realname' => ['like', '%' . $param['realname'] . '%']])->column('realname');
if (in_array($param['realname'], $nameData)) {
for ($j = 1; $j < 100; $j++) {
$name = $param['realname'] . '-' . $j;
if (in_array($name, $nameData)) {
continue;
} else {
$name = $param['realname'] . '-' . $j;
break;
}
}
$param['realname'] = $name;
}
Db::name('HrmUserDet')->where(['user_id' => $param['user_id']])->update($data); Db::name('HrmUserDet')->where(['user_id' => $param['user_id']])->update($data);
$data['realname'] = $param['realname']; $data['realname'] = $param['realname'];
$data['post'] = $param['post']; $data['post'] = $param['post'];
$flag = $this->where(['id' => $param['user_id']])->update($data); $flag = $this->where(['id' => $param['user_id']])->update($data);
if ($flag==0 || $flag==1) { if ($flag == 0 || $flag == 1) {
SystemActionLog($user_id['id'],'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '','编辑了:'.$param['realname']); SystemActionLog($param['user_id'], 'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '', '编辑了:' . $param['realname']);
return true; return true;
} else { } else {
$this->error = '保存失败'; $this->error = '保存失败';
@ -429,6 +442,25 @@ class User extends Common
$this->error = '暂无此数据'; $this->error = '暂无此数据';
return false; return false;
} }
if(request()->action() == 'import'){
// $param['realname'] = $checkData['realname'];
$nameData = db('admin_user')->where('realname', 'like', '%' . $param['realname'] . '%')->column('realname');
if (in_array($param['realname'], $nameData)) {
for ($j = 1; $j < 100; $j++) {
$name = $param['realname'] . '-' . $j;
if (in_array($name, $nameData)) {
continue;
} else {
$name = $param['realname'] . '-' . $j;
break;
}
}
$param['realname'] = $name;
}
$param['userId']=!empty($param['create_user_id'])?:$param['owner_user_id'];
unset($param['owner_user_id']);
unset($param['create_user_id']);
}
if (request()->action() != 'import') { if (request()->action() != 'import') {
if (empty($param['group_id'])) { if (empty($param['group_id'])) {
$this->error = '请至少勾选一个用户组'; $this->error = '请至少勾选一个用户组';
@ -440,15 +472,14 @@ class User extends Common
$this->error = '直属上级不能是自己'; $this->error = '直属上级不能是自己';
return false; return false;
} }
if ((int)$param['parent_id'] !== 1 && in_array($param['parent_id'],$subUserId)) { if ((int)$param['parent_id'] !== 1 && in_array($param['parent_id'], $subUserId)) {
$this->error = '直属上级不能是自己或下属'; $this->error = '直属上级不能是自己或下属';
return false; return false;
} }
if (db('admin_user')->where(['id' => ['neq',$id],'username' => $param['username']])->find()) { if (db('admin_user')->where(['id' => ['neq', $id], 'username' => $param['username']])->find()) {
$this->error = '手机号已存在'; $this->error = '手机号已存在';
return false; return false;
} }
$this->startTrans(); $this->startTrans();
try { try {
$accessModel = model('Access'); $accessModel = model('Access');
@ -460,17 +491,18 @@ class User extends Common
$salt = $userInfo['salt']; $salt = $userInfo['salt'];
$param['password'] = user_md5($param['password'], $salt, $param['username']); $param['password'] = user_md5($param['password'], $salt, $param['username']);
} }
$this->allowField(true)->save($param, ['id' => $id]); $this->allowField(true)->save($param, ['id' => $id]);
$this->commit(); $this->commit();
Cache::rm('user_info' . $id); Cache::rm('user_info' . $id);
SystemActionLog($user_id['id'], 'admin_user','employee', $id, 'update', $userInfo['realname'], '', '','编辑了:'.$userInfo['realname']); SystemActionLog($param['userId'], 'admin_user', 'employee', $id, 'update', $userInfo['realname'], '', '', '编辑了:' . $userInfo['realname']);
// $data['mobile'] = $param['username']; // $data['mobile'] = $param['username'];
$data['email'] = $param['email']; $data['email'] = $param['email'];
$data['sex'] = $param['sex']; $data['sex'] = $param['sex'];
$data['update_time'] = time(); $data['update_time'] = time();
$flagg = Db::name('HrmUserDet')->where('user_id = '.$id)->update($data); $flagg = Db::name('HrmUserDet')->where('user_id = ' . $id)->update($data);
return true; return true;
} catch(\Exception $e) { } catch (\Exception $e) {
$this->rollback(); $this->rollback();
$this->error = '编辑失败'; $this->error = '编辑失败';
return false; return false;
@ -500,7 +532,7 @@ class User extends Common
return false; return false;
} }
} else { } else {
if (!$password){ if (!$password) {
$this->error = '密码不能为空'; $this->error = '密码不能为空';
return false; return false;
} }
@ -546,8 +578,8 @@ class User extends Common
$login_record->createRecord(LoginRecord::TYPE_USER_BANNED); $login_record->createRecord(LoginRecord::TYPE_USER_BANNED);
return false; return false;
} }
$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding) $platform = $paramArr['platform'] ? '_' . $paramArr['platform'] : ''; //请求平台(mobile,ding)
$login_record->createRecord($platform,LoginRecord::TYPE_SUCCESS); $login_record->createRecord($platform, LoginRecord::TYPE_SUCCESS);
// 获取菜单和权限 // 获取菜单和权限
$dataList = $this->getMenuAndRule($userInfo['id']); $dataList = $this->getMenuAndRule($userInfo['id']);
@ -566,15 +598,15 @@ class User extends Common
session_start(); session_start();
$info['userInfo'] = $userInfo; $info['userInfo'] = $userInfo;
$info['sessionId'] = session_id(); $info['sessionId'] = session_id();
$authKey = user_md5($userInfo['username'].$userInfo['password'].$info['sessionId'], $userInfo['salt']); $authKey = user_md5($userInfo['username'] . $userInfo['password'] . $info['sessionId'], $userInfo['salt']);
// $info['_AUTH_LIST_'] = $dataList['rulesList']; // $info['_AUTH_LIST_'] = $dataList['rulesList'];
$info['authKey'] = $authKey; $info['authKey'] = $authKey;
//删除旧缓存 //删除旧缓存
if (Cache::get('Auth_'.$userInfo['authkey'].$platform)) { if (Cache::get('Auth_' . $userInfo['authkey'] . $platform)) {
Cache::rm('Auth_'.$userInfo['authkey'].$platform); Cache::rm('Auth_' . $userInfo['authkey'] . $platform);
} }
Cache::set('Auth_'.$authKey.$platform, $info, $loginExpire); Cache::set('Auth_' . $authKey . $platform, $info, $loginExpire);
unset($userInfo['authkey']); unset($userInfo['authkey']);
// 返回信息 // 返回信息
@ -587,7 +619,7 @@ class User extends Common
//保存authKey信息 //保存authKey信息
$userData = []; $userData = [];
$userData['authkey'] = $authKey; $userData['authkey'] = $authKey;
$userData['authkey_time'] = time()+$loginExpire; $userData['authkey_time'] = time() + $loginExpire;
//把状态未激活至为启用 //把状态未激活至为启用
if ($userInfo['status'] == 2) { if ($userInfo['status'] == 2) {
$userData['status'] = 1; $userData['status'] = 1;
@ -600,7 +632,7 @@ class User extends Common
* 修改密码 * 修改密码
* @param array $param [description] * @param array $param [description]
*/ */
public function updatePaw($userInfo, $old_pwd, $new_pwd) public function updatePaw($userInfo, $old_pwd, $new_pwd,$userId)
{ {
if (!$old_pwd) { if (!$old_pwd) {
$this->error = '请输入旧密码'; $this->error = '请输入旧密码';
@ -617,7 +649,7 @@ class User extends Common
//登录有效时间 //登录有效时间
$cacheConfig = config('cache'); $cacheConfig = config('cache');
$loginExpire = $cacheConfig['expire'] ? : 86400 * 3; $loginExpire = $cacheConfig['expire'] ?: 86400 * 3;
$password = $this->where('id', $userInfo['id'])->value('password'); $password = $this->where('id', $userInfo['id'])->value('password');
if (user_md5($old_pwd, $userInfo['salt'], $userInfo['username']) != $password) { if (user_md5($old_pwd, $userInfo['salt'], $userInfo['username']) != $password) {
@ -638,15 +670,13 @@ class User extends Common
$userInfo = $this->where('id', $userInfo['id'])->find(); $userInfo = $this->where('id', $userInfo['id'])->find();
# 添加记录 # 添加记录
$user=new ApiCommon(); SystemActionLog($userId, 'admin_user', 'employee', $userInfo['id'], 'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_user','employee', $userInfo['id'], 'update', $userInfo['realname'], '', '','重置了密码:'.$userInfo['realname']);
// 重新设置缓存 // 重新设置缓存
session_start(); session_start();
$cache['userInfo'] = $userInfo; $cache['userInfo'] = $userInfo;
$cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']); $cache['authKey'] = user_md5($userInfo['username'] . $userInfo['password'] . session_id(), $userInfo['salt']);
cache('Auth_'.$cache['authKey'], null); cache('Auth_' . $cache['authKey'], null);
cache('Auth_'.$cache['authKey'], $cache, $loginExpire); cache('Auth_' . $cache['authKey'], $cache, $loginExpire);
return $cache['authKey'];//把auth_key传回给前端 return $cache['authKey'];//把auth_key传回给前端
} }
@ -659,15 +689,13 @@ class User extends Common
{ {
$syncModel = new \app\admin\model\Sync(); $syncModel = new \app\admin\model\Sync();
$flag = true; $flag = true;
$userInfo = new ApiCommon();
$user_id=$userInfo->userInfo;
foreach ($param['id'] as $value) { foreach ($param['id'] as $value) {
$password = ''; $password = '';
$userInfo = db('admin_user')->where(['id' => $value])->find(); $userInfo = db('admin_user')->where(['id' => $value])->find();
$salt = substr(md5(time()),0,4); $salt = substr(md5(time()), 0, 4);
$temp['salt'] = $salt; $temp['salt'] = $salt;
$temp['password']= $password = user_md5($param['password'], $salt, $userInfo['username']); $temp['password'] = $password = user_md5($param['password'], $salt, $userInfo['username']);
$flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp); $flag = $flag && Db::name('AdminUser')->where('id =' . $value)->update($temp);
$syncData = []; $syncData = [];
$syncData['user_id'] = $value; $syncData['user_id'] = $value;
$syncData['salt'] = $salt; $syncData['salt'] = $salt;
@ -675,16 +703,14 @@ class User extends Common
$resSync = $syncModel->syncData($syncData); $resSync = $syncModel->syncData($syncData);
} }
if ($flag) { if ($flag) {
foreach ($param['id'] as $v){ foreach ($param['id'] as $v) {
$userInfo = db('admin_user')->where(['id' => $v])->find(); $userInfo = db('admin_user')->where(['id' => $v])->find();
# 添加记录 # 添加记录
$user=new ApiCommon(); SystemActionLog($param['user_id'], 'admin_user', 'employee', $v, 'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_user','employee', $v, 'update',$userInfo['realname'],'', '', '重置了密码:'.$userInfo['realname']);
} }
return $flag; return $flag;
} else { } else {
$this->error ='修改失败,请稍后重试'; $this->error = '修改失败,请稍后重试';
return false; return false;
} }
} }
@ -703,7 +729,7 @@ class User extends Common
$menusList = []; $menusList = [];
$ruleMap = []; $ruleMap = [];
$adminTypes = adminGroupTypes($u_id); $adminTypes = adminGroupTypes($u_id);
if (in_array(1,$adminTypes)) { if (in_array(1, $adminTypes)) {
$map['status'] = 1; $map['status'] = 1;
$menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select(); $menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select();
} else { } else {
@ -725,6 +751,10 @@ class User extends Common
foreach ($rules as $k => $v) { foreach ($rules as $k => $v) {
$newRuleIds[] = $v['id']; $newRuleIds[] = $v['id'];
$rules[$k]['name'] = strtolower($v['name']); $rules[$k]['name'] = strtolower($v['name']);
if ($v['name'] == 'market') {
$rules[$k]['name'] = 'activityForm';
}
} }
//菜单管理(弃用) //菜单管理(弃用)
// $menuMap['status'] = 1; // $menuMap['status'] = 1;
@ -738,8 +768,8 @@ class User extends Common
//权限数组 //权限数组
$authList = rulesListToArray($rulesList, $newRuleIds); $authList = rulesListToArray($rulesList, $newRuleIds);
//应用控制 //应用控制
$adminConfig = db('admin_config')->where(['pid' => 0,'status' => 1])->column('module'); $adminConfig = db('admin_config')->where(['pid' => 0, 'status' => 1])->column('module');
$adminConfig = $adminConfig ? array_merge($adminConfig,['bi','admin']) : ['bi','admin']; $adminConfig = $adminConfig ? array_merge($adminConfig, ['bi', 'admin']) : ['bi', 'admin'];
# 通讯录 # 通讯录
if (in_array('book', $adminConfig) && !empty($authList['oa']['addresslist']['index'])) { if (in_array('book', $adminConfig) && !empty($authList['oa']['addresslist']['index'])) {
@ -747,14 +777,14 @@ class User extends Common
} }
# 商业智能权限细化 # 商业智能权限细化
if ($authList['bi']) { if ($authList['bi']) {
if (!in_array('taskExamine',$adminConfig) && !in_array('crm',$adminConfig)) { if (!in_array('taskExamine', $adminConfig) && !in_array('crm', $adminConfig)) {
unset($authList['bi']); unset($authList['bi']);
} else { } else {
foreach ($authList['bi'] as $key=>$val) { foreach ($authList['bi'] as $key => $val) {
if (!in_array('taskExamine',$adminConfig)) { if (!in_array('taskExamine', $adminConfig)) {
unset($authList['bi']['oa']); unset($authList['bi']['oa']);
} }
if (!in_array('crm',$adminConfig)) { if (!in_array('crm', $adminConfig)) {
unset($authList['bi']['customer']); unset($authList['bi']['customer']);
unset($authList['bi']['business']); unset($authList['bi']['business']);
unset($authList['bi']['product']); unset($authList['bi']['product']);
@ -769,8 +799,8 @@ class User extends Common
unset($authList['bi']); unset($authList['bi']);
} }
# 任务审批 # 任务审批
if (in_array('taskExamine', $adminConfig) ) { if (in_array('taskExamine', $adminConfig)) {
$authList['oa']['taskExamine'] = (Object)[]; $authList['oa']['taskExamine'] = (object)[];
} }
# 项目 # 项目
if (in_array('work', $adminConfig)) { if (in_array('work', $adminConfig)) {
@ -781,18 +811,19 @@ class User extends Common
} }
# 日志 # 日志
if (in_array('log', $adminConfig)) { if (in_array('log', $adminConfig)) {
$authList['oa']['log'] = (Object)[]; $authList['oa']['log'] = (object)[];
} }
# 日历 # 日历
if (in_array('calendar', $adminConfig)) { if (in_array('calendar', $adminConfig)) {
$authList['oa']['calendar'] = (Object)[]; $authList['oa']['calendar'] = (object)[];
} }
# 公海权限 # 公海权限
$structureId = db('admin_user')->where('id', $u_id)->value('structure_id'); $structureId = db('admin_user')->where('id', $u_id)->value('structure_id');
$poolStatus = db('crm_customer_pool')->whereLike('admin_user_ids', '%,' . $u_id . ',%') $poolStatus = db('crm_customer_pool')->where('status', 1)->where(function ($requery) use ($u_id, $structureId, $adminTypes) {
->whereOr('user_ids', 'like', '%,' . $u_id . ',%') if (!in_array(1, $adminTypes)) $requery->whereLike('admin_user_ids', '%,' . $u_id . ',%');
->whereOr('department_ids', 'like', '%,' . $structureId . ',%') if (!in_array(1, $adminTypes)) $requery->whereOr('user_ids', 'like', '%,' . $u_id . ',%');
->value('pool_id'); if (!in_array(1, $adminTypes)) $requery->whereOr('department_ids', 'like', '%,' . $structureId . ',%');
})->value('pool_id');
if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true]; if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true];
$ret['authList'] = $this->resetAuthorityFiled($authList); $ret['authList'] = $this->resetAuthorityFiled($authList);
@ -828,6 +859,13 @@ class User extends Common
# 发票 # 发票
if (isset($authList['crm']['invoice']['setinvoice'])) { if (isset($authList['crm']['invoice']['setinvoice'])) {
$authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice']; $authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice'];
$authList['crm']['invoice']['resetInvoiceStatus'] = $authList['crm']['invoice']['resetinvoicestatus'];
unset($authList['crm']['invoice']['resetinvoicestatus']);
}
# 市场活动
if (isset($authList['crm']['marketing']['updatestatus'])) {
$authList['crm']['marketing']['updateStatus'] = $authList['crm']['marketing']['updatestatus'];
unset($authList['crm']['marketing']['updatestatus']);
} }
# 发票抬头权限 # 发票抬头权限
if (!empty($authList['crm']['invoice']['index'])) { if (!empty($authList['crm']['invoice']['index'])) {
@ -927,12 +965,12 @@ class User extends Common
$adminAuth = [ $adminAuth = [
'configSet.read', 'crm.achievement', 'crm.field', 'crm.pool', 'crm.setting', 'configSet.read', 'crm.achievement', 'crm.field', 'crm.pool', 'crm.setting',
'examineFlow.index', 'init.initData', 'oa.examine', 'system.read', 'users.read', 'examineFlow.index', 'init.initData', 'oa.examine', 'system.read', 'users.read',
'work.update','permission.update' 'work.update', 'permission.update'
]; ];
foreach ($authList['manage'] AS $key1 => $value1) { foreach ($authList['manage'] as $key1 => $value1) {
foreach ($value1 AS $key2 => $value2) { foreach ($value1 as $key2 => $value2) {
if (in_array($key1.'.'.$key2, $adminAuth)) { if (in_array($key1 . '.' . $key2, $adminAuth)) {
$authList['manage']['other_rule'] = [ $authList['manage']['other_rule'] = [
'setwelcome' => true, 'setwelcome' => true,
'setworklogrule' => true, 'setworklogrule' => true,
@ -948,10 +986,10 @@ class User extends Common
# 通讯录 # 通讯录
$authList['email'] = (Object)[]; $authList['email'] = (object)[];
$authList['hrm'] = (Object)[]; $authList['hrm'] = (object)[];
$authList['jxc'] = (Object)[]; $authList['jxc'] = (object)[];
$authList['knowledge'] = (Object)[]; $authList['knowledge'] = (object)[];
return $authList; return $authList;
} }
@ -964,12 +1002,12 @@ class User extends Common
{ {
$ruleMap = []; $ruleMap = [];
$adminTypes = adminGroupTypes($uid); $adminTypes = adminGroupTypes($uid);
if (in_array(1,$adminTypes)) { if (in_array(1, $adminTypes)) {
$map['status'] = 1; $map['status'] = 1;
} else { } else {
$groups = $this->get($uid)->groups; $groups = $this->get($uid)->groups;
$ruleIds = []; $ruleIds = [];
foreach($groups as $k => $v) { foreach ($groups as $k => $v) {
if (stringToArray($v['rules'])) { if (stringToArray($v['rules'])) {
$ruleIds = array_merge($ruleIds, stringToArray($v['rules'])); $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
} }
@ -989,7 +1027,7 @@ class User extends Common
$tree = new \com\Tree(); $tree = new \com\Tree();
$rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid')); $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
$rulesList = rulesDeal($rulesList); $rulesList = rulesDeal($rulesList);
return $rulesList ? : []; return $rulesList ?: [];
} }
/** /**
@ -1000,12 +1038,12 @@ class User extends Common
{ {
//根据$m,$c,$a 获取对应的$a 的rule_id //根据$m,$c,$a 获取对应的$a 的rule_id
$rulesList = $this->getRulesList($uid); $rulesList = $this->getRulesList($uid);
if (!in_array($m.'-'.$c.'-'.$a, $rulesList)) { if (!in_array($m . '-' . $c . '-' . $a, $rulesList)) {
return false; return false;
} }
$mRuleId = db('admin_rule')->where(['name'=>$m,'level'=>1])->value('id'); $mRuleId = db('admin_rule')->where(['name' => $m, 'level' => 1])->value('id');
$cRuleId = db('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id'); $cRuleId = db('admin_rule')->where(['name' => $c, 'level' => 2, 'pid' => $mRuleId])->value('id');
$aRuleId = db('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id'); $aRuleId = db('admin_rule')->where(['name' => $a, 'level' => 3, 'pid' => $cRuleId])->value('id');
//获取用户组 //获取用户组
$groups = $this->get($uid)->groups; $groups = $this->get($uid)->groups;
if (!$groups) { if (!$groups) {
@ -1017,7 +1055,7 @@ class User extends Common
$groupTypes[] = $g['type']; $groupTypes[] = $g['type'];
} }
} }
return $groupTypes ? : []; return $groupTypes ?: [];
} }
/** /**
@ -1026,12 +1064,12 @@ class User extends Common
*/ */
public function getAllUserByAction($m, $c, $a) public function getAllUserByAction($m, $c, $a)
{ {
$mRuleId = db('admin_rule')->where(['name'=>$m,'level'=>1])->value('id'); $mRuleId = db('admin_rule')->where(['name' => $m, 'level' => 1])->value('id');
$cRuleId = db('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id'); $cRuleId = db('admin_rule')->where(['name' => $c, 'level' => 2, 'pid' => $mRuleId])->value('id');
$aRuleId = db('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id'); $aRuleId = db('admin_rule')->where(['name' => $a, 'level' => 3, 'pid' => $cRuleId])->value('id');
$groups = db('admin_group')->where(['rules' => ['in',$aRuleId]])->column('id'); $groups = db('admin_group')->where(['rules' => ['in', $aRuleId]])->column('id');
$userIds = db('admin_access')->where(['group_id' => ['in',$groups]])->column('user_id'); $userIds = db('admin_access')->where(['group_id' => ['in', $groups]])->column('user_id');
if (!$userIds) { if (!$userIds) {
//查询管理员 //查询管理员
$userIds = db('admin_user')->where(['id' => 1])->column('id'); $userIds = db('admin_user')->where(['id' => 1])->column('id');
@ -1046,7 +1084,7 @@ class User extends Common
*/ */
public function getSubUserByStr($structure_id, $type = 1) public function getSubUserByStr($structure_id, $type = 1)
{ {
$allStrIds = (array) $structure_id; $allStrIds = (array)$structure_id;
if ($type == 2) { if ($type == 2) {
$structureModel = new \app\admin\model\Structure(); $structureModel = new \app\admin\model\Structure();
foreach ($allStrIds as $v) { foreach ($allStrIds as $v) {
@ -1057,8 +1095,8 @@ class User extends Common
} }
} }
} }
$userIds = db('admin_user')->where(['structure_id' => ['in',$allStrIds]])->column('id'); $userIds = db('admin_user')->where(['structure_id' => ['in', $allStrIds]])->column('id');
return $userIds ? : []; return $userIds ?: [];
} }
/** /**
@ -1086,7 +1124,7 @@ class User extends Common
->find(); ->find();
$data['img'] = $data['img'] ? getFullPath($data['img']) : ''; $data['img'] = $data['img'] ? getFullPath($data['img']) : '';
$data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : ''; $data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : '';
return $data ? : []; return $data ?: [];
} }
/** /**
@ -1097,7 +1135,7 @@ class User extends Common
public function getUserNameById($id = '') public function getUserNameById($id = '')
{ {
$data = $this->where(['id' => $id])->value('realname'); $data = $this->where(['id' => $id])->value('realname');
return $data ? : '查看详情'; return $data ?: '查看详情';
} }
/** /**
@ -1113,7 +1151,7 @@ class User extends Common
$idArr = $ids; $idArr = $ids;
} }
$data = $this->where(['id' => array('in', $idArr)])->column('realname'); $data = $this->where(['id' => array('in', $idArr)])->column('realname');
return $data ? : []; return $data ?: [];
} }
/** /**
@ -1125,7 +1163,7 @@ class User extends Common
{ {
$adminGroupUser = db('admin_access')->where(['group_id' => 1])->column('user_id'); $adminGroupUser = db('admin_access')->where(['group_id' => 1])->column('user_id');
$userIDs = $adminGroupUser ? array_merge($adminGroupUser, [1]) : [1]; $userIDs = $adminGroupUser ? array_merge($adminGroupUser, [1]) : [1];
return $userIDs ? : [1]; return $userIDs ?: [1];
} }
/** /**
@ -1139,7 +1177,7 @@ class User extends Common
->alias('user') ->alias('user')
->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT') ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
->where(['user.id' => ['in', $ids]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select(); ->where(['user.id' => ['in', $ids]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select();
return $list ? : []; return $list ?: [];
} }
/** /**
@ -1147,7 +1185,8 @@ class User extends Common
* @param * @param
* @return * @return
*/ */
public function getUserByPer($m = '', $c = '', $a = ''){ public function getUserByPer($m = '', $c = '', $a = '')
{
$request = Request::instance(); $request = Request::instance();
$header = $request->header(); $header = $request->header();
$authKey = $header['authkey']; $authKey = $header['authkey'];
@ -1156,7 +1195,7 @@ class User extends Common
$c = $c ? strtolower($c) : strtolower($request->controller()); $c = $c ? strtolower($c) : strtolower($request->controller());
$a = $a ? strtolower($a) : strtolower($request->action()); $a = $a ? strtolower($a) : strtolower($request->action());
$cache = cache('Auth_'.$authKey); $cache = cache('Auth_' . $authKey);
if (!$cache) { if (!$cache) {
return false; return false;
} }
@ -1168,7 +1207,7 @@ class User extends Common
//用户组类别1本人2本人及下属3本部门4本部门及下属部门5全部 //用户组类别1本人2本人及下属3本部门4本部门及下属部门5全部
$adminIds = $this->getAdminId(); $adminIds = $this->getAdminId();
$userIds = []; $userIds = [];
if (in_array($userInfo['id'],$adminIds)) { if (in_array($userInfo['id'], $adminIds)) {
$userIds = getSubUserId(true, 1); $userIds = getSubUserId(true, 1);
} else { } else {
if (!$groupTypes) { if (!$groupTypes) {
@ -1191,21 +1230,21 @@ class User extends Common
} }
} }
} }
return $userIds ? : []; return $userIds ?: [];
} }
/* /*
*根据部门ID获取员工列表 *根据部门ID获取员工列表
* *
*/ */
public function getUserListByStructureId($structure_id='') public function getUserListByStructureId($structure_id = '')
{ {
$map =array(); $map = array();
if($structure_id){ if ($structure_id) {
$map['structure_id'] = $structure_id; $map['structure_id'] = $structure_id;
} }
$list = Db::name('AdminUser')->field('id as user_id,realname,post,structure_id')->where($map)->select(); $list = Db::name('AdminUser')->field('id as user_id,realname,post,structure_id')->where($map)->select();
return $list ? : []; return $list ?: [];
} }
/* /*
@ -1215,7 +1254,7 @@ class User extends Common
public function getListByStr($str) public function getListByStr($str)
{ {
$idArr = stringToArray($str); $idArr = stringToArray($str);
$list = db('admin_user')->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select(); $list = db('admin_user')->field('id,username,realname,thumb_img')->where(['id' => ['in', $idArr]])->select();
return $list; return $list;
} }
@ -1240,13 +1279,13 @@ class User extends Common
/** /**
* [getUserThree 员工第三方扩展信息] * [getUserThree 员工第三方扩展信息]
* @param key 分类 * @param key 分类
* @author Michael_xu
* @return [array] * @return [array]
* @author Michael_xu
*/ */
public function getUserThree($key, $user_id) public function getUserThree($key, $user_id)
{ {
$resValue = db('admin_user_threeparty')->where(['key' => $key,'user_id' => $user_id])->value('value'); $resValue = db('admin_user_threeparty')->where(['key' => $key, 'user_id' => $user_id])->value('value');
return $resValue ? : ''; return $resValue ?: '';
} }
/** /**
@ -1299,22 +1338,24 @@ class User extends Common
* @param $param * @param $param
* @return array * @return array
*/ */
public function sortList($param){ public function sortList($param)
$list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->find(); {
$list=unserialize($list['value']); $list = Db::name('admin_sort')->where('user_id', $param['user_id'])->field('value')->find();
return $list?:[]; $list = unserialize($list['value']);
return $list ?: [];
} }
/** /**
* 修改顶部菜单显示 * 修改顶部菜单显示
* @param $param * @param $param
*/ */
public function updateSort($param){ public function updateSort($param)
$list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->select(); {
if($list){ $list = Db::name('admin_sort')->where('user_id', $param['user_id'])->field('value')->select();
$data= Db::name('admin_sort')->where('user_id',$param['user_id'])->update(['value'=>serialize($param['value'])]); if ($list) {
}else{ $data = Db::name('admin_sort')->where('user_id', $param['user_id'])->update(['value' => serialize($param['value'])]);
$data= Db::name('admin_sort')->insert(['user_id'=>$param['user_id'],'value'=>serialize($param['value'])]); } else {
$data = Db::name('admin_sort')->insert(['user_id' => $param['user_id'], 'value' => serialize($param['value'])]);
} }
return $data; return $data;
} }
@ -1341,16 +1382,16 @@ class User extends Common
} }
Db::startTrans(); Db::startTrans();
try{ try {
# 删除员工角色关联数据 # 删除员工角色关联数据
Db::name('admin_access')->whereIn('user_id', $userIds)->delete(); Db::name('admin_access')->whereIn('user_id', $userIds)->delete();
# 重新设置员工角色 # 重新设置员工角色
foreach ($userIds AS $key => $value) { foreach ($userIds as $key => $value) {
# 默认跳过超级管理员 # 默认跳过超级管理员
if ($value == 1) continue; if ($value == 1) continue;
foreach ($groupIds AS $k => $v) { foreach ($groupIds as $k => $v) {
$userGroup[] = [ $userGroup[] = [
'user_id' => $value, 'user_id' => $value,
'group_id' => $v 'group_id' => $v
@ -1361,11 +1402,9 @@ class User extends Common
if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup); if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);
Db::commit(); Db::commit();
$user= new ApiCommon(); foreach ($userIds as $key => $value) {
$user_id=$user->userInfo; $userInfo = Db::name('admin_user')->where('id', $value)->find();
foreach ($userIds AS $key => $value) { SystemActionLog($param['userId'], 'admin_user', 'employee', $value, 'update', $userInfo['realname'], '', '', '编辑员工角色:' . $userInfo['realname']);
$userInfo=Db::name('admin_user')->where('id', $value)->find();
SystemActionLog($user_id['id'], 'admin_user','employee', $value, 'update', $userInfo['realname'], '', '','编辑员工角色:'.$userInfo['realname']);
} }
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
@ -1385,21 +1424,21 @@ class User extends Common
* @since 2021/4/24 0024 14:05 * @since 2021/4/24 0024 14:05
* *
*/ */
public function setUserDept($ids = [],$param) public function setUserDept($ids = [], $param)
{ {
if (empty($ids)) { if (empty($ids)) {
$this->error = '参数错误'; $this->error = '参数错误';
return false; return false;
} }
foreach ($ids as $v){ foreach ($ids as $v) {
$data['id']=$v; $data['id'] = $v;
$data['structure_id']=$param['structure_id']; $data['structure_id'] = $param['structure_id'];
$flag=foreachData('',$data); $flag = foreachData('', $data);
} }
if ($flag) { if ($flag) {
return $flag; return $flag;
} else { } else {
$this->error ='修改失败,请稍后重试'; $this->error = '修改失败,请稍后重试';
return false; return false;
} }
} }
@ -1410,7 +1449,8 @@ class User extends Common
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/24 0024 14:42 * @since 2021/4/24 0024 14:42
*/ */
public function countNumOfUser(){ public function countNumOfUser()
{
//全部 //全部
// $data['allUserCount']=$this->count(); // $data['allUserCount']=$this->count();
// //未激活 // //未激活
@ -1421,17 +1461,17 @@ class User extends Common
// $data['disableCount']=$this->where('status',0)->count(); // $data['disableCount']=$this->where('status',0)->count();
// //新增 // //新增
// $data['addNewlyCount']=$this->where('create_time','gt',strtotime('-1 week'))->count(); // $data['addNewlyCount']=$this->where('create_time','gt',strtotime('-1 week'))->count();
$time=strtotime('-1 week'); $time = strtotime('-1 week');
$list=db('admin_user')->field([ $list = db('admin_user')->field([
'count(id) as allUserCount, 'count(id) as allUserCount,
count(case status when 2 then id else null end) as inactiveCount, count(case status when 2 then id else null end) as inactiveCount,
count(case status when 1 then id else null end) as activateCount, count(case status when 1 then id else null end) as activateCount,
count(case status when 0 then id else null end) as disableCount, count(case status when 0 then id else null end) as disableCount,
count(case when create_time >' .$time.' then id else null end) as addNewlyCount count(case when create_time >' . $time . ' then id else null end) as addNewlyCount
' '
])->select(); ])->select();
$data=[]; $data = [];
$data['list']=$list; $data['list'] = $list;
return $data; return $data;
} }
} }

@ -0,0 +1,262 @@
<?php
/**
* 字段验证(线索、客户、联系人、商机、合同、回款、回访、产品、办公审批)
*/
namespace app\admin\traits;
trait FieldVerificationTrait
{
/**
* 数据验证
*
* @param array $param 要验证的数据
* @param int $userId 用户ID
* @param string $types 自定义表栏目类型crm_leads、crm_customer ...
* @param int $dataId 编辑时相应的模块数据的ID
* @param int $typesId 自定义表栏目类型ID
* @author fanqi
* @since 2021-05-18
* @return string
*/
public function fieldDataValidate($param, $types, $userId, $dataId = 0, $typesId = 0)
{
$error = '';
$grantData = getFieldGrantData($userId); # 字段授权
$userLevel = isSuperAdministrators($userId); # 用户级别
# 查询自定义字段表数据
$fieldList = $this->getFieldList($types, $typesId);
# 验证
foreach ($fieldList AS $key => $value) {
# 字段授权,没有读写权限,跳过验证。
if (!$userLevel && !empty($grantData[$types])) {
$status = getFieldGrantStatus($value['field'], $grantData[$types]);
if (empty($status['read']) || (empty($dataId) && empty($status['write']))) continue;
}
# 验证非明细表格字段数据
if (!empty($value['is_null']) && !in_array($value['form_type'], ['detail_table', 'boolean_value']) && (isset($param[$value['field']]) && empty($param[$value['field']]))) {
$error = $value['name'] . '字段不能为空!';
break;
}
# 验证字段长度
if (!empty($value['max_length']) && $value['form_type'] != 'detail_table' && strlen($param[$value['field']]) > $value['max_length']) {
$error = $value['name'] . '字段超过设定长度!';
break;
}
# 验证百分数字段长度
if ($value['form_type'] == 'percent' && strlen($param[$value['field']]) > 11) {
$error = $value['name'] . "字段长度不能大于10位";
break;
}
# 验证数字字段长度
if ($value['form_type'] == 'number' && strlen($param[$value['field']]) > 16) {
$error = $value['name'] . "字段长度不能大于16位";
break;
}
# 验证明细表格不能为空
if (!empty($value['is_null']) && $value['form_type'] == 'detail_table' && isset($param[$value['field']]) && empty($param[$value['field']])) {
$error = $value['name'] . '数据不能为空!';
}
# 验证明细表格可以为空,明细表格里的字段不能为空的情况。
if ($value['form_type'] == 'detail_table') {
foreach ($param[$value['field']] AS $val) {
foreach ($val AS $v) {
if (!empty($v['is_null']) && empty($v['is_hidden']) && isset($v['value']) && empty($v['value'])) {
$error = $value['name'] . '中的' . $v['name'] . '字段不能为空!';
break;
}
}
}
}
if (empty($value['is_unique'])) continue;
// 人员、部门、文件、手写签名、描述文字、多选、明细表格跳过验证
if (in_array($value['form_type'], ['user', 'structure', 'file', 'handwriting_sign', 'desc_text', 'checkbox', 'detail_table'])) continue;
$uniqueStatus = false;
# 验证唯一性
if ($value['form_type'] == 'date_interval' && !empty($param[$value['field']])) {
// 日期区间
$uniqueStatus = $this->checkDataUniqueForDateInterval($types, $value['field'], $param[$value['field']], $dataId);
} elseif ($value['form_type'] == 'position' && !empty($param[$value['field']])) {
// 地址
$uniqueStatus = $this->checkDataUniqueForPosition($types, $value['field'], $param[$value['field']], $dataId);
} elseif ($value['form_type'] == 'location' && !empty($param[$value['field']])) {
// 定位
$uniqueStatus = $this->checkDataUniqueForLocation($types, $value['field'], $param[$value['field']], $dataId);
} else {
if (!empty($param[$value['field']])) $uniqueStatus = $this->checkDataUniqueForCommon($types, $value['field'], $param[$value['field']], $dataId);
}
if (!empty($uniqueStatus)) {
$error = $types == 'crm_customer' ? '(客户/公海)中的' . $value['name'] . "字段值重复!" : $value['name'] . "字段值重复!";
break;
}
}
return $error;
}
/**
* 验证唯一性(通用)
* 单行文本、多行文本、网址、布尔值、单选、数字
* 手机、邮箱、日期、日期时间、货币、百分数
*
* @param string $types 栏目类型
* @param string $field 字段名称
* @param string $value 字段值
* @param int $dataId 更新时传来的数据ID
* @author fanqi
* @since 2021-05-18
* @return float|mixed|string
*/
private function checkDataUniqueForCommon($types, $field, $value, $dataId = 0)
{
if (empty($value)) return false;
# 主键
$primaryKey = getPrimaryKeyName($types);
# 查询条件
$where[$field] = $value;
if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
return db($types)->where($where)->value($primaryKey);
}
/**
* 验证唯一性(日期区间)
*
* @param string $types 栏目类型
* @param string $field 字段名称
* @param array $value 字段值
* @param int $dataId 更新时传来的数据ID
* @author fanqi
* @since 2021-05-18
* @return float|mixed|string
*/
private function checkDataUniqueForDateInterval($types, $field, $value, $dataId = 0)
{
if (empty($value)) return false;
# 主键
$primaryKey = getPrimaryKeyName($types);
# 查询条件
$where[$field] = implode('_', $value);
if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
return db($types)->where($where)->value($primaryKey);
}
/**
* 验证唯一性(地址)
*
* @param string $types 栏目类型
* @param string $field 字段名称
* @param array $value 字段值
* @param int $dataId 更新时传来的数据ID
* @author fanqi
* @since 2021-05-18
* @return float|mixed|string
*/
private function checkDataUniqueForPosition($types, $field, $value, $dataId = 0)
{
if (empty($value)) return false;
# 主键
$primaryKey = getPrimaryKeyName($types);
# 查询条件
$where[$field] = implode(',', array_column($value, 'name'));
if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
return db($types)->where($where)->value($primaryKey);
}
/**
* 验证唯一性(定位)
*
* @param string $types 栏目类型
* @param string $field 字段名称
* @param array $value 字段值
* @param int $dataId 更新时传来的数据ID
* @author fanqi
* @since 2021-05-18
* @return float|mixed|string
*/
private function checkDataUniqueForLocation($types, $field, $value, $dataId = 0)
{
if (empty($value['address'])) return false;
# 主键
$primaryKey = getPrimaryKeyName($types);
# 查询条件
$where[$field] = $value['address'];
if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
return db($types)->where($where)->value($primaryKey);
}
// /**
// * 验证唯一性(部门)
// *
// * @param string $types 栏目类型
// * @param string $field 字段名称
// * @param string $value 字段值
// * @param int $dataId 更新时传来的数据ID
// * @author fanqi
// * @since 2021-05-18
// * @return float|mixed|string
// */
// private function checkDataUniqueForStructure($types, $field, $value, $dataId = 0)
// {
// if (empty($value)) return false;
//
// # 主键
// $primaryKey = getPrimaryKeyName($types);
//
// # 查询条件
// $where[$field] = ',' . $value . ',';
// if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
//
// return db($types)->where($where)->value($primaryKey);
// }
/**
* 自定义字段列表
*
* @param string $types 自定义表栏目类型crm_leads、crm_customer ...
* @param int $typesId 自定义表栏目类型ID
* @author fanqi
* @since 2021-05-18
* @return bool|\PDOStatement|string|\think\Collection
*/
private function getFieldList($types, $typesId)
{
# 查询条件
$where = [
'types' => $types,
'types_id' => $typesId,
'is_hidden' => 0,
'form_type' => ['neq', 'desc_text']
];
# 查询字段
$fields = ['field', 'name', 'form_type', 'is_unique', 'is_null', 'max_length'];
return db('admin_field')->field($fields)->where($where)->select();
}
}

@ -42,46 +42,8 @@
<h1 style="text-align:center;padding-top: 20px;">安装悟空CRM数据库超时请手动导入SQL文件</h1> <h1 style="text-align:center;padding-top: 20px;">安装悟空CRM数据库超时请手动导入SQL文件</h1>
<div class="desc" style="overflow:scroll;overflow-x:hidden;height:500px;color:#666666;font-weight: 600; margin-top: 50px; line-height:30px; text-align: left;padding-left: 20px;"> <div class="desc" style="overflow:scroll;overflow-x:hidden;height:500px;color:#666666;font-weight: 600; margin-top: 50px; line-height:30px; text-align: left;padding-left: 20px;">
<p>1、SQL文件位置public/sql/5kcrm.sql、public/sql/install.sql</p> <p>1、SQL文件位置public/sql/5kcrm.sql、public/sql/install.sql</p>
<p>2、在config目录下创建database.php文件</p> <p>2、修改config目录下database_template.php文件的数据库连接信息</p>
<p>3、database.php文件内容</p> <p>3、最后将database_template.php重名为database.php</p>
<p>return [</p>
<p>// 数据库类型</p>
<p>'type' => 'mysql',</p>
<p>// 服务器地址</p>
<p>'hostname' => '127.0.0.1',</p>
<p>// 数据库名</p>
<p>'database' => '',</p>
<p>// 用户名</p>
<p>'username' => '',</p>
<p>// 密码</p>
<p>'password' => '',</p>
<p>// 端口</p>
<p>'hostport' => '3306',</p>
<p>// 连接dsn</p>
<p>'dsn' => '',</p>
<p>// 数据库连接参数</p>
<p>'params' => [],</p>
<p>// 数据库编码默认采用utf8</p>
<p>'charset' => 'utf8',</p>
<p>// 数据库表前缀</p>
<p>'prefix' => '5kcrm_',</p>
<p>// 数据库调试模式</p>
<p>'debug' => true,</p>
<p>// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)</p>
<p>'deploy' => 0,</p>
<p>// 数据库读写是否分离 主从式有效</p>
<p>'rw_separate' => false,</p>
<p>// 读写分离后 主服务器数量</p>
<p>'master_num' => 1,</p>
<p>// 指定从服务器序号</p>
<p>'slave_no' => '',</p>
<p>// 自动读取主库数据</p>
<p>'read_master' => false,</p>
<p>// 是否严格检查字段是否存在</p>
<p>'fields_strict' => true,</p>
<p>// 数据集返回类型</p>
<p>'resultset_type' => 'array',</p>
<p>];</p>
</div> </div>
</div> </div>
</div> </div>

@ -12,4 +12,5 @@
return [ return [
app\common\command\ImportFollowRecord::class, app\common\command\ImportFollowRecord::class,
app\common\command\PoolCommand::class, app\common\command\PoolCommand::class,
app\common\command\Team::class,
]; ];

@ -166,10 +166,19 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
if (!empty($v['start'])) $v['start'] = date('Y-m-d', $v['start']); if (!empty($v['start'])) $v['start'] = date('Y-m-d', $v['start']);
if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']); if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']);
} }
# 创建人、负责人、回访人(非自定义字段) # 自定义字段的user team_id非自定义字段
// if ($v['form_type'] == 'user' && in_array($k, ['create_user_id', 'owner_user_id'])) { if ($v['form_type'] == 'user' && in_array($k, ['team_id'])) {
// if ($v['condition'] == 'is') $v['condition'] = 'contains'; // ro_user_id rw_user_id
// } if ($v['condition'] == 'in') {
return "(" . $c . 'ro_user_id' . " like ',%" . $v['value'] . "OR " . $c . 'rw_user_id' . " like ',%" . $v['value'] . ")";
} elseif ($v['condition'] == 'not in') {
return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
} elseif ($v['condition'] == 'isNull') {
return "(" . $c . 'ro_user_id' . "eq" . $v['value'] . "OR " . $c . 'rw_user_id' . " eq" . $v['value'] . ")";
} elseif ($v['condition'] == 'isNotNull') {
return "(" . $c . 'ro_user_id' . "neq" . $v['value'] . "OR " . $c . 'rw_user_id' . " neq" . $v['value'] . ")";
}
}
# 自定义字段的user、structure类型 # 自定义字段的user、structure类型
if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') { if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
if ($v['condition'] == 'is') $v['condition'] = 'contains'; if ($v['condition'] == 'is') $v['condition'] = 'contains';
@ -308,6 +317,488 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
return $where ?: []; return $where ?: [];
} }
/**
* 高级筛选
*
* @param array $param 搜索参数
* @param string $m 模块crm log work ...
* @param string $c 栏目leads customer ...
* @param string $a 方法index save ...
* @return array
* @since 2021-05-20
* @author fanqi
*/
function advancedQuery($param, $m = '', $c = '', $a = '')
{
// 结果数据
$result = [];
// 原始前缀
$prefix = $c . '.';
// 等于(时间段)类型
$betweenType = [
'year', 'lastYear', 'nextYear', 'firstHalfYear', 'nextHalfYear', 'quarter', 'lastQuarter',
'nextQuarter', 'month', 'lastMonth', 'nextMonth', 'week', 'lastWeek', 'nextWeek', 'today',
'yesterday', 'tomorrow', 'previous7day', 'previous30day', 'future7day', 'future30day'
];
foreach ($param as $key => $value) {
// 过滤不能参与搜索的字段类型
if (!empty($value['form_type']) && in_array($value['form_type'], ['file', 'handwriting_sign', 'desc_text', 'detail_table', 'date_interval'])) continue;
// 初始化前缀
$c = $prefix;
// 清除空格
if (isset($value['condition'])) $value['condition'] = trim($value['condition']);
// 处理表前缀和字段名称
list($c, $key) = advancedQueryParam($c, $key, $value['name']);
if ($key == 'check_status' && !is_array($value)) $result[$c . $key] = $value;
if ($key == 'status_id' && !is_array($value)) $result[$c . $key] = $value;
if ($key == 'customer_id' && !is_array($value)) $result['customer.' . $key] = $value;
if ($key == 'contract_id' && !is_array($value)) $result['contract.' . $key] = $value;
if ($key == 'business_id' && !is_array($value)) $result['business.' . $key] = $value;
// 仪表盘参数
if (!empty($value['value'][0]) && empty($value['condition'])) {
$value['condition'] = 'is';
$value['form_type'] = 'user';
}
if (!empty($value['start']) && !empty($value['end'])) {
$value['value'][0] = date('Y-m-d H:i:s', $value['start']);
$value['value'][1] = date('Y-m-d H:i:s', $value['end']);
$value['form_type'] = 'datetime';
$value['condition'] = 'between';
}
if ($key == 'check_status' && !is_array($value)) {
unset($value);
$value['value'][0] = '审核通过';
$value['form_type'] = 'check_status';
$value['name'] = '审核状态';
$value['type'] = 'check_status';
$value['condition'] = 'is';
}
if (!empty($value['value'][0]) && in_array($value['value'][0], $betweenType)) {
$value = advancedQueryHandleDate($value);
}
// 代办事项
if (isset($value) && !isset($value['condition']) && !isset($value['value']) && !isset($value['form_type'])) {
$result[$c . $key] = is_array($value) ? $value : ['in', $value];
continue;
}
// 模块、审核状态、成交状态、产品分类、单行文本、多行文本、网址、手机、邮箱、下拉框、布尔值、多选、定位、创建人、负责人
if (isset($value['form_type']) && in_array($value['form_type'], ['module', 'check_status', 'deal_status', 'category', 'text', 'textarea', 'mobile', 'email', 'select', 'boolean_value', 'checkbox', 'location', 'website']) || in_array($key, ['create_user_id', 'owner_user_id'])) {
$result[$c . $key] = advancedQueryFormatForCommon($value['value'], $value['condition'], $value['form_type'], $key);
}
// 日期、日期时间、数字、货币、百分数、下次联系时间
if (isset($value['form_type']) && in_array($value['form_type'], ['date', 'datetime', 'number', 'floatnumber', 'percent', 'next_time'])) {
$result[$c . $key] = advancedQueryFormatForDate($value);
}
// 地址(固定字段)、地址(自定义字段)
if (isset($value['form_type']) && in_array($value['form_type'], ['map_address', 'position'])) {
$result[$c . $key] = advancedQueryFormatForAddress($value['value'], $value['form_type']);
}
// 人员、部门
if (isset($value['form_type']) && in_array($value['form_type'], ['user', 'structure', 'single_user']) && !in_array($key, ['create_user_id', 'owner_user_id']) && $value['type'] != 'team_id') {
$result[$c . $key] = advancedQueryFormatForPersonnel($value['value'], $value['condition']);
}
// 商机状态组
if (isset($value['form_type']) && $value['form_type'] == 'business_type') {
if (!empty($value['type_id'])) $result[$c . 'type_id'] = ['eq', $value['type_id']];
if (!empty($value['status_id']) && in_array($value['status_id'], [1, 2, 3])) $result[$c . 'is_end'] = ['eq', $value['status_id']];
if (!empty($value['status_id']) && !in_array($value['status_id'], [1, 2, 3])) $result[$c . 'status_id'] = ['eq', $value['status_id']];
}
// 回款计划
if (isset($value['form_type']) && $value['form_type'] == 'receivables_plan' && !empty($value['value'])) {
$result[$c . 'plan_id'] = advancedQueryFormatForPlan($value['value']);
}
}
return $result;
}
/**
* 处理高级筛选查询前缀、字段名称
*
* @param string $prefix 表前缀
* @param string $field 字段名
* @param string $name 字段中文名
* @return array
* @since 2021-05-22
* @author fanqi
*/
function advancedQueryParam($prefix, $field, $name)
{
// 要变更的前缀
$prefixChange = [
'customer_name' => 'customer.',
'contacts_name' => 'contacts.',
'business_name' => 'business.',
'contract_name' => 'contract.',
'business_id' => 'business.',
'contacts_id' => 'contacts.'
];
// 处理客户名称、联系人名称、商机名称、合同名称字段
if (in_array($field, ['customer_name', 'contacts_name', 'business_name', 'contract_name']) && $name != '合同编号') {
$prefix = $prefixChange[$field];
$field = 'name';
}
// 处理合同下的商机ID、客户ID字段
if ($prefix == 'contract.' && in_array($field, ['business_id', 'contacts_id'])) {
$prefix = $prefixChange[$field];
$field = 'name';
}
// 处理回款、回访下的合同编号
if (in_array($prefix, ['receivables.', 'visit.']) && $name == '合同编号') {
$prefix = 'contract.';
$field = 'num';
}
// 处理回访下的联系人
if ($prefix == 'visit.' && $field == 'contacts_id') {
$prefix = 'contacts.';
$field = 'name';
}
return [$prefix, $field];
}
/**
* 回款计划查询条件
*
* @param array $data 搜索参数
* @return array
* @since 2021-05-22
* @author fanqi
*/
function advancedQueryFormatForPlan($data)
{
$result = [];
$planIds = db('crm_receivables_plan')->whereIn('num', $data)->column('plan_id');
if (!empty($planIds)) $result = ['in', $planIds];
return $result;
}
/**
* 地址(固定字段)、地址(自定义字段)查询条件
*
* @param array $data 搜索参数
* @param string $formType 字段类型
* @return array
* @since 2021-05-21
* @author fanqi
*/
function advancedQueryFormatForAddress($data, $formType)
{
if ($formType == 'map_address') $data = implode(chr(10), $data);
if ($formType == 'position') {
$data = array_filter(array_column($data[0], 'name'));
$data = implode(',', $data);
}
return ['like', '%' . trim($data) . '%'];
}
/**
* 人员、部门、回访人查询条件
*
* @param array $data 查询参数
* @param string $condition 查询条件
* @return array
*/
function advancedQueryFormatForPersonnel($data, $condition)
{
// 处理查询条件
if ($condition == 'is') $condition = 'contains';
if ($condition == 'isNot') $condition = 'notContains';
// 处理查询参数
$data = advancedQueryDataTransform($data, $condition);
// 搜索条件
return advancedQueryWhere($condition, $data);
}
/**
* 日期、日期时间、数字、货币、百分数查询条件
*
* @param array $data 搜索参数、类型、条件
* @return array
* @since 2021-05-20
* @author fanqi
*/
function advancedQueryFormatForDate($data)
{
# 转换日期时间类型格式
if (in_array($data['form_type'], ['datetime', 'next_time']) && !empty($data['value'][0])) $data['value'][0] = strtotime($data['value'][0]);
if (in_array($data['form_type'], ['datetime', 'next_time']) && !empty($data['value'][1])) $data['value'][1] = strtotime($data['value'][1]);
return advancedQueryWhere($data['condition'], count($data['value']) == 2 ? $data['value'] : $data['value'][0]);
}
/**
* 模块、审核状态、成交状态、产品分类、单行文本、多行文本、网址、手机、邮箱、下拉框、布尔值、多选、定位、创建人、负责人
*
* @param array $data 要查询的数据
* @param string $condition 查询方式
* @param string $formType 字段类型
* @return array
* @since 2021-05-20
* @author fanqi
*/
function advancedQueryFormatForCommon($data, $condition, $formType, $key)
{
// 处理查询方式
if (in_array($formType, ['checkbox']) && $condition == 'is') $condition = 'contains';
if (in_array($formType, ['checkbox']) && $condition == 'isNot') $condition = 'notContains';
// 处理查询参数
if (in_array($condition, ['contains', 'notContains', 'startWith', 'endWith'])) $data = advancedQueryDataTransform($data, $condition);
// 处理回访形式
if (in_array($key, ['shape', 'satisfaction'])) {
array_walk($data, function ($value, $key) use (&$data) {
$data[$key] = $value . "\r";
});
}
// 处理审核状态
if ($formType == 'check_status') {
$data[0] = str_replace('待审核', 0, $data[0]);
$data[0] = str_replace('审核中', 1, $data[0]);
$data[0] = str_replace('审核通过', 2, $data[0]);
$data[0] = str_replace('审核失败', 3, $data[0]);
$data[0] = str_replace('已撤回', 4, $data[0]);
$data[0] = str_replace('未提交', 5, $data[0]);
$data[0] = str_replace('已作废', 6, $data[0]);
}
return advancedQueryWhere($condition, $data);
}
/**
* 设置搜索条件
*
* @param string $condition 查询方式
* @param string $data 查询数据
* @return array
* @since 2021-05-22
* @author fanqi
*/
function advancedQueryWhere($condition, $data)
{
$result = [];
// NULL(0)不存在、IS(1)等于、IS_NOT(2)不等于、CONTAINS(3)包含、NOT_CONTAINS(4)不包含、IS_NULL(5)为空、IS_NOT_NULL(6)不为空
// GT(7)大于、EGT(8)大于等于、LT(9)小于、ELT(10)小于等于、ID(11)通过id、PREFIX(12) 前缀匹配、SUFFIX(13) 后缀匹配、RANGE(14) 数字区间
if ($condition == "in") $result = ['in', $data]; // 等于
if ($condition == 'is') $result = ['in', $data]; // 等于
if ($condition == 'isNot') $result = ['notin', $data]; // 不等于
if ($condition == 'contains') $result = ['like', $data, 'OR']; // 包含
if ($condition == 'notContains') $result = ['notlike', $data, 'AND']; // 不包含
if ($condition == 'startWith') $result = ['like', $data, 'OR']; // 开始于
if ($condition == 'endWith') $result = ['like', $data, 'OR']; // 结束于
if ($condition == 'gt') $result = ['gt', $data]; // 大于
if ($condition == 'lt') $result = ['lt', $data]; // 小于
if ($condition == 'egt') $result = ['egt', $data]; // 大于等于
if ($condition == 'elt') $result = ['elt', $data]; // 小于等于
if ($condition == 'between') $result = ['between', $data]; // 处于某个时间段
if ($condition == 'range') $result = ['between', $data]; // 处于某个时间段
if ($condition == 'isNull') $result = [['eq', ''], ['null'], 'OR']; // 为空
if ($condition == 'isNotNull') $result = [['neq', ''], ['not null'], 'AND']; // 不为空
return $result;
}
/**
* 处理要查询的数据
*
* @param array $data 要查询的数据
* @param string $condition 查询方式
* @return mixed
* @since 2021-05-20
* @author fanqi
*/
function advancedQueryDataTransform($data, $condition)
{
if (in_array($condition, ['contains', 'notContains'])) {
array_walk($data, function ($value, $key) use (&$data) {
$data[$key] = '%' . $value . '%';
});
}
if ($condition == 'startWith') {
array_walk($data, function ($value, $key) use (&$data) {
$data[$key] = $value . '%';
});
}
if ($condition == 'endWith') {
array_walk($data, function ($value, $key) use (&$data) {
$data[$key] = '%' . $value;
});
}
return $data;
}
/**
* 等于(时间段)数据处理
*
* @param $data
* @return array
* @since 2021-06-11
* @author fanqi
*/
function advancedQueryHandleDate($data)
{
// 本年度
if ($data['value'][0] == 'year') {
$data['value'][0] = date('Y-m-d 00:00:00');
$data['value'][1] = date('Y-m-d 23:59:59');
}
// 上一年度
if ($data['value'][0] == 'lastYear') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-1 year'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 year'));
}
// 下一年度
if ($data['value'][0] == 'nextYear') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 year'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+1 year'));
}
// 上半年
if ($data['value'][0] == 'firstHalfYear') {
$data['value'][0] = date('Y-01-01 00:00:00');
$data['value'][1] = date('Y-06-30 23:59:59');
}
// 下半年
if ($data['value'][0] == 'nextHalfYear') {
$data['value'][0] = date('Y-07-01 00:00:00');
$data['value'][1] = date('Y-12-31 23:59:59');
}
// 本季度
if ($data['value'][0] == 'quarter') {
$season = ceil((date('n')) / 3);
$data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
$data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
}
// 上一季度
if ($data['value'][0] == 'lastQuarter') {
$season = ceil((date('n')) / 3) - 1;
$data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
$data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
}
// 下一季度
if ($data['value'][0] == 'nextQuarter') {
$season = ceil((date('n')) / 3);
$data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 + 1, 1, date('Y')));
$data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3 + 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
}
// 本月
if ($data['value'][0] == 'month') {
$data['value'][0] = date('Y-m-01 00:00:00');
$data['value'][1] = date('Y-m-31 23:59:59');
}
// 上月
if ($data['value'][0] == 'lastMonth') {
$data['value'][0] = date('Y-m-01 00:00:00', strtotime(date('Y-m-d') . '-1 month'));
$data['value'][1] = date('Y-m-31 23:59:59', strtotime(date('Y-m-d') . '-1 month'));
}
// 下月
if ($data['value'][0] == 'nextMonth') {
$data['value'][0] = date('Y-m-01 00:00:00', strtotime(date('Y-m-d') . '+1 month'));
$data['value'][1] = date('Y-m-31 23:59:59', strtotime(date('Y-m-d') . '+1 month'));
}
// 本周
if ($data['value'][0] == 'week') {
$data['value'][0] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y')));
$data['value'][1] = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y')));
}
// 上周
if ($data['value'][0] == 'lastWeek') {
$date = date("Y-m-d");
$w = date("w", strtotime($date));
$d = $w ? $w - 1 : 6;
$start = date("Y-m-d", strtotime($date . " - " . $d . " days"));
$data['value'][0] = date('Y-m-d', strtotime($start . " - 7 days"));
$data['value'][1] = date('Y-m-d', strtotime($start . " - 1 days"));
}
// 下周
if ($data['value'][0] == 'nextWeek') {
$date = date("Y-m-d");
$w = date("w", strtotime($date));
$d = $w ? $w - 1 : 6;
$start = date("Y-m-d", strtotime($date . " - " . $d . " days"));
$data['value'][0] = date('Y-m-d', strtotime($start . " + 7 days"));
$data['value'][1] = date('Y-m-d', strtotime($start . " + 13 days"));
}
// 今天
if ($data['value'][0] == 'today') {
$data['value'][0] = date('Y-m-d 00:00:00');
$data['value'][1] = date('Y-m-d 23:59:59');
}
// 昨天
if ($data['value'][0] == 'yesterday') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-1 day'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
}
// 明天
if ($data['value'][0] == 'tomorrow') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+1 day'));
}
// 过去7天
if ($data['value'][0] == 'previous7day') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-7 day'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
}
// 过去30天
if ($data['value'][0] == 'previous30day') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-30 day'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
}
// 未来7天
if ($data['value'][0] == 'future7day') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+7 day'));
}
// 未来30天
if ($data['value'][0] == 'future30day') {
$data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
$data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+30 day'));
}
return $data;
}
/** /**
* 根据搜索生成where条件 * 根据搜索生成where条件
* *
@ -1308,22 +1799,18 @@ function getTimeByType($type = 'today', $is_last = false)
switch ($type) { switch ($type) {
case 'yesterday' : case 'yesterday' :
$timeArr = Time::yesterday(); $timeArr = Time::yesterday();
$lastArr = Time::yesterday(1);
break; break;
case 'week' : case 'week' :
$timeArr = Time::week(); $timeArr = Time::week();
$lastArr = Time::lastWeek();
break; break;
case 'lastWeek' : case 'lastWeek' :
$timeArr = Time::lastWeek(); $timeArr = Time::lastWeek();
break; break;
case 'month' : case 'month' :
$timeArr = Time::month(); $timeArr = Time::month();
$lastArr = Time::lastMonth();
break; break;
case 'lastMonth' : case 'lastMonth' :
$timeArr = Time::lastMonth(); $timeArr = Time::lastMonth();
$lastArr = Time::lastMonth(1);
break; break;
case 'quarter' : case 'quarter' :
//本季度 //本季度
@ -1341,25 +1828,7 @@ function getTimeByType($type = 'today', $is_last = false)
$daterange_start_time = strtotime(date('Y-10-01 00:00:00')); $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
$daterange_end_time = strtotime(date("Y-12-31 23:59:59")); $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
} }
//上季度
$month = date('m');
if ($month == 1 || $month == 2 || $month == 3) {
$year = date('Y') - 1;
$daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
$daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
} elseif ($month == 4 || $month == 5 || $month == 6) {
$daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
$daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
} elseif ($month == 7 || $month == 8 || $month == 9) {
$daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
$daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
} else {
$daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
$daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
}
$timeArr = array($daterange_start_time, $daterange_end_time); $timeArr = array($daterange_start_time, $daterange_end_time);
$lastArr = array($daterange_start_time_last_time, $daterange_end_time_last_time);
break; break;
case 'lastQuarter' : case 'lastQuarter' :
//上季度 //上季度
@ -1379,19 +1848,15 @@ function getTimeByType($type = 'today', $is_last = false)
$daterange_end_time = strtotime(date("Y-09-30 23:59:59")); $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
} }
$timeArr = array($daterange_start_time, $daterange_end_time); $timeArr = array($daterange_start_time, $daterange_end_time);
$lastArr = array($daterange_start_time_last_time, $daterange_end_time_last_time);
break; break;
case 'year' : case 'year' :
$timeArr = Time::year(); $timeArr = Time::year();
$lastArr = Time::lastYear();
break; break;
case 'lastYear' : case 'lastYear' :
$timeArr = Time::lastYear(); $timeArr = Time::lastYear();
$lastArr = Time::lastYear(1);
break; break;
default : default :
$timeArr = Time::today(); $timeArr = Time::today();
$lastArr = Time::yesterday();
break; break;
} }
if ($is_last) { if ($is_last) {
@ -1408,7 +1873,7 @@ function getTimeByType($type = 'today', $is_last = false)
function getFullPath($path) function getFullPath($path)
{ {
if ($path) { if ($path) {
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https'; $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
return $protocol . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER["SCRIPT_NAME"], 0, -10) . substr(str_replace(DS, '/', $path), 1); return $protocol . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER["SCRIPT_NAME"], 0, -10) . substr(str_replace(DS, '/', $path), 1);
} else { } else {
return ''; return '';
@ -2256,14 +2721,15 @@ if (!function_exists('getFieldGrantStatus')) {
return $result; return $result;
} }
}
/** /**
* 仪表盘日志使用 * 仪表盘日志使用
* 根据类型获取开始结束时间戳数组 * 根据类型获取开始结束时间戳数组
* @param * @param
*/ */
function ByDateTime($type = 'today') function ByDateTime($type = 'today')
{ {
switch ($type) { switch ($type) {
case 'yesterday' : case 'yesterday' :
$timeArr = DataTime::yesterday(); $timeArr = DataTime::yesterday();
@ -2271,7 +2737,7 @@ if (!function_exists('getFieldGrantStatus')) {
break; break;
case 'week' : case 'week' :
$timeArr = DataTime::week(); $timeArr = DataTime::week();
$timeArr['last_time'] = DataTime::lastWeek(1); $timeArr['last_time'] = DataTime::lastWeek();
break; break;
case 'lastWeek' : case 'lastWeek' :
$timeArr = DataTime::lastWeek(); $timeArr = DataTime::lastWeek();
@ -2279,7 +2745,7 @@ if (!function_exists('getFieldGrantStatus')) {
break; break;
case 'month' : case 'month' :
$timeArr = DataTime::month(); $timeArr = DataTime::month();
$timeArr['last_time'] = DataTime::lastMonth(1); $timeArr['last_time'] = DataTime::lastMonth();
break; break;
case 'lastMonth' : case 'lastMonth' :
$timeArr = DataTime::lastMonth(); $timeArr = DataTime::lastMonth();
@ -2318,9 +2784,8 @@ if (!function_exists('getFieldGrantStatus')) {
$daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00')); $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
$daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59")); $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
} }
$timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
$timeArr = array($daterange_start_time, $daterange_end_time); $timeArr = array($daterange_start_time, $daterange_end_time);
$timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
break; break;
case 'lastQuarter' : case 'lastQuarter' :
//上季度 //上季度
@ -2360,7 +2825,7 @@ if (!function_exists('getFieldGrantStatus')) {
break; break;
case 'year' : case 'year' :
$timeArr = DataTime::year(); $timeArr = DataTime::year();
$timeArr['last_time'] = DataTime::lastYear(1); $timeArr['last_time'] = DataTime::lastYear();
break; break;
case 'lastYear' : case 'lastYear' :
$timeArr = DataTime::lastYear(); $timeArr = DataTime::lastYear();
@ -2374,13 +2839,13 @@ if (!function_exists('getFieldGrantStatus')) {
break; break;
default : default :
$timeArr = DataTime::today(); $timeArr = DataTime::today();
$timeArr['last_time'] = DataTime::yesterday(1); $timeArr['last_time'] = DataTime::yesterday();
break; break;
} }
return $timeArr; return $timeArr;
} }
/** /**
* 系统操作日志 * 系统操作日志
* @param int $user_id 用户 * @param int $user_id 用户
* @param string $types 方法所属模块 * @param string $types 方法所属模块
@ -2395,8 +2860,8 @@ if (!function_exists('getFieldGrantStatus')) {
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/3/26 0026 15:10 * @since 2021/3/26 0026 15:10
*/ */
function SystemActionLog($user_id, $types, $module_name, $action_id, $action_name, $target_name, $oldData = [], $newData = [], $content = '') function SystemActionLog($user_id, $types, $module_name, $action_id, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
{ {
//action_name 修改添加删除新建 action_id 操作id client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module_name 模块 系统管理 固定 user_id 用户 //action_name 修改添加删除新建 action_id 操作id client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module_name 模块 系统管理 固定 user_id 用户
$data = []; $data = [];
$data['user_id'] = $user_id; $data['user_id'] = $user_id;
@ -2409,9 +2874,9 @@ if (!function_exists('getFieldGrantStatus')) {
$data['controller_name'] = $types; $data['controller_name'] = $types;
$data['content'] = $content; $data['content'] = $content;
db('admin_system_log')->insert($data); db('admin_system_log')->insert($data);
} }
/** /**
* 系统操作日志 * 系统操作日志
* @param int $user_id 用户 * @param int $user_id 用户
* @param string $types 方法所属模块 * @param string $types 方法所属模块
@ -2424,8 +2889,8 @@ if (!function_exists('getFieldGrantStatus')) {
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/2 0026 15:10 * @since 2021/4/2 0026 15:10
*/ */
function RecordActionLog($user_id, $types, $action_name, $target_name, $oldData = [], $newData = [], $content = '') function RecordActionLog($user_id, $types, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
{ {
//action_name 修改 添加 删除 client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module 模块 user_id 用户 //action_name 修改 添加 删除 client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module 模块 user_id 用户
if (is_array($oldData) && is_array($newData) && $user_id) { if (is_array($oldData) && is_array($newData) && $user_id) {
$differentData = array_diff_assoc($newData, $oldData); $differentData = array_diff_assoc($newData, $oldData);
@ -2526,5 +2991,123 @@ if (!function_exists('getFieldGrantStatus')) {
$data['content'] = $content; $data['content'] = $content;
db('admin_operation_log')->insert($data); db('admin_operation_log')->insert($data);
} }
}
if (!function_exists('getFieldGroupOrderData')) {
/**
* 对自定义字段进行分组排序
*
* @param array $data 自定义字段数据
* @return array
* @since 2021-04-27
* @author fanqi
*/
function getFieldGroupOrderData($data)
{
$formPositionEmpty = [];
$formPositionExist = [];
$result = [];
// 处理数据,将有位置信息和无位置信息的数据分开存放。
foreach ($data as $key => $value) {
if (empty($value['form_position'])) {
$formPositionEmpty[] = $value;
continue;
}
$formPositionArray = explode(',', $value['form_position']);
$x = (int)$formPositionArray[0];
$y = (int)$formPositionArray[1];
if (!isset($value['xaxis'])) $value['xaxis'] = $x;
if (!isset($value['yaxis'])) $value['yaxis'] = $y;
$formPositionExist[$x][$y] = $value;
}
// 排序
ksort($formPositionExist);
// 处理有位置信息的数据
foreach ($formPositionExist as $key => $value) {
foreach ($value as $k => $v) {
if (!empty($formPositionExist[$key][$k])) $result[$key][$k] = $v;
}
$result[$key] = array_values($result[$key]);
}
// 将无位置信息的数据放置尾端
foreach ($formPositionEmpty as $key => $value) {
$result[] = [$value];
}
return array_values($result);
} }
} }
if (!function_exists('getPrimaryKeyName')) {
/**
* 获取主键
*
* @param string $types 栏目类型
* @return string
* @since 2021-05-18
* @author fanqi
*/
function getPrimaryKeyName($types)
{
$primaryKey = '';
if ($types == 'crm_leads') $primaryKey = 'leads_id';
if ($types == 'crm_customer') $primaryKey = 'customer_id';
if ($types == 'crm_contacts') $primaryKey = 'contacts_id';
if ($types == 'crm_business') $primaryKey = 'business_id';
if ($types == 'crm_contract') $primaryKey = 'contract_id';
if ($types == 'crm_receivables') $primaryKey = 'receivables_id';
if ($types == 'crm_receivables_plan') $primaryKey = 'plan_id';
if ($types == 'crm_visit') $primaryKey = 'visit_id';
if ($types == 'crm_product') $primaryKey = 'product_id';
if ($types == 'crm_invoice') $primaryKey = 'invoice_id';
if ($types == 'oa_examine') $primaryKey = 'examine_id';
return $primaryKey;
}
}
function advancedQueryFormatForTeam($requestMap,$db,$db_id)
{
// 处理查询条件
foreach ($requestMap['team_id']['value'] as $v) {
if ($requestMap['team_id']['condition'] == 'contains') {
$date = function ($query) use ($v) {
$query->where('FIND_IN_SET("'.$v.'", ro_user_id)')
->whereOr('FIND_IN_SET("'.$v.'", rw_user_id)');
};
} elseif ($requestMap['team_id']['condition'] == 'notContains') {
$date = function ($query) use ($v) {
$query->where('FIND_IN_SET("'.$v.'", ro_user_id)')
->where('FIND_IN_SET("'.$v.'", rw_user_id)');
};
} elseif ($requestMap['team_id']['condition'] == 'isNull') {
$date = function ($query) {
$query->where('ro_user_id', ['eq', ''])
->whereOr('rw_user_id', 'null');
};
} elseif ($requestMap['team_id']['condition'] == 'isNotNull') {
$date = function ($query) {
$query->where('ro_user_id', ['neq', ''])
->where('rw_user_id', ['not null']);
};
}
$part[] = db($db)->where($date)->column($db_id);
}
$result = [];
array_walk_recursive($part, function($value) use (&$result) {
array_push($result, $value);
});
$result=array_unique($result);
$partMap['customer.customer_id'] = ['in', trim(arrayToString($result), ',')];
return $partMap ?: [];
}

@ -32,7 +32,7 @@ class PoolCommand extends Command
->setDescription('公海回收定时器'); ->setDescription('公海回收定时器');
// 读取数据库配置文件 // 读取数据库配置文件
$filename = ROOT_PATH . 'config'.DS.'database.php'; $filename = ROOT_PATH . 'config' . DS . 'database.php';
// 重新加载数据库配置文件 // 重新加载数据库配置文件
Config::load($filename, 'database'); Config::load($filename, 'database');
} }
@ -47,7 +47,7 @@ class PoolCommand extends Command
{ {
global $argv; global $argv;
$argv[1] = $input->getArgument('status') ? : 'start'; $argv[1] = $input->getArgument('status') ?: 'start';
if ($input->hasOption('d')) { if ($input->hasOption('d')) {
$argv[2] = '-d'; $argv[2] = '-d';
@ -100,7 +100,7 @@ class PoolCommand extends Command
'into_pool_time' => time() 'into_pool_time' => time()
]); ]);
} }
$this->updateInfo($ruleList,$customerWhere);
# 删除联系人的负责人 # 删除联系人的负责人
Db::name('crm_contacts')->whereIn('customer_id', $customerWhere)->update(['owner_user_id' => '']); Db::name('crm_contacts')->whereIn('customer_id', $customerWhere)->update(['owner_user_id' => '']);
@ -113,6 +113,8 @@ class PoolCommand extends Command
}); });
} }
protected function execute(Input $input, Output $output) protected function execute(Input $input, Output $output)
{ {
# 动态修改运行时参数 # 动态修改运行时参数
@ -133,16 +135,16 @@ class PoolCommand extends Command
* 整理修改客户数据的条件 * 整理修改客户数据的条件
* *
* @param array $customerIds 客户ID * @param array $customerIds 客户ID
* @author fanqi
* @since 2021-04-01
* @return array * @return array
* @since 2021-04-01
* @author fanqi
*/ */
private function getCustomerQueryCondition($customerIds) private function getCustomerQueryCondition($customerIds)
{ {
$result = []; $result = [];
foreach ($customerIds AS $k1 => $v1) { foreach ($customerIds as $k1 => $v1) {
foreach ($v1 AS $k2 => $v2) { foreach ($v1 as $k2 => $v2) {
$result[] = $v2; $result[] = $v2;
} }
} }
@ -154,9 +156,9 @@ class PoolCommand extends Command
* 客户公海关联数据 * 客户公海关联数据
* *
* @param array $customerIds 客户ID * @param array $customerIds 客户ID
* @author fanqi
* @since 2021-04-01
* @return array * @return array
* @since 2021-04-01
* @author fanqi
*/ */
private function getCustomerPoolRelationData($customerIds) private function getCustomerPoolRelationData($customerIds)
{ {
@ -165,9 +167,9 @@ class PoolCommand extends Command
# 用于排重 # 用于排重
$repeat = []; $repeat = [];
foreach ($customerIds AS $k1 => $v1) { foreach ($customerIds as $k1 => $v1) {
$customerArray = array_unique($v1); $customerArray = array_unique($v1);
foreach ($customerArray AS $k2 => $v2) { foreach ($customerArray as $k2 => $v2) {
if (!empty($repeat[$k1][$v2])) continue; if (!empty($repeat[$k1][$v2])) continue;
$result[] = [ $result[] = [
@ -186,17 +188,17 @@ class PoolCommand extends Command
* 获取符合公海条件的客户 * 获取符合公海条件的客户
* *
* @param array $rules 公海规则数据 * @param array $rules 公海规则数据
* @author fanqi
* @since 2021-04-01
* @return array * @return array
* @since 2021-04-01
* @author fanqi
*/ */
private function getQueryCondition($rules) private function getQueryCondition($rules)
{ {
$result = []; $result = [];
foreach ($rules AS $k => $v) { foreach ($rules as $k => $v) {
if (!isset($result[$v['pool_id']])) $result[$v['pool_id']] = [];
if (!isset($result[$v['pool_id']])) $result[$v['pool_id']] = [];
if ($v['type'] == 1) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getFollowUpQueryResult($v['level_conf'], $v['level'], $v['deal_handle'], $v['business_handle'])); if ($v['type'] == 1) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getFollowUpQueryResult($v['level_conf'], $v['level'], $v['deal_handle'], $v['business_handle']));
if ($v['type'] == 2) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getBusinessQueryResult($v['level_conf'], $v['level'], $v['deal_handle'])); if ($v['type'] == 2) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getBusinessQueryResult($v['level_conf'], $v['level'], $v['deal_handle']));
if ($v['type'] == 3) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getDealQueryResult($v['level_conf'], $v['level'], $v['business_handle'])); if ($v['type'] == 3) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getDealQueryResult($v['level_conf'], $v['level'], $v['business_handle']));
@ -212,9 +214,9 @@ class PoolCommand extends Command
* @param Json $levels 级别数据 * @param Json $levels 级别数据
* @param int $dealStatus 是否排除成交用户1 排除0 不排除 * @param int $dealStatus 是否排除成交用户1 排除0 不排除
* @param int $businessStatus 是否排除有商机用户1 排除0 不排除 * @param int $businessStatus 是否排除有商机用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array * @return array
* @since 2021-04-01
* @author fanqi
*/ */
private function getFollowUpQueryResult($type, $levels, $dealStatus, $businessStatus) private function getFollowUpQueryResult($type, $levels, $dealStatus, $businessStatus)
{ {
@ -226,23 +228,23 @@ class PoolCommand extends Command
# 所有用户,不区分级别 # 所有用户,不区分级别
if ($type == 1) { if ($type == 1) {
foreach ($levels AS $k1 => $v1) { foreach ($levels as $k1 => $v1) {
if (!empty($v1['limit_day'])) { if (!empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day']; $time = time() - 24 * 60 * 60 * $v1['limit_day'];
$where .= " AND ((`customer`.`last_time` < ".$time." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`obtain_time` < ".$time." AND ISNULL(`customer`.`last_time`)))"; $where .= " AND ((`customer`.`last_time` < " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`obtain_time` < " . $time . " AND ISNULL(`customer`.`last_time`)))";
} }
} }
} }
# 根据用户级别设置条件 # 根据用户级别设置条件
if ($type == 2) { if ($type == 2) {
foreach ($levels AS $k1 => $v1) { foreach ($levels as $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) { if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = (time() - 24 * 60 * 60 * $v1['limit_day']); $time = (time() - 24 * 60 * 60 * $v1['limit_day']);
if ($k1 == 0) { if ($k1 == 0) {
$where .= " AND ( ((`customer`.`level` = '".$v1['level']."' AND `customer`.`last_time` < ".$time." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < ".$time." AND ISNULL(`customer`.`last_time`)))"; $where .= " AND ( ((`customer`.`level` = '" . $v1['level'] . "' AND `customer`.`last_time` < " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '" . $v1['level'] . "' AND `customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '" . $v1['level'] . "' AND `customer`.`obtain_time` < " . $time . " AND ISNULL(`customer`.`last_time`)))";
} else { } else {
$where .= " OR ((`customer`.`level` = '".$v1['level']."' AND `customer`.`last_time` < " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < " . $time . " AND ISNULL(`customer`.`last_time`)))"; $where .= " OR ((`customer`.`level` = '" . $v1['level'] . "' AND `customer`.`last_time` < " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '" . $v1['level'] . "' AND `customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '" . $v1['level'] . "' AND `customer`.`obtain_time` < " . $time . " AND ISNULL(`customer`.`last_time`)))";
} }
} }
} }
@ -251,7 +253,7 @@ class PoolCommand extends Command
$minLimit = $this->getMinDay($levels); $minLimit = $this->getMinDay($levels);
$minTime = (time() - 24 * 60 * 60 * $minLimit); $minTime = (time() - 24 * 60 * 60 * $minLimit);
$where .= " OR ((!`customer`.`level` AND `customer`.`last_time` < ".$minTime." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` < ".$minTime." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` < ".$minTime." AND ISNULL(`customer`.`last_time`))) )"; $where .= " OR ((!`customer`.`level` AND `customer`.`last_time` < " . $minTime . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` < " . $minTime . " AND `customer`.`obtain_time` > `customer`.`last_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` < " . $minTime . " AND ISNULL(`customer`.`last_time`))) )";
} }
# 选择不进入公海的客户(已成交客户) # 选择不进入公海的客户(已成交客户)
@ -275,9 +277,9 @@ class PoolCommand extends Command
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分 * @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据 * @param Json $levels 级别数据
* @param int $dealStatus 是否排除成交用户1 排除0 不排除 * @param int $dealStatus 是否排除成交用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array|false|string * @return array|false|string
* @since 2021-04-01
* @author fanqi
*/ */
private function getBusinessQueryResult($type, $levels, $dealStatus) private function getBusinessQueryResult($type, $levels, $dealStatus)
{ {
@ -289,23 +291,23 @@ class PoolCommand extends Command
# 所有用户,不区分级别 # 所有用户,不区分级别
if ($type == 1) { if ($type == 1) {
foreach ($levels AS $k1 => $v1) { foreach ($levels as $k1 => $v1) {
if (!empty($v1['limit_day'])) { if (!empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day']; $time = time() - 24 * 60 * 60 * $v1['limit_day'];
$where .= " AND ( (ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$time.") OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `business`.`create_time`) OR (`business`.`create_time` < ".$time." AND `business`.`create_time` > `customer`.`obtain_time`) )"; $where .= " AND ( (ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < " . $time . ") OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `business`.`create_time`) OR (`business`.`create_time` < " . $time . " AND `business`.`create_time` > `customer`.`obtain_time`) )";
} }
} }
} }
# 根据用户级别设置条件 # 根据用户级别设置条件
if ($type == 2) { if ($type == 2) {
foreach ($levels AS $k1 => $v1) { foreach ($levels as $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) { if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day']; $time = time() - 24 * 60 * 60 * $v1['limit_day'];
if ($k1 == 0) { if ($k1 == 0) {
$where .= " AND ( ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`business`.`create_time` < ".$time." AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))"; $where .= " AND ( ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < " . $time . " AND `customer`.`level` = '" . $v1['level'] . "') OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '" . $v1['level'] . "') OR (`business`.`create_time` < " . $time . " AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '" . $v1['level'] . "'))";
} else { } else {
$where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`business`.`create_time` < ".$time." AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))"; $where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < " . $time . " AND `customer`.`level` = '" . $v1['level'] . "') OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '" . $v1['level'] . "') OR (`business`.`create_time` < " . $time . " AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '" . $v1['level'] . "'))";
} }
} }
} }
@ -314,7 +316,7 @@ class PoolCommand extends Command
$minLimit = $this->getMinDay($levels); $minLimit = $this->getMinDay($levels);
$minTime = (time() - 24 * 60 * 60 * $minLimit); $minTime = (time() - 24 * 60 * 60 * $minLimit);
$where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$minTime." AND !`customer`.`level`) OR (`customer`.`obtain_time` < ".$minTime." AND `customer`.`obtain_time` > `business`.`create_time` AND !`customer`.`level`) OR (`business`.`create_time` < ".$minTime." AND `business`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )"; $where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < " . $minTime . " AND !`customer`.`level`) OR (`customer`.`obtain_time` < " . $minTime . " AND `customer`.`obtain_time` > `business`.`create_time` AND !`customer`.`level`) OR (`business`.`create_time` < " . $minTime . " AND `business`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )";
} }
# 选择不进入公海的客户(已成交客户) # 选择不进入公海的客户(已成交客户)
@ -335,9 +337,9 @@ class PoolCommand extends Command
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分 * @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据 * @param Json $levels 级别数据
* @param int $businessStatus 是否排除有商机用户1 排除0 不排除 * @param int $businessStatus 是否排除有商机用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array|false|string * @return array|false|string
* @since 2021-04-01
* @author fanqi
*/ */
private function getDealQueryResult($type, $levels, $businessStatus) private function getDealQueryResult($type, $levels, $businessStatus)
{ {
@ -349,23 +351,23 @@ class PoolCommand extends Command
# 所有用户,不区分级别 # 所有用户,不区分级别
if ($type == 1) { if ($type == 1) {
foreach ($levels AS $k1 => $v1) { foreach ($levels as $k1 => $v1) {
if (!empty($v1['limit_day'])) { if (!empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day']; $time = time() - 24 * 60 * 60 * $v1['limit_day'];
$where .= " AND ( (ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$time.") OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `contract`.`create_time`) OR (`contract`.`create_time` < ".$time." AND `contract`.`create_time` > `customer`.`obtain_time`) )"; $where .= " AND ( (ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < " . $time . ") OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `contract`.`create_time`) OR (`contract`.`create_time` < " . $time . " AND `contract`.`create_time` > `customer`.`obtain_time`) )";
} }
} }
} }
# 根据用户级别设置条件 # 根据用户级别设置条件
if ($type == 2) { if ($type == 2) {
foreach ($levels AS $k1 => $v1) { foreach ($levels as $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) { if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day']; $time = time() - 24 * 60 * 60 * $v1['limit_day'];
if ($k1 == 0) { if ($k1 == 0) {
$where .= " AND ( ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `contract`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`contract`.`create_time` < ".$time." AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))"; $where .= " AND ( ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < " . $time . " AND `customer`.`level` = '" . $v1['level'] . "') OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `contract`.`create_time` AND `customer`.`level` = '" . $v1['level'] . "') OR (`contract`.`create_time` < " . $time . " AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '" . $v1['level'] . "'))";
} else { } else {
$where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `contract`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`contract`.`create_time` < ".$time." AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))"; $where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < " . $time . " AND `customer`.`level` = '" . $v1['level'] . "') OR (`customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `contract`.`create_time` AND `customer`.`level` = '" . $v1['level'] . "') OR (`contract`.`create_time` < " . $time . " AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '" . $v1['level'] . "'))";
} }
} }
} }
@ -374,7 +376,7 @@ class PoolCommand extends Command
$minLimit = $this->getMinDay($levels); $minLimit = $this->getMinDay($levels);
$minTime = (time() - 24 * 60 * 60 * $minLimit); $minTime = (time() - 24 * 60 * 60 * $minLimit);
$where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$minTime." AND !`customer`.`level`) OR (`customer`.`obtain_time` < ".$minTime." AND `customer`.`obtain_time` > `contract`.`create_time` AND !`customer`.`level`) OR (`contract`.`create_time` < ".$minTime." AND `contract`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )"; $where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < " . $minTime . " AND !`customer`.`level`) OR (`customer`.`obtain_time` < " . $minTime . " AND `customer`.`obtain_time` > `contract`.`create_time` AND !`customer`.`level`) OR (`contract`.`create_time` < " . $minTime . " AND `contract`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )";
} }
# 选择不进入公海的客户(有商机客户) # 选择不进入公海的客户(有商机客户)
@ -394,15 +396,15 @@ class PoolCommand extends Command
* 获取公海规则最小数字(最快进入公海天数) * 获取公海规则最小数字(最快进入公海天数)
* *
* @param $data * @param $data
* @author fanqi
* @since 2021-04-19
* @return int * @return int
* @since 2021-04-19
* @author fanqi
*/ */
private function getMinDay($data) private function getMinDay($data)
{ {
$number = 1; $number = 1;
foreach ($data AS $k1 => $v1) { foreach ($data as $k1 => $v1) {
if (empty($number) || $v1['limit_day'] < $number) $number = $v1['limit_day']; if (empty($number) || $v1['limit_day'] < $number) $number = $v1['limit_day'];
} }

@ -0,0 +1,153 @@
<?php
/**
* 使用定时器将符合条件的团队成员移出团队
*
* @author guogaobo
* @since 2021-05-20
*/
namespace app\common\command;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\response\Json;
use Workerman\Lib\Timer;
use Workerman\Worker;
class Team extends Command
{
protected $timer;
protected $interval = 10;
protected function configure()
{
$this->setName('team')
->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
->addOption('d', null, Option::VALUE_NONE, 'daemon守护进程方式启动')
->setDescription('团队成员移出定时器');
// 读取数据库配置文件
$filename = ROOT_PATH . 'config' . DS . 'database.php';
// 重新加载数据库配置文件
Config::load($filename, 'database');
}
/**
* 初始化
*
* @param Input $input
* @param Output $output
*/
protected function init(Input $input, Output $output)
{
global $argv;
$argv[1] = $input->getArgument('status') ?: 'start';
if ($input->hasOption('d')) {
$argv[2] = '-d';
} else {
unset($argv[2]);
}
}
/**
* 停止定时器
*/
public function stop()
{
Timer::del($this->timer);
}
/**
* 启动定时器
*/
public function start()
{
$this->timer = Timer::add(1, function () {
# 只在凌晨12点至6点间执行
if ((int)date('H') >= 0 && (int)date('H') < 6) {
# 团队成员过滤规则
db('crm_team')->where('target_time',0)->delete();
$ruleList = db('crm_team')
->where('target_time', '<', time())->select();
if (!empty($ruleList)) {
Db::startTrans();
try {
foreach ($ruleList as $v) {
switch ($v['types']) {
case 1 :
$data_name = 'customer_id';
$types = 'crm_customer';
$typesName = '客户';
break;
case 2 :
$data_name = 'contacts_id';
$types = 'crm_contacts';
$typesName = '联系人';
break;
case 3 :
$data_name = 'business_id';
$types = 'crm_business';
$typesName = '商机';
break;
case 4 :
$data_name = 'contract_id';
$types = 'crm_contract';
$typesName = '合同';
break;
case 5 :
$data_name = 'receivables_id';
$types = 'crm_receivables';
$typesName = '回款';
break;
}
$resData = db($types)->where([$data_name => $v['target_id']])->field('name,rw_user_id,ro_user_id')->find();
if ($v['types'] == 5) {
$resData = db($types)->where([$data_name => $v['target_id']])->field('number as name,rw_user_id,ro_user_id')->find();
}
$team_user_id = array_column($ruleList, 'team_user_id');
$old_rw_user_id = !empty($resData['rw_user_id']) ? explode(',', trim($resData['rw_user_id'], ',')) : []; //去重
//只读
$old_ro_user_id = !empty($resData['ro_user_id']) ? explode(',', trim($resData['ro_user_id'], ',')) : []; //去重
if ($v['auth'] == 1) {
$all_rw_user_id = $team_user_id ? array_diff($old_ro_user_id, $team_user_id) : ''; // 差集
$data['ro_user_id'] = $all_rw_user_id ? ',' . implode(',', $all_rw_user_id) . ',' : ''; //去空
} else {
$all_ro_user_id = $team_user_id ? array_diff($old_rw_user_id, $team_user_id) : ''; // 差集
$data['rw_user_id'] = $all_ro_user_id ? ',' . implode(',', $all_ro_user_id) . ',' : ''; //去空 ;
}
$upData = db($types)->where([$data_name => $v['target_id']])->update($data);
db('crm_team')->where(['target_id' => $v['target_id'], 'types' => $v['types'], 'team_user_id' => ['in', arrayToString($team_user_id)]])->delete();
}
Db::commit();
} catch (\Exception $e) {
Db::rollback();
}
}
}
});
}
protected function execute(Input $input, Output $output)
{
# 动态修改运行时参数
set_time_limit(0);
ini_set('memory_limit', '512M');
$this->init($input, $output);
# 创建定时器任务
$worker = new Worker();
$worker->name = 'team';
$worker->count = 1;
$worker->onWorkerStart = [$this, 'start'];
$worker->runAll();
}
}

@ -1,12 +1,11 @@
<?php <?php
//权限控制 //权限控制
\think\Hook::add('check_auth','app\\common\\behavior\\AuthenticateBehavior'); \think\Hook::add('check_auth', 'app\\common\\behavior\\AuthenticateBehavior');
use think\Db; use think\Db;
/** /**
* 处理相关团队 * 处理相关团队
* @author
* @param types 类型 * @param types 类型
* @param types 类型ID * @param types 类型ID
* @param type 权限 1只读2读写 * @param type 权限 1只读2读写
@ -14,8 +13,9 @@ use think\Db;
* @param is_del 1 移除操作, 2编辑操作, 3添加操作 * @param is_del 1 移除操作, 2编辑操作, 3添加操作
* @param owner_user_id 操作人 * @param owner_user_id 操作人
* @param is_module 相关 1相关不进行数据权限判断 * @param is_module 相关 1相关不进行数据权限判断
* @author
*/ */
function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id, $is_module = 0) function teamUserId($param, $types, $types_id, $type, $user_id, $is_del, $owner_user_id, $is_module = 0)
{ {
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$authIds = []; $authIds = [];
@ -40,23 +40,32 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
$data_name = 'contract_id'; $data_name = 'contract_id';
$authIds = $userModel->getUserByPer('crm', 'contract', 'teamsave'); $authIds = $userModel->getUserByPer('crm', 'contract', 'teamsave');
break; break;
case 'crm_receivables' :
$data_name = 'receivables_id';
$authIds = $userModel->getUserByPer('crm', 'receivables', 'teamsave');
break;
} }
if (!is_array($types_id) && $types_id) { if (!is_array($types_id) && $types_id) {
$types_id = [$types_id]; $types_id = [$types_id];
} }
$errorMessage = []; $errorMessage = [];
foreach ($types_id as $k=>$v) { foreach ($types_id as $k => $v) {
if ($types == 'crm_receivables') {
$resData = db($types)->where([$data_name => $v])->field('number as name,owner_user_id,rw_user_id,ro_user_id')->find();
} else {
$resData = db($types)->where([$data_name => $v])->field('name,owner_user_id,rw_user_id,ro_user_id')->find(); $resData = db($types)->where([$data_name => $v])->field('name,owner_user_id,rw_user_id,ro_user_id')->find();
if (!in_array($resData['owner_user_id'],$authIds) && $resData['owner_user_id'] && $is_module !== 1) { }
$errorMessage[] = $resData['name'].'处理团队操作失败,错误原因:无权限';
if (!in_array($resData['owner_user_id'], $authIds) && $resData['owner_user_id'] && $is_module !== 1) {
$errorMessage[] = $resData['name'] . '处理团队操作失败,错误原因:无权限';
continue; continue;
} }
$type = $type ? : 1; $type = $type ?: 1;
$data = []; $data = [];
//读写 //读写
$old_rw_user_id = stringToArray($resData['rw_user_id']) ? : []; //去重 $old_rw_user_id = stringToArray($resData['rw_user_id']) ?: []; //去重
//只读 //只读
$old_ro_user_id = stringToArray($resData['ro_user_id']) ? : []; //去重 $old_ro_user_id = stringToArray($resData['ro_user_id']) ?: []; //去重
if ($is_del == 1) { if ($is_del == 1) {
$all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $user_id) : ''; // 差集 $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $user_id) : ''; // 差集
$data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空 $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空
@ -76,7 +85,7 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
} else { } else {
$del_ro_user_id = []; //需要删除的只读 $del_ro_user_id = []; //需要删除的只读
$del_rw_user_id = []; //需要删除的读写 $del_rw_user_id = []; //需要删除的读写
foreach ($user_id as $key=>$val) { foreach ($user_id as $key => $val) {
if (in_array($val, $old_ro_user_id) && !in_array($val, $old_rw_user_id) && $type == 2) { if (in_array($val, $old_ro_user_id) && !in_array($val, $old_rw_user_id) && $type == 2) {
$del_ro_user_id[] = $val; $del_ro_user_id[] = $val;
} }
@ -100,12 +109,30 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
} }
} }
} }
$res = !empty($param['user_id']) ?$param['user_id'] :[];
$types_data = ['crm_leads' => 6, 'crm_customer' => 1, 'crm_contacts' => 2, 'crm_business' => 3, 'crm_contract' => 4, 'crm_receivables' => 5];
$target_time = $param['target_time'];
$request = [];
foreach ($res as $val) {
$request['team_user_id'] = $val;
$request['target_time'] = $target_time;
$request['auth'] = $type;
$request['target_id'] = $v;
$dataInfo = db('crm_team')->where(['target_id' => $v, 'types' => $types_data[$types],'team_user_id'=>$val])->find();
if ($dataInfo) {
$res = db('crm_team')->where(['target_id' => $v, 'types' => $types_data[$types],'team_user_id'=>$val])->update($request);
} else {
$request['types'] = $types_data[$types];
$res = db('crm_team')->insert($request);
}
}
$upData = db($types)->where([$data_name => $v])->update($data); $upData = db($types)->where([$data_name => $v])->update($data);
if (!$upData) { if (!$upData && !$res) {
$errorMessage[] = $resData['name'].'处理团队操作失败'; $errorMessage[] = $resData['name'] . '处理团队操作失败';
} }
} }
return $errorMessage ? : 1; return $errorMessage ?: 1;
} }
//根据时间段获取所包含的年份 //根据时间段获取所包含的年份
@ -114,7 +141,7 @@ function getYearByTime($start_time, $end_time)
$yearArr = []; $yearArr = [];
$monthArr = monthList($start_time, $end_time); $monthArr = monthList($start_time, $end_time);
foreach ($monthArr as $v) { foreach ($monthArr as $v) {
$yearArr[date('Y',$v)] = date('Y',$v); $yearArr[date('Y', $v)] = date('Y', $v);
} }
return $yearArr; return $yearArr;
} }
@ -125,7 +152,60 @@ function getmonthByTime($start_time, $end_time)
$monthList = []; $monthList = [];
$monthArr = monthList($start_time, $end_time); $monthArr = monthList($start_time, $end_time);
foreach ($monthArr as $v) { foreach ($monthArr as $v) {
$monthList[date('Y',$v)][] = date('m',$v); $monthList[date('Y', $v)][] = date('m', $v);
} }
return $monthList; return $monthList;
} }
function encrypt($data, $key)
{
header('Content-type:text/html;charset=utf-8');
$key = md5($key);
$x = 0;
$len = mb_strlen($data);
$l = mb_strlen($key);
for ($i = 0; $i < $len; $i++) {
if ($x == $l) {
$x = 0;
}
$char .= $key{$x};
$x++;
}
for ($i = 0; $i < $len; $i++) {
$str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
}
return base64_encode($str);
}
/**
* [对加密的数据进行解密]
* @E-mial wuliqiang_aa@163.com
* @TIME 2017-04-07
* @WEB http://blog.iinu.com.cn
* @param [数据] $data [已经进行加密的数据]
* @param [密钥] $key [解密的唯一方法]
*/
function decrypt($data, $key = '72-crm')
{
header('Content-type:text/html;charset=utf-8');
$key = md5($key);
$x = 0;
$data = base64_decode($data);
$len = mb_strlen($data);
$l = mb_strlen($key);
for ($i = 0; $i < $len; $i++) {
if ($x == $l) {
$x = 0;
}
$char .= mb_substr($key, $x, 1);
$x++;
}
for ($i = 0; $i < $len; $i++) {
if (ord(mb_substr($data, $i, 1)) < ord(mb_substr($char, $i, 1))) {
$str .= chr((ord(mb_substr($data, $i, 1)) + 256) - ord(mb_substr($char, $i, 1)));
} else {
$str .= chr(ord(mb_substr($data, $i, 1)) - ord(mb_substr($char, $i, 1)));
}
}
return $str;
}

@ -5,6 +5,7 @@
* @author qifan * @author qifan
* @date 2020-12-09 * @date 2020-12-09
*/ */
namespace app\crm\controller; namespace app\crm\controller;
use app\admin\controller\ApiCommon; use app\admin\controller\ApiCommon;
@ -23,10 +24,10 @@ class Activity extends ApiCommon
public function _initialize() public function _initialize()
{ {
$action = [ $action = [
'permission'=>[], 'permission' => [],
'allow'=>['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth','excelimport','excelexport','exceldownload'] 'allow' => ['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth', 'excelimport', 'excelexport', 'exceldownload']
]; ];
Hook::listen('check_auth',$action); Hook::listen('check_auth', $action);
$request = Request::instance(); $request = Request::instance();
$a = strtolower($request->action()); $a = strtolower($request->action());
if (!in_array($a, $action['permission'])) { if (!in_array($a, $action['permission'])) {
@ -137,12 +138,13 @@ class Activity extends ApiCommon
*/ */
public function delete(ActivityLogic $activityLogic) public function delete(ActivityLogic $activityLogic)
{ {
$userInfo = $this->userInfo;
if (!checkPerByAction('crm', 'activity', 'delete')) { if (!checkPerByAction('crm', 'activity', 'delete')) {
return resultArray(['error' => '你没有删除跟进记录的权限!']); return resultArray(['error' => '你没有删除跟进记录的权限!']);
} }
if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']); if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
if (!$activityLogic->delete($this->param['activity_id'])) return resultArray(['error' => '操作失败!']); if (!$activityLogic->delete($this->param['activity_id'], $userInfo['id'])) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
@ -194,18 +196,20 @@ class Activity extends ApiCommon
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 导入模板下载 * 导入模板下载
* @author alvin guogaobo * @author alvin guogaobo
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/10 0010 16:01 * @since 2021/4/10 0010 16:01
*/ */
public function excelDownload($save_path = ''){ public function excelDownload($save_path = '')
{
$param = $this->param; $param = $this->param;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
$field_list=$this->importData($param); $field_list = $this->importData($param);
$types='crm_activity'; $types = 'crm_activity';
$excelModel->importDown($field_list,$types,$save_path); $excelModel->excelImportDownload($field_list, $types, $save_path);
} }
/** /**
@ -216,157 +220,139 @@ class Activity extends ApiCommon
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/13 0013 11:15 * @since 2021/4/13 0013 11:15
*/ */
public function importData($param){ public function importData($param)
switch ($param['label']){ {
$field_list = [];
switch ($param['crmType']) {
case 1 : case 1 :
$field = [ $field = [
'2' => [ '2' => [
'name' => '所属线索', 'name' => '所属线索',
'field' => 'activity_type_id', 'field' => 'activity_type_id',
'types' => 'log', 'form_type' => 'leads_id',
'form_type' => 'datetime',
'is_null' => 1, 'is_null' => 1,
] ]
]; ];
$name = '所属线索';
break; break;
case 3: case 3:
$field = [ $field = [
'2' => [ '2' => [
'name' => '所属联系人', 'name' => '所属联系人',
'field' => 'activity_type_id', 'field' => 'activity_type_id',
'types' => 'log', 'form_type' => 'contacts_id',
'form_type' => 'datetime',
'is_null' => 1, 'is_null' => 1,
], ],
]; ];
$name = '所属联系人';
break; break;
case 5: case 5:
$field = [ $field = [
'2' => [ '2' => [
'name' => '所属商机', 'name' => '所属商机',
'field' => 'activity_type_id', 'field' => 'activity_type_id',
'types' => 'log', 'form_type' => 'business_id',
'form_type' => 'text',
'is_null' => 1, 'is_null' => 1,
] ],
]; ];
$name = '所属商机';
break; break;
case 6: case 6:
$field = [ $field = [
'2' => [ '2' => [
'name' => '所属合同', 'name' => '所属合同',
'field' => 'activity_type_id', 'field' => 'activity_type_id',
'types' => 'log', 'form_type' => 'contract_id',
'form_type' => 'text',
'is_null' => 1, 'is_null' => 1,
], ],
]; ];
$name = '所属合同';
break; break;
case 2: case 2:
$field_list = [ $field = [
'0' => [
'name' => '跟进内容',
'field' => 'content',
'types' => 'log',
'form_type' => 'text',
'is_null' => 1,
],
'1' => [
'name' => '创建人',
'field' => 'create_user_id',
'types' => 'log',
'form_type' => 'user',
'is_null' => 1,
],
'2' => [ '2' => [
'name' => '所属客户', 'name' => '所属客户',
'field' => 'activity_type_id', 'field' => 'activity_type_id',
'types' => 'log', 'form_type' => 'customer_id',
'form_type' => 'text',
'is_null' => 1, 'is_null' => 1,
], ],
'3' => [
'name' => '跟进时间-例:2020-2-1',
'field' => 'next_time',
'types' => 'log',
'form_type' => 'datetime',
],
'4' => [
'name' => '跟进方式',
'field' => 'category',
'types' => 'log',
'form_type' => 'text',
],
'5' => [
'name' => '相关联系人',
'field' => 'contacts_ids',
'types' => 'log',
'form_type' => 'text',
],
'6' => [
'name' => '相关商机',
'field' => 'business_ids',
'types' => 'log',
'form_type' => 'text',
]
]; ];
$name = '所属客户';
break; break;
} }
$fields = [ $fields = [
'0' => [ '0' => [
'name' => '跟进内容', 'name' => '跟进内容',
'field' => 'content', 'field' => 'content',
'types' => 'log',
'form_type' => 'text', 'form_type' => 'text',
'is_null' => 1, 'is_null' => 1,
], ],
'1' => [ '1' => [
'name' => '创建人', 'name' => '创建人',
'field' => 'create_user_id', 'field' => 'create_user_id',
'types' => 'log',
'form_type' => 'user', 'form_type' => 'user',
'is_null' => 1, 'is_null' => 1,
], ],
'2' => [ '2' => [
'name' => '所属111',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'is_null' => 1,
],
'3' => [
'name' => '跟进时间-例:2020-2-1', 'name' => '跟进时间-例:2020-2-1',
'field' => 'next_time', 'field' => 'next_time',
'types' => 'log',
'form_type' => 'datetime', 'form_type' => 'datetime',
], ],
'4' => [ '3' => [
'name' => '跟进方式', 'name' => '跟进方式',
'field' => 'category', 'field' => 'category',
'types' => 'log', 'form_type' => 'select',
'form_type' => 'text', 'setting' =>
array
(
0 => "见面拜访",
1 => "电话",
2 => "短信",
3 => "邮件",
4 => "微信"
)
], ],
]; ];
// 导入的字段列表 // 导入的字段列表
if(!empty($param['down'])){ if ($param['is_excel']) {
$field_list = [ $field_lists = [
'0' => ['name' => '所属客户', 'field' => 'activity_type_name'], '0' => ['name' => $name, 'field' => 'activity_type_name'],
'1' => ['name' => '跟进内容', 'field' => 'content'], '1' => ['name' => '跟进内容', 'field' => 'content'],
'2' => ['name' => '创建人', 'field' => 'create_user_name'], '2' => ['name' => '创建人', 'field' => 'create_user_name'],
'3' => ['name' => '跟进时间', 'field' => 'create_time'], '3' => ['name' => '跟进时间', 'field' => 'create_time'],
'4' => ['name' => '跟进方式','field' => 'category'], '4' => ['name' => '跟进方式', 'field' => 'category'],
'5' => ['name' => '下次联系时间', 'field' => 'next_time'], '5' => ['name' => '下次联系时间', 'field' => 'next_time']
];
if ($param['crmType'] == 2) {
$fields = [
'6' => ['name' => '相关联系人', 'field' => 'contacts_ids'], '6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
'7' => ['name' => '相关商机', 'field' => 'business_ids'], '7' => ['name' => '相关商机', 'field' => 'business_ids'],];
$field_list = array_merge($field_lists, $fields);
} else {
$field_list =$field_lists;
}
} else {
$first_array = array_splice($fields, 2, 0, $field);
$field_list = $fields;
if ($param['crmType'] == 2) {
$field = [
'5' => [
'name' => '相关联系人',
'field' => 'contacts_ids',
'form_type' => 'contacts_id',
],
'6' => [
'name' => '相关商机',
'field' => 'business_ids',
'form_type' => 'business_id',
]
]; ];
}else{ $field_list = array_merge($field_list, $field);
if(empty($field_list)){
$field_list=array_merge($fields,$field);
} }
} }
return $field_list; return $field_list;
} }
/** /**
* 导入数据 * 导入数据
* *
@ -374,34 +360,37 @@ class Activity extends ApiCommon
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/10 0010 16:27 * @since 2021/4/10 0010 16:27
*/ */
public function excelImport(){ public function excelImport()
{
$param = $this->param; $param = $this->param;
$field_list=$this->importData($param['label']); $userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$field_list = $this->importData($param);
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
$file = request()->file('file'); $file = request()->file('file');
switch ($param['label']){ switch ($param['crmType']) {
case 1 : case 1 :
$param['types']='crm_leads'; $param['types'] = 'crm_leads';
$param['activity_type']=1; $param['activity_type'] = 1;
break; break;
case 3: case 3:
$param['types']='crm_contacts'; $param['types'] = 'crm_contacts';
$param['activity_type']=3; $param['activity_type'] = 3;
break; break;
case 5: case 5:
$param['types']='crm_business'; $param['types'] = 'crm_business';
$param['activity_type']=5; $param['activity_type'] = 5;
break; break;
case 6: case 6:
$param['types']='crm_contract'; $param['types'] = 'crm_contract';
$param['activity_type']=6; $param['activity_type'] = 6;
break; break;
case 2: case 2:
$param['types']='crm_customer'; $param['types'] = 'crm_customer';
$param['activity_type']=2; $param['activity_type'] = 2;
break; break;
} }
$res = $excelModel->ActivityImport($file,$field_list, $param,$this); $res = $excelModel->ActivityImport($file, $field_list, $param, $this);
if (!$res) { if (!$res) {
return resultArray(['error' => $excelModel->getError()]); return resultArray(['error' => $excelModel->getError()]);
} }
@ -417,16 +406,19 @@ class Activity extends ApiCommon
* @version 1.0 版本号 * @version 1.0 版本号
* @since 2021/4/13 0013 11:32 * @since 2021/4/13 0013 11:32
*/ */
public function excelExport(){ public function excelExport()
{
$activityLogic=new ActivityLogic(); $activityLogic = new ActivityLogic();
$indexLogic=new \app\crm\logic\IndexLogic(); $indexLogic = new \app\crm\logic\IndexLogic();
$userInfo = $this->userInfo;
$param = $this->param; $param = $this->param;
$param['action']='crm_activity'; $param['action'] = 'crm_activity';
$list=$indexLogic->activityList($param); $param['is_excel'] = 1;
// $param['down']=1; $param['id'] = $userInfo['id'];
$field_list=$this->importData($param); $list = $indexLogic->activityList($param);
$data=$activityLogic->excelExport($field_list,$list); $field_list = $this->importData($param);
$data = $activityLogic->excelExport($field_list, $list);
return $data; return $data;
} }
} }

@ -190,6 +190,8 @@ class Business extends ApiCommon
if (!$data) { if (!$data) {
return resultArray(['error' => $businessModel->getError()]); return resultArray(['error' => $businessModel->getError()]);
} }
// 删除客户扩展数据
db('crm_business_data')->whereIn('business_id', $delIds)->delete();
//删除跟进记录 //删除跟进记录
$recordModel->delDataByTypes(5, $delIds); $recordModel->delDataByTypes(5, $delIds);
//删除关联附件 //删除关联附件
@ -231,6 +233,8 @@ class Business extends ApiCommon
$list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']); $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
} }
cache($key, $list, config('business_status_cache_time')); cache($key, $list, config('business_status_cache_time'));
}else{
cache($key, NULL);
} }
return resultArray(['data' => $list]); return resultArray(['data' => $list]);
@ -252,7 +256,6 @@ class Business extends ApiCommon
$settingModel = model('Setting'); $settingModel = model('Setting');
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$authIds = $userModel->getUserByPer(); //权限范围的user_id $authIds = $userModel->getUserByPer(); //权限范围的user_id
if (!$param['owner_user_id']) { if (!$param['owner_user_id']) {
return resultArray(['error' => '变更负责人不能为空']); return resultArray(['error' => '变更负责人不能为空']);
} }
@ -278,12 +281,14 @@ class Business extends ApiCommon
} }
//权限判断 //权限判断
if (!in_array($businessInfo['owner_user_id'], $authIds)) { if (!in_array($businessInfo['owner_user_id'], $authIds)) {
$errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:无权限;'; $errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:无权限;';
continue; continue;
} }
//团队成员 //团队成员
teamUserId( teamUserId(
$param,
'crm_business', 'crm_business',
$business_id, $business_id,
$type, $type,

@ -105,7 +105,7 @@ class BusinessStatus extends ApiCommon
$businessStatusModel = model('BusinessStatus'); $businessStatusModel = model('BusinessStatus');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id']=$userInfo['id'];
$res = $businessStatusModel->updateDataById($param, $param['type_id']); $res = $businessStatusModel->updateDataById($param, $param['type_id']);
if ($res) { if ($res) {
$key = 'BI_queryCache_StatusList_Data'; $key = 'BI_queryCache_StatusList_Data';
@ -156,7 +156,9 @@ class BusinessStatus extends ApiCommon
{ {
$businessStatusModel = model('BusinessStatus'); $businessStatusModel = model('BusinessStatus');
$param = $this->param; $param = $this->param;
$data = $businessStatusModel->delDataById($param['id'], true); $userInfo=$this->userInfo;
$param['user_id']=$userInfo['id'];
$data = $businessStatusModel->delDataById($param, true);
if (!$data) { if (!$data) {
return resultArray(['error' => $businessStatusModel->getError()]); return resultArray(['error' => $businessStatusModel->getError()]);
} }

@ -175,11 +175,14 @@ class Contacts extends ApiCommon
$delIds[] = $v; $delIds[] = $v;
} }
} }
$dataInfo = $contactsModel->getDataById($v);
if ($delIds) { if ($delIds) {
$data = $contactsModel->delDatas($delIds); $data = $contactsModel->delDatas($delIds);
if (!$data) { if (!$data) {
return resultArray(['error' => $contactsModel->getError()]); return resultArray(['error' => $contactsModel->getError()]);
} }
// 删除联系人扩展数据
db('crm_contacts_data')->whereIn('contacts_id', $delIds)->delete();
//删除跟进记录 //删除跟进记录
$recordModel->delDataByTypes(3,$delIds); $recordModel->delDataByTypes(3,$delIds);
//删除关联附件 //删除关联附件
@ -188,8 +191,8 @@ class Contacts extends ApiCommon
$actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]); $actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
foreach ($contacts_id as $k => $v) { foreach ($contacts_id as $k => $v) {
$data = $contactsModel->getDataById($v);
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $data['name'], '', '', '删除了联系人:' . $data['name']); RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $dataInfo['name'], '', '', '删除了联系人:' . $dataInfo['name']);
} }
} }
if ($errorMessage) { if ($errorMessage) {
@ -270,6 +273,7 @@ class Contacts extends ApiCommon
*/ */
public function excelDownload($save_path = '') public function excelDownload($save_path = '')
{ {
# 下次升级
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
@ -279,35 +283,22 @@ class Contacts extends ApiCommon
$fieldParam['types'] = 'crm_contacts'; $fieldParam['types'] = 'crm_contacts';
$fieldParam['action'] = 'excel'; $fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam); $field_list = $fieldModel->field($fieldParam);
$res = $excelModel->excelImportDownload($field_list, 'crm_contacts', $save_path); $array=[];
# 下次升级 $field=[1=>[
// $param = $this->param; 'field'=>'owner_user_id',
// $userInfo = $this->userInfo; 'types'=>'crm_contacts',
// $excelModel = new \app\admin\model\Excel(); 'name'=>'负责人',
// 'form_type'=>'user',
// // 导出的字段列表 'default_value'=>'',
// $fieldModel = new \app\admin\model\Field(); 'is_null' => 1,
// $fieldParam['types'] = 'crm_contacts'; 'input_tips' =>'',
// $fieldParam['action'] = 'excel'; 'setting' => Array(),
// $field_list = $fieldModel->field($fieldParam); 'is_hidden'=>0,
// $array=[]; 'writeStatus' => 1,
// $field=[1=>[ 'value' => '']
// 'field'=>'owner_user_id', ];
// 'types'=>'crm_contacts', $first_array = array_splice($field_list, 2,0, $field);
// 'name'=>'负责人', $excelModel->excelImportDownload($field_list, 'crm_contacts', $save_path);
// 'form_type'=>'user',
// 'default_value'=>'',
// 'is_unique' => 1,
// 'is_null' => 1,
// 'input_tips' =>'',
// 'setting' => Array(),
// 'is_hidden'=>0,
// 'writeStatus' => 1,
// 'value' => '']
// ];
// $first_array = array_splice($field_list, 0, 2);
// $array = array_merge($first_array, $field, $field_list);
// $res = $excelModel->excelImportDownload($array, 'crm_contacts', $save_path);
} }
/** /**
@ -331,7 +322,7 @@ class Contacts extends ApiCommon
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$field_list = $fieldModel->getIndexFieldConfig('crm_contacts', $userInfo['id']); $field_list = $fieldModel->getIndexFieldConfig('crm_contacts', $userInfo['id'],'','excel');
// 文件名 // 文件名
$file_name = '5kcrm_contacts_'.date('Ymd'); $file_name = '5kcrm_contacts_'.date('Ymd');
@ -534,6 +525,13 @@ class Contacts extends ApiCommon
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
# 团队成员
$contacts = Db::name('crm_contacts')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contacts_id', $contactsId)->find();
$contacts['ro_user_id'] = stringToArray($contacts['ro_user_id']);
$contacts['rw_user_id'] = stringToArray($contacts['rw_user_id']);
$contacts['owner_user_id'] = [$contacts['owner_user_id']];
$teamCount = array_filter(array_unique(array_merge($contacts['ro_user_id'], $contacts['rw_user_id'], $contacts['owner_user_id'])));
# 查询联系人和商机的关联表 # 查询联系人和商机的关联表
$businessIds = Db::name('crm_contacts_business')->where('contacts_id', $contactsId)->column('business_id'); $businessIds = Db::name('crm_contacts_business')->where('contacts_id', $contactsId)->column('business_id');
@ -548,7 +546,8 @@ class Contacts extends ApiCommon
$data = [ $data = [
'businessCount' => $businessCount, 'businessCount' => $businessCount,
'fileCount' => $fileCount 'fileCount' => $fileCount,
'memberCount' => count($teamCount),
]; ];
return resultArray(['data' => $data]); return resultArray(['data' => $data]);

@ -343,6 +343,8 @@ class Contract extends ApiCommon
if (!$data) { if (!$data) {
return resultArray(['error' => $contractModel->getError()]); return resultArray(['error' => $contractModel->getError()]);
} }
// 删除合同扩展数据
db('crm_contract_data')->whereIn('contract_id', $delIds)->delete();
//删除跟进记录 //删除跟进记录
$recordModel->delDataByTypes(6,$delIds); $recordModel->delDataByTypes(6,$delIds);
//删除关联附件 //删除关联附件
@ -414,6 +416,7 @@ class Contract extends ApiCommon
//团队成员 //团队成员
teamUserId( teamUserId(
$param,
'crm_contract', 'crm_contract',
$contract_id, $contract_id,
$type, $type,
@ -707,7 +710,6 @@ class Contract extends ApiCommon
$field_list = $fieldModel->getIndexFieldConfig('crm_contract', $userInfo['id']); $field_list = $fieldModel->getIndexFieldConfig('crm_contract', $userInfo['id']);
// 文件名 // 文件名
$file_name = '5kcrm_contract_'.date('Ymd'); $file_name = '5kcrm_contract_'.date('Ymd');
$model = model('Contract'); $model = model('Contract');
$temp_file = $param['temp_file']; $temp_file = $param['temp_file'];
unset($param['temp_file']); unset($param['temp_file']);

@ -82,6 +82,7 @@ class Customer extends ApiCommon
$customerModel = model('Customer'); $customerModel = model('Customer');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$param['create_user_id'] = $userInfo['id']; $param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
if ($res = $customerModel->createData($param)) { if ($res = $customerModel->createData($param)) {
@ -235,11 +236,13 @@ class Customer extends ApiCommon
if (!$delRes) { if (!$delRes) {
return resultArray(['error' => $customerModel->getError()]); return resultArray(['error' => $customerModel->getError()]);
} }
//删除跟进记录 // 删除客户扩展数据
db('crm_customer_data')->whereIn('customer_id', $delIds)->delete();
// 删除跟进记录
$recordModel->delDataByTypes(2, $delIds); $recordModel->delDataByTypes(2, $delIds);
//删除关联附件 // 删除关联附件
$fileModel->delRFileByModule('crm_customer', $delIds); $fileModel->delRFileByModule('crm_customer', $delIds);
//删除关联操作记录 // 删除关联操作记录
$actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]); $actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]);
foreach ($dataInfo as $k => $v) { foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']); RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']);
@ -404,7 +407,7 @@ class Customer extends ApiCommon
$userId = $userInfo['id']; $userId = $userInfo['id'];
$customerIds = $this->param['customer_id']; $customerIds = $this->param['customer_id'];
$poolId = $this->param['pool_id']; $poolId = $this->param['pool_id'];
$customerModel=new \app\crm\model\Customer();
# 消息数据 # 消息数据
$message = []; $message = [];
@ -429,7 +432,10 @@ class Customer extends ApiCommon
continue; continue;
} }
if (!$customerModel->checkData($value)) {
$message[] = '"' . $customerData[$value]['name'] . '"放入公海失败,错误原因:无权限';
continue;
}
if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) { if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
$message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!'; $message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
unset($customerIds[(int)$key]); unset($customerIds[(int)$key]);
@ -767,7 +773,7 @@ class Customer extends ApiCommon
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$field_list = $fieldModel->getIndexFieldConfig('crm_customer', $userInfo['id']); $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $userInfo['id'],'','excel');
// 文件名 // 文件名
$file_name = '5kcrm_customer_' . date('Ymd'); $file_name = '5kcrm_customer_' . date('Ymd');
@ -796,43 +802,30 @@ class Customer extends ApiCommon
*/ */
public function excelDownload($save_path = '') public function excelDownload($save_path = '')
{ {
# 下次升级
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
// 导入的字段列表 // 导入的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$fieldParam['types'] = 'crm_customer'; $fieldParam['types'] = 'crm_customer';
$fieldParam['action'] = 'excel'; $fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam); $field_list = $fieldModel->field($fieldParam);
$field=[1=>[
'field'=>'owner_user_id',
'types'=>'crm_customer',
'name'=>'负责人',
'form_type'=>'user',
'default_value'=>'',
'is_null' => 1,
'input_tips' =>'',
'setting' => Array(),
'is_hidden'=>0,
'writeStatus' => 1,
'value' => '']
];
$first_array = array_splice($field_list, 2,0, $field);
$excelModel->excelImportDownload($field_list, 'crm_customer', $save_path); $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
# 下次升级
// $param = $this->param;
// $userInfo = $this->userInfo;
// $excelModel = new \app\admin\model\Excel();
//
// // 导入的字段列表
// $fieldModel = new \app\admin\model\Field();
// $fieldParam['types'] = 'crm_customer';
// $fieldParam['action'] = 'excel';
// $field_list = $fieldModel->field($fieldParam);
// $field=[1=>[
// 'field'=>'owner_user_id',
// 'types'=>'crm_customer',
// 'name'=>'负责人',
// 'form_type'=>'user',
// 'default_value'=>'',
// 'is_unique' => 1,
// 'is_null' => 1,
// 'input_tips' =>'',
// 'setting' => Array(),
// 'is_hidden'=>0,
// 'writeStatus' => 1,
// 'value' => '']
// ];
// $first_array = array_splice($field_list, 2,0, $field);
// $array = array_merge($first_array, $field, $field_list);
// $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
} }

@ -44,7 +44,7 @@ class CustomerPool extends ApiCommon
'export' 'export'
] ]
]; ];
Hook::listen('check_auth',$action); Hook::listen('check_auth', $action);
$request = Request::instance(); $request = Request::instance();
$a = strtolower($request->action()); $a = strtolower($request->action());
if (!in_array($a, $action['permission'])) { if (!in_array($a, $action['permission'])) {
@ -55,9 +55,9 @@ class CustomerPool extends ApiCommon
/** /**
* 公海列表 * 公海列表
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function index() public function index()
{ {
@ -71,9 +71,9 @@ class CustomerPool extends ApiCommon
/** /**
* 详情 * 详情
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function read() public function read()
{ {
@ -91,9 +91,9 @@ class CustomerPool extends ApiCommon
/** /**
* 删除公海客户 * 删除公海客户
* *
* @author fanqi
* @since 2021-04-15
* @return Json * @return Json
* @since 2021-04-15
* @author fanqi
*/ */
public function delete() public function delete()
{ {
@ -111,9 +111,9 @@ class CustomerPool extends ApiCommon
/** /**
* 公海池列表 * 公海池列表
* *
* @author fanqi
* @since 2021-04-13
* @return Json * @return Json
* @since 2021-04-13
* @author fanqi
*/ */
public function pondList() public function pondList()
{ {
@ -125,9 +125,9 @@ class CustomerPool extends ApiCommon
/** /**
* 公海字段 * 公海字段
* *
* @author fanqi
* @since 2021-04-13
* @return Json * @return Json
* @since 2021-04-13
* @author fanqi
*/ */
public function field() public function field()
{ {
@ -145,9 +145,9 @@ class CustomerPool extends ApiCommon
/** /**
* 高级筛选字段列表 * 高级筛选字段列表
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function advanced() public function advanced()
{ {
@ -161,9 +161,9 @@ class CustomerPool extends ApiCommon
/** /**
* 领取公海池客户 * 领取公海池客户
* *
* @author fanqi
* @since 2021-04-15
* @return Json * @return Json
* @since 2021-04-15
* @author fanqi
*/ */
public function receive() public function receive()
{ {
@ -182,9 +182,9 @@ class CustomerPool extends ApiCommon
/** /**
* 分配公海客户 * 分配公海客户
* *
* @author fanqi
* @since 2021-04-15
* @return Json * @return Json
* @since 2021-04-15
* @author fanqi
*/ */
public function distribute() public function distribute()
{ {
@ -199,28 +199,29 @@ class CustomerPool extends ApiCommon
} }
// 公海客户导入模板下载 // 公海客户导入模板下载
public function excelDownload($save_path='') public function excelDownload($save_path = '')
{ {
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
$param=$this->param; $param = $this->param;
$field_list=$this->fieldsData($param); $field_list = $this->fieldsData($param);
$excelModel->excelImportDownload($field_list, 'crm_customer', $save_path); $excelModel->excelImportDownload($field_list, 'crm_pool', $save_path);
} }
// 导入 // 导入
public function import() public function import()
{ {
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
$param['create_user_id'] = $userInfo['id']; $param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $userInfo['id'];
$param['deal_time'] = time(); $param['deal_time'] = time();
$param['types'] = 'crm_customer'; $param['types'] = 'crm_customer';
$param['deal_status'] = '未成交';
$file = request()->file('file'); $file = request()->file('file');
// $res = $excelModel->importExcel($file, $param, $this); // $res = $excelModel->importExcel($file, $param, $this);
$res = $excelModel->batchImportData($file, $param, $this); $res = $excelModel->batchImportData($file, $param, $this);
RecordActionLog($userInfo['id'],'crm_customer','excel','导入公海客户','','','导入公海客户'); RecordActionLog($userInfo['id'], 'crm_customer', 'excel', '导入公海客户', '', '', '导入公海客户');
return resultArray(['data' => $excelModel->getError()]); return resultArray(['data' => $excelModel->getError()]);
} }
@ -229,28 +230,14 @@ class CustomerPool extends ApiCommon
{ {
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$action_name='导出全部'; $action_name = '导出全部';
if ($param['customer_id']) { if ($param['customer_id']) {
$action_name='导出选中'; $action_name = '导出选中';
} }
$param['is_excel'] = 1; $param['is_excel'] = 1;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $field_list = $this->fieldsData($param);
$field_list=$this->fieldsData($param);
$field=[
1=>[
'field'=>'before_owner_user_name',
'types'=>'crm_customer',
'name'=>'前负责人',
],
2=>[
'field'=>'into_pool_time',
'types'=>'crm_customer',
'name'=>'进入公海时间',
]
];
$field_list=array_merge($field_list,$field);
// 文件名 // 文件名
$file_name = '5kcrm_customer_' . date('Ymd'); $file_name = '5kcrm_customer_' . date('Ymd');
$model = model('Customer'); $model = model('Customer');
@ -259,7 +246,7 @@ class CustomerPool extends ApiCommon
$page = $param['page'] ?: 1; $page = $param['page'] ?: 1;
unset($param['page']); unset($param['page']);
unset($param['export_queue_index']); unset($param['export_queue_index']);
// p($field_list);
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) { return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page; $param['page'] = $page;
$param['limit'] = $limit; $param['limit'] = $limit;
@ -267,16 +254,16 @@ class CustomerPool extends ApiCommon
$data['list'] = $model->exportHandle($data['list'], $field_list, 'customer'); $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
return $data; return $data;
}); });
RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户'); RecordActionLog($userInfo['id'], 'crm_customer', 'excelexport', $action_name, '', '', '导出客户');
return resultArray(['error' => 'error']); return resultArray(['error' => 'error']);
} }
/** /**
* 公海权限 * 公海权限
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function authority() public function authority()
{ {
@ -292,9 +279,9 @@ class CustomerPool extends ApiCommon
/** /**
* 公海字段样式 * 公海字段样式
* *
* @author fanqi
* @since 2021-04-22
* @return Json * @return Json
* @since 2021-04-22
* @author fanqi
*/ */
public function fieldConfig() public function fieldConfig()
{ {
@ -312,9 +299,9 @@ class CustomerPool extends ApiCommon
/** /**
* 设置公海字段宽度 * 设置公海字段宽度
* *
* @author fanqi
* @since 2021-04-22
* @return Json * @return Json
* @since 2021-04-22
* @author fanqi
*/ */
public function setFieldWidth() public function setFieldWidth()
{ {
@ -334,9 +321,9 @@ class CustomerPool extends ApiCommon
/** /**
* 设置公海字段样式 * 设置公海字段样式
* *
* @author fanqi
* @since 2021-04-22
* @return Json * @return Json
* @since 2021-04-22
* @author fanqi
*/ */
public function setFieldConfig() public function setFieldConfig()
{ {
@ -351,14 +338,62 @@ class CustomerPool extends ApiCommon
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
public function fieldsData($param){
$pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select(); /**
$fieldModel = new \app\admin\model\Field(); * 导入模板
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/17 0017 11:34
*/
public function fieldsData($param)
{
$where=['pool_id' => $param['pool_id'], 'is_hidden' => 0,
'field_name' => ['not in', ['deal_status','create_user_id']]];
if($param['is_excel']==1){
$where=['pool_id' => $param['pool_id'], 'is_hidden' => 0,
'field_name' => ['not in', ['deal_status']]];
}
$pool_list = db('crm_customer_pool_field_setting')->where($where)->field('field_name as field,form_type,name')->select();
$fieldParam['types'] = 'crm_customer'; $fieldParam['types'] = 'crm_customer';
$fieldParam['action'] = 'excel'; $fieldParam['action'] = 'excel';
$merge_list = $fieldModel->field($fieldParam); $setting = [];
$field_list=array_intersect($merge_list,$pool_list); $list=[];
return $field_list; foreach ($pool_list as $k => &$v) {
switch ($v['field']) {
case 'address':
if($param['is_excel']!=1){
$v['field'] = 'customer_address';
$v['form_type'] = 'map_address';
$list[]=$v;
unset($pool_list[$k]);
}
break;
case 'detail_address':
unset($pool_list[$k]);
break;
case ($v['form_type'] == 'select') || ($v['form_type'] == 'checkbox') :
$set= db('admin_field')->where(['types' => 'crm_customer', 'field' => $v['field']])->find();
$pool_list[$k]['setting'] = explode(chr(10), $set['setting']);
break;
default :
if($param['is_excel']!=1){
$pool_list[$k]['setting'] = [];
}
break;
}
// if($param['is_excel']==1){
// foreach ( $pool_list as &$v){
// if($v['field']=='create_user_id'){
// $v['field'] = 'create_user_name';
// }elseif($v['field']=='before_owner_user_id'){
// $v['field'] = 'create_user_name';
// }
// }
// }
}
$pool_list=array_merge($pool_list,$list);
return $pool_list;
} }
} }

@ -46,7 +46,7 @@ class Index extends ApiCommon
'autonumberstatus', 'autonumberstatus',
'dashboard', 'dashboard',
'updatedashboard', 'updatedashboard',
'activitylist' 'activitylist',
] ]
]; ];
Hook::listen('check_auth', $action); Hook::listen('check_auth', $action);
@ -316,10 +316,14 @@ class Index extends ApiCommon
$achievement=Db::name('crm_achievement')->where($userWhere)->select(); $achievement=Db::name('crm_achievement')->where($userWhere)->select();
$data_time=date('m',strtotime($val['type'])); $data_time=date('m',strtotime($val['type']));
$num=''; $num='';
if($achievement){
foreach ($achievement as $val){ foreach ($achievement as $val){
$num+=(int)$val[$this->monthName[$data_time]]; $num+=(int)$val[$this->monthName[$data_time]];
$item['achievement']=$num; $item['achievement']=$num;
} }
}else{
$item['achievement']=0;
}
$list[] = $item; $list[] = $item;
} }
$data['list'] = $list; $data['list'] = $list;
@ -667,7 +671,6 @@ class Index extends ApiCommon
*/ */
public function ranking() public function ranking()
{ {
// Db::query('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id'] = $param['user_id']?:$userInfo['id']; $param['user_id'] = $param['user_id']?:$userInfo['id'];
@ -691,7 +694,7 @@ class Index extends ApiCommon
} }
/** /**
* 销售漏斗点击查看赢单输单 * 销售漏斗点击查看
*/ */
public function businessList() public function businessList()
{ {

@ -11,6 +11,7 @@ namespace app\crm\controller;
use app\admin\controller\ApiCommon; use app\admin\controller\ApiCommon;
use app\admin\model\Message; use app\admin\model\Message;
use app\admin\model\User; use app\admin\model\User;
use app\admin\traits\FieldVerificationTrait;
use app\crm\logic\InvoiceLogic; use app\crm\logic\InvoiceLogic;
use app\crm\model\NumberSequence; use app\crm\model\NumberSequence;
use app\crm\traits\AutoNumberTrait; use app\crm\traits\AutoNumberTrait;
@ -20,7 +21,7 @@ use think\Request;
class Invoice extends ApiCommon class Invoice extends ApiCommon
{ {
use AutoNumberTrait; use AutoNumberTrait, FieldVerificationTrait;
/** /**
* 用于判断权限 * 用于判断权限
@ -34,7 +35,7 @@ class Invoice extends ApiCommon
'permission' => [], 'permission' => [],
'allow' => ['check', 'revokecheck', 'count', 'read'] 'allow' => ['check', 'revokecheck', 'count', 'read']
]; ];
Hook::listen('check_auth',$action); Hook::listen('check_auth', $action);
$request = Request::instance(); $request = Request::instance();
$a = strtolower($request->action()); $a = strtolower($request->action());
if (!in_array($a, $action['permission'])) { if (!in_array($a, $action['permission'])) {
@ -54,7 +55,7 @@ class Invoice extends ApiCommon
$param = $this->param; $param = $this->param;
$param['user_id'] = $this->userInfo['id']; $param['user_id'] = $this->userInfo['id'];
$data = $invoiceLogic->index($param, true); $data = $invoiceLogic->index($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
@ -121,22 +122,120 @@ class Invoice extends ApiCommon
if ($examineFlowData['config'] == 1) { if ($examineFlowData['config'] == 1) {
# 固定审批流 # 固定审批流
$nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0); $nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0);
$next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : ''; $next_user_ids = arrayToString($nextStepData['next_user_ids']) ?: '';
$check_user_id = $next_user_ids ? : []; $check_user_id = $next_user_ids ?: [];
$param['order_id'] = 1; $param['order_id'] = 1;
} else { } else {
# 授权审批流 # 授权审批流
$check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : ''; $check_user_id = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
} }
if (!$check_user_id) { if (!$check_user_id) {
return resultArray(['error' => '无可用审批人,请联系管理员']); return resultArray(['error' => '无可用审批人,请联系管理员']);
} }
$param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id; $param['check_user_id'] = is_array($check_user_id) ? ',' . implode(',', $check_user_id) . ',' : $check_user_id;
} else { } else {
# 审批流停用,将状态改为审核通过 # 审批流停用,将状态改为审核通过
$param['check_status'] = 2; $param['check_status'] = 2;
} }
// 数据验证
// $validateResult = $this->fieldDataValidate($param, 'crm_invoice', $userId);
// if (!empty($validateResult)) {
// $this->error = $validateResult;
// return false;
// }
// 发票扩展表数据
$invoiceData = [];
$fieldModel = new \app\admin\model\Field();
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_invoice');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_invoice', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_invoice', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType('crm_invoice', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_invoice', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_invoice', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_invoice', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if (!$invoice_id = $invoiceLogic->save($param)) { if (!$invoice_id = $invoiceLogic->save($param)) {
return resultArray(['error' => '创建失败!']); return resultArray(['error' => '创建失败!']);
} }
@ -152,13 +251,13 @@ class Invoice extends ApiCommon
# 更新crm_number_sequence表中的last_date、create_time字段 # 更新crm_number_sequence表中的last_date、create_time字段
if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']); if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票'); updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
RecordActionLog($param['create_user_id'],'crm_invoice','save',$param['invoice_apple_number'],'','','新增了发票'.$param['invoice_apple_number']); RecordActionLog($param['create_user_id'], 'crm_invoice', 'save', $param['invoice_apple_number'], '', '', '新增了发票' . $param['invoice_apple_number']);
# 创建待办事项的关联数据 # 创建待办事项的关联数据
$checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id'); $checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds); $checkUserIdArray = stringToArray($checkUserIds);
$dealtData = []; $dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) { foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [ $dealtData[] = [
'types' => 'crm_invoice', 'types' => 'crm_invoice',
'types_id' => $invoice_id, 'types_id' => $invoice_id,
@ -167,6 +266,12 @@ class Invoice extends ApiCommon
} }
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData); if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加发票扩展数据
array_walk($invoiceData, function (&$val) use ($invoice_id) {
$val['invoice_id'] = $invoice_id;
});
db('crm_invoice_data')->insertAll($invoiceData);
return resultArray(['data' => '创建成功!']); return resultArray(['data' => '创建成功!']);
} }
@ -198,7 +303,7 @@ class Invoice extends ApiCommon
$invoiceAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'invoice', 'level' => 2])->value('id'); $invoiceAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'invoice', 'level' => 2])->value('id');
$invoiceReadAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'read', 'level' => 3, 'pid' => $invoiceAuthId])->value('id'); $invoiceReadAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'read', 'level' => 3, 'pid' => $invoiceAuthId])->value('id');
foreach ($authArray AS $key => $value) { foreach ($authArray as $key => $value) {
if (!empty($value) && in_array($invoiceReadAuthId, stringToArray($value))) $readStatus = true; if (!empty($value) && in_array($invoiceReadAuthId, stringToArray($value))) $readStatus = true;
} }
@ -226,7 +331,7 @@ class Invoice extends ApiCommon
if (empty($param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']); if (empty($param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']);
if (empty($param['title_type'])) return resultArray(['error' => '请选择抬头类型!']); if (empty($param['title_type'])) return resultArray(['error' => '请选择抬头类型!']);
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$dataInfo = $this->get($param['invoice_id']); $dataInfo = db('crm_invoice')->where('invoice_id',$param['invoice_id'])->find();
# 审批是否停用 # 审批是否停用
$examineStatus = $param['examineStatus']; $examineStatus = $param['examineStatus'];
# 删除无用参数 # 删除无用参数
@ -263,7 +368,7 @@ class Invoice extends ApiCommon
if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) { if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) {
//保存为草稿 //保存为草稿
$param['check_status'] = 5; //草稿(未提交) $param['check_status'] = 5; //草稿(未提交)
$param['check_user_id'] = $param['check_user_id'] ? ','.$param['check_user_id'].',' : ''; $param['check_user_id'] = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
} else { } else {
# 将合同审批状态至为待审核,提交后重新进行审批 # 将合同审批状态至为待审核,提交后重新进行审批
if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) { if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
@ -283,48 +388,145 @@ class Invoice extends ApiCommon
if ($examineFlowData['config'] == 1) { if ($examineFlowData['config'] == 1) {
# 固定审批流 # 固定审批流
$nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0); $nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0);
$next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : ''; $next_user_ids = arrayToString($nextStepData['next_user_ids']) ?: '';
$check_user_id = $next_user_ids ? : []; $check_user_id = $next_user_ids ?: [];
$param['order_id'] = 1; $param['order_id'] = 1;
} else { } else {
# 授权审批流 # 授权审批流
$check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : ''; $check_user_id = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
} }
if ($param['is_draft']) { if ($param['is_draft']) {
//保存为草稿 //保存为草稿
$param['check_status'] = 5; $param['check_status'] = 5;
$param['check_user_id'] = $param['check_user_id'] ? ','.$param['check_user_id'].',' : ''; $param['check_user_id'] = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
} else { } else {
if (!$check_user_id) { if (!$check_user_id) {
return resultArray(['error' => '无可用审批人,请联系管理员']); return resultArray(['error' => '无可用审批人,请联系管理员']);
} }
$param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id; $param['check_user_id'] = is_array($check_user_id) ? ',' . implode(',', $check_user_id) . ',' : $check_user_id;
$param['check_status'] = 0; $param['check_status'] = 0;
} }
$param['flow_user_id'] = ''; $param['flow_user_id'] = '';
} }
} }
// 数据验证
// $validateResult = $this->fieldDataValidate($param, 'crm_invoice', $userId);
// if (!empty($validateResult)) {
// $this->error = $validateResult;
// return false;
// }
// 发票扩展表数据
$invoiceData = [];
$fieldModel = new \app\admin\model\Field();
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_invoice');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_invoice', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_invoice', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType('crm_invoice', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_invoice', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_invoice', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_invoice', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$invoiceData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if (!$invoiceLogic->update($param)) { if (!$invoiceLogic->update($param)) {
return resultArray(['error' => '编辑失败!']); return resultArray(['error' => '编辑失败!']);
} }
//将审批记录至为无效 //将审批记录至为无效
$examineRecordModel = new \app\admin\model\ExamineRecord(); $examineRecordModel = new \app\admin\model\ExamineRecord();
$examineRecordModel->setEnd(['types' => 'crm_invoice','types_id' => $param['invoice_id']]); $examineRecordModel->setEnd(['types' => 'crm_invoice', 'types_id' => $param['invoice_id']]);
# 更新crm_number_sequence表中的last_date、create_time字段 # 更新crm_number_sequence表中的last_date、create_time字段
if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']); if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param); updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_invoice', 'update',$dataInfo['invoice_apple_number'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_invoice', 'update', $dataInfo['invoice_apple_number'], $dataInfo, $param);
# 删除待办事项的关联数据 # 删除待办事项的关联数据
db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete(); db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
# 创建待办事项的关联数据 # 创建待办事项的关联数据
$checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id'); $checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds); $checkUserIdArray = stringToArray($checkUserIds);
$dealtData = []; $dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) { foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [ $dealtData[] = [
'types' => 'crm_invoice', 'types' => 'crm_invoice',
'types_id' => $param['invoice_id'], 'types_id' => $param['invoice_id'],
@ -333,6 +535,14 @@ class Invoice extends ApiCommon
} }
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData); if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加客户扩展数据
$invoiceId = $param['invoice_id'];
db('crm_invoice_data')->where('invoice_id', $invoiceId)->delete();
array_walk($invoiceData, function (&$val) use ($invoiceId) {
$val['invoice_id'] = $invoiceId;
});
db('crm_invoice_data')->insertAll($invoiceData);
return resultArray(['data' => '编辑成功!']); return resultArray(['data' => '编辑成功!']);
} }
@ -359,7 +569,7 @@ class Invoice extends ApiCommon
if (!isSuperAdministrators($userinfo['id'])) { if (!isSuperAdministrators($userinfo['id'])) {
$list = $invoiceLogic->getExamineStatus($idString, true); $list = $invoiceLogic->getExamineStatus($idString, true);
foreach ($list AS $key => $value) { foreach ($list as $key => $value) {
if (!in_array($value['check_status'], [4, 5])) { if (!in_array($value['check_status'], [4, 5])) {
$status = false; $status = false;
break; break;
@ -368,13 +578,13 @@ class Invoice extends ApiCommon
} }
if (!$status) return resultArray(['error' => '不能删除审批中或审批结束的发票信息!']); if (!$status) return resultArray(['error' => '不能删除审批中或审批结束的发票信息!']);
$dataInfo=db('crm_invoice')->where('invoice_id',['in',$idArray])->select(); $dataInfo = db('crm_invoice')->where('invoice_id', ['in', $idArray])->select();
if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']); if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']);
# 删除附件 # 删除附件
$fileModel->delRFileByModule('crm_invoice', $idArray); $fileModel->delRFileByModule('crm_invoice', $idArray);
//删除关联操作记录 //删除关联操作记录
$actionRecordModel->delDataById(['types'=>'crm_invoice','action_id'=>$idArray]); $actionRecordModel->delDataById(['types' => 'crm_invoice', 'action_id' => $idArray]);
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) { foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']); RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']);
@ -393,17 +603,17 @@ class Invoice extends ApiCommon
$ownerUserId = $this->param['owner_user_id']; $ownerUserId = $this->param['owner_user_id'];
$invoiceIds = $this->param['invoice_id']; $invoiceIds = $this->param['invoice_id'];
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$userInfo=$this->userInfo; $userInfo = $this->userInfo;
if (empty($ownerUserId)) return resultArray(['error' => '请选择负责人!']); if (empty($ownerUserId)) return resultArray(['error' => '请选择负责人!']);
if (empty($invoiceIds)) return resultArray(['error' => '请选择发票!']); if (empty($invoiceIds)) return resultArray(['error' => '请选择发票!']);
if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误']); if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误']);
if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']); if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']);
$owner_user_info = $userModel->getUserById($ownerUserId); $owner_user_info = $userModel->getUserById($ownerUserId);
foreach ($invoiceIds as $v){ foreach ($invoiceIds as $v) {
$invoice_info=db('crm_invoice')->where('invoice_id',$v)->find(); $invoice_info = db('crm_invoice')->where('invoice_id', $v)->find();
updateActionLog($userInfo['id'], 'crm_invoice', $v, '', '', '将发票转移给:' . $owner_user_info['realname']); updateActionLog($userInfo['id'], 'crm_invoice', $v, '', '', '将发票转移给:' . $owner_user_info['realname']);
RecordActionLog($userInfo['id'], 'crm_invoice', 'transfer',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'转移给:' . $owner_user_info['realname']); RecordActionLog($userInfo['id'], 'crm_invoice', 'transfer', $invoice_info['invoice_apple_number'], '', '', '将发票:' . $invoice_info['invoice_apple_number'] . '转移给:' . $owner_user_info['realname']);
} }
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
@ -477,7 +687,7 @@ class Invoice extends ApiCommon
$checkData['check_time'] = time(); $checkData['check_time'] = time();
$checkData['content'] = $param['content']; $checkData['content'] = $param['content'];
$checkData['flow_id'] = $dataInfo['flow_id']; $checkData['flow_id'] = $dataInfo['flow_id'];
$checkData['order_id'] = $dataInfo['order_id'] ? : 1; $checkData['order_id'] = $dataInfo['order_id'] ?: 1;
$checkData['status'] = $status; $checkData['status'] = $status;
if ($status == 1) { if ($status == 1) {
@ -485,8 +695,8 @@ class Invoice extends ApiCommon
# 固定流程 # 固定流程
# 获取下一审批信息 # 获取下一审批信息
$nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_invoice', $param['id'], $dataInfo['order_id'], $user_id); $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_invoice', $param['id'], $dataInfo['order_id'], $user_id);
$next_user_ids = $nextStepData['next_user_ids'] ? : []; $next_user_ids = $nextStepData['next_user_ids'] ?: [];
$invoiceData['order_id'] = $nextStepData['order_id'] ? : ''; $invoiceData['order_id'] = $nextStepData['order_id'] ?: '';
if (!$next_user_ids) { if (!$next_user_ids) {
$is_end = 1; $is_end = 1;
# 审批结束 # 审批结束
@ -499,7 +709,7 @@ class Invoice extends ApiCommon
} else { } else {
# 自选流程 # 自选流程
$is_end = $param['is_end'] ? 1 : ''; $is_end = $param['is_end'] ? 1 : '';
$check_user_id = $param['check_user_id'] ? : ''; $check_user_id = $param['check_user_id'] ?: '';
if ($is_end !== 1 && empty($check_user_id)) { if ($is_end !== 1 && empty($check_user_id)) {
return resultArray(['error' => '请选择下一审批人']); return resultArray(['error' => '请选择下一审批人']);
} }
@ -516,7 +726,7 @@ class Invoice extends ApiCommon
$invoiceData['check_status'] = 3; $invoiceData['check_status'] = 3;
} }
# 已审批人ID # 已审批人ID
$invoiceData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']),[$user_id])) : arrayToString([$user_id]); $invoiceData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']), [$user_id])) : arrayToString([$user_id]);
$resContract = $invoiceLogic->setExamineInfo($invoiceData); $resContract = $invoiceLogic->setExamineInfo($invoiceData);
if ($resContract) { if ($resContract) {
# 审批记录 # 审批记录
@ -638,10 +848,83 @@ class Invoice extends ApiCommon
# 开票状态 # 开票状态
$this->param['invoice_status'] = 1; $this->param['invoice_status'] = 1;
$invoice_info=db('crm_invoice')->where('invoice_id',$this->param['invoice_id'])->find(); $invoice_info = db('crm_invoice')->where('invoice_id', $this->param['invoice_id'])->find();
if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']); if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
RecordActionLog($userInfo['id'], 'crm_invoice', 'update',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'重置开票状态'); RecordActionLog($userInfo['id'], 'crm_invoice', 'update', $invoice_info['invoice_apple_number'], '', '', '将发票:' . $invoice_info['invoice_apple_number'] . '重置开票状态');
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/**
* 导出
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/22 0022 14:34
*/
public function excelExport()
{
$param = $this->param;
$userInfo = $this->userInfo;
$action_name = '导出全部';
$param['is_excel'] = 1;
$invoiceLogic=new InvoiceLogic();
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$fieldModel = new \app\admin\model\Field();
$field_list = $fieldModel->getIndexFieldConfig('crm_invoice', $userInfo['id'],'','excel');
if ($param['invoice_id']) {
$param['invoice_id'] = ['condition' => 'in', 'value' => $param['invoice_id'], 'form_type' => 'text', 'name' => ''];
$action_name = '导出选中';
}
$field = [
0 => [
'field' => 'check_status',
'name' => '审核状态',
'form_type' => 'text',
'is_hidden' => 0,
],
1 => [
'field' => 'invoice_status',
'name' => '开票状态',
'form_type' => 'text',
'is_hidden' => 0
],
2 => [
'field' => 'real_invoice_date',
'name' => '实际开票日期',
'form_type' => 'date',
'is_hidden' => 0
],
3 => [
'field' => 'invoice_number',
'name' => '发票号码',
'form_type' => 'text',
'is_hidden' => 0
],
4 => [
'field' => 'logistics_number',
'name' => '物流单号',
'form_type' => 'text',
'is_hidden' => 0,
]
];
$field_list=array_merge($field_list,$field);
// 文件名
$file_name = '5kcrm_invoice_' . date('Ymd');
$model = model('Invoice');
$temp_file = $param['temp_file'];
unset($param['temp_file']);
$page = $param['page']?: 1;
unset($param['page']);
unset($param['export_queue_index']);
// RecordActionLog($userInfo['id'],'crm_invoice','excelexport',$action_name,'','','导出客户');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list,$invoiceLogic) {
$param['page'] = $page;
$param['limit'] = $limit;
$data = $invoiceLogic->index($param);
$data['list'] = $model->exportHandle($data['list'], $field_list, 'invoice');
return $data;
});
}
} }

@ -181,6 +181,8 @@ class Leads extends ApiCommon
if (!$data) { if (!$data) {
return resultArray(['error' => $leadsModel->getError()]); return resultArray(['error' => $leadsModel->getError()]);
} }
// 删除线索扩展数据
db('crm_leads_data')->whereIn('leads_id', $delIds)->delete();
//删除跟进记录 //删除跟进记录
$recordModel->delDataByTypes(1, $delIds); $recordModel->delDataByTypes(1, $delIds);
//删除关联附件 //删除关联附件
@ -346,7 +348,7 @@ class Leads extends ApiCommon
*/ */
public function excelDownload($save_path = '') public function excelDownload($save_path = '')
{ {
# 下次升级使用
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
@ -355,37 +357,21 @@ class Leads extends ApiCommon
$fieldParam['types'] = 'crm_leads'; $fieldParam['types'] = 'crm_leads';
$fieldParam['action'] = 'excel'; $fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam); $field_list = $fieldModel->field($fieldParam);
// $field_list = $fieldModel->getIndexFieldList('crm_leads', $userInfo['id']); $field=[1=>[
$data = $excelModel->excelImportDownload($field_list, 'crm_leads', $save_path); 'field'=>'owner_user_id',
'types'=>'crm_leads',
# 下次升级使用 'name'=>'负责人',
// $param = $this->param; 'form_type'=>'user',
// $userInfo = $this->userInfo; 'default_value'=>'',
// $excelModel = new \app\admin\model\Excel(); 'is_null' => 1,
// // 导出的字段列表 'input_tips' =>'',
// $fieldModel = new \app\admin\model\Field(); 'setting' => Array(),
// $fieldParam['types'] = 'crm_leads'; 'is_hidden'=>0,
// $fieldParam['action'] = 'excel'; 'writeStatus' => 1,
// $field_list = $fieldModel->field($fieldParam); 'value' => '']
// $field=[1=>[ ];
// 'field'=>'owner_user_id', $first_array = array_splice($field_list, 2,0, $field);
// 'types'=>'crm_leads', $excelModel->excelImportDownload($field_list, 'crm_leads', $save_path);
// 'name'=>'负责人',
// 'form_type'=>'user',
// 'default_value'=>'',
// 'is_unique' => 1,
// 'is_null' => 1,
// 'input_tips' =>'',
// 'setting' => Array(),
// 'is_hidden'=>0,
// 'writeStatus' => 1,
// 'value' => '']
// ];
// $first_array = array_splice($field_list, 0, 2);
// $array = array_merge($first_array, $field, $field_list);
// $data = $excelModel->excelImportDownload($array, 'crm_leads', $save_path);
return resultArray(['data' => $data]);
} }
/** /**
@ -409,7 +395,7 @@ class Leads extends ApiCommon
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$field_list = $fieldModel->getIndexFieldConfig('crm_leads', $userInfo['id']); $field_list = $fieldModel->getIndexFieldConfig('crm_leads', $userInfo['id'],'','excel');
// 文件名 // 文件名
$file_name = '5kcrm_leads_' . date('Ymd'); $file_name = '5kcrm_leads_' . date('Ymd');

@ -9,6 +9,8 @@ namespace app\crm\controller;
use app\admin\controller\ApiCommon; use app\admin\controller\ApiCommon;
use app\crm\logic\InvoiceLogic; use app\crm\logic\InvoiceLogic;
use app\crm\logic\MessageLogic;
use think\Cache;
use think\cache\driver\Redis; use think\cache\driver\Redis;
use think\Db; use think\Db;
use think\Hook; use think\Hook;
@ -80,7 +82,6 @@ class Message extends ApiCommon
$configDataModel = model('ConfigData'); $configDataModel = model('ConfigData');
$configData = $configDataModel->getData(); $configData = $configDataModel->getData();
$data = []; $data = [];
# 今日需联系线索 # 今日需联系线索
$todayLeadsTime = cache('todayLeadsTime'.$userInfo['id']); $todayLeadsTime = cache('todayLeadsTime'.$userInfo['id']);
$todayLeadsCount = cache('todayLeadsCount'.$userInfo['id']); $todayLeadsCount = cache('todayLeadsCount'.$userInfo['id']);
@ -106,7 +107,7 @@ class Message extends ApiCommon
# 今日需联系商机 # 今日需联系商机
$todayBusinessTime = cache('todayBusinessTime'.$userInfo['id']); $todayBusinessTime = cache('todayBusinessTime'.$userInfo['id']);
$todayBusinessCount = cache('todayBusinessCount'.$userInfo['id']); $todayBusinessCount = cache('todayBusinessCount'.$userInfo['id']);
if ($todayBusinessTime <= time()) { if (time() <= $todayBusinessTime) {
$data['todayBusiness'] = (int)$todayBusinessCount; $data['todayBusiness'] = (int)$todayBusinessCount;
} else { } else {
$todayBusiness = $this->todayBusiness(true); $todayBusiness = $this->todayBusiness(true);
@ -163,9 +164,11 @@ class Message extends ApiCommon
$checkInvoiceCount = cache('checkInvoiceCount'.$userInfo['id']); $checkInvoiceCount = cache('checkInvoiceCount'.$userInfo['id']);
if (time() <= $checkInvoiceTime) { if (time() <= $checkInvoiceTime) {
$data['checkInvoice'] = (int)$checkInvoiceCount; $data['checkInvoice'] = (int)$checkInvoiceCount;
} else { } else {
$checkInvoice = $this->checkInvoice(true); $checkInvoice = $this->checkInvoice(true);
$data['checkInvoice'] = $checkInvoice['dataCount'] ? : 0; $data['checkInvoice'] = $checkInvoice['dataCount'] ? : 0;
cache('checkInvoiceCount'.$userInfo['id'], $data['checkInvoice']); cache('checkInvoiceCount'.$userInfo['id'], $data['checkInvoice']);
cache('checkInvoiceTime'.$userInfo['id'], time() + 180); cache('checkInvoiceTime'.$userInfo['id'], time() + 180);
} }
@ -235,37 +238,12 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
$todayTime = getTimeByType('today');
unset($param['types']); unset($param['types']);
unset($param['type']); $param['user_id'] = $userId;
unset($param['isSub']);
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$messageLogic= new MessageLogic();
$leadsModel = new \app\crm\model\Leads(); $data = $messageLogic->todayLeads($param);
# 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
# 类型1今日需联系2已逾期3已联系
switch ($type) {
case '1' :
$param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
$param['is_dealt'] = ['neq', 1];
break;
case '2' :
$param['next_time'] = ['between', [1, time()]];
$param['is_dealt'] = ['neq', 1];
break;
case '3' :
$param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
$param['is_dealt'] = ['eq', 1];
break;
}
$param['user_id'] = $userId;
$data = $leadsModel->getDataList($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
@ -281,36 +259,15 @@ class Message extends ApiCommon
public function todayCustomer($getCount = false) public function todayCustomer($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
if ($getCount == true) { if ($getCount == true) {
$param['getCount'] = 1; $param['getCount'] = 1;
} }
unset($param['types']); unset($param['types']);
unset($param['type']); $param['user_id'] = $userId;
unset($param['isSub']); $messageLogic= new MessageLogic();
$customerModel = model('Customer'); $data = $messageLogic->remindCustomer($param);
$todayTime = getTimeByType('today');
$param['owner_user_id'] = !empty($isSub) ? ['in',getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
switch ($type) {
case '1' :
$param['next_time'] = ['between',array($todayTime[0],$todayTime[1])];
$param['is_dealt'] = ['neq', 1];
break;
case '2' :
$param['next_time'] = ['between',array(1,time())];
$param['is_dealt'] = ['neq', 1];
break;
case '3' :
$param['last_time'] = ['between',array($todayTime[0],$todayTime[1])];
$param['is_dealt'] = ['eq', 1];
break;
}
$data = $customerModel->getDataList($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
@ -331,37 +288,11 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
$todayTime = getTimeByType('today');
unset($param['types']); unset($param['types']);
unset($param['type']);
unset($param['isSub']);
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$messageLogic= new MessageLogic();
$businessModel = new \app\crm\model\Business();
# 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
# 类型1今日需联系2已逾期3已联系
switch ($type) {
case '1' :
$param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
$param['is_dealt'] = ['neq', 1];
break;
case '2' :
$param['next_time'] = ['between', [1, time()]];
$param['is_dealt'] = ['neq', 1];
break;
case '3' :
$param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
$param['is_dealt'] = ['eq', 1];
break;
}
$param['user_id'] = $userId; $param['user_id'] = $userId;
$data = $businessModel->getDataList($param); $data = $messageLogic->todayBusiness($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
@ -378,29 +309,11 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
unset($param['types']); unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$leadsModel = model('Leads');
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$param['owner_user_id'] = $userInfo['id'];
switch ($type) {
case '1' :
$param['follow'] = [['neq','已跟进'], null, 'or'];
$param['is_allocation'] = 1;
break;
case '2' :
$param['follow'] = ['eq','已跟进'];
$param['is_allocation'] = 1;
break;
}
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = $leadsModel->getDataList($param); $messageLogic=new MessageLogic();
$data = $messageLogic->followLeads($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
@ -417,29 +330,13 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
if ($getCount == true) { if ($getCount == true) {
$param['getCount'] = 1; $param['getCount'] = 1;
} }
unset($param['types']); unset($param['types']);
unset($param['type']); $messageLogic=new MessageLogic();
unset($param['isSub']); $param['user_id'] = $userInfo['id'];
$customerModel = model('Customer'); $data = $messageLogic->followCustomer($param);
$param['owner_user_id'] = $userInfo['id'];
switch ($type) {
case '1' :
$param['follow'] = [['eq','待跟进'], null, 'or'];
$param['is_allocation'] = 1;
break;
case '2' :
$param['follow'] = ['eq','已跟进'];
$param['is_allocation'] = 1;
break;
}
$data = $customerModel->getDataList($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
@ -457,31 +354,13 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
unset($param['types']); unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$contractModel = model('Contract');
if ($getCount == true) { if ($getCount == true) {
$param['getCount'] = 1; $param['getCount'] = 1;
} }
$messageLogic=new MessageLogic();
switch ($type) {
case '1' :
$param['check_status'] = ['lt','2'];
$param['check_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
# 要提醒的合同ID
$contractIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'user_id' => ['eq', $userInfo['id']]])->column('types_id');
$param['contractIdArray'] = !empty($contractIdArray) ? $contractIdArray : -1;
break;
case '2' :
$param['flow_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
break;
}
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = $contractModel->getDataList($param); $data = $messageLogic->checkContract($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
@ -498,30 +377,11 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
unset($param['types']); unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$receivablesModel = model('Receivables');
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$messageLogic=new MessageLogic();
switch ($type) {
case '1' :
# 待审核、审核中
$param['check_status'] = ['lt','2'];
$param['check_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
# 要提醒的回款ID
$receivablesIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'user_id' => ['eq', $userInfo['id']]])->column('types_id');
$param['receivablesIdArray'] = !empty($receivablesIdArray) ? $receivablesIdArray : -1;
break;
case '2' :
# 全部
$param['flow_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
break;
}
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = $receivablesModel->getDataList($param); $data = $messageLogic->checkReceivables($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
@ -540,33 +400,12 @@ class Message extends ApiCommon
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
# 清除与模型无关的数据 # 清除与模型无关的数据
unset($param['types']); unset($param['types']);
unset($param['type']); $param['user_id'] = $userId;
unset($param['isSub']); $messageLogic=new MessageLogic();
$data = $messageLogic->checkInvoice($param);
switch ($type) {
case '1' :
# 待审核、审核中
$param['check_status'] = ['lt', 2];
$param['check_user_id'] = ['like', ',%'. $userId .'%,'];
# 要提醒的发票ID
$invoiceIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'user_id' => ['eq', $userId]])->column('types_id');
$param['invoiceIdArray'] = !empty($invoiceIdArray) ? $invoiceIdArray : -1;
$param['dealt'] = 1;
break;
case '2' :
# 全部
$param['flow_user_id'] = ['like', ',%'. $userId .'%,'];
$param['dealt'] = 1;
break;
}
$data = (new InvoiceLogic())->index($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
@ -594,14 +433,14 @@ class Message extends ApiCommon
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
if ($isSub) { if ($isSub) {
$param['owner_user_id'] = array('in',getSubUserId(false)); $param['owner_user_id'] = ['in', getSubUserId(false)];
} }
switch ($type) { switch ($type) {
case '1' : case '1' :
$param['receivables_id'] = 0; $param['receivables_id'] = 0;
$param['check_status'] = array('lt',2); $param['check_status'] = ['lt', 2];
$param['remind_date'] = array('elt',date('Y-m-d',time())); $param['remind_date'] = ['elt', date('Y-m-d', time())];
$param['return_date'] = array('egt',date('Y-m-d',time())); $param['return_date'] = ['egt', date('Y-m-d', time())];
$param['types'] = 1; $param['types'] = 1;
$param['is_dealt'] = 0; $param['is_dealt'] = 0;
break; break;
@ -612,7 +451,7 @@ class Message extends ApiCommon
break; break;
case '3' : case '3' :
$param['receivables_id'] = 0; $param['receivables_id'] = 0;
$param['remind_date'] = array('lt',date('Y-m-d',time())); $param['return_date'] = ['lt', date('Y-m-d', time())];
break; break;
} }
$data = $receivablesPlanModel->getDataList($param); $data = $receivablesPlanModel->getDataList($param);
@ -642,7 +481,8 @@ class Message extends ApiCommon
$configModel = new \app\crm\model\ConfigData(); $configModel = new \app\crm\model\ConfigData();
$configInfo = $configModel->getData(); $configInfo = $configModel->getData();
$expireDay = $configInfo['contract_day'] ? : '7'; $expireDay = $configInfo['contract_day'] ? : '7';
// 合同到期不提醒
if (empty($configInfo['contract_config'])) return resultArray(['data' => []]);
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
if ($isSub) { if ($isSub) {
$param['owner_user_id'] = array('in',getSubUserId(false)); $param['owner_user_id'] = array('in',getSubUserId(false));
@ -907,7 +747,31 @@ class Message extends ApiCommon
if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]); if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]);
} }
cache::rm('todayLeadsCount'.$userId);
cache::rm('todayCustomerCount'.$userId);
cache::rm('todayBusinessCount'.$userId);
cache::rm('followLeadsCount'.$userId);
cache::rm('followCustomerCount'.$userId);
cache::rm('checkContractCount'.$userId);
cache::rm('checkReceivablesCount'.$userId);
cache::rm('checkInvoiceCount'.$userId);
cache::rm('remindReceivablesPlanCount'.$userId);
cache::rm('visitContractCount'.$userId);
cache::rm('endContractCount'.$userId);
cache::rm('remindCustomerCount'.$userId);
cache::rm('todayLeadsTime'.$userId);
cache::rm('todayCustomerTime'.$userId);
cache::rm('todayBusinessTime'.$userId);
cache::rm('followLeadsTime'.$userId);
cache::rm('followCustomerTime'.$userId);
cache::rm('checkContractTime'.$userId);
cache::rm('checkReceivablesTime'.$userId);
cache::rm('checkInvoiceTime'.$userId);
cache::rm('remindReceivablesPlanTime'.$userId);
cache::rm('visitContractTime'.$userId);
cache::rm('endContractTime'.$userId);
cache::rm('remindCustomerTime'.$userId);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
} }

@ -187,6 +187,7 @@ class Product extends ApiCommon
*/ */
public function excelDownload($save_path = '') public function excelDownload($save_path = '')
{ {
# 下次升级
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
@ -196,34 +197,21 @@ class Product extends ApiCommon
$fieldParam['types'] = 'crm_product'; $fieldParam['types'] = 'crm_product';
$fieldParam['action'] = 'excel'; $fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam); $field_list = $fieldModel->field($fieldParam);
$field=[1=>[
'field'=>'owner_user_id',
'types'=>'crm_product',
'name'=>'负责人',
'form_type'=>'user',
'default_value'=>'',
'is_null' => 1,
'input_tips' =>'',
'setting' => Array(),
'is_hidden'=>0,
'writeStatus' => 1,
'value' => '']
];
$first_array = array_splice($field_list, 2,0, $field);
$excelModel->excelImportDownload($field_list, 'crm_product', $save_path); $excelModel->excelImportDownload($field_list, 'crm_product', $save_path);
# 下次升级
// $param = $this->param;
// $userInfo = $this->userInfo;
// $excelModel = new \app\admin\model\Excel();
//
// // 导出的字段列表
// $fieldModel = new \app\admin\model\Field();
// $fieldParam['types'] = 'crm_product';
// $fieldParam['action'] = 'excel';
// $field_list = $fieldModel->field($fieldParam);
// $field=[1=>[
// 'field'=>'owner_user_id',
// 'types'=>'crm_product',
// 'name'=>'负责人',
// 'form_type'=>'user',
// 'default_value'=>'',
// 'is_unique' => 1,
// 'is_null' => 1,
// 'input_tips' =>'',
// 'setting' => Array(),
// 'is_hidden'=>0,
// 'writeStatus' => 1,
// 'value' => '']
// ];
// $first_array = array_splice($field_list, 0, 2);
// $array = array_merge($first_array, $field, $field_list);
// $excelModel->excelImportDownload($array, 'crm_product', $save_path);
} }
/** /**
@ -246,7 +234,7 @@ class Product extends ApiCommon
$excelModel = new \app\admin\model\Excel(); $excelModel = new \app\admin\model\Excel();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$field_list = $fieldModel->getIndexFieldConfig('crm_product', $userInfo['id']); $field_list = $fieldModel->getIndexFieldConfig('crm_product', $userInfo['id'],'','excel');
// 文件名 // 文件名
$file_name = '5kcrm_product_'.date('Ymd'); $file_name = '5kcrm_product_'.date('Ymd');
@ -337,6 +325,8 @@ class Product extends ApiCommon
if ($res == count($delIds)) { if ($res == count($delIds)) {
// 事务提交 // 事务提交
ProductModel::commit(); ProductModel::commit();
// 删除客户扩展数据
db('crm_product_data')->whereIn('product_id', $delIds)->delete();
// 删除关联附件 // 删除关联附件
(new FileModel)->delRFileByModule('crm_product', $delIds); (new FileModel)->delRFileByModule('crm_product', $delIds);
// 操作记录 // 操作记录

@ -86,7 +86,7 @@ class ProductCategory extends ApiCommon
$categoryModel = model('ProductCategory'); $categoryModel = model('ProductCategory');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id']=$userInfo['id'];
$res = $categoryModel->updateDataById($param, $param['id']); $res = $categoryModel->updateDataById($param, $param['id']);
if ($res) { if ($res) {
return resultArray(['data' => '编辑成功']); return resultArray(['data' => '编辑成功']);
@ -105,7 +105,9 @@ class ProductCategory extends ApiCommon
{ {
$categoryModel = model('ProductCategory'); $categoryModel = model('ProductCategory');
$param = $this->param; $param = $this->param;
$data = $categoryModel->delDataById($param['id'], true); $userInfo=$this->userInfo;
$param['user_id']=$userInfo['id'];
$data = $categoryModel->delDataById($param, true);
if (!$data) { if (!$data) {
return resultArray(['error' => $categoryModel->getError()]); return resultArray(['error' => $categoryModel->getError()]);
} }

@ -348,6 +348,8 @@ class Receivables extends ApiCommon
if (!$data) { if (!$data) {
return resultArray(['error' => $receivablesModel->getError()]); return resultArray(['error' => $receivablesModel->getError()]);
} }
// 删除回款扩展数据
db('crm_receivables_data')->whereIn('receivables_id', $delIds)->delete();
//删除跟进记录 //删除跟进记录
$recordModel->delDataByTypes(7,$delIds); $recordModel->delDataByTypes(7,$delIds);
# 删除附件 # 删除附件
@ -643,9 +645,17 @@ class Receivables extends ApiCommon
{ {
if (empty($this->param['receivables_id'])) return resultArray(['error' => '参数错误!']); if (empty($this->param['receivables_id'])) return resultArray(['error' => '参数错误!']);
$receivablesId = $this->param['receivables_id'];
# 团队成员
$receivables = Db::name('crm_receivables')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('receivables_id', $receivablesId)->find();
$receivables['ro_user_id'] = stringToArray($receivables['ro_user_id']);
$receivables['rw_user_id'] = stringToArray($receivables['rw_user_id']);
$receivables['owner_user_id'] = [$receivables['owner_user_id']];
$teamCount = array_filter(array_unique(array_merge($receivables['ro_user_id'], $receivables['rw_user_id'], $receivables['owner_user_id'])));
# 附件 # 附件
$fileCount = Db::name('crm_receivables_file')->alias('receivables')->join('__ADMIN_FILE__ file', 'file.file_id = receivables.file_id', 'LEFT')->where('receivables_id', $this->param['receivables_id'])->count(); $fileCount = Db::name('crm_receivables_file')->alias('receivables')->join('__ADMIN_FILE__ file', 'file.file_id = receivables.file_id', 'LEFT')->where('receivables_id', $this->param['receivables_id'])->count();
return resultArray(['data' => ['fileCount' => $fileCount]]); return resultArray(['data' => ['fileCount' => $fileCount,'memberCount' => count($teamCount)]]);
} }
} }

@ -61,6 +61,7 @@ class ReceivablesPlan extends ApiCommon
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['create_user_id'] = $userInfo['id']; $param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
$param['user_id'] = $userInfo['id'];
$res = $receivablesPlanModel->createData($param); $res = $receivablesPlanModel->createData($param);
if ($res) { if ($res) {
@ -111,6 +112,7 @@ class ReceivablesPlan extends ApiCommon
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作'])); exit(json_encode(['code'=>102,'error'=>'无权操作']));
} }
$param['user_id'] = $userInfo['id'];
$res = $receivablesPlanModel->updateDataById($param, $param['id']); $res = $receivablesPlanModel->updateDataById($param, $param['id']);
if ($res) { if ($res) {
return resultArray(['data' => '编辑成功']); return resultArray(['data' => '编辑成功']);
@ -153,6 +155,8 @@ class ReceivablesPlan extends ApiCommon
if (!$res) { if (!$res) {
return resultArray(['error' => model('ReceivablesPlan')->getError()]); return resultArray(['error' => model('ReceivablesPlan')->getError()]);
} }
// 删除回款计划扩展数据
db('crm_receivables_plan_data')->where('plan_id', $plan_id)->delete();
return resultArray(['data' => '删除成功']); return resultArray(['data' => '删除成功']);
} else { } else {
return resultArray(['error'=>'参数错误']); return resultArray(['error'=>'参数错误']);

@ -107,6 +107,9 @@ class Setting extends ApiCommon
case 'crm_contract' : case 'crm_contract' :
$dataModel = new \app\crm\model\Contract(); $dataModel = new \app\crm\model\Contract();
break; break;
case 'crm_receivables' :
$dataModel = new \app\crm\model\Receivables();
break;
} }
$resData = $dataModel->getDataById($param['types_id']); $resData = $dataModel->getDataById($param['types_id']);
$ro_user_ids = $resData['ro_user_id'] ? array_filter(explode(',', $resData['ro_user_id'])) : []; //只读权限 $ro_user_ids = $resData['ro_user_id'] ? array_filter(explode(',', $resData['ro_user_id'])) : []; //只读权限
@ -133,6 +136,7 @@ class Setting extends ApiCommon
$user_list = array_merge($owner_user_arr, $rw_user_arr, $ro_user_arr); $user_list = array_merge($owner_user_arr, $rw_user_arr, $ro_user_arr);
$new_user_list = []; $new_user_list = [];
$types_data = ['crm_leads' => 6, 'crm_customer' => 1, 'crm_contacts' => 2, 'crm_business' => 3, 'crm_contract' => 4, 'crm_receivables' => 5];
foreach ($user_list as $k => $v) { foreach ($user_list as $k => $v) {
if ($v['user_id']) { if ($v['user_id']) {
$userInfo = []; $userInfo = [];
@ -140,6 +144,7 @@ class Setting extends ApiCommon
$userInfo['group_name'] = $v['group_name']; $userInfo['group_name'] = $v['group_name'];
$userInfo['authority'] = $v['authority']; $userInfo['authority'] = $v['authority'];
$userInfo['type'] = $v['type']; $userInfo['type'] = $v['type'];
$userInfo['target_time'] = db('crm_team')->where(['team_user_id' => ['in', $v], 'target_id' => $param['types_id'], 'types' => $types_data[$param['types']]])->value('target_time') ? date('Y-m-d', db('crm_team')->where(['team_user_id' => ['in', $v], 'target_id' => $param['types_id'], 'types' => $types_data[$param['types']]])->value('target_time')) : '无限';
$new_user_list[] = $userInfo; $new_user_list[] = $userInfo;
} }
} }
@ -286,13 +291,62 @@ class Setting extends ApiCommon
} }
$message_type = Message::TEAM_CONTRACT; $message_type = Message::TEAM_CONTRACT;
continue; continue;
case 'crm_leads' :
$typesName = '线索';
$leadsModel = new \app\crm\model\Leads();
$dataInfo = db('crm_leads')->where(['leads_id' => $v])->find();
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'leads', 'teamSave');
if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
$error = true;
$errorMessage = "线索'" . $dataInfo['name'] . "'操作失败,错误原因:无权操作";
}
if (in_array($dataInfo['owner_user_id'], $param['user_id'])) {
$error = true;
$errorMessage = "线索'" . $dataInfo['name'] . "'操作失败,错误原因:不能对负责人进行添加或移出操作!";
}
$message_type = Message::TEAM_CONTRACT;
continue;
case 'crm_receivables' :
$typesName = '回款';
$receivablesModel = new \app\crm\model\Receivables();
$dataInfo = db('crm_receivables')->where(['receivables_id' => $v])->find();
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'teamSave');
if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
$error = true;
$errorMessage = "回款'" . $dataInfo['name'] . "'操作失败,错误原因:无权操作";
}
if (in_array($dataInfo['owner_user_id'], $param['user_id'])) {
$error = true;
$errorMessage = "回款'" . $dataInfo['name'] . "'操作失败,错误原因:不能对负责人进行添加或移出操作!";
}
$message_type = Message::TEAM_CONTRACT;
continue;
case 'crm_contacts' :
$typesName = '联系人';
$leadsModel = new \app\crm\model\Leads();
$dataInfo = db('crm_contacts')->where(['contacts_id' => $v])->find();
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'teamSave');
if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
$error = true;
$errorMessage = "联系人'" . $dataInfo['name'] . "'操作失败,错误原因:无权操作";
}
if (in_array($dataInfo['owner_user_id'], $param['user_id'])) {
$error = true;
$errorMessage = "联系人'" . $dataInfo['name'] . "'操作失败,错误原因:不能对负责人进行添加或移出操作!";
}
$message_type = Message::TEAM_CONTRACT;
continue;
} }
if ($error !== true) { if ($error !== true) {
$param['type_id'] = $v; $param['type_id'] = $v;
$param['type'] = $param['type'] ?: 1; $param['type'] = $param['type'] ?: 1;
$param['is_del'] = $param['is_del'] ?: 3; $param['is_del'] = $param['is_del'] ?: 3;
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
if (empty($param['is_del'])) { $param['target_time'] = strtotime($param['target_time']);
if ($param['is_del'] == 3) {
$res = $settingModel->createTeamData($param); $res = $settingModel->createTeamData($param);
if (!$res) { if (!$res) {
$errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败"; $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
@ -305,14 +359,15 @@ class Setting extends ApiCommon
], ],
$param['user_id'] $param['user_id']
); );
$username=db('admin_user')->where('id',['in',$param['user_id']])->column('realname'); $username = db('admin_user')->where('id', ['in', $param['user_id']])->column('realname');
RecordActionLog($userInfo['id'], 'crm_customer', 'teamSave',$dataInfo['name'], '','','给' . $typesName. $dataInfo['name'].'添加了团队成员 '.implode(',',$username)); RecordActionLog($userInfo['id'], $param['types'], 'teamSave', $dataInfo['name'], '', '', '给' . $typesName . $dataInfo['name'] . '添加了团队成员 ' . implode(',', $username));
updateActionLog($userInfo['id'], $param['types'], $v, '', '', $typesName . $dataInfo['name'] . '添加了团队成员' . implode(',', $username));
} }
} else { } else {
$res = $settingModel->createTeamData($param); $res = $settingModel->createTeamData($param);
if (!$res) { if (!$res) {
$errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败"; $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
}else{ } else {
(new Message())->send( (new Message())->send(
Message::TEAM_END, Message::TEAM_END,
[ [
@ -322,10 +377,10 @@ class Setting extends ApiCommon
$param['user_id'] $param['user_id']
); );
} }
$username=db('admin_user')->where('id',['in',$param['user_id']])->column('realname'); $username = db('admin_user')->where('id', ['in', $param['user_id']])->column('realname');
RecordActionLog($userInfo['id'], 'crm_customer', 'teamSave',$dataInfo['name'], '','','移除了' . $typesName. $dataInfo['name'].'团队成员 '.implode(',',$username)); RecordActionLog($userInfo['id'], $param['types'], 'teamSave', $dataInfo['name'], '', '', '移除了' . $typesName . $dataInfo['name'] . '团队成员 ' . implode(',', $username));
updateActionLog($userInfo['id'], $param['types'], $v, '', '', $typesName . $dataInfo['name'] . '移除了团队成员' . implode(',', $username));
} }
} }
} }
if ($errorMessage) { if ($errorMessage) {
@ -350,14 +405,14 @@ class Setting extends ApiCommon
exit(json_encode(['code' => 102, 'error' => '无权操作'])); exit(json_encode(['code' => 102, 'error' => '无权操作']));
} }
$param = $this->param; $param = $this->param;
$userInfo=$this->userInfo; $userInfo = $this->userInfo;
$data = []; $data = [];
$contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0; $contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0;
$contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0; $contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0;
$res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]); $res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]);
if ($contract_day && $contract_config == 1) $res = db('crm_config')->where(['name' => 'contract_day'])->update(['value' => $contract_day]); if ($contract_day && $contract_config == 1) $res = db('crm_config')->where(['name' => 'contract_day'])->update(['value' => $contract_day]);
# 系统操作日志 # 系统操作日志
SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','' , '', '','编辑了合同到期提醒设置'); SystemActionLog($userInfo['id'], 'crm_config', 'customer', 1, 'update', '', '', '', '编辑了合同到期提醒设置');
return resultArray(['data' => '设置成功']); return resultArray(['data' => '设置成功']);
} }
@ -374,7 +429,7 @@ class Setting extends ApiCommon
public function recordEdit() public function recordEdit()
{ {
$param = $this->param; $param = $this->param;
$userInfo=$this->userInfo; $userInfo = $this->userInfo;
//权限判断 //权限判断
if (!checkPerByAction('admin', 'crm', 'setting')) { if (!checkPerByAction('admin', 'crm', 'setting')) {
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
@ -385,18 +440,18 @@ class Setting extends ApiCommon
$record_type = db('crm_config')->where(['name' => 'record_type'])->find(); $record_type = db('crm_config')->where(['name' => 'record_type'])->find();
if ($record_type) { if ($record_type) {
$res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]); $res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]);
$id=$record_type['id']; $id = $record_type['id'];
} else { } else {
$data = array(); $data = array();
$data['name'] = 'record_type'; $data['name'] = 'record_type';
$data['value'] = $array; $data['value'] = $array;
$data['description'] = '跟进记录类型'; $data['description'] = '跟进记录类型';
$res = db('crm_config')->insertGetId($data); $res = db('crm_config')->insertGetId($data);
$id=$res; $id = $res;
$record_type['description']='跟进记录类型'; $record_type['description'] = '跟进记录类型';
} }
if ($res) { if ($res) {
SystemActionLog($userInfo['id'], 'crm_config','customer', $id, 'update',$record_type['description'] , '', '','编辑了跟进记录类型:'.$record_type['description']); SystemActionLog($userInfo['id'], 'crm_config', 'customer', $id, 'update', $record_type['description'], '', '', '编辑了跟进记录类型:' . $record_type['description']);
return resultArray(['data' => '设置成功']); return resultArray(['data' => '设置成功']);
} else { } else {
return resultArray(['error' => '设置失败,请重试!']); return resultArray(['error' => '设置失败,请重试!']);
@ -460,7 +515,8 @@ class Setting extends ApiCommon
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code' => 102, 'error' => '无权操作'])); exit(json_encode(['code' => 102, 'error' => '无权操作']));
} }
$userInfo = $this->userInfo;
$this->param['user_id'] = $userInfo['id'];
$customerConfigModel = new \app\crm\model\CustomerConfig(); $customerConfigModel = new \app\crm\model\CustomerConfig();
if (!$customerConfigModel->createData($this->param)) { if (!$customerConfigModel->createData($this->param)) {
return resultArray(['error' => $customerConfigModel->getError()]); return resultArray(['error' => $customerConfigModel->getError()]);
@ -581,10 +637,10 @@ class Setting extends ApiCommon
{ {
$status = !empty($this->param['status']) ? $this->param['status'] : 0; $status = !empty($this->param['status']) ? $this->param['status'] : 0;
$day = !empty($this->param['day']) ? $this->param['day'] : 0; $day = !empty($this->param['day']) ? $this->param['day'] : 0;
$userInfo = $this->userInfo;
$settingModel = new \app\crm\model\Setting(); $settingModel = new \app\crm\model\Setting();
if (!$settingModel->setVisitDay($status, $day)) return resultArray(['error' => '操作失败!']); if (!$settingModel->setVisitDay($status, $day, $userInfo['id'])) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
@ -602,6 +658,7 @@ class Setting extends ApiCommon
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 设置自动编号 * 设置自动编号
* *
@ -610,11 +667,50 @@ class Setting extends ApiCommon
public function setNumber() public function setNumber()
{ {
if (empty($this->param) || !is_array($this->param)) return resultArray(['error' => '参数错误!']); if (empty($this->param) || !is_array($this->param)) return resultArray(['error' => '参数错误!']);
$userInfo = $this->userInfo;
$settingModel = new \app\crm\model\Setting();
if ($settingModel->setNumber($this->param, $userInfo['id']) === false) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
}
/**
* 手机端导航栏显示
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 11:27
*/
public function appMenuConfig(){
$param=$this->userInfo['id'];
$settingModel = new \app\crm\model\Setting(); $settingModel = new \app\crm\model\Setting();
$data=$settingModel->appMenuConfig($param);
return resultArray(['data' => $data]);
}
if ($settingModel->setNumber($this->param) === false) return resultArray(['error' => '操作失败!']); /**
* 手机端办公数量
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 13:44
*/
public function oaNumber(){
$userInfo=$this->userInfo;
return resultArray(['data' => '操作成功!']); # 日志
$logNum=db('oa_log')->where('create_user_id',$userInfo['id'])->count();
#审批
$examineNum=db('oa_examine')->where('create_user_id',$userInfo['id'])->count();
#任务
$taskNum=db('task')->where('create_user_id',$userInfo['id'])->count();
#跟进
$activityNum=db('crm_activity')->where(['create_user_id'=>$userInfo['id'],'type'=>1])->count();
$data=[];
$data['logNum']=$logNum;
$data['examineNum']=$examineNum;
$data['taskNum']=$taskNum;
$data['activityNu']=$activityNum;
return $data;
} }
} }

@ -444,7 +444,11 @@ class ActivityLogic
$param['business_ids'] = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : ''; $param['business_ids'] = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
$param['create_time'] = time(); $param['create_time'] = time();
$param['update_time'] = time(); $param['update_time'] = time();
if(empty($param['excel'])){
if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ','; if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ',';
}else{
unset($param['excel']);
}
$activityJson = Activity::create($param); $activityJson = Activity::create($param);
if (empty($activityJson)) return false; if (empty($activityJson)) return false;
@ -549,7 +553,7 @@ class ActivityLogic
* @param $activityId * @param $activityId
* @return Activity * @return Activity
*/ */
public function delete($activityId) public function delete($activityId,$userId)
{ {
$activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find(); $activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find();
if (Activity::update(['activity_id' => $activityId, 'status' => 0])) { if (Activity::update(['activity_id' => $activityId, 'status' => 0])) {
@ -563,9 +567,7 @@ class ActivityLogic
if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete(); if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete();
if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete(); if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete();
if ($activityInfo['activity_type'] == 6) db('crm_contract_file')->whereIn('file_id', $fileIds)->delete(); if ($activityInfo['activity_type'] == 6) db('crm_contract_file')->whereIn('file_id', $fileIds)->delete();
$user=new ApiCommon(); RecordActionLog($userId,'crm_activity','delete','删除跟进记录','','','删除了'.$recordModules[$types].$name);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'],'crm_activity','delete','删除跟进记录','','','删除了'.$recordModules[$types].$name);
return true; return true;
} else { } else {
return false; return false;

@ -10,16 +10,19 @@ namespace app\crm\logic;
use app\admin\controller\ApiCommon; use app\admin\controller\ApiCommon;
use app\admin\model\User; use app\admin\model\User;
use app\admin\traits\FieldVerificationTrait;
use app\crm\model\Customer; use app\crm\model\Customer;
use think\Db; use think\Db;
use think\Validate; use think\Validate;
class CommonLogic class CommonLogic
{ {
use FieldVerificationTrait;
public $error = '操作失败!'; public $error = '操作失败!';
/** /**
* 快捷编辑【线索、客户、联系人、商机、合同、回款、回访、产品】 * 快捷编辑【线索、客户、联系人、商机、合同、回款、发票、回访、产品】
* *
* @param $param * @param $param
* @return false|int|string * @return false|int|string
@ -48,51 +51,46 @@ class CommonLogic
$model = db($types); $model = db($types);
# 主键 # 主键
$primaryKey = ''; $primaryKey = getPrimaryKeyName($types);
// author guogaobo $item模块
$info=''; $info='';
switch ($types) { switch ($types) {
case 'crm_leads' : case 'crm_leads' :
$primaryKey = 'leads_id';
$dataModel=new \app\crm\model\Leads(); $dataModel=new \app\crm\model\Leads();
$info=$dataModel->getDataById($actionId); $info=$dataModel->getDataById($actionId);
break; break;
case 'crm_customer' : case 'crm_customer' :
$primaryKey = 'customer_id';
$info=db('crm_customer')->where('customer_id',$actionId)->find(); $info=db('crm_customer')->where('customer_id',$actionId)->find();
break; break;
case 'crm_contacts' : case 'crm_contacts' :
$primaryKey = 'contacts_id';
$dataModel=new \app\crm\model\Contacts(); $dataModel=new \app\crm\model\Contacts();
$info=$dataModel->getDataById($actionId); $info=$dataModel->getDataById($actionId);
break; break;
case 'crm_business' : case 'crm_business' :
$primaryKey = 'business_id';
$dataModel=new \app\crm\model\Business(); $dataModel=new \app\crm\model\Business();
$info=$dataModel->getDataById($actionId); $info=$dataModel->getDataById($actionId);
break; break;
case 'crm_contract' : case 'crm_contract' :
$primaryKey = 'contract_id';
$info=db('crm_contract')->where('customer_id',$actionId)->find(); $info=db('crm_contract')->where('customer_id',$actionId)->find();
break; break;
case 'crm_receivables' : case 'crm_receivables' :
$primaryKey = 'receivables_id';
$info=db('crm_receivables')->where('customer_id',$actionId)->find(); $info=db('crm_receivables')->where('customer_id',$actionId)->find();
break; break;
case 'crm_invoice' :
$info = $model->where($primaryKey, $actionId)->find();
break;
case 'crm_visit' : case 'crm_visit' :
$primaryKey = 'visit_id';
$dataModel=new \app\crm\logic\VisitLogic(); $dataModel=new \app\crm\logic\VisitLogic();
$info=$dataModel->getDataById($actionId); $info=$dataModel->getDataById($actionId);
break; break;
case 'crm_product' : case 'crm_product' :
$primaryKey = 'product_id';
$dataModel=new \app\crm\model\Product(); $dataModel=new \app\crm\model\Product();
$info=$dataModel->getDataById($actionId); $info=$dataModel->getDataById($actionId);
break; break;
} }
$apiCommon = new ApiCommon(); $apiCommon = new ApiCommon();
$userModel = new User(); $userModel = new User();
$userInfo = $apiCommon->userInfo;
if (in_array($types, ['crm_contract', 'crm_receivables'])) { if (in_array($types, ['crm_contract', 'crm_receivables'])) {
$checkStatus = $model->where($primaryKey, $actionId)->value('check_status'); $checkStatus = $model->where($primaryKey, $actionId)->value('check_status');
@ -101,6 +99,22 @@ class CommonLogic
return false; return false;
} }
} }
// 数据验证
$validateData = [];
if (!empty($param['list'])) {
foreach ($param['list'] AS $key => $value) {
foreach ($value AS $k => $v) {
$validateData[$k] = $v;
}
}
}
$validateResult = $this->fieldDataValidate($validateData, $types, $userInfo['id'], $actionId);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
# 产品修改验证 # 产品修改验证
if($types == 'crm_product'){ if($types == 'crm_product'){
foreach ($param['list'] as $val){ foreach ($param['list'] as $val){
@ -164,41 +178,27 @@ class CommonLogic
$userField = $fieldModel->getFieldByFormType($types, 'user'); $userField = $fieldModel->getFieldByFormType($types, 'user');
# 部门类型 # 部门类型
$structureField = $fieldModel->getFieldByFormType($types, 'structure'); $structureField = $fieldModel->getFieldByFormType($types, 'structure');
# 地址
$positionField = $fieldModel->getFieldByFormType($types, 'position');
# 定位
$locationField = $fieldModel->getFieldByFormType($types, 'location');
# 日期区间
$dateIntervalField = $fieldModel->getFieldByFormType($types, 'date_interval');
# 手写签名
$handwritingField = $fieldModel->getFieldByFormType($types, 'handwriting_sign');
# 明细表格
$detailTableField = $fieldModel->getFieldByFormType($types, 'detail_table');
foreach ($param['list'] as $key => $value) { # 处理数据 data 常规数据 extraData 扩展数据(地址、定位、日期区间、详细表格)
foreach ($value as $k => $v) {
# 查询自定义字段信息
$fieldInfo = Db::name('admin_field')->field(['max_length', 'is_unique', 'is_null', 'name'])
->where('types', $types)->where('field', $k)->find();
# 字符长度
if (!empty($fieldInfo['max_length']) && strlen($v) > $fieldInfo['max_length']) {
$this->error = $fieldInfo['name'] . ' 字符长度不能超过 ' . $fieldInfo['max_length'] . ' 个字符!';
return false;
}
# 必填
if (!empty($fieldInfo['is_null']) && empty($v)) {
$this->error = $fieldInfo['name'] . ' 是必填信息,不能为空!';
return false;
}
# 唯一
if (!empty($fieldInfo['is_unique']) && $model->where([$primaryKey => ['neq', $actionId]])->where($k, $v)->value($primaryKey)) {
$this->error = $fieldInfo['name'] . ' 内容重复!';
return false;
}
}
}
# 编辑参数
$data = []; $data = [];
$extraData = [];
$deleteExtraWhere = [];
if (!empty($param['list'])) { if (!empty($param['list'])) {
foreach ($param['list'] as $key => $value) { foreach ($param['list'] as $key => $value) {
foreach ($value as $k => $v) { foreach ($value as $k => $v) {
if ($k == 'next_time' || in_array($k, $datetimeField)) { if ($k == 'next_time' || in_array($k, $datetimeField)) {
# 处理下次联系时间格式、datetime类型数据 # 处理下次联系时间格式、datetime类型数据
$data[$k] = !empty($v) ? strtotime($v) : ''; $data[$k] = !empty($v) && $v == strtotime($v) ? strtotime($v) : $v;
} elseif ($types == 'crm_product' && $k == 'category_id') { } elseif ($types == 'crm_product' && $k == 'category_id') {
# 处理产品类别 # 处理产品类别
$categorys = explode(',', $v); $categorys = explode(',', $v);
@ -209,25 +209,84 @@ class CommonLogic
} elseif ($types == 'crm_visit' && $k == 'contract_id') { } elseif ($types == 'crm_visit' && $k == 'contract_id') {
# 处理回访提交过来的合同编号 # 处理回访提交过来的合同编号
if (!empty($v[0]['contract_id'])) $data[$k] = $v[0]['contract_id']; if (!empty($v[0]['contract_id'])) $data[$k] = $v[0]['contract_id'];
} elseif (in_array($k, $handwritingField)) {
// 手写签名
$data[$k] = !empty($v['file_id']) ? $v['file_id'] : 0;
} elseif (in_array($k, $positionField)) {
// 地址
if (!empty($v)) {
$extraData[] = [
$primaryKey => $actionId,
'field' => $k,
'content' => json_encode($v),
'create_time' => time()
];
$positionNames = array_column($v, 'name');
$data[$k] = implode(',', $positionNames);
} else {
$data[$k] = '';
}
$deleteExtraWhere[] = $k;
} elseif (in_array($k, $locationField)) {
// 定位
if (!empty($v)) {
$extraData[] = [
$primaryKey => $actionId,
'field' => $k,
'content' => json_encode($v),
'create_time' => time()
];
$data[$k] = $v['address'];
} else {
$data[$k] = '';
}
$deleteExtraWhere[] = $k;
} elseif (in_array($k, $dateIntervalField)) {
// 日期区间
if (!empty($v)) {
$extraData[] = [
$primaryKey => $actionId,
'field' => $k,
'content' => json_encode($v),
'create_time' => time()
];
$data[$k] = implode('_', $v);
} else {
$data[$k] = '';
}
$deleteExtraWhere[] = $k;
} elseif (in_array($k, $detailTableField)) {
// 明细表格
if (!empty($v)) {
$extraData[] = [
$primaryKey => $actionId,
'field' => $k,
'content' => json_encode($v),
'create_time' => time()
];
}
$deleteExtraWhere[] = $k;
} else { } else {
$data[$k] = $v; $data[$k] = $v;
} }
$item[$k]=$v;
} }
} }
$data[$primaryKey] = $actionId; $data[$primaryKey] = $actionId;
$data['update_time'] = time(); $data['update_time'] = time();
} }
$res = $model->update($data); $res = $model->update($data);
unset($data[$primaryKey]); unset($data[$primaryKey]);
unset($data['update_time']); unset($data['update_time']);
//详细信息修改新增操作记录 // 详细信息修改新增操作记录、处理扩展数据
if ($res) { if ($res) {
//修改记录 // 删除扩展数据
$user_id = $apiCommon->userInfo; if (!empty($deleteExtraWhere)) db($types . '_data')->where([$primaryKey => $actionId, 'field' => ['in', $deleteExtraWhere]])->delete();
updateActionLog($user_id['id'], $types, $actionId, $info, $data); // 添加扩展数据
RecordActionLog($user_id['id'], $types, 'update',$info['name'], $info, $data); if (!empty($extraData)) db($types . '_data')->insertAll($extraData);
// 修改记录
updateActionLog($userInfo['id'], $types, $actionId, $info, $data);
RecordActionLog($userInfo['id'], $types, 'update',$info['name'], $info, $data);
} }
return $res; return $res;
} }

@ -39,10 +39,10 @@ class CustomerPoolLogic extends Common
$orderField = $param['order_field']; $orderField = $param['order_field'];
$orderType = $param['order_type']; $orderType = $param['order_type'];
# 基础条件 // 基础条件
$where['relation.pool_id'] = $poolId; $where['relation.pool_id'] = $poolId;
# 普通搜索 // 普通搜索
$searchMap = []; $searchMap = [];
if ($param['search'] == '0' || !empty($param['search'])) { if ($param['search'] == '0' || !empty($param['search'])) {
$search = $param['search']; $search = $param['search'];
@ -53,37 +53,38 @@ class CustomerPoolLogic extends Common
}; };
} }
# 处理排序参数 // 处理排序参数
if (!empty($orderField)) { if (!empty($orderField)) {
if ($orderField == 'create_user_id_name') $orderField = 'create_user_id'; if ($orderField == 'create_user_id_name') $orderField = 'create_user_id';
if ($orderField == 'before_owner_user_name') $orderField = 'before_owner_user_id'; if ($orderField == 'before_owner_user_name') $orderField = 'before_owner_user_id';
} }
# 公海条件 // 公海条件
if ($param['is_excel'] == 1 && !empty($param['customer_id'])) { if ($param['is_excel'] == 1 && !empty($param['customer_id'])) {
$authMap['customer.customer_id'] = ['in', trim(arrayToString($param['customer_id']),',')]; $authMap['customer.customer_id'] = ['in', trim(arrayToString($param['customer_id']),',')];
} }
# 排序 // 排序
if (!empty($orderField) && !empty($orderType)) { if (!empty($orderField) && !empty($orderType)) {
$order = $fieldModel->getOrderByFormtype('crm_customer','customer', $orderField, $orderType); $order = $fieldModel->getOrderByFormtype('crm_customer','customer', $orderField, $orderType);
} else { } else {
$order = 'customer.update_time desc'; $order = 'customer.update_time desc';
} }
# 删除参数 // 删除参数
unset($param['pool_id']); unset($param['pool_id']);
unset($param['search']); unset($param['search']);
unset($param['order_field']); unset($param['order_field']);
unset($param['order_type']); unset($param['order_type']);
unset($param['is_excel']); unset($param['is_excel']);
unset($param['customer_id']); unset($param['customer_id']);
# 格式化参数 // 格式化参数
$request = $this->fmtRequest( $param ); $request = $this->fmtRequest( $param );
$requestMap = !empty($request['map']) ? $request['map'] : []; $requestMap = !empty($request['map']) ? $request['map'] : [];
# 高级搜索 // 高级搜索
$map = where_arr($requestMap, 'crm', 'customer', 'index'); $map = advancedQuery($requestMap, 'crm', 'customer', 'index');
# 公海字段
// 公海字段
$customerFieldString = $this->getPoolQueryField($poolId); $customerFieldString = $this->getPoolQueryField($poolId);
# 公海数据 // 公海数据
$customerPoolCount = db('crm_customer_pool_relation')->alias('relation') $customerPoolCount = db('crm_customer_pool_relation')->alias('relation')
->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT') ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
->where($where)->where($searchMap)->where($map)->where($authMap)->count(); ->where($where)->where($searchMap)->where($map)->where($authMap)->count();
@ -93,18 +94,31 @@ class CustomerPoolLogic extends Common
->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT') ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
->limit($request['offset'], $request['length'])->where($where)->where($searchMap)->where($map)->where($authMap)->orderRaw($order)->select(); ->limit($request['offset'], $request['length'])->where($where)->where($searchMap)->where($map)->where($authMap)->orderRaw($order)->select();
# 员工列表 // 员工列表
$userData = $this->getUserList(); $userData = $this->getUserList();
# 部门列表 // 部门列表
$structureData = $this->getStructureList(); $structureData = $this->getStructureList();
# 特殊字段 // 特殊字段
$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); # 人员类型 $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); # 人员类型
$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); # 部门类型 $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); # 部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); # 日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); # 日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_customer', 'boolean_value'); // 布尔值类型字段
$dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_customer', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_customer', 'location'); // 定位类型字段
# 整理公海数据 // 扩展数据
$extraData = [];
$customerIds = array_column($customerPoolList, 'customer_id');
$extraList = db('crm_customer_data')->whereIn('customer_id', $customerIds)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['customer_id']][$value['field']] = $value['content'];
}
// 整理公海数据
foreach ($customerPoolList AS $key => $value) { foreach ($customerPoolList AS $key => $value) {
$customerPoolList[$key]['create_user_name'] = !empty($userData[$value['create_user_id']]) ? $userData[$value['create_user_id']] : ''; $customerPoolList[$key]['create_user_name'] = !empty($userData[$value['create_user_id']]) ? $userData[$value['create_user_id']] : '';
$customerPoolList[$key]['before_owner_user_name'] = !empty($userData[$value['before_owner_user_id']]) ? $userData[$value['before_owner_user_id']] : ''; $customerPoolList[$key]['before_owner_user_name'] = !empty($userData[$value['before_owner_user_id']]) ? $userData[$value['before_owner_user_id']] : '';
@ -115,23 +129,40 @@ class CustomerPoolLogic extends Common
$customerPoolList[$key]['last_time'] = !empty($value['last_time']) ? date('Y-m-d H:i:s', $value['last_time']) : null; $customerPoolList[$key]['last_time'] = !empty($value['last_time']) ? date('Y-m-d H:i:s', $value['last_time']) : null;
$customerPoolList[$key]['into_pool_time'] = !empty($value['into_pool_time']) ? date('Y-m-d H:i:s', $value['into_pool_time']) : null; $customerPoolList[$key]['into_pool_time'] = !empty($value['into_pool_time']) ? date('Y-m-d H:i:s', $value['into_pool_time']) : null;
# 处理日期时间类型的自定义字段 // 处理日期时间类型的自定义字段
foreach ($datetimeField AS $k => $v) { foreach ($datetimeField AS $k => $v) {
if (isset($datetimeField[$key][$v])) { if (!empty($value[$v])) $customerPoolList[$key][$v] = date('Y-m-d H:i:s', $value[$v]);
$datetimeField[$key][$v] = !empty($value[$v]) ? date('Y-m-d H:i:s', $value[$v]) : null;
} }
} // 处理人员类型的自定义字段
# 处理人员类型的自定义字段
foreach ($userField AS $k => $v) { foreach ($userField AS $k => $v) {
if (isset($datetimeField[$key][$v]) && !empty($value[$v])) { if (!empty($value[$v])) {
$datetimeField[$key][$v] = $this->fieldTransformToText($value[$v], $userData); $customerPoolList[$key][$v] = $this->fieldTransformToText($value[$v], $userData);
} }
} }
# 处理部门类型的自定义字段 // 处理部门类型的自定义字段
foreach ($structureField AS $k => $v) { foreach ($structureField AS $k => $v) {
if (isset($datetimeField[$key][$v]) && !empty($value[$v])) { if (!empty($value[$v])) $customerPoolList[$key][$v] = $this->fieldTransformToText($value[$v], $structureData);
$datetimeField[$key][$v] = $this->fieldTransformToText($value[$v], $structureData); }
// 布尔值类型字段
foreach ($booleanField AS $k => $v) {
$customerPoolList[$key][$v] = !empty($value[$v]) ? (string)$value[$v] : '0';
} }
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $k => $v) {
$customerPoolList[$key][$v] = !empty($extraData[$value['customer_id']][$v]) ? json_decode($extraData[$value['customer_id']][$v], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $k => $v) {
$customerPoolList[$key][$v] = !empty($extraData[$value['customer_id']][$v]) ? json_decode($extraData[$value['customer_id']][$v], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $k => $v) {
$handwritingData = !empty($value[$v]) ? db('admin_file')->where('file_id', $value[$v])->value('file_path') : null;
$customerPoolList[$key][$v] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $k => $v) {
$customerPoolList[$key][$v] = !empty($extraData[$value['customer_id']][$v]) ? json_decode($extraData[$value['customer_id']][$v], true) : null;
} }
} }
@ -307,12 +338,14 @@ class CustomerPoolLogic extends Common
*/ */
public function getPondList($param) public function getPondList($param)
{ {
$adminTypes = adminGroupTypes($param['user_id']);
return db('crm_customer_pool')->field(['pool_id', 'pool_name']) return db('crm_customer_pool')->field(['pool_id', 'pool_name'])
->where('status', 1) ->where('status', 1)
->where(function ($query) use ($param) { ->where(function ($query) use ($param, $adminTypes) {
$query->where('admin_user_ids', 'like', '%,' . $param['user_id'] . ',%'); if (!in_array(1, $adminTypes)) $query->where('admin_user_ids', 'like', '%,' . $param['user_id'] . ',%');
$query->whereOr('user_ids', 'like', '%,' . $param['user_id'] . ',%'); if (!in_array(1, $adminTypes)) $query->whereOr('user_ids', 'like', '%,' . $param['user_id'] . ',%');
$query->whereOr('department_ids', '%,' . $param['structure_id'] . ',%'); if (!in_array(1, $adminTypes)) $query->whereOr('department_ids', '%,' . $param['structure_id'] . ',%');
})->select(); })->select();
} }
@ -329,7 +362,12 @@ class CustomerPoolLogic extends Common
$data = []; $data = [];
# 自定义字段 # 自定义字段
$list = db('crm_customer_pool_field_setting')->where('pool_id', $param['pool_id'])->where('is_hidden', 0)->select(); $where = [
'pool_id' => $param['pool_id'],
'is_hidden' => 0,
'form_type' => ['notin', ['file', 'desc_text', 'detail_table']]
];
$list = db('crm_customer_pool_field_setting')->where($where)->select();
# 处理公海字段 # 处理公海字段
foreach ($list AS $key => $value) { foreach ($list AS $key => $value) {
@ -346,9 +384,6 @@ class CustomerPoolLogic extends Common
default : default :
$list[$key]['fieldName'] = $value['field_name']; $list[$key]['fieldName'] = $value['field_name'];
} }
if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field_name'], ['create_user_id', 'owner_user_id', 'before_owner_user_id'])) {
$list[$key]['fieldName'] = $value['field_name'] . '_name';
}
if (in_array($value['field_name'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'deal_status'])) { if (in_array($value['field_name'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'deal_status'])) {
$list[$key]['system'] = 1; $list[$key]['system'] = 1;
@ -395,7 +430,7 @@ class CustomerPoolLogic extends Common
['field' => 'into_pool_time', 'name' => '进入公海时间', 'form_type' => 'datetime', 'setting' => ''], ['field' => 'into_pool_time', 'name' => '进入公海时间', 'form_type' => 'datetime', 'setting' => ''],
]; ];
# 自定义字段 # 自定义字段
$list = db('admin_field')->field(['field', 'name', 'form_type', 'setting'])->where('types', 'crm_customer')->select(); $list = db('admin_field')->field(['field', 'name', 'form_type', 'setting'])->where('types', 'crm_customer')->whereNotIn('form_type', ['file', 'handwriting_sign', 'desc_text', 'detail_table', 'date_interval'])->select();
$list = array_merge($list, $base); $list = array_merge($list, $base);
# 整理数据 # 整理数据
@ -416,6 +451,7 @@ class CustomerPoolLogic extends Common
*/ */
public function receiveCustomers($param) public function receiveCustomers($param)
{ {
if (empty($param['user_id'])) return ['缺少员工ID']; if (empty($param['user_id'])) return ['缺少员工ID'];
# 查询参数 # 查询参数
@ -453,15 +489,15 @@ class CustomerPoolLogic extends Common
$message[] = '客户《' . $customerData[$value]['name'] . '》领取失败,失败原因:持有客户数达到上限!'; $message[] = '客户《' . $customerData[$value]['name'] . '》领取失败,失败原因:持有客户数达到上限!';
} }
} }
# 可以领取的客户ID取差集 # 可以领取的客户ID取差集
$addCustomerId = count($customerId) == 1 ? $customerId : array_diff($customerId, $failCustomer); $addCustomerId = count($customerId) == 1 ? $customerId : array_diff($customerId, $failCustomer);
# 检查是否还有要领取的客户 # 检查是否还有要领取的客户
if (empty($addCustomerId)) return $message; if (empty($addCustomerId)) return $message;
# 查询领取客户的公海id
$poolId=db('crm_customer_pool_relation')->whereIn('customer_id',$customerId)->value('pool_id');
# 公海配置 # 公海配置
$poolConfig = db('crm_customer_pool')->field(['before_owner_conf', 'before_owner_day', 'receive_conf', 'receive_count'])->where('pool_id', $param['pool_id'])->find(); $poolConfig = db('crm_customer_pool')->field(['before_owner_conf', 'before_owner_day', 'receive_conf', 'receive_count'])->where('pool_id', $poolId)->find();
# 前负责人N天内不能领取客户 # 前负责人N天内不能领取客户
if (!empty($poolConfig['before_owner_conf'])) { if (!empty($poolConfig['before_owner_conf'])) {
@ -483,7 +519,7 @@ class CustomerPoolLogic extends Common
# 检查每天领取的个数限制 # 检查每天领取的个数限制
$countWhere['type'] = 1; $countWhere['type'] = 1;
$countWhere['pool_id'] = $param['pool_id']; $countWhere['pool_id'] = $poolId;
$countWhere['user_id'] = $userId; $countWhere['user_id'] = $userId;
$countWhere['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]]; $countWhere['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
$receiveCount = db('crm_customer_pool_record')->where($countWhere)->count(); $receiveCount = db('crm_customer_pool_record')->where($countWhere)->count();
@ -527,7 +563,7 @@ class CustomerPoolLogic extends Common
$addReceiveData[] = [ $addReceiveData[] = [
'customer_id' => $value, 'customer_id' => $value,
'user_id' => $userId, 'user_id' => $userId,
'pool_id' => $param['pool_id'], 'pool_id' => $poolId,
'type' => 1, 'type' => 1,
'create_time' => time() 'create_time' => time()
]; ];
@ -615,7 +651,8 @@ class CustomerPoolLogic extends Common
# 检查是否还有要领取的客户 # 检查是否还有要领取的客户
if (empty($addCustomerId)) return $message; if (empty($addCustomerId)) return $message;
# 查询分配客户的公海id
$poolId=db('crm_customer_pool_relation')->whereIn('customer_id',$customerId)->value('pool_id');
# 整理客户更新数据 # 整理客户更新数据
$addCustomerData = [ $addCustomerData = [
'owner_user_id' => $userId, 'owner_user_id' => $userId,
@ -653,7 +690,7 @@ class CustomerPoolLogic extends Common
$addReceiveData[] = [ $addReceiveData[] = [
'customer_id' => $value, 'customer_id' => $value,
'user_id' => $userId, 'user_id' => $userId,
'pool_id' => $param['pool_id'], 'pool_id' => $poolId,
'type' => 3, 'type' => 3,
'create_time' => time() 'create_time' => time()
]; ];
@ -755,7 +792,11 @@ class CustomerPoolLogic extends Common
$data = !empty($data) ? json_decode($data, true) :[]; $data = !empty($data) ? json_decode($data, true) :[];
if (!empty($data)) { if (!empty($data)) {
$exceptFields = db('admin_field')->where(['types' => 'crm_customer', 'form_type' => ['in', ['file', 'handwriting_sign', 'desc_text', 'detail_table']]])->column('field');
foreach ($data AS $key => $value) { foreach ($data AS $key => $value) {
if (in_array($value['field'], $exceptFields)) continue;
if (!empty($value['is_hidden'])) { if (!empty($value['is_hidden'])) {
$hideList[] = $value; $hideList[] = $value;
} else { } else {
@ -764,7 +805,12 @@ class CustomerPoolLogic extends Common
} }
} else { } else {
# 公海字段-后台配置数据 # 公海字段-后台配置数据
$poolField = db('crm_customer_pool_field_setting')->where('pool_id', $param['pool_id'])->select(); $where = [
'pool_id' => $param['pool_id'],
'is_hidden' => 0,
'form_type' => ['notin', ['file', 'handwriting_sign', 'desc_text', 'detail_table']]
];
$poolField = db('crm_customer_pool_field_setting')->where($where)->select();
foreach ($poolField AS $key => $value) { foreach ($poolField AS $key => $value) {
if (empty($value['is_hidden'])) { if (empty($value['is_hidden'])) {
$showList[] = [ $showList[] = [

@ -37,16 +37,15 @@ class IndexLogic extends Common
$contractModel = new \app\crm\model\Contract(); $contractModel = new \app\crm\model\Contract();
$receivablesModel = new \app\crm\model\Receivables(); $receivablesModel = new \app\crm\model\Receivables();
$activityModel = new \app\crm\model\Activity(); $activityModel = new \app\crm\model\Activity();
$last_between_time = ByDateTime($param['type']);
if($param['start_time'] && $param['end_time']){ if($param['start_time'] && $param['end_time']){
$param['start_time']=$param['start_time'].'00:00:00'; $param['start_time']=$param['start_time'].' 00:00:00';
$param['end_time']=$param['end_time'].'23:59:59'; $param['end_time']=$param['end_time'].' 23:59:59';
} }
$whereArr = $adminModel->getWhere($param, 1, ''); //统计条件 $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
$lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件 // $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
$userIds = $whereArr['userIds']; $userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time']; $between_time = $whereArr['between_time'];
$last_between_time = $lastArr['between_time'];
$customerNum = 0; //新增客户 $customerNum = 0; //新增客户
$customerLastNum = 0; //上期对比 $customerLastNum = 0; //上期对比
@ -89,11 +88,10 @@ class IndexLogic extends Common
'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1], 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1],
]) ])
); );
$resLastCount = queryCache( $resLastCount = queryCache(
$this->getCountSql([ $this->getCountSql([
'start_time' => $last_between_time[0], 'start_time' => $last_between_time['last_time'][0],
'end_time' => $last_between_time[1], 'end_time' => $last_between_time['last_time'][1],
'customer_auth_user_ids' => array_intersect($userIds, $customer_auth_user_ids) ? : [-1], 'customer_auth_user_ids' => array_intersect($userIds, $customer_auth_user_ids) ? : [-1],
'contacts_auth_user_ids' => array_intersect($userIds, $contacts_auth_user_ids) ? : [-1], 'contacts_auth_user_ids' => array_intersect($userIds, $contacts_auth_user_ids) ? : [-1],
'business_auth_user_ids' => array_intersect($userIds, $business_auth_user_ids) ? : [-1], 'business_auth_user_ids' => array_intersect($userIds, $business_auth_user_ids) ? : [-1],
@ -120,7 +118,6 @@ class IndexLogic extends Common
$contractLastMoneyNum = $resLastCount[3]['count2'] ?: 0; $contractLastMoneyNum = $resLastCount[3]['count2'] ?: 0;
$receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0; $receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0;
$recordLastNum = (int)$resLastCount[5]['count'] ?: 0; $recordLastNum = (int)$resLastCount[5]['count'] ?: 0;
$data = []; $data = [];
$data['data']['customerNum'] = $customerNum; $data['data']['customerNum'] = $customerNum;
$data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum); $data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum);
@ -145,19 +142,12 @@ class IndexLogic extends Common
$data['data']['receivablesMoneyNum'] = $receivablesMoneyNum; $data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
$data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum); $data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
return $data; return $data;
} }
public function getCountSql($param) public function getCountSql($param)
{ {
$configModel = new \app\crm\model\ConfigData();
$configInfo = $configModel->getData();
$follow_day = $configInfo['follow_day'] ? : 0;
$deal_day = $configInfo['deal_day'] ? : 0;
//默认公海条件(没有负责人或已经到期)
$data['follow_time'] = time()-$follow_day*86400;
$data['deal_time'] = time()-$deal_day*86400;
$data['deal_status'] = '未成交';
$countSql = "SELECT $countSql = "SELECT
count(1) count1, count(1) count1,
0 count2 0 count2
@ -210,15 +200,14 @@ class IndexLogic extends Common
///计算涨幅 ///计算涨幅
public function getProportion($now, $last) public function getProportion($now, $last)
{ {
$res = 0;
if ($last && $last != 0.00) { if ($last && $last != 0.00) {
if ($now && $now != 0.00) { if($now-$last>0){
$res = round(($now / $last), 2); $res = round(($now-$last) / $last,2);
}else{
$res =round(($now-$last) / $last,2);
} }
} else { } else {
if ($now && $now != 0.00) { $res = 0;
$res = 1;
}
} }
return $res; return $res;
} }
@ -363,10 +352,6 @@ class IndexLogic extends Common
->field([ ->field([
'SUM(CASE WHEN check_status = 2 THEN money ELSE 0 END) as money', 'SUM(CASE WHEN check_status = 2 THEN money ELSE 0 END) as money',
'contract.owner_user_id as owner_user_id', 'contract.owner_user_id as owner_user_id',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name'
]) ])
->where([ ->where([
'contract.owner_user_id' => ['in', $auth_user_ids], 'contract.owner_user_id' => ['in', $auth_user_ids],
@ -388,10 +373,6 @@ class IndexLogic extends Common
->field([ ->field([
'SUM(CASE WHEN receivables.check_status = 2 THEN receivables.money ELSE 0 END) as money', 'SUM(CASE WHEN receivables.check_status = 2 THEN receivables.money ELSE 0 END) as money',
'receivables.owner_user_id as owner_user_id', 'receivables.owner_user_id as owner_user_id',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name'
]) ])
->where([ ->where([
'receivables.owner_user_id' => ['in', $auth_user_ids], 'receivables.owner_user_id' => ['in', $auth_user_ids],
@ -414,10 +395,6 @@ class IndexLogic extends Common
->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id') ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
->field([ ->field([
'count(contract.contract_id) as count', 'count(contract.contract_id) as count',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name',
'contract.owner_user_id as owner_user_id']) 'contract.owner_user_id as owner_user_id'])
->where([ ->where([
'contract.owner_user_id' => ['in', $auth_user_ids], 'contract.owner_user_id' => ['in', $auth_user_ids],
@ -440,10 +417,6 @@ class IndexLogic extends Common
->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id') ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
->field([ ->field([
'count(customer.customer_id) as count', 'count(customer.customer_id) as count',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name',
'customer.owner_user_id as owner_user_id']) 'customer.owner_user_id as owner_user_id'])
->where( ->where(
'customer.owner_user_id' ,['in', $auth_user_ids] 'customer.owner_user_id' ,['in', $auth_user_ids]
@ -462,10 +435,6 @@ class IndexLogic extends Common
->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id') ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
->field([ ->field([
'count(contacts.contacts_id) as count', 'count(contacts.contacts_id) as count',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name',
'contacts.contacts_id', 'contacts.contacts_id',
'contacts.owner_user_id as owner_user_id']) 'contacts.owner_user_id as owner_user_id'])
->where([ ->where([
@ -484,9 +453,6 @@ class IndexLogic extends Common
->join('__ADMIN_USER__ user', 'activity.create_user_id=user.id') ->join('__ADMIN_USER__ user', 'activity.create_user_id=user.id')
->field([ ->field([
'count(activity.activity_id) as count', 'count(activity.activity_id) as count',
'user.realname as realname',
'user.id',
'user.thumb_img',
'activity.create_user_id as create_user_id']) 'activity.create_user_id as create_user_id'])
->where([ ->where([
'activity.create_user_id' => ['in', $auth_user_ids], 'activity.create_user_id' => ['in', $auth_user_ids],
@ -500,7 +466,15 @@ class IndexLogic extends Common
->select(); ->select();
break; break;
} }
foreach ($list as $k=>$v){
$userInfo=$userModel->getUserById($v['owner_user_id']);
if(!empty($v['create_user_id'])){
$userInfo=$userModel->getUserById($v['create_user_id']);
}
$list[$k]['realname']= $userInfo['realname'];
$list[$k]['id']= $userInfo['id'];
$list[$k]['thumb_img']=$userInfo['thumb_img'] ? getFullPath($v['thumb_img']) : '';
}
//业绩目标 //业绩目标
$between_time = getTimeByType($param['type']); $between_time = getTimeByType($param['type']);
$start_time = $between_time[0]; $start_time = $between_time[0];
@ -587,10 +561,10 @@ class IndexLogic extends Common
$business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index'); $business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
$contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'index'); $contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'index');
$receivables_auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index'); $receivables_auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
$receivablesPlan_auth_user_ids = $userModel->getUserByPer('crm', 'receivables_plan', 'index');
$record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index'); $record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
$resDataArr = []; $resDataArr = [];
for ($i = 1; $i <= 5; $i++) { for ($i = 1; $i <= 6; $i++) {
$resData = queryCache( $resData = queryCache(
$this->getQueryDataSql([ $this->getQueryDataSql([
'type' => $i, 'type' => $i,
@ -602,6 +576,7 @@ class IndexLogic extends Common
'contract_auth_user_ids' => array_intersect($userIds, $contract_auth_user_ids) ? : [-1], 'contract_auth_user_ids' => array_intersect($userIds, $contract_auth_user_ids) ? : [-1],
'receivables_auth_user_ids' => array_intersect($userIds, $receivables_auth_user_ids) ? : [-1], 'receivables_auth_user_ids' => array_intersect($userIds, $receivables_auth_user_ids) ? : [-1],
'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? : [-1], 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? : [-1],
'$receivablesPlan_auth_user_ids' => array_intersect($userIds, $receivablesPlan_auth_user_ids) ? : [-1],
]) ])
); );
$resDataArr = array_merge($resDataArr, $resData[0]); $resDataArr = array_merge($resDataArr, $resData[0]);
@ -661,51 +636,59 @@ class IndexLogic extends Common
SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS contractMoney SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS contractMoney
FROM 5kcrm_crm_contract FROM 5kcrm_crm_contract
WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
AND owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")"; AND owner_user_id IN (" . implode(',', $param['contract_auth_user_ids']) . ")";
break; break;
case 5 : case 5 :
$start_time=date('Y-m-d',$param['start_time']);
$end_time=date('Y-m-d',$param['end_time']);
$countSql = "SELECT $countSql = "SELECT
SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney, SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney
SUM(CASE WHEN p.money > 0 THEN p.money ELSE 0 END) AS planMoney
FROM 5kcrm_crm_receivables as r FROM 5kcrm_crm_receivables as r
LEFT JOIN 5kcrm_crm_receivables_plan AS p ON p.receivables_id = r.receivables_id WHERE r.create_time BETWEEN " . "'".$start_time."'" . " AND " ."'".$end_time."'" . "
WHERE r.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " AND r.owner_user_id IN (" . implode(',', $param['receivables_auth_user_ids']) . ")";
AND r.owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")"; break;
case 6 :
$start_time=date('Y-m-d',$param['start_time']);
$end_time=date('Y-m-d',$param['end_time']);
$countSql = "SELECT
SUM(r.money) AS planMoney
FROM 5kcrm_crm_receivables_plan as r
WHERE r.return_date BETWEEN " . "'".$start_time."'" . " AND " ."'". $end_time."'" . " AND r.receivables_id = 0
AND r.owner_user_id IN (" . implode(',', $param['receivables_auth_user_ids']) . ")";
break; break;
} }
return $countSql; return $countSql;
} }
/** /**
* 赢单输单查看 * 销售漏斗查看
*/ */
public function businessList($param) public function businessList($param)
{ {
$userModel = new \app\admin\model\User();
$adminModel = new \app\admin\model\Admin(); $adminModel = new \app\admin\model\Admin();
if($param['start_time'] && $param['end_time']){ if($param['start_time'] && $param['end_time']){
$param['start_time']=$param['start_time'].'00:00:00'; $between_time[0]=$param['start_time'].'00:00:00';
$param['end_time']=$param['end_time'].'23:59:59'; $between_time[1]=$param['end_time'].'23:59:59';
} }
$whereArr = $adminModel->getWhere($param, 1, ''); //统计条件 $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
$user_id = $param['user_id'] ?: [-1];
$userIds = $whereArr['userIds']; $userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time']; $between_time = $whereArr['between_time'];
//权限控制 $start_time = $between_time[0];
$where_customer['create_time'] = array('between', $between_time); $end_time = $between_time[1];
$auth_customer_user_ids = $userModel->getUserByPer('bi', 'ranking', 'read'); //场景默认全部
$auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集 $scene_id = db('admin_scene')->where(['types' => 'crm_business', 'bydata' => 'all'])->value('scene_id');
$where_customer['owner_user_id'] = array('in', $auth_customer_user_ids); $param['scene_id'] = $scene_id ?: '';
$businessList = db('crm_business') $param['create_time']['start'] = $start_time;
->where([ $param['create_time']['end'] = $end_time;
'owner_user_id' => $where_customer['owner_user_id'],
'create_time' => $where_customer['create_time'], $param['owner_user_id']['value'] = $userIds;
'status_id' => $param['status_id'] unset($param['type']);
]) unset($param['dataType']);
->select(); unset($param['label']);
$data = []; unset($param['log_type']);
$data['businesslist'] = $businessList; unset($param['types']);
$businessModel = new \app\crm\model\Business();
$data=$businessModel->getDataList($param);
return $data; return $data;
} }
@ -792,10 +775,10 @@ class IndexLogic extends Common
$auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集 $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
$where_activity['t.create_user_id'] = array('in', $auth_customer_user_ids); $where_activity['t.create_user_id'] = array('in', $auth_customer_user_ids);
# 跟进记录类型 # 跟进记录类型
$where_activity['t.activity_type'] = $param['activity_type']; $where_activity['t.activity_type'] = $param['activity_type']?:['elt',7];
$where_activity['t.type'] = 1; $where_activity['t.type'] = 1;
$where_activity['t.status'] = 1; $where_activity['t.status'] = 1;
if ($param['label'] == 2) { if ($param['label'] != 1) {
if ($param['search']) { if ($param['search']) {
$type['t.content'] = array('like', '%' . $param['search'] . '%'); $type['t.content'] = array('like', '%' . $param['search'] . '%');
} }
@ -822,14 +805,15 @@ class IndexLogic extends Common
$type['t.type'] = $param['queryType']; $type['t.type'] = $param['queryType'];
} }
if ($param['user_id'] == '') { if ($param['user_id'] == '') {
if ($param['subUser'] == '0') {
if ($param['subUser'] === "0" || $param['subUser']===0) {
$type['t.create_user_id'] = $param['id']; $type['t.create_user_id'] = $param['id'];
//下属创建 //下属创建
} elseif ($param['subUser'] == '1') { } elseif ($param['subUser'] == '1') {
$subList = getSubUserId(false, 0, $param['id']); $subList = getSubUserId(false, 0, $param['id']);
$subStr = $subList ? implode(',', $subList) : '-1'; $subStr = $subList ? implode(',', $subList) : '-1';
$type['t.create_user_id'] = array('in', $subStr); $type['t.create_user_id'] = array('in', $subStr);
} elseif ($param['subUser'] == '') { } else {
$userIds = getSubUserId(true, 0, $param['id']); $userIds = getSubUserId(true, 0, $param['id']);
$subStr = $userIds ? implode(',', $userIds) : '-1'; $subStr = $userIds ? implode(',', $userIds) : '-1';
$type['t.create_user_id'] = array('in', $subStr); $type['t.create_user_id'] = array('in', $subStr);
@ -846,6 +830,15 @@ class IndexLogic extends Common
->page($param['page'], $param['limit']) ->page($param['page'], $param['limit'])
->order('t.create_time desc') ->order('t.create_time desc')
->select(); ->select();
if($param['is_excel']){
$list = db('crm_activity')
->alias('t')
->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
->field('t.content,t.next_time,t.category,t.activity_type,t.type,t.activity_id,t.activity_type_id,t.update_time,t.create_time,user.realname as create_user_name,user.thumb_img')
->where($type)
->order('t.create_time desc')
->select();
}
$dataCount = db('crm_activity') $dataCount = db('crm_activity')
->alias('t') ->alias('t')
->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT') ->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
@ -864,6 +857,7 @@ class IndexLogic extends Common
$activity_contacts = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->select(); $activity_contacts = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->select();
$list[$k]['business_list'] = $activity_business ?: []; $list[$k]['business_list'] = $activity_business ?: [];
$list[$k]['contacts_list'] = $activity_contacts ?: []; $list[$k]['contacts_list'] = $activity_contacts ?: [];
} }
if ($v['activity_type'] == 3) { if ($v['activity_type'] == 3) {
@ -901,21 +895,18 @@ class IndexLogic extends Common
$imgList[] = $val; $imgList[] = $val;
} }
} }
} };
$list[$k]['fileList'] = $fileList ?: []; $list[$k]['fileList'] = $fileList ?: [];
$list[$k]['imgList'] = $imgList ?: []; $list[$k]['imgList'] = $imgList ?: [];
$dataInfo['customerList'] = $relation_list['customer_list'] ?: [];
$dataInfo['contactsList'] = $relation_list['contacts_list'] ?: []; $dataInfo['customerList'] = $relation_list['customerList'] ?: [];
$dataInfo['businessList'] = $relation_list['business_list'] ?: []; $dataInfo['contactsList'] = $relation_list['contactsList'] ?: [];
$dataInfo['contractList'] = $relation_list['contract_list'] ?: []; $dataInfo['businessList'] = $relation_list['businessList'] ?: [];
$dataInfo['contractList'] = $relation_list['contractList'] ?: [];
$list[$k]['business_ids'] = implode(',',array_column($relation_list['businessList'],'name'));
$list[$k]['contacts_ids'] = implode(',',array_column($relation_list['contactsList'],'name'));
$list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : ''; $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
$list[$k]['dataInfo'] = $dataInfo ?: []; $list[$k]['dataInfo'] = $dataInfo ?: [];
$list[$k]['relation'] = arrayToString(array_column($relationArr['businessList'], 'name')) . ' ' .
arrayToString(array_column($relationArr['contactsList'], 'name')) . ' ' .
arrayToString(array_column($relationArr['contractList'], 'name')) . ' ' .
arrayToString(array_column($relationArr['customerList'], 'name'));
} }
} else { } else {
$list = db('crm_activity') $list = db('crm_activity')
@ -981,14 +972,12 @@ class IndexLogic extends Common
} }
$list[$k]['fileList'] = $fileList ?: []; $list[$k]['fileList'] = $fileList ?: [];
$list[$k]['imgList'] = $imgList ?: []; $list[$k]['imgList'] = $imgList ?: [];
$dataInfo['customerList'] = $relation_list['customer_list'] ?: []; $dataInfo['customerList'] = $relation_list['customerList'] ?: [];
$dataInfo['contactsList'] = $relation_list['contacts_list'] ?: []; $dataInfo['contactsList'] = $relation_list['contactsList'] ?: [];
$dataInfo['businessList'] = $relation_list['business_list'] ?: []; $dataInfo['businessList'] = $relation_list['businessList'] ?: [];
$dataInfo['contractList'] = $relation_list['contract_list'] ?: []; $dataInfo['contractList'] = $relation_list['contractList'] ?: [];
$list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : ''; $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
$list[$k]['dataInfo'] = $dataInfo ?: []; $list[$k]['dataInfo'] = $dataInfo ?: [];
$list[$k]['contacts_ids'] = arrayToString(array_column($relationArr['contactsList'], 'name'));
$list[$k]['business_ids'] = arrayToString(array_column($relationArr['businessList'], 'name'));
} }
} }
@ -1002,7 +991,7 @@ class IndexLogic extends Common
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) { } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false; $data['firstPage'] = false;
$data['lastPage'] = false; $data['lastPage'] = false;
} else if ($param['page'] == 1) { } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = true; $data['firstPage'] = true;
$data['lastPage'] = false; $data['lastPage'] = false;
} }

@ -16,6 +16,7 @@ use think\Db;
class InvoiceLogic class InvoiceLogic
{ {
private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据']; private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据'];
private $check_status = ['待审核', '审核中', '审核通过', '审核未通过', '撤回'];
/** /**
* 列表 * 列表
@ -25,101 +26,207 @@ class InvoiceLogic
* @return array * @return array
* @throws \think\exception\DbException * @throws \think\exception\DbException
*/ */
public function index($param, $search = false) public function index($param)
{ {
$field = [ $fieldModel = new \app\admin\model\Field();
'invoice_id', //列表展示字段
'invoice_apple_number', $field = $fieldModel->getIndexField('crm_invoice', $param['user_id'], 1) ?: array('name');
'invoice_money', if (!empty($param['is_excel']) && !empty($param['invoice_id'])) {
'invoice_date', $param['invoice_id'] = ['in', arrayToString($param['invoice_id'])];
'real_invoice_date', }
'invoice_type',
'invoice_number',
'logistics_number',
'check_status',
'invoice_status',
'customer_id',
'contract_id',
'owner_user_id',
'flow_id'
];
$limit = $param['limit'];
$getCount = $param['getCount']; $getCount = $param['getCount'];
$userId = $param['user_id']; $userId = $param['user_id'];
$invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数 $invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数
$dealt = $param['dealt']; $dealt = $param['dealt'];
$order_field = $param['order_field'];
$order_type = $param['order_type'];
$is_excel = $param['is_excel'];
$search = $param['search'];
$scene_id = $param['scene_id'];
$isMessage = !empty($param['isMessage']);
$common = new Common();
unset($param['getCount']); unset($param['getCount']);
unset($param['limit']); // unset($param['limit']); 导出使用 暂未发现为何去掉分页参数
unset($param['page']); // unset($param['page']);
unset($param['user_id']); unset($param['user_id']);
unset($param['invoiceIdArray']); unset($param['invoiceIdArray']);
unset($param['dealt']); unset($param['dealt']);
unset($param['search']);
$where = []; unset($param['order_field']);
if ($search) { unset($param['order_type']);
# 处理基本参数 unset($param['is_excel']);
$scene_id = $param['scene_id'];
unset($param['scene_id']); unset($param['scene_id']);
unset($param['isMessage']);
$common = new Common(); $request = $common->fmtRequest($param);
$where = [];
# 高级搜索 # 高级搜索
$request = $common->fmtRequest($param);
$requestMap = !empty($request['map']) ? $request['map'] : []; $requestMap = !empty($request['map']) ? $request['map'] : [];
unset($requestMap['search']); unset($requestMap['search']);
# 场景 # 场景
$sceneMap = []; $sceneMap = [];
if (!empty($scene_id) && $scene_id == 1) { $sceneModel = new \app\admin\model\Scene();
# 我负责的 if ($scene_id) {
$sceneMap['owner_user_id'] = $userId; //自定义场景
$sceneMap = $sceneModel->getDataById($scene_id, $userId, 'invoice') ?: [];
} else {
//默认场景
$sceneMap = $sceneModel->getDefaultData('crm_invoice', $userId) ?: [];
} }
if (!empty($scene_id) && $scene_id == 2) { //普通筛选
# 我下属负责的 if ($search) {
$subordinate = getSubUserId(false, 0, $userId); # 处理基本参数
$sceneMap['owner_user_id'] = !empty($subordinate) ? ['in', $subordinate] : 0; $searchWhere = function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query->whereLike('customer.name', '%' . $search . '%');
})->whereOr(function ($query) use ($search) {
$query->whereLike('contract.num', '%' . $search . '%');
})->whereOr(function ($query) use ($search) {
$query->whereLike('invoice.invoice_apple_number', '%' . $search . '%');
});
};
} }
# 合并高级搜索和场景的查询条件 # 合并高级搜索和场景的查询条件
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
$map = where_arr($map, 'crm', 'invoice', 'index'); $map = where_arr($map, 'crm', 'invoice', 'index');
# 替换掉字段前缀,不修改公共函数 # 替换掉字段前缀,不修改公共函数
foreach ($map AS $key => $value) { foreach ($map as $key => $value) {
$k = str_replace('invoice.', '', $key); $k = str_replace('invoice.', '', $key);
$where[$k] = $value; $where[$k] = $value;
} }
# 重置查询条件
if ($where) $param = $where;
}
# 待办事项查询参数 # 待办事项查询参数
$dealtWhere = []; $dealtWhere = [];
if (!empty($invoiceIdArray)) $dealtWhere['invoice_id'] = ['in', $invoiceIdArray]; if (!empty($invoiceIdArray)) $dealtWhere['invoice.invoice_id'] = ['in', $invoiceIdArray];
# 权限,不是待办事项,则加上列表权限 # 权限,不是待办事项,则加上列表权限
$auth = []; $auth = [];
if (empty($dealt)) {
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$authUserIds = $userModel->getUserByPer('crm', 'invoice', 'index'); $a = 'index';
$auth['owner_user_id'] = ['in', $authUserIds]; if ($is_excel) $a = 'excelExport';
$auth_user_ids = $userModel->getUserByPer('crm', 'invoice', $a);
if (empty($dealt)) {
//过滤权限
if (isset($map['invoice.owner_user_id']) && $map['invoice.owner_user_id'][0] != 'like') {
if (!is_array($map['invoice.owner_user_id'][1])) {
$map['invoice.owner_user_id'][1] = [$map['invoice.owner_user_id'][1]];
} }
if (in_array($map['invoice.owner_user_id'][0], ['neq', 'notin'])) {
$auth_user_ids = array_diff($auth_user_ids, $map['invoice.owner_user_id'][1]) ?: []; //取差集
} else {
$auth_user_ids = array_intersect($map['invoice.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
}
unset($map['invoice.owner_user_id']);
}
}
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
// 待办事项的待审核发票不一定是自己创建的
if (!$isMessage) {
$auth['invoice.owner_user_id'] = ['in', $auth_user_ids];
}
if ($order_type && $order_field) {
$order = $fieldModel->getOrderByFormtype('crm_invoice', 'invoice', $order_field, $order_type);
} else {
$order = 'invoice.update_time desc';
}
$join = [
['__CRM_CUSTOMER__ customer', 'customer.customer_id=invoice.customer_id', 'LEFT'],
['__CRM_CONTRACT__ contract', 'contract.contract_id=invoice.contract_id', 'LEFT'],
['__ADMIN_USER__ user', 'user.id=invoice.owner_user_id', 'LEFT'],
['__ADMIN_USER__ u', 'u.id=invoice.create_user_id', 'LEFT'],
];
# 查询数据 # 查询数据
$list = Invoice::with(['toCustomer', 'toContract', 'toAdminUser'])->field($field)->where($auth) $list = db('crm_invoice')
->where($param)->where($dealtWhere)->limit($limit)->order('update_time', 'desc')->paginate($limit)->toArray(); ->alias('invoice')
->join($join)
->field(array_merge($field, [
'customer.name' => 'customer_name',
'user.realname' => 'owner_user_name',
'contract.num' => 'contract_num',
'contract.money' => 'contract_money',
'u.realname' => 'create_user_name',
]))->where($auth)
->where($map)
->where($dealtWhere)
->where($searchWhere)
->limit($request['offset'], $request['length'])
->orderRaw($order)
->select();
$dataCount = db('crm_invoice')
->alias('invoice')
->join($join)
->field(array_merge($field, [
'customer.name' => 'customer_name',
'user.realname' => 'owner_user_name',
'contract.num' => 'contract_num',
'contract.money' => 'contract_money',
'u.realname' => 'create_user_name',
]))->where($auth)
->where($map)
->where($dealtWhere)->where($searchWhere)->count();
$userField = $fieldModel->getFieldByFormType('crm_invoice', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_invoice', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_invoice', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_invoice', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_invoice', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_invoice', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_invoice', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_invoice', 'location'); // 定位类型字段
# 扩展数据
$extraData = [];
$invoice_id_list = !empty($list) ? array_column($list, 'invoice_id') : [];
$extraList = db('crm_invoice_data')->whereIn('invoice_id', $invoice_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['invoice_id']][$value['field']] = $value['content'];
}
# 处理发票类型 # 处理发票类型
// foreach ($list['data'] AS $key => $value) { foreach ($list as $key => $value) {
// $list['data'][$key]['invoice_type'] = $this->invoiceType[$value['invoice_type']]; $list[$key]['check_status_info'] = $this->check_status[$value['check_status']];
// } $list[$key]['invoice_status'] = !empty($value['invoice_status']) ? '已开票' : '未开票';
$list[$key]['create_time'] = !empty($value['create_time']) ? date('Y-m-d H:i:s',$value['create_time']) : null;
return ['list' => $list['data'], 'dataCount' => $list['total']]; $list[$key]['update_time'] = !empty($value['update_time']) ? date('Y-m-d H:i:s',$value['update_time']) : null;
foreach ($userField as $k => $val) {
$usernameField = !empty($value[$val]) ? db('admin_user')->whereIn('id', stringToArray($value[$val]))->column('realname') : [];
$list[$key][$val] = implode($usernameField, ',');
}
foreach ($structureField as $k => $val) {
$structureNameField = !empty($value[$val]) ? db('admin_structure')->whereIn('id', stringToArray($value[$val]))->column('name') : [];
$list[$key][$val] = implode($structureNameField, ',');
}
foreach ($datetimeField as $k => $val) {
$list[$key][$val] = !empty($value[$val]) ? date('Y-m-d H:i:s', $value[$val]) : null;
}
foreach ($booleanField as $k => $val) {
$list[$key][$val] = !empty($value[$val]) ? (string)$value[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField as $k => $val) {
$list[$key][$val] = !empty($extraData[$value['invoice_id']][$val]) ? json_decode($extraData[$value['invoice_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField as $k => $val) {
$list[$key][$val] = !empty($extraData[$value['invoice_id']][$val]) ? json_decode($extraData[$value['invoice_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $k => $val) {
$handwritingData = !empty($value[$val]) ? db('admin_file')->where('file_id', $value[$val])->value('file_path') : null;
$list[$key][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField as $k => $val) {
$list[$key][$val] = !empty($extraData[$value['invoice_id']][$val]) ? json_decode($extraData[$value['invoice_id']][$val], true) : null;
}
}
$data = [];
$data['list'] = $list ?: [];
$data['dataCount'] = $dataCount ?: 0;
return $data;
} }
/** /**
@ -169,12 +276,12 @@ class InvoiceLogic
$result['invoice_number'] = $dataArray['invoice_number']; # 发票号码 $result['invoice_number'] = $dataArray['invoice_number']; # 发票号码
$result['real_invoice_date'] = $dataArray['real_invoice_date']; # 开票日期 $result['real_invoice_date'] = $dataArray['real_invoice_date']; # 开票日期
$result['flow_id'] = $dataArray['flow_id']; # 审核ID $result['flow_id'] = $dataArray['flow_id']; # 审核ID
$check=['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'审核未通过','4'=>'撤销','5'=>'草稿(未提交)','6'=>'作废']; $check = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '审核未通过', '4' => '撤销', '5' => '草稿(未提交)', '6' => '作废'];
# 基本信息 # 基本信息
$result['essential'] = [ $result['essential'] = [
'invoice_apple_number' => $dataArray['invoice_apple_number'], 'invoice_apple_number' => $dataArray['invoice_apple_number'],
'customer_name' => $dataArray['customer_name'], 'customer_name' => $dataArray['customer_name'],
'contract_number' => $dataArray['contract_number'], 'contract_num' => $dataArray['contract_number'],
'contract_money' => $dataArray['contract_money'], 'contract_money' => $dataArray['contract_money'],
'invoice_money' => $dataArray['invoice_money'], 'invoice_money' => $dataArray['invoice_money'],
'invoice_date' => $dataArray['invoice_date'], 'invoice_date' => $dataArray['invoice_date'],

@ -0,0 +1,272 @@
<?php
namespace app\crm\logic;
use app\admin\model\Common;
use app\crm\model\Customer;
use think\Db;
use function foo\func;
class MessageLogic extends Common
{
/**
*
* 今日续联系线索列表
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/24 0024 11:43
*/
public function todayLeads($param)
{
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
$todayTime = getTimeByType('today');
unset($param['type']);
unset($param['isSub']);
$request = $this->where($param, $type, $isSub, $todayTime);
$leadsModel = new \app\crm\model\Leads();
$data = $leadsModel->getDataList($request);
return $data;
}
/**
* 客户
* @param $request
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/25 0025 09:17
*/
public function remindCustomer($param)
{
$type = $param['type'] ?: 1;
$isSub = $param['isSub'] ?: '';
$todayTime = getTimeByType('today');
unset($param['type']);
unset($param['isSub']);
$request = $this->where($param, $type, $isSub, $todayTime);
$customerModel = model('Customer');
$data = $customerModel->getDataList($request);
return $data;
}
/**
*
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 10:13
*/
public function todayBusiness($param)
{
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
$todayTime = getTimeByType('today');
unset($param['type']);
unset($param['isSub']);
$request = $this->where($param, $type, $isSub, $todayTime);
$businessModel = new \app\crm\model\Business();
$data = $businessModel->getDataList($request);
return $data;
}
/**
* 分配给我的线索
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 10:32
*/
public function followLeads($param)
{
$type = $param['type'] ?: 1;
unset($param['type']);
$request = $this->where($param, $type, '', '');
$leadsModel = model('Leads');
$data = $leadsModel->getDataList($request);
return $data;
}
/**
* 分配给我的客户
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 10:36
*/
public function followCustomer($param)
{
$type = $param['type'] ?: 1;
$isSub = $param['isSub'] ?: '';
unset($param['type']);
unset($param['isSub']);
$request = $this->where($param, $type, $isSub, '');
unset($param['user_id']);
$customerModel = model('Customer');
$data = $customerModel->getDataList($request);
return $data;
}
/**
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 11:42
*/
public function checkContract($param)
{
$type = $param['type'] ?: 1;
unset($param['type']);
$contractModel = model('Contract');
$request = $this->whereCheck($param, $type);
$request['isMessage'] = true;
$data = $contractModel->getDataList($request);
return $data;
}
/**
* 待审核回款
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 11:48
*/
public function checkReceivables($param){
$type = $param['type'] ? : 1;
$isSub = 1;
unset($param['type']);
$receivablesModel = model('Receivables');
$request = $this->whereCheck($param, $type,$isSub);
$request['isMessage'] = true;
$data = $receivablesModel->getDataList($request);
return $data;
}
/**
*待审核发票
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 13:35
*/
public function checkInvoice($param){
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = 2;
# 清除与模型无关的数据
unset($param['type']);
$request = $this->whereCheck($param, $type,$isSub);
$request['isMessage'] = true;
$data = (new InvoiceLogic())->index($request);
return $data;
}
/**
* 审批查询条件
* @param $param
* @param $type
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 11:43
*/
public function whereCheck($param, $type,$isSub='')
{
if(empty($isSub)){
switch ($type) {
case '1' :
$param['check_status'] = ['lt', '2'];
$param['check_user_id'] = ['like', '%,' . $param['user_id'] . ',%'];
# 要提醒的合同ID
$contractIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'user_id' => ['eq', $param['user_id']]])->column('types_id');
$param['contractIdArray'] = !empty($contractIdArray) ? $contractIdArray : -1;
break;
case '2' :
$param['flow_user_id'] = ['like', '%,' . $param['user_id'] . ',%'];
break;
}
}else if($isSub==1){
switch ($type) {
case '1' :
# 待审核、审核中
$param['check_status'] = ['lt','2'];
$param['check_user_id'] = ['like','%,'.$param['user_id'].',%'];
# 要提醒的回款ID
$receivablesIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'user_id' => ['eq', $param['user_id']]])->column('types_id');
$param['receivablesIdArray'] = !empty($receivablesIdArray) ? $receivablesIdArray : -1;
break;
case '2' :
# 全部
$param['flow_user_id'] = ['like','%,'.$param['user_id'].',%'];
break;
}
}elseif($isSub==2){
switch ($type) {
case '1' :
# 待审核、审核中
$param['check_status'] = ['lt', 2];
$param['check_user_id'] = ['like', '%,'. $param['user_id'] .',%'];
# 要提醒的发票ID
$invoiceIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'user_id' => ['eq', $param['user_id']]])->column('types_id');
$param['invoiceIdArray'] = !empty($invoiceIdArray) ? $invoiceIdArray : -1;
$param['dealt'] = 1;
break;
case '2' :
# 全部
$param['flow_user_id'] = ['like', '%,'. $param['user_id'] .',%'];
$param['dealt'] = 1;
break;
}
}
return $param;
}
/**
* 负责人查询条件
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/24 0024 09:46
*/
public function where($param, $type, $isSub, $todayTime)
{
# 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $param['user_id'])] : ['eq', $param['user_id']];
# 类型1今日需联系2已逾期3已联系
if (empty($isSub) && empty($todayTime)) {
switch ($type) {
case '1' :
$param['follow'] = [['neq', '已跟进'], null, 'or'];
$param['is_allocation'] = 1;
break;
case '2' :
$param['follow'] = ['eq', '已跟进'];
$param['is_allocation'] = 1;
break;
}
} else {
switch ($type) {
case '1' :
$param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
$param['is_dealt'] = ['neq', 1];
break;
case '2' :
$param['next_time'] = ['between', [1, time()]];
$param['overdue'] = true;
$param['is_dealt'] = ['neq', 1];
break;
case '3' :
$param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
break;
}
}
return $param;
}
}

@ -328,6 +328,9 @@ class PrintingLogic
$contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find(); $contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find();
# 查询产品数据 # 查询产品数据
$businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('business_id', $contractData['business_id'])->select(); $businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('business_id', $contractData['business_id'])->select();
if (empty($businessProduct)) {
$businessProduct = Db::name('crm_contract_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('contract_id', $id)->select();
}
$productIdArray = []; $productIdArray = [];
foreach ($businessProduct AS $key => $value) { foreach ($businessProduct AS $key => $value) {
$productIdArray[] = $value['product_id']; $productIdArray[] = $value['product_id'];
@ -525,8 +528,8 @@ class PrintingLogic
} }
# 替换整单折扣 # 替换整单折扣
$content = str_replace('{整单折扣}', $businessData['discount_rate'], $content); $content = str_replace('{整单折扣}', !empty($businessData['discount_rate']) ? $businessData['discount_rate'] : $contractData['discount_rate'], $content);
$content = str_replace('{产品总金额}', $businessData['money'], $content); $content = str_replace('{产品总金额}', !empty($businessData['money']) ? $businessData['money'] : $contractData['money'], $content);
return $content; return $content;
} }

@ -4,12 +4,14 @@ namespace app\crm\logic;
use app\admin\controller\ApiCommon; use app\admin\controller\ApiCommon;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\traits\FieldVerificationTrait;
use app\crm\model\Visit; use app\crm\model\Visit;
use think\Db; use think\Db;
use think\Validate;
class VisitLogic extends Common class VisitLogic extends Common
{ {
use FieldVerificationTrait;
/** /**
* 获取回访列表 * 获取回访列表
* @param $param * @param $param
@ -54,7 +56,7 @@ class VisitLogic extends Common
} }
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'visit', 'index'); $map = advancedQuery($map, 'crm', 'visit', 'index');
$authMap = []; $authMap = [];
if (!$partMap) { if (!$partMap) {
@ -93,6 +95,11 @@ class VisitLogic extends Common
$userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型 $userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_visit', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_visit', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_visit', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_visit', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_visit', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_visit', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_visit', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -133,7 +140,13 @@ class VisitLogic extends Common
->join('__CRM_CONTRACT__ contract', 'visit.contract_id=contract.contract_id', 'LEFT') ->join('__CRM_CONTRACT__ contract', 'visit.contract_id=contract.contract_id', 'LEFT')
->join('__CRM_CONTACTS__ contacts', 'visit.contacts_id=contacts.contacts_id', 'LEFT') ->join('__CRM_CONTACTS__ contacts', 'visit.contacts_id=contacts.contacts_id', 'LEFT')
->where($map)->where($partMap)->where($authMap)->group('visit.visit_id')->count('visit.visit_id'); ->where($map)->where($partMap)->where($authMap)->group('visit.visit_id')->count('visit.visit_id');
# 扩展数据
$extraData = [];
$visit_id_list = !empty($list) ? array_column($list, 'visit_id') : [];
$extraList = db('crm_visit_data')->whereIn('visit_id', $visit_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['visit_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) { foreach ($list as $k => $v) {
$list[$k]['contract_num'] = $v['contract_number']; $list[$k]['contract_num'] = $v['contract_number'];
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
@ -151,6 +164,26 @@ class VisitLogic extends Common
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['visit_id']][$val]) ? json_decode($extraData[$v['visit_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['visit_id']][$val]) ? json_decode($extraData[$v['visit_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['visit_id']][$val]) ? json_decode($extraData[$v['visit_id']][$val], true) : null;
}
$list[$k]['contract_id_info']['contract_id'] = $v['contract_id']; $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'];
$list[$k]['contract_id_info']['name'] = $v['contract_name']; $list[$k]['contract_id_info']['name'] = $v['contract_name'];
$list[$k]['customer_id_info']['customer_id'] = $v['create_user_id']; $list[$k]['customer_id_info']['customer_id'] = $v['create_user_id'];
@ -232,16 +265,18 @@ class VisitLogic extends Common
*/ */
public function createData($param) public function createData($param)
{ {
// 回访扩展表数据
$visitData = [];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证 // 数据验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, 'crm_visit', $param['create_user_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$result = $validate->check($param); $this->error = $validateResult;
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
if (!$param['customer_id']) { if (!$param['customer_id']) {
$this->error = '请选择相关客户'; $this->error = '请选择相关客户';
return false; return false;
@ -263,14 +298,88 @@ class VisitLogic extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_visit', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType('crm_visit', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_visit', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_visit', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_visit', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
$visitModel = new Visit(); $visitModel = new Visit();
if ($visitModel->data($param)->allowField(true)->save()) { if ($visitModel->data($param)->allowField(true)->save()) {
$visit_id = $visitModel->visit_id; $visit_id = $visitModel->visit_id;
$data['visit_id'] = $visit_id;
updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访'); updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
RecordActionLog($param['create_user_id'],'crm_visit','save',$param['number'],'','','新增了客户回访'.$param['number']); RecordActionLog($param['create_user_id'],'crm_visit','save',$param['number'],'','','新增了客户回访'.$param['number']);
$data = []; // 添加回访扩展数据
$data['visit_id'] = $visit_id; array_walk($visitData, function (&$val) use ($data) {
$val['visit_id'] = $data['visit_id'];
});
db('crm_visit_data')->insertAll($visitData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -283,6 +392,9 @@ class VisitLogic extends Common
*/ */
public function updateDataById($param, $visit_id = '') public function updateDataById($param, $visit_id = '')
{ {
// 回访扩展表数据
$visitData = [];
$Visit = model('Visit'); $Visit = model('Visit');
$productModel = new \app\crm\model\Product(); $productModel = new \app\crm\model\Product();
$dataInfo = $this->getDataById($visit_id); $dataInfo = $this->getDataById($visit_id);
@ -298,15 +410,14 @@ class VisitLogic extends Common
} }
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, 'crm_visit', $param['user_id'], $param['visit_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$result = $validate->check($param); $this->error = $validateResult;
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_visit'); $arrFieldAtt = $fieldModel->getArrayField('crm_visit');
foreach ($arrFieldAtt as $k => $v) { foreach ($arrFieldAtt as $k => $v) {
@ -320,13 +431,88 @@ class VisitLogic extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_visit', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType('crm_visit', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_visit', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_visit', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_visit', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$visitData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($Visit->update($param, ['visit_id' => $visit_id], true)) { if ($Visit->update($param, ['visit_id' => $visit_id], true)) {
$data['visit_id'] = $visit_id;
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_visit', $visit_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_visit', $visit_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_visit', 'update',$dataInfo['number'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_visit', 'update',$dataInfo['number'], $dataInfo, $param);
$data = []; // 添加回访扩展数据
$data['visit_id'] = $visit_id; db('crm_visit_data')->where('visit_id', $visit_id)->delete();
array_walk($visitData, function (&$val) use ($visit_id) {
$val['visit_id'] = $visit_id;
});
db('crm_visit_data')->insertAll($visitData);
return $data; return $data;
} else { } else {
$this->rollback(); $this->rollback();
@ -371,6 +557,8 @@ class VisitLogic extends Common
if (!$data) { if (!$data) {
return resultArray(['error' => $this->getError()]); return resultArray(['error' => $this->getError()]);
} }
// 删除回访扩展数据
db('crm_visit_data')->whereIn('visit_id', $delIds)->delete();
//删除关联附件 //删除关联附件
$fileModel->delRFileByModule('crm_visit', $delIds); $fileModel->delRFileByModule('crm_visit', $delIds);
//删除关联操作记录 //删除关联操作记录

@ -6,14 +6,15 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use think\Request;
use think\Validate;
use app\crm\model\Business as CrmBusinessModel; use app\crm\model\Business as CrmBusinessModel;
class Business extends Common class Business extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -47,6 +48,7 @@ class Business extends Common
$getCount = $request['getCount']; $getCount = $request['getCount'];
$businessTypeId = $request['typesId']; // 针对mobile $businessTypeId = $request['typesId']; // 针对mobile
$businessStatusId = $request['statusId']; // 针对mobile $businessStatusId = $request['statusId']; // 针对mobile
$overdue = $request['overdue']; // 待办事项下需联系商机(逾期)
unset($request['scene_id']); unset($request['scene_id']);
unset($request['search']); unset($request['search']);
unset($request['user_id']); unset($request['user_id']);
@ -57,7 +59,7 @@ class Business extends Common
unset($request['getCount']); unset($request['getCount']);
unset($request['typesId']); unset($request['typesId']);
unset($request['statusId']); unset($request['statusId']);
unset($request['overdue']);
$request = $this->fmtRequest($request); $request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: []; $requestMap = $request['map'] ?: [];
$sceneModel = new \app\admin\model\Scene(); $sceneModel = new \app\admin\model\Scene();
@ -97,18 +99,16 @@ class Business extends Common
} }
$partMap = []; $partMap = [];
//优先级:普通筛选>高级筛选>场景 //优先级:普通筛选>高级筛选>场景
if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) { if ($requestMap['team_id']) {
//相关团队查询 //相关团队查询
$map = $requestMap; $map = $requestMap;
$partMap = function ($query) use ($sceneMap) { $partMap= advancedQueryFormatForTeam($requestMap,'crm_business','business_id');
$query->where('business.ro_user_id', array('like', '%,' . $sceneMap['ro_user_id'] . ',%')) unset($map['team_id']);
->whereOr('business.rw_user_id', array('like', '%,' . $sceneMap['rw_user_id'] . ',%'));
};
} else { } else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
} }
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'business', 'index'); $map = advancedQuery($map, 'crm', 'business', 'index');
$authMap = []; $authMap = [];
if (!$partMap) { if (!$partMap) {
$a = 'index'; $a = 'index';
@ -156,6 +156,11 @@ class Business extends Common
$userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型 $userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_business', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_business', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_business', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_business', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_business', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_business', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_business', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_business', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -178,13 +183,20 @@ class Business extends Common
$map['is_end']=abs($businessStatusId); $map['is_end']=abs($businessStatusId);
} }
} }
// 待办事项下需联系商机(逾期)
$overdueWhere = '';
if (!empty($overdue)) {
$overdueWhere = "(FROM_UNIXTIME(`business`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`business`.`next_time`,'%Y-%m-%d') OR (ISNULL(`business`.`last_time`) AND `business`.`next_time` < ".time()."))";
}
$readAuthIds = $userModel->getUserByPer('crm', 'business', 'read'); $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
$updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update'); $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete'); $deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
$dataCount = db('crm_business') $dataCount = db('crm_business')
->alias('business') ->alias('business')
->join('__CRM_CUSTOMER__ customer', 'business.customer_id = customer.customer_id', 'LEFT') ->join('__CRM_CUSTOMER__ customer', 'business.customer_id = customer.customer_id', 'LEFT')
->where($map)->where($partMap)->where($authMap)->count('business_id'); ->where($map)->where($partMap)->where($authMap)->where($overdueWhere)->count('business_id');
if (!empty($getCount) && $getCount == 1) { if (!empty($getCount) && $getCount == 1) {
$data['dataCount'] = !empty($dataCount) ? $dataCount : 0; $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
# 商机总金额 # 商机总金额
@ -199,11 +211,19 @@ class Business extends Common
->where($map) ->where($map)
->where($partMap) ->where($partMap)
->where($authMap) ->where($authMap)
->where($overdueWhere)
->limit($request['offset'], $request['length']) ->limit($request['offset'], $request['length'])
->field('business.*,customer.name as customer_name') ->field('business.*,customer.name as customer_name')
->orderRaw($order) ->orderRaw($order)
->select(); ->select();
$endStatus = ['1' => '赢单', '2' => '输单', '3' => '无效']; $endStatus = ['1' => '赢单', '2' => '输单', '3' => '无效'];
# 扩展数据
$extraData = [];
$business_id_list = !empty($list) ? array_column($list, 'business_id') : [];
$extraList = db('crm_business_data')->whereIn('business_id', $business_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['business_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) { foreach ($list as $k => $v) {
$list[$k]['customer_id_info']['customer_id'] = $v['customer_id']; $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
$list[$k]['customer_id_info']['name'] = $v['customer_name']; $list[$k]['customer_id_info']['name'] = $v['customer_name'];
@ -213,15 +233,35 @@ class Business extends Common
$list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : ''; $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val.'_name'] = implode($usernameField, ','); $list[$k][$val] = implode($usernameField, ',');
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $list[$k][$val] = implode($structureNameField, ',');
} }
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['business_id']][$val]) ? json_decode($extraData[$v['business_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['business_id']][$val]) ? json_decode($extraData[$v['business_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['business_id']][$val]) ? json_decode($extraData[$v['business_id']][$val], true) : null;
}
$statusInfo = []; $statusInfo = [];
$status_count = 0; $status_count = 0;
if (!$v['is_end']) { if (!$v['is_end']) {
@ -281,14 +321,15 @@ class Business extends Common
*/ */
public function createData($param) public function createData($param)
{ {
// 商机扩展表数据
$businessData = [];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$productModel = new \app\crm\model\Product(); $productModel = new \app\crm\model\Product();
// 自动验证 // 数据验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$result = $validate->check($param); $this->error = $validateResult;
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
if (!$param['customer_id']) { if (!$param['customer_id']) {
@ -308,6 +349,75 @@ class Business extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 设置今日需联系商机 # 设置今日需联系商机
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0; if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
@ -318,6 +428,7 @@ class Business extends Common
updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机'); updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']); RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']);
$business_id = $this->business_id; $business_id = $this->business_id;
$data['business_id'] = $business_id;
if ($param['product']) { if ($param['product']) {
//产品数据处理 //产品数据处理
$resProduct = $productModel->createObject('crm_business', $param, $business_id); $resProduct = $productModel->createObject('crm_business', $param, $business_id);
@ -334,11 +445,6 @@ class Business extends Common
$data_log['owner_user_id'] = $param['owner_user_id']; $data_log['owner_user_id'] = $param['owner_user_id'];
$data_log['remark'] = '新建商机'; $data_log['remark'] = '新建商机';
Db::name('CrmBusinessLog')->insert($data_log); Db::name('CrmBusinessLog')->insert($data_log);
$data = [];
$data['business_id'] = $business_id;
# 添加活动记录 # 添加活动记录
Db::name('crm_activity')->insert([ Db::name('crm_activity')->insert([
'type' => 2, 'type' => 2,
@ -350,6 +456,11 @@ class Business extends Common
'create_time' => time(), 'create_time' => time(),
'customer_ids' => ',' . $param['customer_id'] . ',' 'customer_ids' => ',' . $param['customer_id'] . ','
]); ]);
// 添加商机扩展数据
array_walk($businessData, function (&$val) use ($data) {
$val['business_id'] = $data['business_id'];
});
db('crm_business_data')->insertAll($businessData);
return $data; return $data;
} else { } else {
@ -366,6 +477,9 @@ class Business extends Common
*/ */
public function updateDataById($param, $business_id = '') public function updateDataById($param, $business_id = '')
{ {
// 商机扩展表数据
$businessData = [];
$productModel = new \app\crm\model\Product(); $productModel = new \app\crm\model\Product();
$dataInfo = $this->getDataById($business_id); $dataInfo = $this->getDataById($business_id);
if (!$dataInfo) { if (!$dataInfo) {
@ -380,14 +494,11 @@ class Business extends Common
} }
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['business_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$this->error = $validateResult;
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
@ -408,6 +519,75 @@ class Business extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$businessData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 设置今日需联系商机 # 设置今日需联系商机
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0; if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
@ -422,13 +602,19 @@ class Business extends Common
$param['is_end'] = $param['status_id']; $param['is_end'] = $param['status_id'];
} }
if ($this->update($param, ['business_id' => $business_id], true)) { if ($this->update($param, ['business_id' => $business_id], true)) {
$data['business_id'] = $business_id;
//产品数据处理 //产品数据处理
$resProduct = $productModel->createObject('crm_business', $param, $business_id); $resProduct = $productModel->createObject('crm_business', $param, $business_id);
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_business', 'update',$dataInfo['name'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_business', 'update',$dataInfo['name'], $dataInfo, $param);
$data = []; // 添加商机扩展数据
$data['business_id'] = $business_id; db('crm_business_data')->where('business_id', $business_id)->delete();
array_walk($businessData, function (&$val) use ($business_id) {
$val['business_id'] = $business_id;
});
db('crm_business_data')->insertAll($businessData);
return $data; return $data;
} else { } else {
$this->rollback(); $this->rollback();

@ -199,9 +199,7 @@ class BusinessStatus extends Common
// 提交事务 // 提交事务
Db::commit(); Db::commit();
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); SystemActionLog($param['user_id'], 'crm_business','customer', $type_id, 'update',$dataInfo['name'] , '', '','编辑了商机组:'.$dataInfo['name']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_business','customer', $type_id, 'update',$dataInfo['name'] , '', '','编辑了商机组:'.$dataInfo['name']);
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error = '编辑失败'; $this->error = '编辑失败';
@ -230,13 +228,13 @@ class BusinessStatus extends Common
/** /**
* [delDataById 根据id删除数据] * [delDataById 根据id删除数据]
* @param string $id [主键] * @param string $param['id'] [主键]
* @param boolean $delSon [是否删除子孙数据] * @param boolean $delSon [是否删除子孙数据]
* @return [type] [description] * @return [type] [description]
*/ */
public function delDataById($id = '', $delSon = false) public function delDataById($param = '', $delSon = false)
{ {
if (!$id) { if (!$param['id']) {
$this->error = '删除失败'; $this->error = '删除失败';
return false; return false;
} }
@ -249,16 +247,12 @@ class BusinessStatus extends Common
//启动事务 //启动事务
Db::startTrans(); Db::startTrans();
try { try {
db('crm_business_type')->where(['type_id' => $id])->update(['is_display' => 0]); db('crm_business_type')->where(['type_id' => $param['id']])->update(['is_display' => 0]);
// db('crm_business_type')->where(['type_id' => $id])->delete();
// db('crm_business_status')->where(['type_id' => $id])->delete();
// 提交事务 // 提交事务
Db::commit(); Db::commit();
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); $data=db('crm_business_type')->where(['type_id' => $param['id']])->find();
$userInfo=$user->userInfo; SystemActionLog($param['user_id'], 'crm_business','customer', $param['id'], 'update',$data['name'] , '', '','删除了商机组:'.$data['name']);
$data=db('crm_business_type')->where(['type_id' => $id])->find();
SystemActionLog($userInfo['id'], 'crm_business','customer', $id, 'update',$data['name'] , '', '','删除了商机组:'.$data['name']);
return true; return true;
} catch(\Exception $e) { } catch(\Exception $e) {

@ -6,13 +6,15 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use think\Request;
use think\Validate; use think\Validate;
class Contacts extends Common class Contacts extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -24,11 +26,11 @@ class Contacts extends Common
/** /**
* [getDataList 联系人list] * [getDataList 联系人list]
* @author Michael_xu
* @param [string] $map [查询条件] * @param [string] $map [查询条件]
* @param [number] $page [当前页数] * @param [number] $page [当前页数]
* @param [number] $limit [每页数量] * @param [number] $limit [每页数量]
* @return [array] [description] * @return [array] [description]
* @author Michael_xu
*/ */
public function getDataList($request) public function getDataList($request)
{ {
@ -46,37 +48,45 @@ class Contacts extends Common
$pageType = $request['pageType']; $pageType = $request['pageType'];
$getCount = $request['getCount']; $getCount = $request['getCount'];
//需要过滤的参数 //需要过滤的参数
$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap','business_id','check_status']; $unsetRequest = ['scene_id', 'search', 'user_id', 'is_excel', 'action', 'order_field', 'order_type', 'is_remind', 'getCount', 'type', 'otherMap', 'business_id', 'check_status'];
foreach ($unsetRequest as $v) { foreach ($unsetRequest as $v) {
unset($request[$v]); unset($request[$v]);
} }
$request = $this->fmtRequest( $request ); $request = $this->fmtRequest($request);
$requestMap = $request['map'] ? : []; $requestMap = $request['map'] ?: [];
$sceneModel = new \app\admin\model\Scene(); $sceneModel = new \app\admin\model\Scene();
if ($scene_id) { if ($scene_id) {
//自定义场景 //自定义场景
$sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ? : []; $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ?: [];
} else { } else {
//默认场景 //默认场景
$sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ? : []; $sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ?: [];
} }
$searchMap = []; $searchMap = [];
if ($search || $search == '0') { if ($search || $search == '0') {
//普通筛选 //普通筛选
$searchMap = function($query) use ($search){ $searchMap = function ($query) use ($search) {
$query->where('contacts.name',array('like','%'.$search.'%')) $query->where('contacts.name', array('like', '%' . $search . '%'))
->whereOr('contacts.mobile',array('like','%'.$search.'%')) ->whereOr('contacts.mobile', array('like', '%' . $search . '%'))
->whereOr('contacts.telephone',array('like','%'.$search.'%')); ->whereOr('contacts.telephone', array('like', '%' . $search . '%'));
}; };
// $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '联系人姓名'];
} }
$partMap = [];
//优先级:普通筛选>高级筛选>场景 //优先级:普通筛选>高级筛选>场景
if ($requestMap['team_id']) {
//相关团队查询
$map = $requestMap;
$partMap= advancedQueryFormatForTeam($requestMap,'crm_contacts','contacts_id');
unset($map['team_id']);
} else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'contacts', 'index'); $map = advancedQuery($map, 'crm', 'contacts', 'index');
//权限 //权限
if (!$partMap) {
$a = 'index'; $a = 'index';
if ($is_excel) $a = 'excelExport'; if ($is_excel) $a = 'excelExport';
$authMap = []; $authMap = [];
@ -86,29 +96,46 @@ class Contacts extends Common
$map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]]; $map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]];
} }
if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) { if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) {
$auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ? : []; //取差集 $auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ?: []; //取差集
} else { } else {
$auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ? : []; //取交集 $auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
} }
unset($map['contacts.owner_user_id']); unset($map['contacts.owner_user_id']);
} $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
//负责人、相关团队 //负责人、相关团队
$authMap['contacts.owner_user_id'] = ['in',$auth_user_ids]; $authMap['contacts.owner_user_id'] = ['in', $auth_user_ids];
} else {
$authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id;
$authMap = function ($query) use ($authMapData) {
$query->where('contacts.owner_user_id', array('in', $authMapData['auth_user_ids']))
->whereOr('contacts.ro_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'))
->whereOr('contacts.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
};
}
}
//联系人商机 //联系人商机
if ($business_id) { if ($business_id) {
$contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id'); $contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
if ($contacts_id) { if ($contacts_id) {
$map['contacts.contacts_id'] = array('in',$contacts_id); $map['contacts.contacts_id'] = array('in', $contacts_id);
}else{ } else {
$map['contacts.contacts_id'] = array('eq',-1); $map['contacts.contacts_id'] = array('eq', -1);
} }
} }
//列表展示字段 //列表展示字段
$indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ? : array('name'); $indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ?: array('name');
$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型 $userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_contacts', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_contacts', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_contacts', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_contacts', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -116,7 +143,7 @@ class Contacts extends Common
} }
//排序 //排序
if ($order_type && $order_field) { if ($order_type && $order_field) {
$order = $fieldModel->getOrderByFormtype('crm_contacts','contacts',$order_field,$order_type); $order = $fieldModel->getOrderByFormtype('crm_contacts', 'contacts', $order_field, $order_type);
} else { } else {
$order = 'contacts.update_time desc'; $order = 'contacts.update_time desc';
} }
@ -130,52 +157,80 @@ class Contacts extends Common
} }
$dataCount = db('crm_contacts') $dataCount = db('crm_contacts')
->alias('contacts') ->alias('contacts')
->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
->where($map) ->where($map)
->where($searchMap) ->where($searchMap)
->where($authMap) ->where($authMap)
->where($partMap)
->where($customerWhere) ->where($customerWhere)
->count('contacts_id'); ->count('contacts_id');
if ($getCount == 1) { if ($getCount == 1) {
$data['dataCount'] = $dataCount ? : 0; $data['dataCount'] = $dataCount ?: 0;
return $data; return $data;
} }
$list = db('crm_contacts') $list = db('crm_contacts')
->alias('contacts') ->alias('contacts')
->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
->where($map) ->where($map)
->where($searchMap) ->where($searchMap)
->where($partMap)
->where($authMap) ->where($authMap)
->where($customerWhere) ->where($customerWhere)
->limit($request['offset'], $request['length']) ->limit($request['offset'], $request['length'])
->field('contacts.*,customer.name as customer_name') ->field('contacts.*,customer.name as customer_name')
->orderRaw($order) ->orderRaw($order)
->select(); ->select();
foreach ($list as $k=>$v) { # 扩展数据
$extraData = [];
$contacts_id_list = !empty($list) ? array_column($list, 'contacts_id') : [];
$extraList = db('crm_contacts_data')->whereIn('contacts_id', $contacts_id_list)->select();
foreach ($extraList as $key => $value) {
$extraData[$value['contacts_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : ''; $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ?: '';
$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : ''; $list[$k]['customer_id_info']['name'] = $v['customer_name'] ?: '';
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val.'_name'] = implode($usernameField, ','); $list[$k][$val] = implode($usernameField, ',');
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $list[$k][$val] = implode($structureNameField, ',');
} }
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField as $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
}
//权限 //权限
$permission = []; $permission = [];
$is_read = 0; $is_read = 0;
$is_update = 0; $is_update = 0;
$is_delete = 0; $is_delete = 0;
if (in_array($v['owner_user_id'],$readAuthIds)) $is_read = 1; if (in_array($v['owner_user_id'], $readAuthIds)) $is_read = 1;
if (in_array($v['owner_user_id'],$updateAuthIds)) $is_update = 1; if (in_array($v['owner_user_id'], $updateAuthIds)) $is_update = 1;
if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1; if (in_array($v['owner_user_id'], $deleteAuthIds)) $is_delete = 1;
$permission['is_read'] = $is_read; $permission['is_read'] = $is_read;
$permission['is_update'] = $is_update; $permission['is_update'] = $is_update;
$permission['is_delete'] = $is_delete; $permission['is_delete'] = $is_delete;
@ -196,30 +251,34 @@ class Contacts extends Common
} }
$data = []; $data = [];
$data['list'] = $list; $data['list'] = $list;
$data['dataCount'] = $dataCount ? : 0; $data['dataCount'] = $dataCount ?: 0;
return $data; return $data;
} }
/** /**
* 创建联系人主表信息 * 创建联系人主表信息
* @author Michael_xu
* @param * @param
* @return * @return
* @author Michael_xu
*/ */
public function createData($param) public function createData($param)
{ {
unset($param['excel']);
// 联系人扩展表数据
$contactsData = [];
$businessId = $param['business_id']; $businessId = $param['business_id'];
unset($param['business_id']); unset($param['business_id']);
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validate = new Validate($validateArr['rule'], $validateArr['message']); $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
$result = $validate->check($param); if (!empty($validateResult)) {
if (!$result) { $this->error = $validateResult;
$this->error = $validate->getError();
return false; return false;
} }
# 处理客户首要联系人 # 处理客户首要联系人
$primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id'); $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) { if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
@ -233,20 +292,89 @@ class Contacts extends Common
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contacts'); $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
foreach ($arrFieldAtt as $k=>$v) { foreach ($arrFieldAtt as $k => $v) {
$param[$v] = arrayToString($param[$v]); $param[$v] = arrayToString($param[$v]);
} }
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) { if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人'); updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
RecordActionLog($param['create_user_id'],'crm_contacts','save',$param['name'],'','','新增了联系人'.$param['name']); RecordActionLog($param['create_user_id'], 'crm_contacts', 'save', $param['name'], '', '', '新增了联系人' . $param['name']);
$data = []; $data = [];
$data['contacts_id'] = $this->contacts_id; $data['contacts_id'] = $this->contacts_id;
@ -267,6 +395,12 @@ class Contacts extends Common
Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]); Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
} }
// 添加联系人扩展数据
array_walk($contactsData, function (&$val) use ($data) {
$val['contacts_id'] = $data['contacts_id'];
});
db('crm_contacts_data')->insertAll($contactsData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -281,7 +415,7 @@ class Contacts extends Common
if (!$idArr) { if (!$idArr) {
return []; return [];
} }
$list = Db::name('CrmContacts')->where(['contacts_id' => ['in',$idArr]])->select(); $list = Db::name('CrmContacts')->where(['contacts_id' => ['in', $idArr]])->select();
return $list; return $list;
} }
@ -299,6 +433,9 @@ class Contacts extends Common
*/ */
public function updateDataById($param, $contacts_id = '') public function updateDataById($param, $contacts_id = '')
{ {
// 联系人扩展表数据
$contactsData = [];
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$dataInfo = $this->getDataById($contacts_id); $dataInfo = $this->getDataById($contacts_id);
if (!$dataInfo) { if (!$dataInfo) {
@ -307,41 +444,107 @@ class Contacts extends Common
} }
//判断权限 //判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update'); $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
if (!in_array($dataInfo['owner_user_id'],$auth_user_ids)) { if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
$this->error = '无权操作'; $this->error = '无权操作';
return false; return false;
} }
$param['contacts_id'] = $contacts_id; $param['contacts_id'] = $contacts_id;
//过滤不能修改的字段 //过滤不能修改的字段
$unUpdateField = ['create_user_id','is_deleted','delete_time']; $unUpdateField = ['create_user_id', 'is_deleted', 'delete_time'];
foreach ($unUpdateField as $v) { foreach ($unUpdateField as $v) {
unset($param[$v]); unset($param[$v]);
} }
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contacts_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$this->error = $validateResult;
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contacts'); $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
foreach ($arrFieldAtt as $k=>$v) { foreach ($arrFieldAtt as $k => $v) {
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]); if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
} }
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 处理首要联系人 # 处理首要联系人
$primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id'); $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
@ -355,11 +558,17 @@ class Contacts extends Common
} }
if ($this->update($param, ['contacts_id' => $contacts_id], true)) { if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
$data['contacts_id'] = $contacts_id;
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_contacts', 'update',$dataInfo['name'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_contacts', 'update', $dataInfo['name'], $dataInfo, $param);
$data = []; // 添加联系人扩展数据
$data['contacts_id'] = $contacts_id; db('crm_contacts_data')->where('contacts_id', $contacts_id)->delete();
array_walk($contactsData, function (&$val) use ($contacts_id) {
$val['contacts_id'] = $contacts_id;
});
db('crm_contacts_data')->insertAll($contactsData);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';
@ -410,7 +619,7 @@ class Contacts extends Common
if (!empty($userId)) { if (!empty($userId)) {
$grantData = getFieldGrantData($userId); $grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId); $userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) { foreach ($dataInfo as $key => $value) {
if (!$userLevel && !empty($grantData['crm_contacts'])) { if (!$userLevel && !empty($grantData['crm_contacts'])) {
$status = getFieldGrantStatus($key, $grantData['crm_contacts']); $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
@ -424,11 +633,11 @@ class Contacts extends Common
/** /**
* [联系人转移] * [联系人转移]
* @author Michael_xu
* @param ids 联系人ID数组 * @param ids 联系人ID数组
* @param owner_user_id 变更负责人 * @param owner_user_id 变更负责人
* @param is_remove 1移出2转为团队成员 * @param is_remove 1移出2转为团队成员
* @return * @return
* @author Michael_xu
*/ */
public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove) public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
{ {

@ -6,14 +6,15 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\model\Message; use app\admin\model\Message;
use think\Request;
use think\Validate;
class Contract extends Common class Contract extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -48,6 +49,7 @@ class Contract extends Common
$is_excel = $request['is_excel']; //导出 $is_excel = $request['is_excel']; //导出
$getCount = $request['getCount']; $getCount = $request['getCount'];
$contractIdArray = $request['contractIdArray']; // 待办事项提醒参数 $contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
$isMessage = !empty($request['isMessage']);
unset($request['scene_id']); unset($request['scene_id']);
unset($request['search']); unset($request['search']);
@ -57,6 +59,7 @@ class Contract extends Common
unset($request['is_excel']); unset($request['is_excel']);
unset($request['getCount']); unset($request['getCount']);
unset($request['contractIdArray']); unset($request['contractIdArray']);
unset($request['isMessage']);
$request = $this->fmtRequest( $request ); $request = $this->fmtRequest( $request );
@ -85,28 +88,19 @@ class Contract extends Common
$query->whereLike('contract.name', '%' . $search . '%'); $query->whereLike('contract.name', '%' . $search . '%');
}); });
}; };
// if (db('crm_customer')->whereLike('name', '%' . $search . '%')->value('customer_id')) {
// $sceneMap['customer_name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '客户名称'];
// } elseif (db('crm_contract')->whereLike('num', '%' . $search . '%')->value('contract_id')) {
// $sceneMap['num'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '合同编号'];
// } else {
// $sceneMap['name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '合同名称'];
// }
} }
$partMap = []; $partMap = [];
//优先级:普通筛选>高级筛选>场景 //优先级:普通筛选>高级筛选>场景
if ($sceneMap['contract.ro_user_id'] && $sceneMap['contract.rw_user_id']) { if ($requestMap['team_id']) {
//相关团队查询 //相关团队查询
$map = $requestMap; $map = $requestMap;
$partMap = function($query) use ($sceneMap){ $partMap= advancedQueryFormatForTeam($requestMap,'crm_contract','contract_id');
$query->where('contract.ro_user_id',array('like','%,'.$sceneMap['ro_user_id'].',%')) unset($map['team_id']);
->whereOr('contract.rw_user_id',array('like','%,'.$sceneMap['rw_user_id'].',%'));
};
} else { } else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
} }
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'contract', 'index'); $map = advancedQuery($map, 'crm', 'contract', 'index');
$order = ['contract.update_time desc']; $order = ['contract.update_time desc'];
$authMap = []; $authMap = [];
if (!$partMap) { if (!$partMap) {
@ -126,6 +120,8 @@ class Contract extends Common
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1']; $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
$authMap['contract.owner_user_id'] = array('in',$auth_user_ids); $authMap['contract.owner_user_id'] = array('in',$auth_user_ids);
} else { } else {
// 待办事项的待审核合同不一定是自己创建的
if (!$isMessage) {
$authMapData = []; $authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids; $authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id; $authMapData['user_id'] = $user_id;
@ -136,6 +132,7 @@ class Contract extends Common
}; };
} }
} }
}
//合同签约人 | 与高级筛选冲突加一个is_array判断 //合同签约人 | 与高级筛选冲突加一个is_array判断
if ($map['contract.order_user_id'] && !is_array($map['contract.order_user_id'][1])) { if ($map['contract.order_user_id'] && !is_array($map['contract.order_user_id'][1])) {
$map['contract.order_user_id'] = ['like','%,'.$map['contract.order_user_id'][1].',%']; $map['contract.order_user_id'] = ['like','%,'.$map['contract.order_user_id'][1].',%'];
@ -146,6 +143,11 @@ class Contract extends Common
$userField = $fieldModel->getFieldByFormType('crm_contract', 'user'); $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_contract', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_contract', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_contract', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_contract', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -209,6 +211,13 @@ class Contract extends Common
->orderRaw($order) ->orderRaw($order)
->group('contract.contract_id') ->group('contract.contract_id')
->select(); ->select();
# 扩展数据
$extraData = [];
$contract_id_list = !empty($list) ? array_column($list, 'contract_id') : [];
$extraList = db('crm_contract_data')->whereIn('contract_id', $contract_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['contract_id']][$value['field']] = $value['content'];
}
foreach ($list as $k=>$v) { foreach ($list as $k=>$v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@ -216,14 +225,34 @@ class Contract extends Common
$list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : ''; $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val.'_name'] = implode($usernameField, ','); $list[$k][$val] = implode($usernameField, ',');
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $list[$k][$val] = implode($structureNameField, ',');
} }
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
}
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
} }
$list[$k]['business_id_info']['business_id'] = $v['business_id']; $list[$k]['business_id_info']['business_id'] = $v['business_id'];
$list[$k]['business_id_info']['name'] = $v['business_name']; $list[$k]['business_id_info']['name'] = $v['business_name'];
@ -231,6 +260,7 @@ class Contract extends Common
$list[$k]['customer_id_info']['name'] = $v['customer_name']; $list[$k]['customer_id_info']['name'] = $v['customer_name'];
$list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id']; $list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
$list[$k]['contacts_id_info']['name'] = $v['contacts_name']; $list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
$list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
$moneyInfo = []; $moneyInfo = [];
$moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']); $moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
$list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00'; $list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
@ -266,6 +296,8 @@ class Contract extends Common
# 签约人姓名 # 签约人姓名
$orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname'); $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
$list[$k]['order_user_name'] = implode(',', $orderNames); $list[$k]['order_user_name'] = implode(',', $orderNames);
unset($list[$k]['order_user_id']);
$list[$k]['order_user_id_name'] = $v['order_user_id'];
} }
$data = []; $data = [];
$data['list'] = $list; $data['list'] = $list;
@ -364,16 +396,17 @@ class Contract extends Common
*/ */
public function createData($param) public function createData($param)
{ {
// 合同扩展表数据
$contractData = [];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$productModel = new \app\crm\model\Product(); $productModel = new \app\crm\model\Product();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param); // 数据验证
if (!$result) { $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
$this->error = $validate->getError(); if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
@ -392,6 +425,75 @@ class Contract extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 下单时间 # 下单时间
$param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time()); $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
@ -456,6 +558,12 @@ class Contract extends Common
} }
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData); if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加合同扩展数据
array_walk($contractData, function (&$val) use ($data) {
$val['contract_id'] = $data['contract_id'];
});
db('crm_contract_data')->insertAll($contractData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -472,6 +580,9 @@ class Contract extends Common
*/ */
public function updateDataById($param, $contract_id = '') public function updateDataById($param, $contract_id = '')
{ {
// 合同扩展表数据
$contractData = [];
$productModel = new \app\crm\model\Product(); $productModel = new \app\crm\model\Product();
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find(); $dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
@ -482,14 +593,11 @@ class Contract extends Common
} }
$param['contract_id'] = $contract_id; $param['contract_id'] = $contract_id;
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contract_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$this->error = $validateResult;
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
@ -512,6 +620,75 @@ class Contract extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$contractData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->update($param, ['contract_id' => $contract_id], true)) { if ($this->update($param, ['contract_id' => $contract_id], true)) {
//产品数据处理 //产品数据处理
@ -549,6 +726,13 @@ class Contract extends Common
} }
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData); if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加合同扩展数据
db('crm_contract_data')->where('contract_id', $contract_id)->delete();
array_walk($contractData, function (&$val) use ($contract_id) {
$val['contract_id'] = $contract_id;
});
db('crm_contract_data')->insertAll($contractData);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';

@ -8,16 +8,15 @@ namespace app\crm\model;
use app\admin\controller\ApiCommon; use app\admin\controller\ApiCommon;
use app\admin\model\User; use app\admin\model\User;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\model\User as UserModel;
use app\admin\model\Record as RecordModel;
use think\Request;
use think\response\Json; use think\response\Json;
use think\Validate;
class Customer extends Common class Customer extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -49,29 +48,32 @@ class Customer extends Common
public function getDataList($request) public function getDataList($request)
{ {
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$structureModel = new \app\admin\model\Structure();
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$search = $request['search']; $search = $request['search'];
$user_id = $request['user_id']; $user_id = $request['user_id'];
$scene_id = (int)$request['scene_id']; $scene_id = (int)$request['scene_id'];
$is_excel = $request['is_excel']; //导出 $is_excel = $request['is_excel']; //导出
$action = $request['action'];
$order_field = $request['order_field']; $order_field = $request['order_field'];
$order_type = $request['order_type']; $order_type = $request['order_type'];
$is_remind = $request['is_remind']; $is_remind = $request['is_remind'];
$getCount = $request['getCount']; $getCount = $request['getCount'];
$otherMap = $request['otherMap']; $otherMap = $request['otherMap'];
unset($request['poolId']); $overdue = $request['overdue']; // 待办事项下需联系客户(逾期)
//需要过滤的参数
$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap']; # 需要过滤的参数
$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap','poolId','overdue'];
foreach ($unsetRequest as $v) { foreach ($unsetRequest as $v) {
unset($request[$v]); unset($request[$v]);
} }
# 格式化参数
$request = $this->fmtRequest( $request ); $request = $this->fmtRequest( $request );
$requestMap = $request['map'] ? : []; $requestMap = $request['map'] ? : [];
$sceneModel = new \app\admin\model\Scene(); $sceneModel = new \app\admin\model\Scene();
# 默认条件
# 客户默认条件
$customerMap = $this->getWhereByCustomer(); $customerMap = $this->getWhereByCustomer();
# getCount是代办事项传来的参数代办事项不需要使用场景 # getCount是代办事项传来的参数代办事项不需要使用场景
$sceneMap = []; $sceneMap = [];
if (empty($getCount)) { if (empty($getCount)) {
@ -83,33 +85,32 @@ class Customer extends Common
$sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : []; $sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
} }
} }
# 普通筛选
$searchMap = []; $searchMap = [];
if ($search || $search == '0') { if ($search || $search == '0') {
//普通筛选
$searchMap = function($query) use ($search){ $searchMap = function($query) use ($search){
$query->where('customer.name',array('like','%'.$search.'%')) $query->where('customer.name',array('like','%'.$search.'%'))
->whereOr('customer.mobile',array('like','%'.$search.'%')) ->whereOr('customer.mobile',array('like','%'.$search.'%'))
->whereOr('customer.telephone',array('like','%'.$search.'%')); ->whereOr('customer.telephone',array('like','%'.$search.'%'));
}; };
} }
//优先级:普通筛选>高级筛选>场景
# 优先级:普通筛选 > 高级筛选 > 场景
$map = []; $map = [];
$partMap = []; $partMap = [];
if (is_array($sceneMap)) { //团队成员 高级筛选
if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) { if($requestMap['team_id']){
//相关团队查询 $partMap= advancedQueryFormatForTeam($requestMap,'crm_customer','customer_id');
$map = $requestMap; unset($map['team_id']);
$partMap = function($query) use ($sceneMap){ }else{
$query->where('FIND_IN_SET('.$sceneMap['ro_user_id'].', customer.ro_user_id)')
->whereOr('FIND_IN_SET('.$sceneMap['rw_user_id'].', customer.rw_user_id)');
};
} else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
} }
} # 高级筛选
//高级筛选 $map = advancedQuery($map, 'crm', 'customer', 'index');
$map = where_arr($map, 'crm', 'customer', 'index');
//工作台仪表盘
# 工作台仪表盘
$requestData = $this->requestData(); $requestData = $this->requestData();
$dashboardWhere = []; $dashboardWhere = [];
if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') { if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
@ -119,9 +120,9 @@ class Customer extends Common
}; };
unset($map['customer.create_time']); unset($map['customer.create_time']);
} }
//权限
# 权限
$authMap = []; $authMap = [];
$auth_user_ids = [];
if (!$partMap) { if (!$partMap) {
$a = 'index'; $a = 'index';
if ($is_excel) $a = 'excelExport'; if ($is_excel) $a = 'excelExport';
@ -156,6 +157,7 @@ class Customer extends Common
} }
} }
# 代办事项 - 待进入公海 # 代办事项 - 待进入公海
$remindWhere = []; $remindWhere = [];
if ($is_remind) { if ($is_remind) {
@ -163,7 +165,17 @@ class Customer extends Common
$userIds[] = $user_id; $userIds[] = $user_id;
$poolDays = $this->getPoolDay([], $userIds); $poolDays = $this->getPoolDay([], $userIds);
$remindWhere['customer.customer_id'] = ['in', array_keys($poolDays)]; $remindWhere['customer.customer_id'] = ['in', array_keys($poolDays)];
if ($getCount == 1) return ['dataCount' => count($poolDays)]; $remindWhere['customer.pool_remain'] = 0;
if ($getCount == 1) {
$intoPoolCount = db('crm_customer')->alias('customer')->where($remindWhere)->count();
return ['dataCount' => $intoPoolCount];
}
}
// 待办事项下需联系客户(逾期)
$overdueWhere = '';
if (!empty($overdue)) {
$overdueWhere = "(FROM_UNIXTIME(`customer`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`customer`.`next_time`,'%Y-%m-%d') OR (ISNULL(`customer`.`last_time`) AND `customer`.`next_time` < ".time()."))";
} }
$dataCount = db('crm_customer')->alias('customer') $dataCount = db('crm_customer')->alias('customer')
@ -175,23 +187,29 @@ class Customer extends Common
->where($partMap) ->where($partMap)
->where($otherMap) ->where($otherMap)
->where($remindWhere) ->where($remindWhere)
->where($overdueWhere)
->count(); ->count();
if ($getCount == 1) { if ($getCount == 1) {
$data['dataCount'] = $dataCount ? : 0; $data['dataCount'] = $dataCount ? : 0;
return $data; return $data;
} }
//列表展示字段
$indexField = $fieldModel->getIndexField('crm_customer', $user_id, 1) ? : array('name'); $indexField = $fieldModel->getIndexField('crm_customer', $user_id, 1) ? : array('name'); // 列表展示字段
$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); //人员类型 $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); // 人员类型
$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); // 部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); // 日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_customer', 'boolean_value'); // 布尔值类型字段
$dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_customer', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_customer', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
$order_field = $temporaryField; $order_field = $temporaryField;
} }
//排序 # 排序
if ($order_type && $order_field) { if ($order_type && $order_field) {
$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type); $order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
} else { } else {
@ -207,12 +225,11 @@ class Customer extends Common
->where($partMap) ->where($partMap)
->where($otherMap) ->where($otherMap)
->where($remindWhere) ->where($remindWhere)
->where($overdueWhere)
->limit($request['offset'], $request['length']) ->limit($request['offset'], $request['length'])
->field($indexField) ->field($indexField)
->orderRaw($order) ->orderRaw($order)
->select(); ->select();
# 查询公海数据的条件
$poolWhere = [];
$readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read'); $readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
$updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update'); $updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete'); $deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
@ -231,29 +248,62 @@ class Customer extends Common
$business_count = array_column($business_count, null, 'customer_id'); $business_count = array_column($business_count, null, 'customer_id');
$field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id); $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
$field_list = array_column($field_list, 'field'); $field_list = array_column($field_list, 'field');
foreach ($list as $k => $v) { # 扩展数据
$extraData = [];
$extraList = db('crm_customer_data')->whereIn('customer_id', $customer_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['customer_id']][$value['field']] = $value['content'];
}
# 获取进入公海天数
$poolDays = $this->getPoolDay($customer_id_list);
# 整理数据
foreach ($list AS $k => $v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
$list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : ''; $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
$list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : ''; $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
foreach ($userField as $key => $val) { # 用户类型字段
if (in_array($val, $field_list)) { foreach ($userField AS $key => $val) {
if (in_array($val, $indexField)) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val.'_name'] = implode($usernameField, ','); $list[$k][$val] = implode($usernameField, ',');
} }
} }
foreach ($structureField as $key => $val) { # 部门类型字段
if (in_array($val, $field_list)) { foreach ($structureField AS $key => $val) {
if (in_array($val, $indexField)) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $list[$k][$val] = implode($structureNameField, ',');
} }
} }
foreach ($datetimeField as $key => $val) { # 日期时间类型字段
foreach ($datetimeField AS $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
//商机数 // 布尔值类型字段
foreach ($booleanField AS $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['customer_id']][$val]) ? json_decode($extraData[$v['customer_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['customer_id']][$val]) ? json_decode($extraData[$v['customer_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['customer_id']][$val]) ? json_decode($extraData[$v['customer_id']][$val], true) : null;
}
# 商机数
$list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0; $list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0;
//权限 # 权限
$roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read'); $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
$rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update'); $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
$permission = []; $permission = [];
@ -272,22 +322,16 @@ class Customer extends Common
$starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer']; $starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer'];
$star = Db::name('crm_star')->where($starWhere)->value('star_id'); $star = Db::name('crm_star')->where($starWhere)->value('star_id');
$list[$k]['star'] = !empty($star) ? 1 : 0; $list[$k]['star'] = !empty($star) ? 1 : 0;
# 日期 # 日期
$list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null; $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
$list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null; $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
$list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null; $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
//查询公海数据的条件
$poolWhere[] = $v['customer_id']; # 进入公海天数
$list[$k]['pool_day'] = ''; $list[$k]['pool_day'] = isset($poolDays[$v['customer_id']]) ? $poolDays[$v['customer_id']] : '';
$list[$k]['is_pool'] = 0; $list[$k]['is_pool'] = 0;
} }
# 获取公海天数
$poolDays = !empty($poolWhere) ? $this->getPoolDay($poolWhere) : [];
if (!empty($poolDays)) {
foreach ($list AS $key => $value) {
$list[$key]['pool_day'] = isset($poolDays[$value['customer_id']]) ? $poolDays[$value['customer_id']] : '';
}
}
} }
$data = []; $data = [];
$data['list'] = $list ? : []; $data['list'] = $list ? : [];
@ -303,21 +347,31 @@ class Customer extends Common
*/ */
public function createData($param) public function createData($param)
{ {
unset($param['excel']);
// 客户扩展表数据
$customerData = [];
$userId = $param['user_id'];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$userModel = new \app\admin\model\User();
$customerConfigModel = new \app\crm\model\CustomerConfig(); $customerConfigModel = new \app\crm\model\CustomerConfig();
//添加上限检测
// 添加上限检测
if (!$customerConfigModel->checkData($param['create_user_id'],1)) { if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
$this->error = $customerConfigModel->getError(); $this->error = $customerConfigModel->getError();
return false; return false;
} }
// 获取客户时间 // 获取客户时间
$param['obtain_time'] = time(); $param['obtain_time'] = time();
//地址
// 地址
$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : ''; $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
$param['deal_time'] = time(); //领取、分配时间 $param['deal_time'] = time(); //领取、分配时间
$param['deal_status'] = '未成交'; $param['deal_status'] = '未成交';
//线索转客户
// 线索转客户
if ($param['leads_id']) { if ($param['leads_id']) {
$leadsData = $param; $leadsData = $param;
$leadsData['create_user_id'] = $param['create_user_id']; $leadsData['create_user_id'] = $param['create_user_id'];
@ -328,14 +382,16 @@ class Customer extends Common
$param = $leadsData; $param = $leadsData;
} }
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validate = new Validate($validateArr['rule'], $validateArr['message']); $validateResult = $this->fieldDataValidate($param, 'crm_customer', $userId);
$result = $validate->check($param); if (!empty($validateResult)) {
if (!$result) { $this->error = $validateResult;
$this->error = $validate->getError();
return false; return false;
} }
// 删除无效数据
unset($param['user_id']);
unset($param['customer_id']); unset($param['customer_id']);
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
@ -343,6 +399,7 @@ class Customer extends Common
foreach ($arrFieldAtt as $k=>$v) { foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]); $param[$v] = arrayToString($param[$v]);
} }
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_customer', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
@ -351,23 +408,94 @@ class Customer extends Common
} }
} }
# 设置今日需联系客户 // 处理手写签名类型
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0; $handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) { // 处理地址、定位、日期区间、明细表格类型字段
if(!empty($param['pool_id'])){ $positionField = $fieldModel->getFieldByFormType('crm_customer', 'position');
db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$param['pool_id'],'customer_id'=>$this->customer_id]); $locationField = $fieldModel->getFieldByFormType('crm_customer', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_customer', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
} }
//修改记录
if(empty($param['leads_id'])){
updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户');
RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']);
} }
$data = []; // 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 设置今日需联系客户
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
$pool_id = !empty($param['pool_id']) ? $param['pool_id'] : 0;
unset($param['pool_id']);
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
$data['customer_id'] = $this->customer_id; $data['customer_id'] = $this->customer_id;
$data['name'] = $param['name']; $data['name'] = $param['name'];
# 添加活动记录 if(!empty($pool_id)){
db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$pool_id,'customer_id'=>$this->customer_id]);
}
// 修改记录
if (empty($param['leads_id'])) {
updateActionLog($param['create_user_id'], 'crm_customer', $data['customer_id'], '', '', '创建了客户');
RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']);
}
// 添加活动记录
Db::name('crm_activity')->insert([ Db::name('crm_activity')->insert([
'type' => 2, 'type' => 2,
'activity_type' => 2, 'activity_type' => 2,
@ -377,6 +505,11 @@ class Customer extends Common
'update_time' => time(), 'update_time' => time(),
'create_time' => time() 'create_time' => time()
]); ]);
// 添加客户扩展数据
array_walk($customerData, function (&$val) use ($data) {
$val['customer_id'] = $data['customer_id'];
});
db('crm_customer_data')->insertAll($customerData);
return $data; return $data;
} else { } else {
@ -404,20 +537,26 @@ class Customer extends Common
*/ */
public function updateDataById($param, $customer_id = '') public function updateDataById($param, $customer_id = '')
{ {
// 客户扩展表数据
$customerData = [];
$user_id = $param['user_id']; $user_id = $param['user_id'];
$dataInfo = $this->get($customer_id); $dataInfo = $this->get($customer_id);
if (!$dataInfo) { if (!$dataInfo) {
$this->error = '数据不存在或已删除'; $this->error = '数据不存在或已删除';
return false; return false;
} }
$id = $param['id']?:$customer_id; $id = !empty($param['id']) ? $param['id'] : $customer_id;
$param['customer_id'] = $customer_id;
//数据权限判断 // 数据权限判断
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update'); $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
//读写权限
// 读写权限
$rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update'); $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
//判断是否客户池数据
// 判断是否客户池数据
if(empty($param['pool_id'])){ if(empty($param['pool_id'])){
$wherePool = $this->getWhereByPool(); $wherePool = $this->getWhereByPool();
$resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find(); $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find();
@ -426,24 +565,23 @@ class Customer extends Common
return false; return false;
} }
} }
$param['customer_id'] = $customer_id;
//过滤不能修改的字段 // 过滤不能修改的字段
$unUpdateField = ['create_user_id','is_deleted','delete_time','user_id']; $unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
foreach ($unUpdateField as $v) { foreach ($unUpdateField as $v) {
unset($param[$v]); unset($param[$v]);
} }
$param['deal_status'] = $dataInfo['deal_status']; $param['deal_status'] = $dataInfo['deal_status'];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, 'crm_customer', $user_id, $id);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$result = $validate->check($param); $this->error = $validateResult;
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
//地址
// 地址
$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : ''; $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') { if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
$param['deal_time'] = time(); $param['deal_time'] = time();
@ -454,6 +592,7 @@ class Customer extends Common
foreach ($arrFieldAtt as $k=>$v) { foreach ($arrFieldAtt as $k=>$v) {
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]); if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
} }
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_customer', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
@ -462,17 +601,97 @@ class Customer extends Common
} }
} }
# 设置今日需联系客户 // 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType('crm_customer', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_customer', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_customer', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$customerData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
// 设置今日需联系客户
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0; if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
// 修改数据
if ($this->update($param, ['customer_id' => $customer_id], true)) { if ($this->update($param, ['customer_id' => $customer_id], true)) {
if(!empty($param['pool_id'])){ $data['customer_id'] = $customer_id;
db('crm_customer_pool_relation')->where('customer_id',$customer_id) ->update(['pool_id'=>$param['pool_id']]); // 修改公海
if (!empty($param['pool_id'])) {
db('crm_customer_pool_relation')->where('customer_id', $customer_id) ->update(['pool_id' => $param['pool_id']]);
} }
//修改记录 // 修改记录
updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param); updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
RecordActionLog($user_id, 'crm_customer', 'update',$dataInfo['name'], $dataInfo->data, $param); RecordActionLog($user_id, 'crm_customer', 'update',$dataInfo['name'], $dataInfo->data, $param);
$data = []; // 添加客户扩展数据
$data['customer_id'] = $customer_id; db('crm_customer_data')->where('customer_id', $customer_id)->delete();
array_walk($customerData, function (&$val) use ($customer_id) {
$val['customer_id'] = $customer_id;
});
db('crm_customer_data')->insertAll($customerData);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';
@ -537,6 +756,12 @@ class Customer extends Common
} }
} }
} }
// 新建发票时,使用的联系人数据(首要联系人)
$contactsInfo = db('crm_contacts')->field(['mobile', 'name', 'telephone', 'detail_address'])->where(['customer_id' => $id, 'primary' => 1])->find();
$contactsMobile = !empty($contactsInfo['mobile']) ? $contactsInfo['mobile'] : $contactsInfo['telephone'];
$dataInfo['contacts_name'] = $contactsInfo['name'];
$dataInfo['contacts_mobile'] = $contactsMobile;
$dataInfo['contacts_address'] = $contactsInfo['detail_address'];
return $dataInfo; return $dataInfo;
} }
@ -672,93 +897,27 @@ class Customer extends Common
} }
/** /**
* [客户默认条件] * 客户默认条件
* @author Michael_xu *
* @param * @author fanqi
* @return * @since 2021-05-12
* @return array
*/ */
public function getWhereByCustomer() public function getWhereByCustomer()
{ {
return ['customer.owner_user_id' => ['neq', 0]]; return ['customer.owner_user_id' => ['neq', 0]];
// $configModel = new \app\crm\model\ConfigData();
// $userModel = new \app\admin\model\User();
// $configInfo = $configModel->getData();
// $config = $configInfo['config'] ? : 0;
// $follow_day = $configInfo['follow_day'] ? : 0;
// $deal_day = $configInfo['deal_day'] ? : 0;
// //默认条件(没有到期或已锁定)
// $data['follow_time'] = time()-$follow_day*86400;
// $data['deal_time'] = time()-$deal_day*86400;
// if ($config == 1) {
// if ($follow_day < $deal_day) {
// $whereData = function($query) use ($data){
// $query->where(function ($query) use ($data) {
// $query->where(['customer.update_time' => array('gt',$data['follow_time']),'customer.deal_time' => array('gt',$data['deal_time'])]);
// })
// ->whereOr(['customer.deal_status' => '已成交'])
// ->whereOr(['customer.is_lock' => 1]);
// };
// } else {
// $whereData = function($query) use ($data){
// $query->where(function ($query) use ($data) {
// $query->where(['customer.deal_time' => array('gt',$data['deal_time'])]);
// })
// ->whereOr(['customer.deal_status' => '已成交'])
// ->whereOr(['customer.is_lock' => 1]);
// };
// }
// }
// return $whereData ? : '';
} }
/** /**
* [客户公海条件] * 客户公海条件
* @author Michael_xu *
* @param * @author fanqi
* @return * @since 2021-05-12
* @return array
*/ */
public function getWhereByPool() public function getWhereByPool()
{ {
// $configModel = new \app\crm\model\ConfigData(); return ['customer.owner_user_id' => ['eq', 0]];
// $configInfo = $configModel->getData();
// $config = $configInfo['config'] ? : 0;
// $follow_day = $configInfo['follow_day'] ? : 0;
// $deal_day = $configInfo['deal_day'] ? : 0;
// $whereData = [];
// //启用
// if ($config == 1) {
// //默认公海条件(没有负责人或已经到期)
// $data['follow_time'] = time()-$follow_day*86400;
// $data['deal_time'] = time()-$deal_day*86400;
// $data['deal_status'] = '未成交';
// if ($follow_day < $deal_day) {
// $whereData = function($query) use ($data){
// $query->where(['customer.owner_user_id'=>0])
// ->whereOr(function ($query) use ($data) {
// $query->where(function ($query) use ($data) {
// $query->where(['customer.update_time' => array('elt',$data['follow_time'])])
// ->whereOr(['customer.deal_time' => array('elt',$data['deal_time'])]);
// })
// ->where(['customer.is_lock' => 0])
// ->where(['customer.deal_status' => ['neq','已成交']]);
// });
// };
// } else {
// $whereData = function($query) use ($data){
// $query->where(['customer.owner_user_id'=>0])
// ->whereOr(function ($query) use ($data) {
// $query->where(function ($query) use ($data) {
// $query->where(['customer.deal_time' => array('elt',$data['deal_time'])]);
// })
// ->where(['customer.is_lock' => 0])
// ->where(['customer.deal_status' => ['neq','已成交']]);
// });
// };
// }
// } else {
$whereData['customer.owner_user_id'] = 0;
// }
return !empty($whereData) ? $whereData : '';
} }
/** /**
@ -1449,31 +1608,22 @@ class Customer extends Common
*/ */
public function getNearbyList($param) public function getNearbyList($param)
{ {
$apiCommon = new ApiCommon();
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$poolStatus = checkPerByAction('crm', 'customer', 'pool'); # 客户条件
# 客户
$customerAuth = [];
$customerWhere = []; $customerWhere = [];
if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) { if (!empty($param['type']) && $param['type'] == 2) {
$customerWhere = $this->getWhereByCustomer(); $customerWhere = $this->getWhereByCustomer();
} }
# 公海 # 公海条件
$poolWhere = []; $poolWhere = [];
if (!empty($param['type']) && $param['type'] == 9 && $poolStatus) { if (!empty($param['type']) && $param['type'] == 9) {
$poolWhere = ['customer.customer_id' => 0]; $poolWhere = ['customer.owner_user_id' => 0];
$model = '公海客户管理模块'; $model = '公海客户管理模块';
} }
if (!empty($param['type']) && $param['type'] == 9 && !$poolStatus) { # 距离条件
$model = '客户管理模块';
return [];
}
# 附近
$lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']); $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
$lngLatWhere = function ($query) use ($lngLatRange) { $lngLatWhere = function ($query) use ($lngLatRange) {
$query->where(['lng' => ['egt', $lngLatRange['minLng']]]); $query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
@ -1493,14 +1643,12 @@ class Customer extends Common
->where($customerWhere) ->where($customerWhere)
->where($poolWhere) ->where($poolWhere)
->where($lngLatWhere) ->where($lngLatWhere)
->where($customerAuth)
->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time']) ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time'])
->order('update_time', 'desc') ->order('update_time', 'desc')
->select(); ->select();
# 组装数据 # 组装数据
foreach ($list as $key => $value) { foreach ($list as $key => $value) {
# todo 暂时将查询写在循环中
$ownerUserInfo = !empty($value['owner_user_id']) ? $userModel->getUserById($value['owner_user_id']) : []; $ownerUserInfo = !empty($value['owner_user_id']) ? $userModel->getUserById($value['owner_user_id']) : [];
$ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : ''; $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
$list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人'; $list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
@ -1585,15 +1733,18 @@ class Customer extends Common
public function getSystemInfo($id) public function getSystemInfo($id)
{ {
# 客户 # 客户
$field = ['obtain_time', 'deal_status', 'create_time', 'update_time', 'create_time', 'last_time', 'last_record']; $field = ['obtain_time', 'owner_user_id', 'create_user_id', 'deal_status', 'update_time', 'create_time', 'last_time', 'last_record'];
$customer = Db::name('crm_customer')->field($field)->where('customer_id', $id)->find(); $customer = Db::name('crm_customer')->field($field)->where('customer_id', $id)->find();
# 创建人 # 创建人
$realname = Db::name('admin_user')->where('id', $customer['create_user_id'])->value('realname'); $createUserName = Db::name('admin_user')->where('id', $customer['create_user_id'])->value('realname');
# 负责人
$ownerUserName = Db::name('admin_user')->where('id', $customer['owner_user_id'])->value('realname');
return [ return [
'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '', 'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '',
'last_record' => !empty($customer['last_record']) ? $customer['last_record'] : '', 'last_record' => !empty($customer['last_record']) ? $customer['last_record'] : '',
'create_user_id' => $realname, 'create_user_id' => $createUserName,
'owner_user_id' => $ownerUserName,
'create_time' => date('Y-m-d H:i:s', $customer['create_time']), 'create_time' => date('Y-m-d H:i:s', $customer['create_time']),
'update_time' => date('Y-m-d H:i:s', $customer['update_time']), 'update_time' => date('Y-m-d H:i:s', $customer['update_time']),
'last_time' => !empty($customer['last_time']) ? date('Y-m-d H:i:s', $customer['last_time']) : '', 'last_time' => !empty($customer['last_time']) ? date('Y-m-d H:i:s', $customer['last_time']) : '',

@ -93,9 +93,7 @@ class CustomerConfig extends Common
$content='添加员工拥有、锁定客户限制'; $content='添加员工拥有、锁定客户限制';
$action='update'; $action='update';
} }
$user=new ApiCommon(); SystemActionLog($param['user_id'], 'crm_customer','customer', $this->id, $action,$content , '', '',$content);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_customer','customer', $this->id, $action,$content , '', '',$content);
return $data; return $data;
} else { } else {
$this->error = '创建失败'; $this->error = '创建失败';

@ -37,7 +37,6 @@ class Invoice extends Common
{ {
return $this->hasOne('Contract', 'contract_id', 'contract_id')->bind([ return $this->hasOne('Contract', 'contract_id', 'contract_id')->bind([
'contract_number' => 'num', 'contract_number' => 'num',
'contract_money' => 'money'
]); ]);
} }

@ -6,14 +6,14 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\model\Record as RecordModel;
use think\Request;
use think\Validate;
class Leads extends Common class Leads extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -43,6 +43,7 @@ class Leads extends Common
$order_field = $request['order_field']; $order_field = $request['order_field'];
$order_type = $request['order_type']; $order_type = $request['order_type'];
$getCount = $request['getCount']; $getCount = $request['getCount'];
$overdue = $request['overdue']; // 待办事项下需联系线索(逾期)
unset($request['scene_id']); unset($request['scene_id']);
unset($request['search']); unset($request['search']);
unset($request['user_id']); unset($request['user_id']);
@ -50,6 +51,7 @@ class Leads extends Common
unset($request['order_field']); unset($request['order_field']);
unset($request['order_type']); unset($request['order_type']);
unset($request['getCount']); unset($request['getCount']);
unset($request['overdue']);
$request = $this->fmtRequest($request); $request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: []; $requestMap = $request['map'] ?: [];
@ -74,13 +76,13 @@ class Leads extends Common
->whereOr('leads.mobile', array('like', '%' . $search . '%')) ->whereOr('leads.mobile', array('like', '%' . $search . '%'))
->whereOr('leads.telephone', array('like', '%' . $search . '%')); ->whereOr('leads.telephone', array('like', '%' . $search . '%'));
}; };
// $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '线索名称'];
} }
//优先级:普通筛选>高级筛选>场景 //优先级:普通筛选>高级筛选>场景
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'leads', 'index'); $map = advancedQuery($map, 'crm', 'leads', 'index');
// $map = where_arr($map, 'crm', 'leads', 'index');
//权限 //权限
$a = 'index'; $a = 'index';
if ($is_excel) $a = 'excelExport'; if ($is_excel) $a = 'excelExport';
@ -105,6 +107,11 @@ class Leads extends Common
$userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型 $userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_leads', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_leads', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_leads', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_leads', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -121,23 +128,39 @@ class Leads extends Common
$map['leads.is_transform'] = array('neq', 1); $map['leads.is_transform'] = array('neq', 1);
} }
// 待办事项下需联系线索(逾期)
$overdueWhere = '';
if (!empty($overdue)) {
$overdueWhere = "(FROM_UNIXTIME(`leads`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`leads`.`next_time`,'%Y-%m-%d') OR (ISNULL(`leads`.`last_time`) AND `leads`.`next_time` < ".time()."))";
}
$readAuthIds = $userModel->getUserByPer('crm', 'leads', 'read'); $readAuthIds = $userModel->getUserByPer('crm', 'leads', 'read');
$updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update'); $updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'leads', 'delete'); $deleteAuthIds = $userModel->getUserByPer('crm', 'leads', 'delete');
$dataCount = db('crm_leads')->alias('leads')->where($map)->where($searchMap)->where($authMap)->count('leads_id'); $dataCount = db('crm_leads')->alias('leads')->where($map)->where($searchMap)->where($authMap)->where($overdueWhere)->count('leads_id');
if (!empty($getCount) && $getCount == 1) { if (!empty($getCount) && $getCount == 1) {
$data['dataCount'] = !empty($dataCount) ? $dataCount : 0; $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
return $data; return $data;
} }
$list = db('crm_leads') $list = db('crm_leads')
->alias('leads') ->alias('leads')
->where($map) ->where($map)
->where($searchMap) ->where($searchMap)
->where($authMap) ->where($authMap)
->where($overdueWhere)
->limit($request['offset'], $request['length']) ->limit($request['offset'], $request['length'])
->field(implode(',', $indexField)) ->field(implode(',', $indexField))
->orderRaw($order) ->orderRaw($order)
->select(); ->select();
// echo db('crm_leads')->getLastSql();exit;
# 扩展数据
$extraData = [];
$leads_id_list = !empty($list) ? array_column($list, 'leads_id') : [];
$extraList = db('crm_leads_data')->whereIn('leads_id', $leads_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['leads_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) { foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@ -145,15 +168,35 @@ class Leads extends Common
$list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : ''; $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val.'_name'] = implode($usernameField, ','); $list[$k][$val] = implode($usernameField, ',');
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $list[$k][$val] = implode($structureNameField, ',');
} }
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
}
//权限 //权限
$permission = []; $permission = [];
$is_read = 0; $is_read = 0;
@ -201,14 +244,26 @@ class Leads extends Common
*/ */
public function createData($param) public function createData($param)
{ {
unset($param['excel']);
// 线索扩展表数据
$leadsData = [];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param); // // 自动验证
if (!$result) { // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$this->error = $validate->getError(); // $validate = new Validate($validateArr['rule'], $validateArr['message']);
// $result = $validate->check($param);
// if (!$result) {
// $this->error = $validate->getError();
// return false;
// }
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
@ -224,11 +279,81 @@ class Leads extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 设置今日需联系线索 # 设置今日需联系线索
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0; if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) { if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
$data['leads_id'] = $this->leads_id;
//修改记录 //修改记录
updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索'); updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']); RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
@ -245,8 +370,12 @@ class Leads extends Common
'contacts_ids' => null, 'contacts_ids' => null,
'business_ids' => null 'business_ids' => null
]); ]);
$data = []; // 添加线索扩展数据
$data['leads_id'] = $this->leads_id; array_walk($leadsData, function (&$val) use ($data) {
$val['leads_id'] = $data['leads_id'];
});
db('crm_leads_data')->insertAll($leadsData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -262,6 +391,9 @@ class Leads extends Common
*/ */
public function updateDataById($param, $leads_id = '') public function updateDataById($param, $leads_id = '')
{ {
// 线索扩展表数据
$leadsData = [];
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$dataInfo = $this->getDataById($leads_id); $dataInfo = $this->getDataById($leads_id);
if (!$dataInfo) { if (!$dataInfo) {
@ -284,12 +416,17 @@ class Leads extends Common
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证 // 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 // $validate = new Validate($validateArr['rule'], $validateArr['message']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); // $result = $validate->check($param);
$result = $validate->check($param); // if (!$result) {
if (!$result) { // $this->error = $validate->getError();
$this->error = $validate->getError(); // return false;
// }
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $leads_id);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
@ -305,16 +442,90 @@ class Leads extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$leadsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
# 设置今日需联系线索 # 设置今日需联系线索
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0; if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
if ($this->update($param, ['leads_id' => $leads_id], true)) { if ($this->update($param, ['leads_id' => $leads_id], true)) {
$data['leads_id'] = $leads_id;
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_leads','update', $dataInfo['name'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_leads','update', $dataInfo['name'], $dataInfo, $param);
$data = []; // 添加线索扩展数据
$data['leads_id'] = $leads_id; db('crm_leads_data')->where('leads_id', $leads_id)->delete();
array_walk($leadsData, function (&$val) use ($leads_id) {
$val['leads_id'] = $leads_id;
});
db('crm_leads_data')->insertAll($leadsData);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';

@ -6,17 +6,15 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\model\User as UserModel; use app\admin\model\User as UserModel;
use app\admin\model\File as FileModel;
use think\Request;
use think\Validate;
use traits\model\SoftDelete; use traits\model\SoftDelete;
class Product extends Common class Product extends Common
{ {
use SoftDelete; use SoftDelete, FieldVerificationTrait;
protected $deleteTime = 'delete_time'; protected $deleteTime = 'delete_time';
@ -72,7 +70,7 @@ class Product extends Common
//优先级:普通筛选>高级筛选>场景 //优先级:普通筛选>高级筛选>场景
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'product', 'index'); $map = advancedQuery($map, 'crm', 'product', 'index');
if (!empty($isStatus)) { if (!empty($isStatus)) {
$map['product.status'] = '上架'; $map['product.status'] = '上架';
} }
@ -104,6 +102,11 @@ class Product extends Common
$userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型 $userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_product', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_product', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_product', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_product', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_product', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_product', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -132,6 +135,13 @@ class Product extends Common
$dataCount = db('crm_product')->alias('product') $dataCount = db('crm_product')->alias('product')
->where($map)->where($authMap) ->where($map)->where($authMap)
->count('product_id'); ->count('product_id');
# 扩展数据
$extraData = [];
$product_id_list = !empty($list) ? array_column($list, 'product_id') : [];
$extraList = db('crm_product_data')->whereIn('product_id', $product_id_list)->select();
foreach ($extraList AS $key => $value) {
$extraData[$value['product_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) { foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@ -148,6 +158,26 @@ class Product extends Common
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField AS $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
}
//产品类型 //产品类型
$list[$k]['category_id_info'] = $v['category_name']; $list[$k]['category_id_info'] = $v['category_name'];
# 处理日期格式 # 处理日期格式
@ -169,20 +199,28 @@ class Product extends Common
*/ */
public function createData($param) public function createData($param)
{ {
// 产品扩展表数据
$productData = [];
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$productCategoryModel = model('ProductCategory'); $productCategoryModel = model('ProductCategory');
$dataInfo = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->find();
if (isset($dataInfo)) { $productStatus = false;
// 自动验证 if (!empty($param['excel'])) {
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 $productStatus = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->value('product_id');
$validate = new Validate($validateArr['rule'], $validateArr['message']); }
$result = $validate->check($param); // 数据验证
if (!$result) { if (empty($param['excel']) || $productStatus) {
$this->error = $validate->getError(); $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
} }
unset($param['excel']);
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_product'); $arrFieldAtt = $fieldModel->getArrayField('crm_product');
foreach ($arrFieldAtt as $k => $v) { foreach ($arrFieldAtt as $k => $v) {
@ -195,6 +233,75 @@ class Product extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
//产品分类 //产品分类
$category_id = $param['category_id']; $category_id = $param['category_id'];
@ -213,10 +320,15 @@ class Product extends Common
} }
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) { if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
$data['product_id'] = $this->product_id;
updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品'); updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品');
RecordActionLog($param['create_user_id'], 'crm_product', 'save', $param['name'], '', '', '新增了产品' . $param['name']); RecordActionLog($param['create_user_id'], 'crm_product', 'save', $param['name'], '', '', '新增了产品' . $param['name']);
$data = []; // 添加产品扩展数据
$data['product_id'] = $this->product_id; array_walk($productData, function (&$val) use ($data) {
$val['product_id'] = $data['product_id'];
});
db('crm_product_data')->insertAll($productData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -232,6 +344,9 @@ class Product extends Common
*/ */
public function updateDataById($param, $product_id = '') public function updateDataById($param, $product_id = '')
{ {
// 产品扩展表数据
$productData = [];
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$dataInfo = $this->getDataById($product_id); $dataInfo = $this->getDataById($product_id);
$productCategoryModel = model('ProductCategory'); $productCategoryModel = model('ProductCategory');
@ -254,18 +369,14 @@ class Product extends Common
} }
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['product_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$this->error = $validateResult;
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_product'); $arrFieldAtt = $fieldModel->getArrayField('crm_product');
foreach ($arrFieldAtt as $k => $v) { foreach ($arrFieldAtt as $k => $v) {
@ -278,6 +389,75 @@ class Product extends Common
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$productData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
//产品分类 //产品分类
$category_id = $param['category_id']; $category_id = $param['category_id'];
@ -295,11 +475,17 @@ class Product extends Common
} }
} }
if ($this->update($param, ['product_id' => $product_id], true)) { if ($this->update($param, ['product_id' => $product_id], true)) {
$data['product_id'] = $product_id;
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_product', 'update', $dataInfo['name'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_product', 'update', $dataInfo['name'], $dataInfo, $param);
$data = []; // 添加产品扩展数据
$data['product_id'] = $product_id; db('crm_product_data')->where('product_id', $product_id)->delete();
array_walk($productData, function (&$val) use ($product_id) {
$val['product_id'] = $product_id;
});
db('crm_product_data')->insertAll($productData);
return $data; return $data;
} else { } else {
$this->rollback(); $this->rollback();

@ -62,9 +62,7 @@ class ProductCategory extends Common
$data = []; $data = [];
$data['id'] = $this->category_id; $data['id'] = $this->category_id;
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); SystemActionLog($param['create_user_id'], 'crm_product','customer', $this->category_id, 'save',$param['name'] , '', '','添加了产品分类:'.$param['name']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_product','customer', $this->category_id, 'save',$param['name'] , '', '','添加了产品分类:'.$param['name']);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -93,12 +91,11 @@ class ProductCategory extends Common
$this->error = $validate->getError(); $this->error = $validate->getError();
return false; return false;
} }
$user_id=$param['user_id'];
unset($param['user_id']);
if ($this->allowField(true)->save($param, ['category_id' => $category_id])) { if ($this->allowField(true)->save($param, ['category_id' => $category_id])) {
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); SystemActionLog($user_id, 'crm_product','customer', $category_id, 'update',$dataInfo['name'] , '', '','编辑了产品分类:'.$dataInfo['name']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_product','customer', $category_id, 'update',$dataInfo['name'] , '', '','编辑了产品分类:'.$dataInfo['name']);
return true; return true;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';
@ -108,19 +105,19 @@ class ProductCategory extends Common
/** /**
* [delDataById 根据id删除数据] * [delDataById 根据id删除数据]
* @param string $id [主键] * @param string $param['id'] [主键]
* @param boolean $delSon [是否删除子孙数据] * @param boolean $delSon [是否删除子孙数据]
* @return [type] [description] * @return [type] [description]
*/ */
public function delDataById($id = '', $delSon = false) public function delDataById($param = '', $delSon = false)
{ {
if (!$id) { if (!$param['id']) {
$this->error = '删除失败'; $this->error = '删除失败';
return false; return false;
} }
//分类下已有产品,则不能删除 //分类下已有产品,则不能删除
$resDel = true; $resDel = true;
if (db('crm_product')->where(['category_id' => $id])->find()) { if (db('crm_product')->where(['category_id' => $param['id']])->find()) {
$resDel = false; $resDel = false;
} }
if ($delSon && is_numeric($id)) { if ($delSon && is_numeric($id)) {
@ -135,22 +132,20 @@ class ProductCategory extends Common
$this->error = '请先移除该类型及子类下的相关产品'; $this->error = '请先移除该类型及子类下的相关产品';
return false; return false;
} }
$data=db('crm_product_category')->where('category_id' , $id)->find(); $data=db('crm_product_category')->where('category_id' , $param['id'])->find();
//提交事务 //提交事务
$this->startTrans(); $this->startTrans();
try { try {
$this->where(['category_id' => $id])->delete(); $this->where(['category_id' => $param['id']])->delete();
if ($delSon && is_numeric($id)) { if ($delSon && is_numeric($param['id'])) {
// 删除子孙 // 删除子孙
$childIds = $this->getAllChild($id); $childIds = $this->getAllChild($param['id']);
if ($childIds) { if ($childIds) {
$this->where('category_id', 'in', $childIds)->delete(); $this->where('category_id', 'in', $childIds)->delete();
} }
} }
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); SystemActionLog($param['user_id'], 'crm_product','customer', $id, 'update',$data['name'] , '', '','删除了产品分类:'.$data['name']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_product','customer', $id, 'update',$data['name'] , '', '','删除了产品分类:'.$data['name']);
$this->commit(); $this->commit();
return true; return true;
} catch(\Exception $e) { } catch(\Exception $e) {

@ -6,15 +6,17 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\crm\model\Contract as ContractModel; use app\crm\model\Contract as ContractModel;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\model\Message; use app\admin\model\Message;
use think\Request; use think\Request;
use think\Validate;
class Receivables extends Common class Receivables extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -23,7 +25,7 @@ class Receivables extends Common
protected $createTime = 'create_time'; protected $createTime = 'create_time';
protected $updateTime = 'update_time'; protected $updateTime = 'update_time';
protected $autoWriteTimestamp = true; protected $autoWriteTimestamp = true;
private $statusArr = ['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'已拒绝','4'=>'已撤回']; private $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回'];
/** /**
* [getDataList 回款list] * [getDataList 回款list]
@ -46,6 +48,7 @@ class Receivables extends Common
$order_type = $request['order_type']; $order_type = $request['order_type'];
$getCount = $request['getCount']; $getCount = $request['getCount'];
$receivablesIdArray = $request['receivablesIdArray']; // 待办事项提醒参数 $receivablesIdArray = $request['receivablesIdArray']; // 待办事项提醒参数
$isMessage = !empty($request['isMessage']);
unset($request['scene_id']); unset($request['scene_id']);
unset($request['search']); unset($request['search']);
unset($request['user_id']); unset($request['user_id']);
@ -53,9 +56,10 @@ class Receivables extends Common
unset($request['order_type']); unset($request['order_type']);
unset($request['getCount']); unset($request['getCount']);
unset($request['receivablesIdArray']); unset($request['receivablesIdArray']);
unset($request['isMessage']);
$request = $this->fmtRequest( $request ); $request = $this->fmtRequest($request);
$requestMap = $request['map'] ? : []; $requestMap = $request['map'] ?: [];
$sceneModel = new \app\admin\model\Scene(); $sceneModel = new \app\admin\model\Scene();
# getCount是代办事项传来的参数代办事项不需要使用场景 # getCount是代办事项传来的参数代办事项不需要使用场景
@ -63,56 +67,79 @@ class Receivables extends Common
if (empty($getCount)) { if (empty($getCount)) {
if ($scene_id) { if ($scene_id) {
//自定义场景 //自定义场景
$sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'receivables') ? : []; $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'receivables') ?: [];
} else { } else {
//默认场景 //默认场景
$sceneMap = $sceneModel->getDefaultData('crm_receivables', $user_id) ? : []; $sceneMap = $sceneModel->getDefaultData('crm_receivables', $user_id) ?: [];
} }
} }
$searchWhere = []; $searchWhere = [];
if (!empty($search) || $search == '0') { if (!empty($search) || $search == '0') {
//普通筛选 //普通筛选
$searchWhere = function ($query) use ($search) { $searchWhere = function ($query) use ($search) {
$query->where(function ($query) use ($search){ $query->where(function ($query) use ($search) {
$query->whereLike('customer.name', '%' . $search . '%'); $query->whereLike('customer.name', '%' . $search . '%');
})->whereOr(function ($query) use ($search) { })->whereOr(function ($query) use ($search) {
$query->whereLike('receivables.number', '%' . $search . '%'); $query->whereLike('receivables.number', '%' . $search . '%');
}); });
}; };
// if (db('crm_customer')->whereLike('name', '%' . $search . '%')->value('customer_id')) {
// $sceneMap['customer_name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '客户名称'];
// } else {
// $sceneMap['number'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '回款编号'];
// }
} }
$partMap = [];
//优先级:普通筛选>高级筛选>场景
//优先级:普通筛选>高级筛选>场景 //优先级:普通筛选>高级筛选>场景
if ($requestMap['team_id']) {
//相关团队查询
$map = $requestMap;
$partMap= advancedQueryFormatForTeam($requestMap,'crm_receivables','receivables_id');
unset($map['team_id']);
} else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
//高级筛选 //高级筛选
$map = where_arr($map, 'crm', 'receivables', 'index'); $map = advancedQuery($map, 'crm', 'receivables', 'index');
//权限 //权限
$authMap = []; $authMap = [];
if (!$partMap) {
$auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index'); $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
if (isset($map['receivables.owner_user_id']) && $map['receivables.owner_user_id'][0] != 'like') { if (isset($map['receivables.owner_user_id']) && $map['receivables.owner_user_id'][0] != 'like') {
if (!is_array($map['receivables.owner_user_id'][1])) { if (!is_array($map['receivables.owner_user_id'][1])) {
$map['receivables.owner_user_id'][1] = [$map['receivables.owner_user_id'][1]]; $map['receivables.owner_user_id'][1] = [$map['receivables.owner_user_id'][1]];
} }
if (in_array($map['receivables.owner_user_id'][0], ['neq', 'notin'])) { if (in_array($map['receivables.owner_user_id'][0], ['neq', 'notin'])) {
$auth_user_ids = array_diff($auth_user_ids, $map['receivables.owner_user_id'][1]) ? : []; //取差集 $auth_user_ids = array_diff($auth_user_ids, $map['receivables.owner_user_id'][1]) ?: []; //取差集
} else { } else {
$auth_user_ids = array_intersect($map['receivables.owner_user_id'][1], $auth_user_ids) ? : []; //取交集 $auth_user_ids = array_intersect($map['receivables.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
} }
unset($map['receivables.owner_user_id']); unset($map['receivables.owner_user_id']);
} $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
//负责人、相关团队 //负责人、相关团队
$authMap['receivables.owner_user_id'] = ['in',$auth_user_ids]; $authMap['receivables.owner_user_id'] = ['in', $auth_user_ids];
} else {
// 待办事项的待审核回款不一定是自己创建的
if (!$isMessage) {
$authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id;
$authMap = function ($query) use ($authMapData) {
$query->where('receivables.owner_user_id', array('in', $authMapData['auth_user_ids']))
->whereOr('receivables.ro_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'))
->whereOr('receivables.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
};
}
}
}
//列表展示字段 //列表展示字段
$indexField = $fieldModel->getIndexField('crm_receivables', $user_id, 1) ? : array('number'); $indexField = $fieldModel->getIndexField('crm_receivables', $user_id, 1) ?: array('number');
//人员类型 //人员类型
$userField = $fieldModel->getFieldByFormType('crm_receivables', 'user'); $userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
$structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型 $datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_receivables', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_receivables', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_receivables', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_receivables', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段) # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field); $temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) { if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -120,7 +147,7 @@ class Receivables extends Common
} }
//排序 //排序
if ($order_type && $order_field) { if ($order_type && $order_field) {
$order = $fieldModel->getOrderByFormtype('crm_receivables','receivables',$order_field, $order_type); $order = $fieldModel->getOrderByFormtype('crm_receivables', 'receivables', $order_field, $order_type);
} else { } else {
$order = 'receivables.update_time desc'; $order = 'receivables.update_time desc';
} }
@ -134,64 +161,91 @@ class Receivables extends Common
$deleteAuthIds = $userModel->getUserByPer('crm', 'receivables', 'delete'); $deleteAuthIds = $userModel->getUserByPer('crm', 'receivables', 'delete');
$dataCount = db('crm_receivables') $dataCount = db('crm_receivables')
->alias('receivables') ->alias('receivables')
->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'receivables.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT') ->join('__CRM_CONTRACT__ contract', 'receivables.contract_id = contract.contract_id', 'LEFT')
->where($searchWhere)->where($map)->where($authMap)->where($dealtWhere)->count('receivables_id'); ->where($searchWhere)->where($map)->where($authMap)->where($partMap)->where($dealtWhere)->count('receivables_id');
if (!empty($getCount) && $getCount == 1) { if (!empty($getCount) && $getCount == 1) {
$data['dataCount'] = !empty($dataCount) ? $dataCount : 0; $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
$data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)]; $data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
return $data; return $data;
} }
foreach ($indexField AS $kk => $vv) { foreach ($indexField as $kk => $vv) {
if ($vv == 'receivables.contract_num') unset($indexField[(int)$kk]); if ($vv == 'receivables.contract_num') unset($indexField[(int)$kk]);
} }
$list = db('crm_receivables') $list = db('crm_receivables')
->alias('receivables') ->alias('receivables')
->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'receivables.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT') ->join('__CRM_CONTRACT__ contract', 'receivables.contract_id = contract.contract_id', 'LEFT')
->where($searchWhere) ->where($searchWhere)
->where($map) ->where($map)
->where($partMap)
->where($authMap) ->where($authMap)
->where($dealtWhere) ->where($dealtWhere)
->limit($request['offset'], $request['length']) ->limit($request['offset'], $request['length'])
->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money') ->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
->orderRaw($order) ->orderRaw($order)
->select(); ->select();
# 扩展数据
foreach ($list as $k=>$v) { $extraData = [];
$receivables_id_list = !empty($list) ? array_column($list, 'receivables_id') : [];
$extraList = db('crm_receivables_data')->whereIn('receivables_id', $receivables_id_list)->select();
foreach ($extraList as $key => $value) {
$extraData[$value['receivables_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : [];
$list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : ''; $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
$list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : ''; $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : ''; $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ?: '';
$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : ''; $list[$k]['customer_id_info']['name'] = $v['customer_name'] ?: '';
$list[$k]['contract_id_info']['contract_id'] = $v['contract_id'] ? : ''; $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'] ?: '';
$list[$k]['contract_id_info']['name'] = $v['contract_num'] ? : ''; $list[$k]['contract_id_info']['name'] = $v['contract_num'] ?: '';
$list[$k]['contract_id_info']['money'] = $v['contract_money'] ? : '0.00'; $list[$k]['contract_id_info']['money'] = $v['contract_money'] ?: '0.00';
$list[$k]['contract_money'] = $v['contract_money'] ? : '0.00'; $list[$k]['contract_money'] = $v['contract_money'] ?: '0.00';
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val.'_name'] = implode($usernameField, ','); $list[$k][$val] = implode($usernameField, ',');
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $list[$k][$val] = implode($structureNameField, ',');
} }
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null; $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
} }
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['receivables_id']][$val]) ? json_decode($extraData[$v['receivables_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['receivables_id']][$val]) ? json_decode($extraData[$v['receivables_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField as $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['receivables_id']][$val]) ? json_decode($extraData[$v['receivables_id']][$val], true) : null;
}
$list[$k]['check_status_info'] = $this->statusArr[$v['check_status']]; $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
//期数 //期数
$plan_num = db('crm_receivables_plan')->where(['plan_id' => $v['plan_id']])->value('num'); $plan_num = db('crm_receivables_plan')->where(['plan_id' => $v['plan_id']])->value('num');
$list[$k]['plan_id_info'] = $plan_num ? : ''; $list[$k]['plan_id_info'] = $plan_num ?: '';
//权限 //权限
$permission = []; $permission = [];
$is_read = 0; $is_read = 0;
$is_update = 0; $is_update = 0;
$is_delete = 0; $is_delete = 0;
if (in_array($v['owner_user_id'],$readAuthIds)) $is_read = 1; if (in_array($v['owner_user_id'], $readAuthIds)) $is_read = 1;
if (in_array($v['owner_user_id'],$updateAuthIds)) $is_update = 1; if (in_array($v['owner_user_id'], $updateAuthIds)) $is_update = 1;
if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1; if (in_array($v['owner_user_id'], $deleteAuthIds)) $is_delete = 1;
$permission['is_read'] = $is_read; $permission['is_read'] = $is_read;
$permission['is_update'] = $is_update; $permission['is_update'] = $is_update;
$permission['is_delete'] = $is_delete; $permission['is_delete'] = $is_delete;
@ -202,7 +256,7 @@ class Receivables extends Common
} }
$data = []; $data = [];
$data['list'] = $list; $data['list'] = $list;
$data['dataCount'] = $dataCount ? : 0; $data['dataCount'] = $dataCount ?: 0;
$data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)]; $data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
return $data; return $data;
@ -218,8 +272,8 @@ class Receivables extends Common
private function getReceivablesMoney($map, $authMap) private function getReceivablesMoney($map, $authMap)
{ {
$money = db('crm_receivables')->alias('receivables') $money = db('crm_receivables')->alias('receivables')
->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'receivables.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT') ->join('__CRM_CONTRACT__ contract', 'receivables.contract_id = contract.contract_id', 'LEFT')
->where($map)->where($authMap)->where('receivables.check_status', 2)->sum('receivables.money'); ->where($map)->where($authMap)->where('receivables.check_status', 2)->sum('receivables.money');
return !empty($money) ? sprintf("%.2f", $money) : 0.00; return !empty($money) ? sprintf("%.2f", $money) : 0.00;
@ -227,12 +281,15 @@ class Receivables extends Common
/** /**
* 创建回款信息 * 创建回款信息
* @author Michael_xu
* @param * @param
* @return * @return
* @author Michael_xu
*/ */
public function createData($param) public function createData($param)
{ {
// 回款扩展表数据
$receivablesData = [];
if (!$param['customer_id']) { if (!$param['customer_id']) {
$this->error = '请先选择客户'; $this->error = '请先选择客户';
return false; return false;
@ -253,13 +310,11 @@ class Receivables extends Common
} }
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param); // 数据验证
if (!$result) { $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
$this->error = $validate->getError(); if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
@ -271,16 +326,85 @@ class Receivables extends Common
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_receivables'); $arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
foreach ($arrFieldAtt as $k=>$v) { foreach ($arrFieldAtt as $k => $v) {
$param[$v] = arrayToString($param[$v]); $param[$v] = arrayToString($param[$v]);
} }
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->data($param)->allowField(true)->save()) { if ($this->data($param)->allowField(true)->save()) {
//站内信 //站内信
@ -300,7 +424,7 @@ class Receivables extends Common
//修改记录 //修改记录
updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款'); updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款');
RecordActionLog($param['create_user_id'],'crm_receivables','save',$param['number'],'','','新增了回款'.$param['number']); RecordActionLog($param['create_user_id'], 'crm_receivables', 'save', $param['number'], '', '', '新增了回款' . $param['number']);
# 添加活动记录 # 添加活动记录
Db::name('crm_activity')->insert([ Db::name('crm_activity')->insert([
@ -319,7 +443,7 @@ class Receivables extends Common
$checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id'); $checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds); $checkUserIdArray = stringToArray($checkUserIds);
$dealtData = []; $dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) { foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [ $dealtData[] = [
'types' => 'crm_receivables', 'types' => 'crm_receivables',
'types_id' => $data['receivables_id'], 'types_id' => $data['receivables_id'],
@ -328,6 +452,12 @@ class Receivables extends Common
} }
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData); if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加回款扩展数据
array_walk($receivablesData, function (&$val) use ($data) {
$val['receivables_id'] = $data['receivables_id'];
});
db('crm_receivables_data')->insertAll($receivablesData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -347,28 +477,31 @@ class Receivables extends Common
if ($param['obj_type']) { if ($param['obj_type']) {
if ($param['obj_type'] == 1) { //部门 if ($param['obj_type'] == 1) { //部门
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$str = $userModel->getSubUserByStr($param['obj_id'], 1) ? : ['-1']; $str = $userModel->getSubUserByStr($param['obj_id'], 1) ?: ['-1'];
$map['owner_user_id'] = array('in',$str); $map['owner_user_id'] = array('in', $str);
} else { //员工 } else { //员工
$map['owner_user_id'] = $param['obj_id']; $map['owner_user_id'] = $param['obj_id'];
} }
} }
//审核状态 //审核状态
$start = date('Y-m-d',$param['start_time']); $start = date('Y-m-d', $param['start_time']);
$stop = date('Y-m-d',$param['end_time']); $stop = date('Y-m-d', $param['end_time']);
$map['check_status'] = 2; $map['check_status'] = 2;
$data = $this->where($map)->where(['return_time' => ['between',[$start,$stop]]])->sum('money'); $data = $this->where($map)->where(['return_time' => ['between', [$start, $stop]]])->sum('money');
return $data; return $data;
} }
/** /**
* 编辑回款主表信息 * 编辑回款主表信息
* @author Michael_xu
* @param * @param
* @return * @return
* @author Michael_xu
*/ */
public function updateDataById($param, $receivables_id = '') public function updateDataById($param, $receivables_id = '')
{ {
// 回款扩展表数据
$receivablesData = [];
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$dataInfo = db('crm_receivables')->where(['receivables_id' => $receivables_id])->find(); $dataInfo = db('crm_receivables')->where(['receivables_id' => $receivables_id])->find();
if (!$dataInfo) { if (!$dataInfo) {
@ -377,40 +510,106 @@ class Receivables extends Common
} }
$param['receivables_id'] = $receivables_id; $param['receivables_id'] = $receivables_id;
//过滤不能修改的字段 //过滤不能修改的字段
$unUpdateField = ['create_user_id','is_deleted','delete_time','delete_user_id']; $unUpdateField = ['create_user_id', 'is_deleted', 'delete_time', 'delete_user_id'];
foreach ($unUpdateField as $v) { foreach ($unUpdateField as $v) {
unset($param[$v]); unset($param[$v]);
} }
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 // 数据验证
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则 $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['receivables_id']);
$validate = new Validate($validateArr['rule'], $validateArr['message']); if (!empty($validateResult)) {
$this->error = $validateResult;
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
return false; return false;
} }
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_receivables'); $arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
foreach ($arrFieldAtt as $k=>$v) { foreach ($arrFieldAtt as $k => $v) {
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]); if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
} }
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->update($param, ['receivables_id' => $receivables_id], true)) { if ($this->update($param, ['receivables_id' => $receivables_id], true)) {
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_receivables', $receivables_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_receivables', $receivables_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_receivables', 'update',$dataInfo['number'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_receivables', 'update', $dataInfo['number'], $dataInfo, $param);
//站内信 //站内信
$send_user_id = stringToArray($param['check_user_id']); $send_user_id = stringToArray($param['check_user_id']);
if ($send_user_id && empty($param['check_status'])) { if ($send_user_id && empty($param['check_status'])) {
@ -433,7 +632,7 @@ class Receivables extends Common
$checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id'); $checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds); $checkUserIdArray = stringToArray($checkUserIds);
$dealtData = []; $dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) { foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [ $dealtData[] = [
'types' => 'crm_receivables', 'types' => 'crm_receivables',
'types_id' => $data['receivables_id'], 'types_id' => $data['receivables_id'],
@ -442,6 +641,13 @@ class Receivables extends Common
} }
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData); if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加回款扩展数据
db('crm_receivables_data')->where('receivables_id', $receivables_id)->delete();
array_walk($receivablesData, function (&$val) use ($receivables_id) {
$val['receivables_id'] = $receivables_id;
});
db('crm_receivables_data')->insertAll($receivablesData);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';
@ -486,7 +692,7 @@ class Receivables extends Common
if (!empty($userId)) { if (!empty($userId)) {
$grantData = getFieldGrantData($userId); $grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId); $userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) { foreach ($dataInfo as $key => $value) {
if (!$userLevel && !empty($grantData['crm_receivables'])) { if (!$userLevel && !empty($grantData['crm_receivables'])) {
$status = getFieldGrantStatus($key, $grantData['crm_receivables']); $status = getFieldGrantStatus($key, $grantData['crm_receivables']);
@ -525,54 +731,54 @@ class Receivables extends Common
$contractModel = new \app\crm\model\Contract(); $contractModel = new \app\crm\model\Contract();
$adminModel = new \app\admin\model\Admin(); $adminModel = new \app\admin\model\Admin();
$perUserIds = $userModel->getUserByPer('bi', 'receivables', 'read'); //权限范围内userIds $perUserIds = $userModel->getUserByPer('bi', 'receivables', 'read'); //权限范围内userIds
$whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件 $whereData = $adminModel->getWhere($request, '', $perUserIds); //统计条件
$userIds = $whereData['userIds']; $userIds = $whereData['userIds'];
if (!$request['year']) { if (!$request['year']) {
$request['year'] = date('Y'); $request['year'] = date('Y');
} }
if ($request['month']) { if ($request['month']) {
$start = strtotime($request['year'].'-'.$request['month'].'-01'); $start = strtotime($request['year'] . '-' . $request['month'] . '-01');
if ($request['month'] == '12') { if ($request['month'] == '12') {
$next_year = $request['year']+1; $next_year = $request['year'] + 1;
$end = strtotime($next_year.'-01-01'); $end = strtotime($next_year . '-01-01');
} else { } else {
$next_month = $request['month']+1; $next_month = $request['month'] + 1;
$end = strtotime($request['year'].'-'.$next_month.'-01'); $end = strtotime($request['year'] . '-' . $next_month . '-01');
} }
} else { } else {
$next_year = $request['year']+1; $next_year = $request['year'] + 1;
$start = strtotime($request['year'].'-01-01'); $start = strtotime($request['year'] . '-01-01');
$end = strtotime($next_year.'-01-01'); $end = strtotime($next_year . '-01-01');
} }
$map['owner_user_id'] = ['in',$userIds]; $map['owner_user_id'] = ['in', $userIds];
//$map['rec.check_status'] = 3; //$map['rec.check_status'] = 3;
$map['create_time'] = array('between',array($start,$end)); $map['create_time'] = array('between', array($start, $end));
//合同有多个回款 //合同有多个回款
//根据时间查合同 //根据时间查合同
if( $request['type'] == '1'){ if ($request['type'] == '1') {
$map_type['contract.owner_user_id'] = ['in',$userIds]; $map_type['contract.owner_user_id'] = ['in', $userIds];
$map_type['contract.create_time'] = array('between',array($start,$end)); $map_type['contract.create_time'] = array('between', array($start, $end));
$userField = $fieldModel->getFieldByFormType('crm_contract', 'user'); $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型 $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
$list = Db::name('CrmContract')->alias('contract') $list = Db::name('CrmContract')->alias('contract')
->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'contract.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_BUSINESS__ business','contract.contract_id = business.business_id','LEFT') ->join('__CRM_BUSINESS__ business', 'contract.contract_id = business.business_id', 'LEFT')
->join('__CRM_CONTACTS__ contacts','contract.contract_id = contacts.contacts_id','LEFT') ->join('__CRM_CONTACTS__ contacts', 'contract.contract_id = contacts.contacts_id', 'LEFT')
->field('contract.*,customer.name as customer_name,business.name as business_name,contacts.name as contacts_name') ->field('contract.*,customer.name as customer_name,business.name as business_name,contacts.name as contacts_name')
->where($map_type)->select(); ->where($map_type)->select();
if($list){ if ($list) {
foreach ($list as $k=>$v) { foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$list[$k][$val.'_info'] = isset($v[$val]) ? $userModel->getListByStr($v[$val]) : []; $list[$k][$val . '_info'] = isset($v[$val]) ? $userModel->getListByStr($v[$val]) : [];
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$list[$k][$val.'_info'] = isset($v[$val]) ? $structureModel->getDataByStr($v[$val]) : []; $list[$k][$val . '_info'] = isset($v[$val]) ? $structureModel->getDataByStr($v[$val]) : [];
} }
$list[$k]['business_id_info']['business_id'] = $v['business_id']; $list[$k]['business_id_info']['business_id'] = $v['business_id'];
$list[$k]['business_id_info']['name'] = $v['business_name']; $list[$k]['business_id_info']['name'] = $v['business_name'];
@ -587,9 +793,9 @@ class Receivables extends Common
return array(); return array();
} }
} else { //回款 } else { //回款
$map_rec['receivables.owner_user_id'] = ['in',$userIds]; $map_rec['receivables.owner_user_id'] = ['in', $userIds];
//$map['rec.check_status'] = 3; //$map['rec.check_status'] = 3;
$map_rec['receivables.create_time'] = array('between',array($start,$end)); $map_rec['receivables.create_time'] = array('between', array($start, $end));
$map_rec['receivables.check_status'] = 2; $map_rec['receivables.check_status'] = 2;
$userField = $fieldModel->getFieldByFormType('crm_receivables', 'user'); $userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
@ -597,25 +803,25 @@ class Receivables extends Common
$list = db('crm_receivables') $list = db('crm_receivables')
->alias('receivables') ->alias('receivables')
->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT') ->join('__CRM_CUSTOMER__ customer', 'receivables.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT') ->join('__CRM_CONTRACT__ contract', 'receivables.contract_id = contract.contract_id', 'LEFT')
->where($map_rec) ->where($map_rec)
->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money') ->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
->select(); ->select();
foreach ($list as $k=>$v) { foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : []; $list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : []; $list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : [];
$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : ''; $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ?: '';
$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : ''; $list[$k]['customer_id_info']['name'] = $v['customer_name'] ?: '';
$list[$k]['contract_id_info']['contract_id'] = $v['contract_id'] ? : ''; $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'] ?: '';
$list[$k]['contract_id_info']['name'] = $v['contract_name'] ? : ''; $list[$k]['contract_id_info']['name'] = $v['contract_name'] ?: '';
$list[$k]['contract_id_info']['money'] = $v['contract_money'] ? : '0.00'; $list[$k]['contract_id_info']['money'] = $v['contract_money'] ?: '0.00';
$list[$k]['contract_money'] = $v['contract_money'] ? : '0.00'; $list[$k]['contract_money'] = $v['contract_money'] ?: '0.00';
foreach ($userField as $key => $val) { foreach ($userField as $key => $val) {
$list[$k][$val.'_info'] = isset($v[$val]) ? $userModel->getListByStr($v[$val]) : []; $list[$k][$val . '_info'] = isset($v[$val]) ? $userModel->getListByStr($v[$val]) : [];
} }
foreach ($structureField as $key => $val) { foreach ($structureField as $key => $val) {
$list[$k][$val.'_info'] = isset($v[$val]) ? $structureModel->getDataByStr($v[$val]) : []; $list[$k][$val . '_info'] = isset($v[$val]) ? $structureModel->getDataByStr($v[$val]) : [];
} }
$list[$k]['check_status_info'] = $this->statusArr[$v['check_status']]; $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
} }
@ -625,10 +831,10 @@ class Receivables extends Common
/** /**
* [回款统计] 柱状图 * [回款统计] 柱状图
* @author Michael_xu
* @param request [查询条件] * @param request [查询条件]
* @param * @param
* @return [array] * @return [array]
* @author Michael_xu
*/ */
public function getStatistics($request) public function getStatistics($request)
{ {
@ -645,27 +851,27 @@ class Receivables extends Common
$receivablesMoney = '0.00'; $receivablesMoney = '0.00';
$conQuarterMoney = '0.00'; $conQuarterMoney = '0.00';
$reQuarterMoney = '0.00'; $reQuarterMoney = '0.00';
$start_time = strtotime($request['year'].'-'.$i.'-01'); $start_time = strtotime($request['year'] . '-' . $i . '-01');
$next_i = $i+1; $next_i = $i + 1;
$end_time = strtotime($request['year'].'-'.$next_i.'-01')-1; $end_time = strtotime($request['year'] . '-' . $next_i . '-01') - 1;
if ($i == 12) { if ($i == 12) {
$next_year = $request['year']+1; $next_year = $request['year'] + 1;
$end_time = strtotime($next_year.'-01-01')-1; $end_time = strtotime($next_year . '-01-01') - 1;
} }
$where_receivables = []; $where_receivables = [];
$where_contract = []; $where_contract = [];
$where_contract['owner_user_id'] = ['in',$userIds]; $where_contract['owner_user_id'] = ['in', $userIds];
$where_receivables['owner_user_id'] = ['in',$userIds]; $where_receivables['owner_user_id'] = ['in', $userIds];
$where_contract['create_time'] = array('between',array($start_time,$end_time)); $where_contract['create_time'] = array('between', array($start_time, $end_time));
$where_receivables['return_time'] = array('between',array( date('Y-m-d',$start_time),date('Y-m-d',$end_time))); $where_receivables['return_time'] = array('between', array(date('Y-m-d', $start_time), date('Y-m-d', $end_time)));
$where_receivables['owner_user_id'] = ['in',$userIds]; $where_receivables['owner_user_id'] = ['in', $userIds];
$where_receivables['check_status'] = $where_contract['check_status'] = 2; //审核通过 $where_receivables['check_status'] = $where_contract['check_status'] = 2; //审核通过
$contractMoney = db('crm_contract')->where($where_contract)->sum('money'); $contractMoney = db('crm_contract')->where($where_contract)->sum('money');
$receivablesMoney = db('crm_receivables')->where($where_receivables)->sum('money'); $receivablesMoney = db('crm_receivables')->where($where_receivables)->sum('money');
$conQuarterMoney += $charMonthArr[$i]['contractMoney'] = $contractMoney; $conQuarterMoney += $charMonthArr[$i]['contractMoney'] = $contractMoney;
$reQuarterMoney += $charMonthArr[$i]['receivablesMoney'] = $receivablesMoney; $reQuarterMoney += $charMonthArr[$i]['receivablesMoney'] = $receivablesMoney;
if (in_array($i, array('3','4','6','9','12'))) { if (in_array($i, array('3', '4', '6', '9', '12'))) {
//季度 //季度
$quarter++; $quarter++;
$charQuarterArr[$quarter]['conQuarterMoney'] = $conQuarterMoney; $charQuarterArr[$quarter]['conQuarterMoney'] = $conQuarterMoney;
@ -678,26 +884,26 @@ class Receivables extends Common
} }
$data['charMonthArr'] = $charMonthArr; //月度统计 $data['charMonthArr'] = $charMonthArr; //月度统计
$data['charQuarterArr'] = $charQuarterArr; //季度统计 $data['charQuarterArr'] = $charQuarterArr; //季度统计
$data['contractMoneyTotal'] = $contractMoneyTotal ? : 0.00; $data['contractMoneyTotal'] = $contractMoneyTotal ?: 0.00;
$data['receivablesMoneyTotal'] = $receivablesMoneyTotal ? : 0.00; $data['receivablesMoneyTotal'] = $receivablesMoneyTotal ?: 0.00;
return $data; return $data;
} }
/** /**
* [合同回款金额] * [合同回款金额]
* @author Michael_xu
* @param contract_id 合同ID * @param contract_id 合同ID
* @param * @param
* @return * @return
* @author Michael_xu
*/ */
public function getMoneyByContractId($contract_id) public function getMoneyByContractId($contract_id)
{ {
$doneMoney = $this->where(['contract_id' => $contract_id,'check_status' => 2])->sum('money'); $doneMoney = $this->where(['contract_id' => $contract_id, 'check_status' => 2])->sum('money');
$contractMoney = db('crm_contract')->where(['contract_id' => $contract_id])->value('money'); $contractMoney = db('crm_contract')->where(['contract_id' => $contract_id])->value('money');
$unMoney = $contractMoney-$doneMoney; $unMoney = $contractMoney - $doneMoney;
$data['doneMoney'] = $doneMoney ? : '0.00'; $data['doneMoney'] = $doneMoney ?: '0.00';
$data['unMoney'] = (int)$unMoney>0 ? (int)$unMoney : '0.00'; $data['unMoney'] = (int)$unMoney > 0 ? (int)$unMoney : '0.00';
$data['contractMoney'] = $contractMoney ? : '0.00'; $data['contractMoney'] = $contractMoney ?: '0.00';
return $data; return $data;
} }

@ -6,6 +6,7 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\crm\model; namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use app\crm\model\Contract as ContractModel; use app\crm\model\Contract as ContractModel;
@ -14,6 +15,8 @@ use think\Validate;
class ReceivablesPlan extends Common class ReceivablesPlan extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -59,7 +62,8 @@ class ReceivablesPlan extends Common
$map['name'] = ['like', '%'.$map['search'].'%']; $map['name'] = ['like', '%'.$map['search'].'%'];
unset($map['search']); unset($map['search']);
} else { } else {
$map = where_arr($map, 'crm', 'receivables_plan', 'index'); //高级筛选 // 高级筛选
$map = advancedQuery($map, 'crm', 'receivables_plan', 'index');
} }
if ($map['receivables_plan.owner_user_id']) { if ($map['receivables_plan.owner_user_id']) {
$map['contract.owner_user_id'] = $map['receivables_plan.owner_user_id']; $map['contract.owner_user_id'] = $map['receivables_plan.owner_user_id'];
@ -99,12 +103,6 @@ class ReceivablesPlan extends Common
} }
} }
# 待办事项-待回款提醒-已回款
if (!empty($dealt)) {
$map = " (`receivables_plan`.`receivables_id` > ".$request['map']['receivables_id'][1]." )";
}
$dataCount = db('crm_receivables_plan') $dataCount = db('crm_receivables_plan')
->alias('receivables_plan') ->alias('receivables_plan')
->join('__CRM_CONTRACT__ contract','receivables_plan.contract_id = contract.contract_id','LEFT') ->join('__CRM_CONTRACT__ contract','receivables_plan.contract_id = contract.contract_id','LEFT')
@ -148,6 +146,8 @@ class ReceivablesPlan extends Common
*/ */
public function createData($param) public function createData($param)
{ {
$userId = $param['user_id'];
unset($param['user_id']);
if (!$param['contract_id']) { if (!$param['contract_id']) {
$this->error = '请先选择合同'; $this->error = '请先选择合同';
return false; return false;
@ -166,10 +166,16 @@ class ReceivablesPlan extends Common
$this->error = '提前提醒最大时间为 90 天'; $this->error = '提前提醒最大时间为 90 天';
return false; return false;
} }
// 自动验证 // // 自动验证
$validate = validate($this->name); // $validate = validate($this->name);
if (!$validate->check($param)) { // if (!$validate->check($param)) {
$this->error = $validate->getError(); // $this->error = $validate->getError();
// return false;
// }
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_receivables_plan', $userId);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件 if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
@ -178,9 +184,97 @@ class ReceivablesPlan extends Common
$param['num'] = $maxNum ? $maxNum+1 : 1; $param['num'] = $maxNum ? $maxNum+1 : 1;
//提醒日期 //提醒日期
$param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date']; $param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date'];
$fieldModel = new \app\admin\model\Field();
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_receivables_plan');
foreach ($arrFieldAtt AS $key => $value) {
$param[$value] = !empty($param[$value]) ? arrayToString($param[$value]) : '';
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date');
foreach ($dateField AS $key => $value) {
$param[$value] = !empty($param[$value]) ? $param[$value] : null;
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'handwriting_sign');
foreach ($handwritingField AS $key => $value) {
$param[$value] = !empty($param[$value]['file_id']) ? $param[$value]['file_id'] : '';
}
// 处理地址、定位、日期区间、明细表格类型字段
$receivablesPlanData = [];
$positionField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->data($param)->allowField(true)->save()) { if ($this->data($param)->allowField(true)->save()) {
$data = []; $data = [];
$data['plan_id'] = $this->plan_id; $data['plan_id'] = $this->plan_id;
// 添加回款计划扩展数据
array_walk($receivablesPlanData, function (&$val) use ($data) {
$val['plan_id'] = $data['plan_id'];
});
db('crm_receivables_plan_data')->insertAll($receivablesPlanData);
return $data; return $data;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -196,6 +290,8 @@ class ReceivablesPlan extends Common
*/ */
public function updateDataById($param, $plan_id = '') public function updateDataById($param, $plan_id = '')
{ {
$userId = $param['user_id'];
unset($param['user_id']);
$dataInfo = $this->getDataById($plan_id); $dataInfo = $this->getDataById($plan_id);
if (!$dataInfo) { if (!$dataInfo) {
$this->error = '数据不存在或已删除'; $this->error = '数据不存在或已删除';
@ -208,18 +304,114 @@ class ReceivablesPlan extends Common
unset($param[$v]); unset($param[$v]);
} }
// 自动验证 // // 自动验证
$validate = validate($this->name); // $validate = validate($this->name);
if (!$validate->check($param)) { // if (!$validate->check($param)) {
$this->error = $validate->getError(); // $this->error = $validate->getError();
// return false;
// }
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_receivables_plan', $userId, $plan_id);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件 if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
//提醒日期 //提醒日期
$param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date']; $param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date'];
$fieldModel = new \app\admin\model\Field();
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_receivables_plan');
foreach ($arrFieldAtt AS $key => $value) {
$param[$value] = !empty($param[$value]) ? arrayToString($param[$value]) : '';
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date');
foreach ($dateField AS $key => $value) {
$param[$value] = !empty($param[$value]) ? $param[$value] : null;
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'handwriting_sign');
foreach ($handwritingField AS $key => $value) {
$param[$value] = !empty($param[$value]['file_id']) ? $param[$value]['file_id'] : '';
}
// 处理地址、定位、日期区间、明细表格类型字段
$receivablesPlanData = [];
$positionField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'position');
$locationField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'location');
$dateIntervalField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'detail_table');
foreach ($param AS $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$receivablesPlanData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->allowField(true)->save($param, ['plan_id' => $plan_id])) { if ($this->allowField(true)->save($param, ['plan_id' => $plan_id])) {
$data = []; $data = [];
$data['plan_id'] = $plan_id; $data['plan_id'] = $plan_id;
// 添加回款计划扩展数据
db('crm_receivables_plan_data')->where('plan_id', $data['plan_id'])->delete();
array_walk($receivablesPlanData, function (&$val) use ($data) {
$val['plan_id'] = $data['plan_id'];
});
db('crm_receivables_plan_data')->insertAll($receivablesPlanData);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';

@ -36,7 +36,7 @@ class Setting extends Common
if (!is_array($param['types_id'])) { if (!is_array($param['types_id'])) {
$param['types_id'] = [intval($param['types_id'])]; $param['types_id'] = [intval($param['types_id'])];
} }
$res = teamUserId($param['types'], $param['types_id'], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id']); $res = teamUserId($param,$param['types'], $param['types_id'], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id']);
if ($res == '1') { if ($res == '1') {
//同时关联其他模块(仅限客户模块) //同时关联其他模块(仅限客户模块)
if (is_array($param['module']) && $param['types'] == 'crm_customer') { if (is_array($param['module']) && $param['types'] == 'crm_customer') {
@ -49,9 +49,11 @@ class Setting extends Common
case 'crm_contacts' : $module_id = 'contacts_id'; break; case 'crm_contacts' : $module_id = 'contacts_id'; break;
case 'crm_business' : $module_id = 'business_id'; break; case 'crm_business' : $module_id = 'business_id'; break;
case 'crm_contract' : $module_id = 'contract_id'; break; case 'crm_contract' : $module_id = 'contract_id'; break;
case 'crm_leads' : $module_id = 'leads_id'; break;
case 'crm_receivables' : $module_id = 'receivables_id'; break;
} }
foreach ($moduleList as $val) { foreach ($moduleList as $val) {
teamUserId($v, $val[$module_id], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id'], 0); teamUserId($param,$v, $val[$module_id], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id'], 0);
} }
} }
} }
@ -70,7 +72,7 @@ class Setting extends Common
* @throws \think\Exception * @throws \think\Exception
* @throws \think\exception\PDOException * @throws \think\exception\PDOException
*/ */
public function setVisitDay($status, $day) public function setVisitDay($status, $day,$userId)
{ {
$status = intval($status); $status = intval($status);
$day = intval($day); $day = intval($day);
@ -99,9 +101,7 @@ class Setting extends Common
} }
} }
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); SystemActionLog($userId, 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
return true; return true;
} }
@ -124,7 +124,7 @@ class Setting extends Common
* @param $param * @param $param
* @return bool * @return bool
*/ */
public function setNumber($param) public function setNumber($param,$userId)
{ {
$apiCommon = new ApiCommon(); $apiCommon = new ApiCommon();
@ -176,9 +176,7 @@ class Setting extends Common
Db::commit(); Db::commit();
# 系统操作日志 # 系统操作日志
$user=new ApiCommon(); SystemActionLog($userId, 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
return true; return true;
} catch (Exception $e) { } catch (Exception $e) {
Db::rollback(); Db::rollback();
@ -186,4 +184,41 @@ class Setting extends Common
return false; return false;
} }
} }
/**
* 导航列表
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 11:39
*/
public function appMenuConfig($param)
{
$data = db('app_navigation')->where('create_user_id', $param)->value('data');
$data = unserialize($data);
return $data?:[];
}
/**
* 修改导航信息
* @param $param
* @param $userId
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 14:49
*/
public function setMenuConfig($param,$userId){
$data = db('app_navigation')->where('create_user_id', $userId)->value('data');
$res=[];
$res['data']=serialize($param);
if($data){
$list=db('app_navigation')->where('create_user_id', $userId)->update($res);
}else{
$res['create_user_id']=$userId;
$list=db('app_navigation')->insertGetId($res);
}
return $list;
}
} }

@ -47,7 +47,7 @@ trait AutoNumberTrait
if ($currentDate[$value['reset']] != $lastDate[$value['reset']]) { if ($currentDate[$value['reset']] != $lastDate[$value['reset']]) {
Db::name('crm_number_sequence')->where('number_sequence_id', $value['number_sequence_id'])->update([ Db::name('crm_number_sequence')->where('number_sequence_id', $value['number_sequence_id'])->update([
'last_number' => 1 'last_number' => !empty($value['value']) ? $value['value'] : 1
]); ]);
} }
} }

@ -90,192 +90,4 @@ class Addresslist extends ApiCommon
return resultArray(['data' => '设置关注成功!']); return resultArray(['data' => '设置关注成功!']);
} }
//通讯录列表
// public function index()
// {
// $param = $this->param;
// $where = array();
// $where['user.status'] = 1;
// if ($param['search']) {
// $where['user.realname'] = array('like', '%'.$param['search'].'%');
// }
// if ($param['type'] == 1) {
// $datalist = Db::name('AdminUser')
// ->where($where)
// ->alias('user')
// ->join('AdminStructure structure', 'structure.id = user.structure_id', 'LEFT')
// ->field('user.id,user.realname,user.thumb_img,user.post,user.structure_id,structure.name as structure_name,user.username,user.mobile,user.sex,user.email,user.status')
// ->select();
// foreach( $datalist as $k=>$v){
// $datalist[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath( $v['thumb_img'] ) : '';
// }
// $newarray = $this->groupByInitials($datalist,'realname');
// return resultArray(['data' => $newarray]);
// } else {
// $structureList = Db::name('AdminStructure')->select();
// foreach($structureList as $key=>$value){
// $where['user.structure_id'] = $value['id'];
// $userList = Db::name('AdminUser')
// ->where($where)
// ->alias('user')
// ->field('user.id,user.realname,user.username,user.thumb_img,user.post,user.structure_id,user.mobile,user.sex,user.email')
// ->order('realname asc')
// ->select();
// foreach ($userList as $k=>$v){
// $userList[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath( $v['thumb_img'] ) : '';
// }
// $structureList[$key]['userList'] = $userList;
// $structureList[$key]['structure_name'] = $value['name'];
// }
// return resultArray(['data' => $structureList]);
// }
// }
//
// /**
// * 二维数组根据首字母分组排序
// * @param array $data 二维数组
// * @param string $targetKey 首字母的键名
// * @return array 根据首字母关联的二维数组
// */
// public function groupByInitials(array $data, $targetKey = 'name')
// {
// $data = array_map(function ($item) use ($targetKey) {
// return array_merge($item, [
// 'initials' => $this->getInitials($item[$targetKey]),
// ]);
// }, $data);
// $data = $this->sortInitials($data);
// return $data;
// }
//
// /**
// * 按字母排序
// * @param array $data
// * @return array
// */
// public function sortInitials(array $data)
// {
// $sortData = [];
// foreach ($data as $key => $value) {
// $sortData[$value['initials']][] = $value;
// }
// ksort($sortData);
// return $sortData;
// }
//
// /**
// * 获取首字母
// * @param string $str 汉字字符串
// * @return string 首字母
// */
// public function getInitials($str)
// {
// if (empty($str)) {return '';}
// $fchar = ord($str{0});
// if ($fchar >= ord('A') && $fchar <= ord('z')) {
// return strtoupper($str{0});
// }
//
// $s1 = iconv('UTF-8', 'gb2312', $str);
// $s2 = iconv('gb2312', 'UTF-8', $s1);
// $s = $s2 == $str ? $s1 : $str;
// $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
// if($asc == -9300){
// return 'G';
// }
// if ($asc >= -20319 && $asc <= -20284) {
// return 'A';
// }
//
// if ($asc >= -20283 && $asc <= -19776) {
// return 'B';
// }
//
// if ($asc >= -19775 && $asc <= -19219) {
// return 'C';
// }
//
// if ($asc >= -19218 && $asc <= -18711) {
// return 'D';
// }
//
// if ($asc >= -18710 && $asc <= -18527) {
// return 'E';
// }
//
// if ($asc >= -18526 && $asc <= -18240) {
// return 'F';
// }
//
// if ($asc >= -18239 && $asc <= -17923) {
// return 'G';
// }
//
// if ($asc >= -17922 && $asc <= -17418) {
// return 'H';
// }
//
// if ($asc >= -17417 && $asc <= -16475) {
// return 'J';
// }
//
// if ($asc >= -16474 && $asc <= -16213) {
// return 'K';
// }
//
// if ($asc >= -16212 && $asc <= -15641) {
// return 'L';
// }
//
// if ($asc >= -15640 && $asc <= -15166) {
// return 'M';
// }
//
// if ($asc >= -15165 && $asc <= -14923) {
// return 'N';
// }
//
// if ($asc >= -14922 && $asc <= -14915) {
// return 'O';
// }
//
// if ($asc >= -14914 && $asc <= -14631) {
// return 'P';
// }
//
// if ($asc >= -14630 && $asc <= -14150) {
// return 'Q';
// }
//
// if ($asc >= -14149 && $asc <= -14091) {
// return 'R';
// }
//
// if ($asc >= -14090 && $asc <= -13319) {
// return 'S';
// }
//
// if ($asc >= -13318 && $asc <= -12839) {
// return 'T';
// }
//
// if ($asc >= -12838 && $asc <= -12557) {
// return 'W';
// }
//
// if ($asc >= -12556 && $asc <= -11848) {
// return 'X';
// }
//
// if ($asc >= -11847 && $asc <= -11056) {
// return 'Y';
// }
//
// if ($asc >= -11055 && $asc <= -10247) {
// return 'Z';
// }
// return '#';
// }
} }

@ -161,6 +161,7 @@ class Examine extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['create_user_id'] = $userInfo['id']; $param['create_user_id'] = $userInfo['id'];
$param['user_id'] = $userInfo['id'];
$dataInfo = db('oa_examine')->where(['examine_id' => $param['id']])->find(); $dataInfo = db('oa_examine')->where(['examine_id' => $param['id']])->find();
if (!$dataInfo) { if (!$dataInfo) {
return resultArray(['error' => '数据不存在或已删除']); return resultArray(['error' => '数据不存在或已删除']);
@ -249,6 +250,8 @@ class Examine extends ApiCommon
return resultArray(['error' => $examineModel->getError()]); return resultArray(['error' => $examineModel->getError()]);
} }
$fileModel = new \app\admin\model\File(); $fileModel = new \app\admin\model\File();
// 删除自定义字段数据
db('oa_examine_data')->where('examine_id', $param['id'])->delete();
//删除关联附件 //删除关联附件
$fileModel->delRFileByModule('oa_examine',$param['id']); $fileModel->delRFileByModule('oa_examine',$param['id']);
# 删除记录 # 删除记录
@ -445,6 +448,9 @@ class Examine extends ApiCommon
->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%'); ->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%');
}); });
})->order($orderField,$orderSort)->select(); })->order($orderField,$orderSort)->select();
foreach ($list AS $key => $value) {
$list[$key]['category_name'] = $value['title'];
}
return resultArray(['data' => $list]); return resultArray(['data' => $list]);
} }

@ -38,7 +38,8 @@ class Log extends ApiCommon
'activitycount', 'activitycount',
'activitylist', 'activitylist',
'querylog', 'querylog',
'onebulletin' 'onebulletin',
'favourupdate'
] ]
]; ];
Hook::listen('check_auth', $action); Hook::listen('check_auth', $action);
@ -331,6 +332,7 @@ class Log extends ApiCommon
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$log_id = $param['log_id']; $log_id = $param['log_id'];
$param['user_id']=$userInfo['id'];
if ($log_id) { if ($log_id) {
$dataInfo = db('oa_log')->where(['log_id' => $log_id])->find(); $dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
$adminTypes = adminGroupTypes($userInfo['id']); $adminTypes = adminGroupTypes($userInfo['id']);
@ -494,4 +496,20 @@ class Log extends ApiCommon
$data = $TaskLogic->queryLog($param); $data = $TaskLogic->queryLog($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/**
* 点赞取消点赞
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/17 0017 10:00
*/
public function favourUpdate(){
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$TaskLogic = new LogLogic();
$data = $TaskLogic->favourUpdate($param);
return resultArray(['data' => $data]);
}
} }

@ -243,7 +243,11 @@ class LogLogic extends Common
$query->where('create_time', array('between', $between_time)) $query->where('create_time', array('between', $between_time))
->whereOr('obtain_time', array('between', $between_time)); ->whereOr('obtain_time', array('between', $between_time));
}; };
$userMap=function ($query) use ($user_id) {
$query->where('owner_user_id', array('eq', $user_id));
};
$customerNum = Db::name('CrmCustomer') $customerNum = Db::name('CrmCustomer')
->where($userMap)
->where($logMap) ->where($logMap)
->count(); ->count();
$businessNum = Db::name('CrmBusiness') $businessNum = Db::name('CrmBusiness')
@ -304,21 +308,20 @@ class LogLogic extends Common
if ($search) { if ($search) {
$map['name'] = array('like', '%' . $search . '%'); $map['name'] = array('like', '%' . $search . '%');
} }
$customerModel=new \app\crm\model\Customer();
$customerMap =$customerModel->getWhereByCustomer();
$type = $param['log_type']; $type = $param['log_type'];
switch ($type) { switch ($type) {
case '1': case '1':
if ($search) $map['customer.name'] = array('like', '%' . $search . '%'); if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
$map['customer.create_time'] = array('between', $between_time); $logMap=function ($query) use ($between_time) {
$logMap['obtain_time'] = array('between', $between_time); $query->where('customer.create_time', array('between', $between_time))
->whereOr('customer.obtain_time', array('between', $between_time));
};
$activityData = Db::name('CrmCustomer') $activityData = Db::name('CrmCustomer')
->alias('customer') ->alias('customer')
->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT') ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
->where($map) ->where($map)
->where($map1) ->where($map1)
->where($customerMap) ->where($logMap)
->whereOr($logMap)
->order('customer.customer_id desc') ->order('customer.customer_id desc')
->field('customer.customer_id,customer.level,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time,customer.next_time') ->field('customer.customer_id,customer.level,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time,customer.next_time')
->page($param['page'],$param['limit']) ->page($param['page'],$param['limit'])
@ -331,7 +334,8 @@ class LogLogic extends Common
->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT') ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
->where($map) ->where($map)
->where($map1) ->where($map1)
->where($customerMap) ->where($logMap)
->where('customer.owner_user_id' , ['neq', 0])
->count(); ->count();
break; break;
case '2': case '2':
@ -378,20 +382,19 @@ class LogLogic extends Common
$activityData = Db::name('CrmContract') $activityData = Db::name('CrmContract')
->alias('contract') ->alias('contract')
->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT') ->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT')
->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
->where($map) ->where($map)
->where($map3) ->where($map3)
->order('contract.contract_id desc') ->order('contract.contract_id desc')
->page($param['page'],$param['limit']) ->page($param['page'],$param['limit'])
->field(['contract.contract_id', ->field([
'contract.contract_id',
'contract.name', 'contract.name',
'contract.create_time', 'contract.create_time',
'contract.check_status', 'contract.check_status',
'contract.order_date', 'contract.order_date',
'contract.money', 'contract.money',
'u.realname as order_user_name', 'u.realname as order_user_name',
'ifnull(SUM(receivables.money), 0)' => 'done_money', ])
'(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money'])
->select(); ->select();
foreach ($activityData as $k => $v){ foreach ($activityData as $k => $v){
if(!empty($v['contract_id'])){ if(!empty($v['contract_id'])){
@ -835,7 +838,7 @@ class LogLogic extends Common
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) { } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false; $data['firstPage'] = false;
$data['lastPage'] = false; $data['lastPage'] = false;
} else if ($param['page'] == 1) { } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount ) {
$data['firstPage'] = true; $data['firstPage'] = true;
$data['lastPage'] = false; $data['lastPage'] = false;
} }
@ -1015,4 +1018,38 @@ class LogLogic extends Common
$data['list'] = $item; $data['list'] = $item;
return $data; return $data;
} }
/**
* 点赞取消点赞功能
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/17 0017 10:10
*/
public function favourUpdate($param){
$logModel= new Log();
if(empty($param['favour_status'])){
$request=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->update(['status'=>$param['favour_status']]);
$status=0;
}else{
$res=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->find();
if(!empty($res) && $res['status']==0){
$request=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->update(['status'=>1]);
$status=1;
}elseif(!empty($res) && $res['status']==1){
$request=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->update(['status'=>0]);
$status=1;
}else{
$param['status']=$param['favour_status'];
unset($param['favour_status']);
$request=db('oa_log_favour')->insertGetId($param);
$status=1;
}
}
$data=[];
$data['favourUser']=$logModel->favourList($param['log_id'])?:[];
$data['favour_status']=$status;
return $data;
}
} }

@ -311,6 +311,5 @@ class UserLogic
if ($asc >= -10247 && $asc <= -10247) { if ($asc >= -10247 && $asc <= -10247) {
return 'Z'; return 'Z';
} }
// return '#';
} }
} }

@ -360,6 +360,9 @@ class Event extends Common
} }
} else { } else {
$list = db('admin_oa_schedule')->select(); $list = db('admin_oa_schedule')->select();
foreach ($list as $k=>$v){
$list[$k]['is_select'] = 1;
}
} }
$data['list'] = $list; $data['list'] = $list;
return $data; return $data;

@ -6,15 +6,16 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace app\oa\model; namespace app\oa\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db; use think\Db;
use app\admin\model\Common; use app\admin\model\Common;
use app\admin\model\Message; use app\admin\model\Message;
use think\Request;
use think\Validate; use think\Validate;
use app\admin\model\Field;
class Examine extends Common class Examine extends Common
{ {
use FieldVerificationTrait;
/** /**
* 为了数据库的整洁同时又不影响Model和Controller的名称 * 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀 * 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -284,12 +285,19 @@ class Examine extends Common
$this->error = '参数错误'; $this->error = '参数错误';
return false; return false;
} }
// 自动验证 // // 自动验证
$validateArr = $fieldModel->validateField($this->name, $param['category_id']); //获取自定义字段验证规则 // $validateArr = $fieldModel->validateField($this->name, $param['category_id']); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']); // $validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param); // $result = $validate->check($param);
if (!$result) { // if (!$result) {
$this->error = $validate->getError(); // $this->error = $validate->getError();
// return false;
// }
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id'], 0, $param['category_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
@ -297,8 +305,8 @@ class Examine extends Common
$fileArr = $param['file_id']; //接收表单附件 $fileArr = $param['file_id']; //接收表单附件
unset($param['file_id']); unset($param['file_id']);
$param['start_time'] = $param['start_time'] ? strtotime($param['start_time']) : 0; $param['start_time'] = $param['start_time'] ? : 0;
$param['end_time'] = $param['end_time'] ? strtotime($param['end_time']) : 0; $param['end_time'] = $param['end_time'] ? : 0;
if ($this->data($param)->allowField(true)->save()) { if ($this->data($param)->allowField(true)->save()) {
//处理自定义字段数据 //处理自定义字段数据
$resData = $examineDataModel->createData($param, $this->examine_id); $resData = $examineDataModel->createData($param, $this->examine_id);
@ -394,7 +402,9 @@ class Examine extends Common
$examineCategoryModel = new \app\oa\model\ExamineCategory(); $examineCategoryModel = new \app\oa\model\ExamineCategory();
$examineDataModel = new \app\oa\model\ExamineData(); $examineDataModel = new \app\oa\model\ExamineData();
$create_user_id = $param['create_user_id']; $create_user_id = $param['create_user_id'];
$userId = $param['user_id'];
unset($param['id']); unset($param['id']);
unset($param['user_id']);
$dataInfo = db('oa_examine')->where(['examine_id' => $examine_id])->find(); $dataInfo = db('oa_examine')->where(['examine_id' => $examine_id])->find();
if (!$dataInfo) { if (!$dataInfo) {
$this->error = '数据不存在或已删除'; $this->error = '数据不存在或已删除';
@ -409,12 +419,18 @@ class Examine extends Common
$categoryInfo = $examineCategoryModel->getDataById($dataInfo['category_id']); $categoryInfo = $examineCategoryModel->getDataById($dataInfo['category_id']);
//验证 //验证
$fieldModel = new \app\admin\model\Field(); // $fieldModel = new \app\admin\model\Field();
$validateArr = $fieldModel->validateField($this->name, $dataInfo['category_id']); //获取自定义字段验证规则 // $validateArr = $fieldModel->validateField($this->name, $dataInfo['category_id']); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']); // $validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param); // $result = $validate->check($param);
if (!$result) { // if (!$result) {
$this->error = $validate->getError(); // $this->error = $validate->getError();
// return false;
// }
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $userId, $examine_id, $param['category_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false; return false;
} }
@ -524,7 +540,6 @@ class Examine extends Common
public function getDataById($id = '') public function getDataById($id = '')
{ {
$examineData = new \app\oa\model\ExamineData(); $examineData = new \app\oa\model\ExamineData();
$fieldModel = new \app\admin\model\Field();
$fileModel = new \app\admin\model\File(); $fileModel = new \app\admin\model\File();
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$recordModel = new \app\admin\model\Record(); $recordModel = new \app\admin\model\Record();
@ -549,14 +564,21 @@ class Examine extends Common
$dataInfo['create_time'] = $dataInfo['create_time'] ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;; $dataInfo['create_time'] = $dataInfo['create_time'] ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;;
$realname=$userModel->getUserById($dataInfo['create_user_id']); $realname=$userModel->getUserById($dataInfo['create_user_id']);
$dataInfo['value'] = !empty($realname)?$realname['realname']: ''; $dataInfo['value'] = !empty($realname)?$realname['realname']: '';
//表格数据处理
// $fieldList = $fieldModel->getFieldByFormType('oa_examine', 'form'); // 处理自定义字段格式
// foreach ($fieldList as $k=>$v) { $fieldWhere = [
// $dataInfo[$v] = $fieldModel->getFormValueByField($v, $dataInfo[$v]); 'types' => 'oa_examine',
// } 'types_id' => $dataInfo['category_id'],
'form_type' => ['in', ['position', 'location', 'handwriting_sign', 'date_interval', 'detail_table']]
];
$fieldList = db('admin_field')->field(['field', 'form_type'])->where($fieldWhere)->select();
foreach ($fieldList AS $key => $value) {
if (!empty($dataInfo[$value['field']])) {
$dataInfo[$value['field']] = json_decode($dataInfo[$value['field']], true);
}
}
//关联业务 //关联业务
$relationArr = [];
$relationArr = $recordModel->getListByRelationId('examine', $id); $relationArr = $recordModel->getListByRelationId('examine', $id);
$dataInfo['businessList'] = $relationArr['businessList']; $dataInfo['businessList'] = $relationArr['businessList'];
$dataInfo['contactsList'] = $relationArr['contactsList']; $dataInfo['contactsList'] = $relationArr['contactsList'];
@ -604,7 +626,6 @@ class Examine extends Common
$where = []; $where = [];
$where['module'] = 'oa_examine'; $where['module'] = 'oa_examine';
$where['module_id'] = $id; $where['module_id'] = $id;
$newFileList = [];
$newFileList = $fileModel->getDataList($where, 'all'); $newFileList = $fileModel->getDataList($where, 'all');
foreach ($newFileList['list'] as $val) { foreach ($newFileList['list'] as $val) {
if ($val['types'] == 'file') { if ($val['types'] == 'file') {

@ -249,9 +249,7 @@ class ExamineCategory extends Common
$data['delete_user_id'] = $user_id; $data['delete_user_id'] = $user_id;
$this->allowField(true)->save($data, ['category_id' => $id]); $this->allowField(true)->save($data, ['category_id' => $id]);
# 系统操作记录 # 系统操作记录
$user=new ApiCommon(); SystemActionLog($user_id,'oa_examine', 'approval', $id, 'delete',$info['title'] , '', '','删除了:'.$info['title']);
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'],'oa_examine', 'approval', $id, 'delete',$info['title'] , '', '','删除了:'.$info['title']);
$this->commit(); $this->commit();
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {

@ -37,20 +37,29 @@ class ExamineData extends Common
$unField = ['content','remark','start_time','end_time','duration','cause','money','category_id','check_user_id','check_status','flow_id','order_id','create_user_id']; $unField = ['content','remark','start_time','end_time','duration','cause','money','category_id','check_user_id','check_status','flow_id','order_id','create_user_id'];
$data = []; $data = [];
foreach ($fieldList as $k=>$v) { foreach ($fieldList as $k=>$v) {
$field_arr = [];
if (is_array($param[$v['field']])) {
foreach ($param[$v['field']] as $key=>$val) {
$field_arr[] = str_replace(',', '', $val);
}
$param[$v['field']] = $field_arr ? ','.implode(',',$field_arr).',' : '';
}
if (!in_array($v['field'], $unField)) { if (!in_array($v['field'], $unField)) {
$data[$k]['examine_id'] = $examine_id; $data[$k]['examine_id'] = $examine_id;
$data[$k]['field'] = $v['field']; $data[$k]['field'] = $v['field'];
$data[$k]['value'] = $param[$v['field']]; // 处理数据格式是对象的字段position 地址、location 定位、date_interval 日期区间、detail_table 明细表格
if (in_array($v['form_type'], ['position', 'location', 'date_interval', 'detail_table'])) {
$data[$k]['value'] = !empty($param[$v['field']]) ? json_encode($param[$v['field']], JSON_NUMERIC_CHECK) : '';
} else {
$data[$k]['value'] = !empty($param[$v['field']]) ? $param[$v['field']] : '';
}
// 处理手写签名
if ($v['form_type'] == 'handwriting_sign') {
$data[$k]['value'] = !empty($param[$v['field']]['file_id']) ? $param[$v['field']]['file_id'] : '';
}
// 处理附件
if ($v['form_type'] == 'file') {
$data[$k]['value'] = !empty($param[$v['field']]) ? arrayToString($param[$v['field']]) : '';
}
} }
} }
if ($data) { if ($data) {
db('oa_examine_data')->where('examine_id', $examine_id)->delete();
// print_r($data);exit;
$resData = db('oa_examine_data')->insertAll($data); $resData = db('oa_examine_data')->insertAll($data);
if (!$resData) { if (!$resData) {
$this->error = '添加失败'; $this->error = '添加失败';

@ -40,10 +40,8 @@ class Log extends Common
$fileModel = new \app\admin\model\File(); $fileModel = new \app\admin\model\File();
$commonModel = new \app\admin\model\Comment(); $commonModel = new \app\admin\model\Comment();
$recordModel = new \app\admin\model\Record(); $recordModel = new \app\admin\model\Record();
$user_id = $request['read_user_id']; $user_id = $request['read_user_id'];
$by = $request['by'] ?: ''; $by = $request['by'] ?: '';
$map = []; $map = [];
$search = $request['search']; $search = $request['search'];
if (isset($request['search']) && $request['search']) { if (isset($request['search']) && $request['search']) {
@ -130,6 +128,9 @@ class Log extends Common
$list[$k]['imgList'] = $imgList ?: []; $list[$k]['imgList'] = $imgList ?: [];
$list[$k]['sendUserList'] = $userModel->getDataByStr($v['send_user_ids']) ?: []; $list[$k]['sendUserList'] = $userModel->getDataByStr($v['send_user_ids']) ?: [];
$list[$k]['sendStructList'] = $structureModel->getDataByStr($v['send_structure_ids']) ?: []; $list[$k]['sendStructList'] = $structureModel->getDataByStr($v['send_structure_ids']) ?: [];
$favour=$this->favourList($v['log_id']);
$list[$k]['favourUser'] = $favour ?: [];
$list[$k]['favour_status'] =!empty($favour)?1:0 ;
$param['type_id'] = $v['log_id']; $param['type_id'] = $v['log_id'];
$param['type'] = 'oa_log'; $param['type'] = 'oa_log';
$list[$k]['replyList'] = $commonModel->read($param); $list[$k]['replyList'] = $commonModel->read($param);
@ -174,17 +175,17 @@ class Log extends Common
$data = []; $data = [];
$data['page']['list'] = $list; $data['page']['list'] = $list;
$data['page']['dataCount'] = $dataCount ?: 0; $data['page']['dataCount'] = $dataCount ?: 0;
if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) >= (int)$dataCount) {
$data['page']['firstPage'] = false;
$data['page']['lastPage'] = true;
} else if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) < (int)$dataCount) {
$data['page']['firstPage'] = false;
$data['page']['lastPage'] = false;
} else if ($request['page'] == 1) {
$data['page']['firstPage'] = true;
$data['page']['lastPage'] = false;
}
if ($param['page'] != 1 && ($param['page'] * $param['limit']) >= $dataCount) {
$data['firstPage'] = false;
$data['lastPage'] = true;
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false;
$data['lastPage'] = false;
} else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = true;
$data['lastPage'] = true;
}
return $data; return $data;
} }
@ -375,9 +376,7 @@ class Log extends Common
'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : '' 'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
]); ]);
} }
$user=new ApiCommon(); RecordActionLog($param['user_id'], 'oa_log', 'update',$dataInfo['title'], '','','修改了日志:'.$dataInfo['title']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'oa_log', 'update',$dataInfo['title'], '','','修改了日志:'.$dataInfo['title']);
return $data; return $data;
} else { } else {
$this->error = '编辑失败'; $this->error = '编辑失败';
@ -453,8 +452,6 @@ class Log extends Common
*/ */
public function delDataById($param) public function delDataById($param)
{ {
$user=new ApiCommon();
$userInfo=$user->userInfo;
$map['log_id'] = $param['log_id']; $map['log_id'] = $param['log_id'];
$dataInfo = $this->get($map['log_id']); $dataInfo = $this->get($map['log_id']);
if (!$dataInfo) { if (!$dataInfo) {
@ -469,7 +466,7 @@ class Log extends Common
$fileModel->delRFileByModule('oa_log', $param['log_id']); $fileModel->delRFileByModule('oa_log', $param['log_id']);
//删除相关评论 //删除相关评论
$commentModel->delDataById(['type' => 'oa_log', 'type_id' => $param['log_id']]); $commentModel->delDataById(['type' => 'oa_log', 'type_id' => $param['log_id']]);
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $dataInfo['title'], '', '', '删除了日志:' . $dataInfo['title']); RecordActionLog($param['user_id'], 'oa_log', 'delete', $dataInfo['title'], '', '', '删除了日志:' . $dataInfo['title']);
# 删除活动记录 # 删除活动记录
Db::name('crm_activity')->where(['activity_type' => 8, 'activity_type_id' => $param['log_id']])->delete(); Db::name('crm_activity')->where(['activity_type' => 8, 'activity_type_id' => $param['log_id']])->delete();
return true; return true;
@ -478,4 +475,22 @@ class Log extends Common
return false; return false;
} }
} }
/**
* 点赞数据
* @param string $log_id 日志id
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/18 0018 09:29
*/
public function favourList($log_id=''){
$list= db('oa_log_favour')
->alias('favour')
->join('__ADMIN_USER__ user','user.id=favour.user_id','LEFT')
->where(['favour.log_id'=>$log_id,'favour.status'=>1])
->field('user.id,user.realname,user.img,favour.status')
->select();
return $list?:[];
}
} }

@ -158,15 +158,16 @@ class work extends ApiCommon
$workInfo['auth'] = $this->getRuleList($this->param['work_id'], $userId, $groupId); $workInfo['auth'] = $this->getRuleList($this->param['work_id'], $userId, $groupId);
# 下次升级 # 下次升级
// $userInfo=$this->userInfo; $userInfo=$this->userInfo;
// $rule=db('work_user') $rule=db('work_user')
// ->where('user_id',$userInfo['id']) ->where('user_id',$userInfo['id'])
// ->value('group_id'); ->value('group_id');
// $list=db('admin_rule')->where('name','manageTaskOwnerUser')->value('id'); $list=db('admin_rule')->where('name','manageTaskOwnerUser')->value('id');
// $groupList = db('admin_group')->where(['pid' => 5, 'types' => 7, 'type' => 0,'id'=>$rule])->order('system desc')->value('rules'); $groupList = db('admin_group')->where(['pid' => 5, 'types' => 7, 'type' => 0,'id'=>$rule])->order('system desc')->value('rules');
// if(!in_array($list,stringToArray($groupList))){ if(!in_array($list,stringToArray($groupList))){
// $workInfo['is_open']=1; $workInfo['is_open']=1;
// } }
return resultArray(['data' => $workInfo]); return resultArray(['data' => $workInfo]);
} }
@ -288,6 +289,7 @@ class work extends ApiCommon
{ {
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$userId=$userInfo['id'];
if (!$param['work_id'] || !$param['owner_user_id']) { if (!$param['work_id'] || !$param['owner_user_id']) {
return resultArray(['error'=>'参数错误']); return resultArray(['error'=>'参数错误']);
} }
@ -301,7 +303,7 @@ class work extends ApiCommon
// header('Content-Type:application/json; charset=utf-8'); // header('Content-Type:application/json; charset=utf-8');
// exit(json_encode(['code'=>102,'error'=>'无权操作'])); // exit(json_encode(['code'=>102,'error'=>'无权操作']));
// } // }
$res = $workModel->delOwner($param); $res = $workModel->delOwner($param,$userId);
if ($res) { if ($res) {
return resultArray(['data'=>'操作成功']); return resultArray(['data'=>'操作成功']);
@ -381,7 +383,7 @@ class work extends ApiCommon
// header('Content-Type:application/json; charset=utf-8'); // header('Content-Type:application/json; charset=utf-8');
// exit(json_encode(['code'=>102,'error'=>'无权操作'])); // exit(json_encode(['code'=>102,'error'=>'无权操作']));
// } // }
$ret = $workModel->arRecover($param['work_id']); $ret = $workModel->arRecover($param['work_id'],$userInfo['id']);
if ($ret) { if ($ret) {
return resultArray(['data'=>'操作成功']); return resultArray(['data'=>'操作成功']);
} else { } else {

@ -330,6 +330,11 @@ class Task extends Common
->select(); ->select();
$complete = 0; $complete = 0;
foreach ($subTaskList as $key => $value) { foreach ($subTaskList as $key => $value) {
$subTaskList[$key]['main_user'] = [
'id' => $value['main_user_id'],
'img' => $value['thumb_img'],
'realname' => $value['realname']
];
$subTaskList[$key]['thumb_img'] = $value['thumb_img'] ? getFullPath($value['thumb_img']) : ''; $subTaskList[$key]['thumb_img'] = $value['thumb_img'] ? getFullPath($value['thumb_img']) : '';
$subTaskList[$key]['stop_time'] = !empty($value['stop_time']) ? date('Y-m-d', $value['stop_time']) : null; $subTaskList[$key]['stop_time'] = !empty($value['stop_time']) ? date('Y-m-d', $value['stop_time']) : null;
if ($value['status'] == 5) ++$complete; if ($value['status'] == 5) ++$complete;
@ -442,8 +447,6 @@ class Task extends Common
$datalog['task_id'] = $task_id; $datalog['task_id'] = $task_id;
$datalog['work_id'] = $param['work_id'] ?: ''; $datalog['work_id'] = $param['work_id'] ?: '';
$ret = $taskLog->newTaskLog($datalog); $ret = $taskLog->newTaskLog($datalog);
//操作日志
// actionLog($task_id, '', '', '新建了任务');
//抄送站内信 //抄送站内信
(new Message())->send( (new Message())->send(
Message::TASK_ALLOCATION, Message::TASK_ALLOCATION,
@ -480,8 +483,6 @@ class Task extends Common
} }
db('work_task_file')->insertAll($fileData); db('work_task_file')->insertAll($fileData);
} }
$user=new ApiCommon();
$userInfo=$user->userInfo;
# 添加子任务 # 添加子任务
if (!empty($subtask)) { if (!empty($subtask)) {
$subtaskData = []; $subtaskData = [];
@ -503,15 +504,10 @@ class Task extends Common
} }
Db::name('task')->insertAll($subtaskData); Db::name('task')->insertAll($subtaskData);
foreach ($subtaskData as $v){ foreach ($subtaskData as $v){
RecordActionLog($userInfo['id'],'work_task','save',$param['name'],'','','新增了子任务'.$v['name']); RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增了子任务'.$v['name']);
}
} }
if(!empty($param['pid'])){
$dataInfo=Db::name('task')->where('task_id',$param['pid'])->find();
RecordActionLog($userInfo['id'],'work_task','save',$dataInfo['name'],'','','新增了子任务'.$param['name']);
}else{
RecordActionLog($userInfo['id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
} }
RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
return $task_id; return $task_id;
} else { } else {
$this->error = '添加失败'; $this->error = '添加失败';
@ -701,16 +697,13 @@ class Task extends Common
if (!$param['pid']) { if (!$param['pid']) {
$LogModel = new LogModel(); $LogModel = new LogModel();
$taskInfo = $LogModel->taskLogAdd($data); $taskInfo = $LogModel->taskLogAdd($data);
// actionLog($param['task_id'], $param['owner_user_id'], $param['structure_ids'], '修改了任务');
$user=new ApiCommon();
$userInfo=$user->userInfo;
if(empty($name)){ if(empty($name)){
if(!empty($param['description'])){ if(!empty($param['description'])){
$name='描述'; $name='描述';
} }
} }
$count_name=empty($count_name)?$target_name:$count_name; $count_name=empty($count_name)?$target_name:$count_name;
RecordActionLog($userInfo['id'], 'work_task', 'update',$target_name, '','','修改任务'.$name.''.$count_name); RecordActionLog($createUserId, 'work_task', 'update',$target_name, '','','修改任务'.$name.''.$count_name);
$resRelation = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find(); $resRelation = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find();
if ($resRelation) { if ($resRelation) {
Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($rdata); //更新关联关系 Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($rdata); //更新关联关系
@ -847,11 +840,7 @@ class Task extends Common
$dataInfo = json_decode(json_encode($dataInfo), true); $dataInfo = json_decode(json_encode($dataInfo), true);
$flag = $this->where(['task_id' => $param['task_id']])->update($data); $flag = $this->where(['task_id' => $param['task_id']])->update($data);
if ($flag) { if ($flag) {
//添加归档日志 RecordActionLog($param['create_user_id'], 'work_task', 'archiveData',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
// actionLog($param['task_id'], '', '', '归档了任务');
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work_task', 'archiveData',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
return true; return true;
} else { } else {
$this->error = '归档失败'; $this->error = '归档失败';
@ -872,9 +861,7 @@ class Task extends Common
$flag = $this->where(['task_id' => $param['task_id']])->setField('is_archive', 0); $flag = $this->where(['task_id' => $param['task_id']])->setField('is_archive', 0);
if ($flag) { if ($flag) {
//添加日志 //添加日志
$user=new ApiCommon(); RecordActionLog($param['create_user_id'], 'work_task', 'recover',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work_task', 'recover',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
return true; return true;
} else { } else {
$this->error = '操作失败'; $this->error = '操作失败';

@ -76,7 +76,8 @@ class Work extends Common
$ownerData['work_id'] = $workId; $ownerData['work_id'] = $workId;
$ownerData['create_user_id'] = $createUserId; $ownerData['create_user_id'] = $createUserId;
$ownerData['owner_user_id'] = $ownerUserId; $ownerData['owner_user_id'] = $ownerUserId;
$ownerData['group_id'] = !empty($param['group_id']) ? $param['group_id'] : 0; $group= Db::name('admin_group')->field(['id', 'title', 'rules', 'remark', 'system'])->where(['pid' => 5, 'types' => 7, 'status' => 1])->order('id','asc')->select();
$ownerData['group_id'] = !empty($param['group_id']) ? $param['group_id'] : $group[0]['id'];
# 创建项目下的相关成员 # 创建项目下的相关成员
$this->addOwner($ownerData); $this->addOwner($ownerData);
@ -173,9 +174,7 @@ class Work extends Common
$datalog['work_id'] = $param['work_id']; $datalog['work_id'] = $param['work_id'];
$datalog['user_id'] = $userId; $datalog['user_id'] = $userId;
$ret = $logmodel->workLogAdd($datalog); $ret = $logmodel->workLogAdd($datalog);
$user=new ApiCommon(); RecordActionLog($userId, 'work', 'update',$param['name'], '','','编辑了项目:'.$param['name']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'update',$param['name'], '','','编辑了项目:'.$param['name']);
return true; return true;
} else { } else {
$this->error = '重命名失败'; $this->error = '重命名失败';
@ -227,9 +226,7 @@ class Work extends Common
$data['status'] = 3; $data['status'] = 3;
$data['archive_time'] = time(); $data['archive_time'] = time();
Db::name('task')->where($map)->update($data); Db::name('task')->where($map)->update($data);
$user=new ApiCommon(); RecordActionLog($param['create_user_id'], 'work', 'archiveData',$dataInfo['name'], '','','归档了项目:'.$dataInfo['name']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'archiveData',$dataInfo['name'], '','','归档了项目:'.$dataInfo['name']);
return true; return true;
} else { } else {
$this->error = '归档失败'; $this->error = '归档失败';
@ -268,7 +265,7 @@ class Work extends Common
* @param * @param
* @return * @return
*/ */
public function arRecover($work_id='') public function arRecover($work_id='',$userId)
{ {
if (!$work_id) { if (!$work_id) {
$this->error = '参数错误'; $this->error = '参数错误';
@ -281,9 +278,7 @@ class Work extends Common
$this->where($map)->setField('status',1); $this->where($map)->setField('status',1);
$map['status'] = 3; $map['status'] = 3;
Db::name('Task')->where($map)->setField('status',1); Db::name('Task')->where($map)->setField('status',1);
$user=new ApiCommon(); RecordActionLog($userId, 'work', 'recover',$dataInfo['name'], '','','归档恢复项目:'.$dataInfo['name']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'recover',$dataInfo['name'], '','','归档恢复项目:'.$dataInfo['name']);
return true; return true;
} }
@ -301,8 +296,6 @@ class Work extends Common
$this->error = '项目创建人不可以退出'; $this->error = '项目创建人不可以退出';
return false; return false;
} }
$user=new ApiCommon();
$userInfo=$user->userInfo;
//从项目成员中移除 //从项目成员中移除
db('work_user')->where(['work_id' => $work_id,'user_id' => $user_id])->delete(); db('work_user')->where(['work_id' => $work_id,'user_id' => $user_id])->delete();
$str = ','.$user_id.','; $str = ','.$user_id.',';
@ -317,13 +310,13 @@ class Work extends Common
$new_own_user_id = str_replace($str,',',$value['owner_user_id']); $new_own_user_id = str_replace($str,',',$value['owner_user_id']);
$data['owner_user_id'] = $new_own_user_id; $data['owner_user_id'] = $new_own_user_id;
} }
if ($value['main_user_id'] == $param['create_user_id']) { if ($value['main_user_id'] == $workInfo['create_user_id']) {
$data['main_user_id'] = ''; $data['main_user_id'] = '';
} }
if ($data) Db::name('Task')->where(['task_id' => $value['task_id']])->update($data); if ($data) Db::name('Task')->where(['task_id' => $value['task_id']])->update($data);
RecordActionLog($userInfo['id'], 'work_task', 'recover',$value['name'], '','','退出了项目:'.$value['name']); RecordActionLog($user_id, 'work_task', 'recover',$value['name'], '','','退出了项目:'.$value['name']);
} }
RecordActionLog($userInfo['id'], 'work', 'update',$workInfo['name'], '','','退出了项目:'.$workInfo['name']); RecordActionLog($user_id, 'work', 'update',$workInfo['name'], '','','退出了项目:'.$workInfo['name']);
return true; return true;
} }
@ -356,7 +349,7 @@ class Work extends Common
$data['types'] = 0; $data['types'] = 0;
if ($v == $create_user_id) { if ($v == $create_user_id) {
$data['types'] = 1; $data['types'] = 1;
$group_id = 1; $group_id = $param['group_id'];
} else { } else {
# 默认角色 # 默认角色
$group_id = !empty($param['group_id']) ? $param['group_id'] : db('admin_group')->where(['pid' => 5, 'system' => 1])->order('id asc')->value('id'); $group_id = !empty($param['group_id']) ? $param['group_id'] : db('admin_group')->where(['pid' => 5, 'system' => 1])->order('id asc')->value('id');
@ -380,7 +373,7 @@ class Work extends Common
* @param * @param
* @return * @return
*/ */
public function delOwner($param) public function delOwner($param,$userId)
{ {
$work_id = $param['work_id']; $work_id = $param['work_id'];
$workUserInfo = db('work_user')->where(['work_id' => $work_id,'user_id' => $param['owner_user_id']])->find(); $workUserInfo = db('work_user')->where(['work_id' => $work_id,'user_id' => $param['owner_user_id']])->find();
@ -403,11 +396,9 @@ class Work extends Common
$this->error = '删除失败,请重试!'; $this->error = '删除失败,请重试!';
return false; return false;
} }
$user=new ApiCommon();
$userInfo=$user->userInfo;
$user= new \app\admin\model\User(); $user= new \app\admin\model\User();
$user_info=$user->getUserById($param['owner_user_id']); $user_info=$user->getUserById($param['owner_user_id']);
RecordActionLog($userInfo['id'], 'work', 'save',$workInfo['name'], '','','删除了项目成员:'.$user_info['realname']); RecordActionLog($userId, 'work', 'save',$workInfo['name'], '','','删除了项目成员:'.$user_info['realname']);
return true; return true;
} }
@ -423,7 +414,14 @@ class Work extends Common
$workInfo = $this->get($param['work_id']); $workInfo = $this->get($param['work_id']);
if ($workInfo['is_open'] == 1) { if ($workInfo['is_open'] == 1) {
//公开项目 //公开项目
$list = db('admin_user')->where(['status' => 1])->field('username,realname,thumb_img,id')->select(); // $list = db('admin_user')->where(['status' => 1])->field('username,realname,thumb_img,id')->select();
$list = db('work_user')
->alias('work')
->join('__ADMIN_USER__ user', 'user.id = work.user_id', 'LEFT')
->where(['work.work_id' => $param['work_id']])
->field('work.*,user.username,user.realname,user.thumb_img')
->order('work.types desc,user.id asc')
->select();
} else { } else {
// $exp = new \think\db\Expression('field(types,1,0,2)'); // $exp = new \think\db\Expression('field(types,1,0,2)');
$list = db('work_user') $list = db('work_user')

@ -69,9 +69,7 @@ class WorkClass extends Model
$data['order_id'] = $max_order_id ? $max_order_id+1 : 0; $data['order_id'] = $max_order_id ? $max_order_id+1 : 0;
$this->insert($data); $this->insert($data);
$this->commit(); $this->commit();
$user=new ApiCommon(); RecordActionLog( $param['create_user_id'], 'work', 'save',$param['name'], '','','添加了任务分类:'.$param['name']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'save',$param['name'], '','','添加了任务分类:'.$param['name']);
return true; return true;
} catch(\Exception $e) { } catch(\Exception $e) {
$this->rollback(); $this->rollback();
@ -95,9 +93,7 @@ class WorkClass extends Model
$this->error = '重命名失败'; $this->error = '重命名失败';
return false; return false;
} }
$user=new ApiCommon(); RecordActionLog($param['create_user_id'], 'work', 'save',$classInfo['name'], '','','编辑了任务分类:'.$classInfo['name']);
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'save',$classInfo['name'], '','','编辑了任务分类:'.$classInfo['name']);
return true; return true;
} }

2882
composer.lock generated

File diff suppressed because it is too large Load Diff

@ -182,16 +182,20 @@ return [
'cache' => [ 'cache' => [
// 驱动方式 // 驱动方式
'type' => 'redis', 'type' => 'redis',
// 缓存保存目录 // 连接地址
'path' => CACHE_PATH, 'host' => '127.0.0.1',
// 端口
'port' => 6379,
// 密码
'password' => '',
// 缓存前缀 // 缓存前缀
'prefix' => '', 'prefix' => '',
// 缓存有效期 0表示永久缓存 // 缓存有效期 0表示永久缓存
'expire' => 86400*30, 'expire' => 86400*30,
// 缓存保存目录
'path' => CACHE_PATH,
// 禁用缓存子目录 // 禁用缓存子目录
'cache_subdir' => false, 'cache_subdir' => false,
// 密码
'password' => ''
], ],
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------

@ -0,0 +1,39 @@
<?php
return [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => '',
// 用户名
'username' => '',
// 密码
'password' => '',
// 端口
'hostport' => '3306',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => '5kcrm_', // 默认表前缀,不要改为其他值。
// 数据库调试模式
'debug' => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 自动读取主库数据
'read_master' => false,
// 是否严格检查字段是否存在
'fields_strict' => true,
// 数据集返回类型
'resultset_type' => 'array',
];

@ -344,7 +344,29 @@ return [
'admin/setting/customerLevel' => ['admin/setting/customerLevel', ['method' => 'POST']], 'admin/setting/customerLevel' => ['admin/setting/customerLevel', ['method' => 'POST']],
//【设置】公海字段 //【设置】公海字段
'admin/setting/poolField' => ['admin/setting/poolField', ['method' => 'POST']], 'admin/setting/poolField' => ['admin/setting/poolField', ['method' => 'POST']],
// 获取配置角色查看范围
'admin/rules/groupauth' => ['admin/rules/groupauth', ['method' => 'POST']],
// 授权配置角色查看范围
'admin/rules/upgroupauth' => ['admin/rules/upgroupauth', ['method' => 'POST']],
// 获取配置角色
'admin/rules/getgroupauth' => ['admin/rules/getgroupauth', ['method' => 'POST']],
// 授权配置角色查看范围id
'admin/rules/groupauthid' => ['admin/rules/groupauthid', ['method' => 'POST']],
//【市场活动】市场活动列表
'admin/market/index' => ['admin/market/index', ['method' => 'POST']],
//【市场活动】市场活动添加
'admin/market/save' => ['admin/market/save', ['method' => 'POST']],
//【市场活动】市场活动修改
'admin/market/update' => ['admin/market/update', ['method' => 'POST']],
//【市场活动】市场活动删除
'admin/market/delete' => ['admin/market/delete', ['method' => 'POST']],
//【市场活动】市场活动启用停用
'admin/market/enables' => ['admin/market/enables', ['method' => 'POST']],
//【市场活动】市场活动自定义字段列表
'admin/market/getField' => ['admin/market/getField', ['method' => 'POST']],
//【市场活动】市场活动自定义字段表单
'admin/market/updateFields' => ['admin/market/updateFields', ['method' => 'POST']],
// MISS路由 // MISS路由
'__miss__' => 'admin/base/miss', '__miss__' => 'admin/base/miss',
]; ];

@ -298,6 +298,8 @@ return [
'crm/invoice/count' => ['crm/invoice/count', ['method' => 'POST']], 'crm/invoice/count' => ['crm/invoice/count', ['method' => 'POST']],
// 【发票】重置开票信息 // 【发票】重置开票信息
'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']], 'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']],
// 【发票】导出
'crm/invoice/excelExport' => ['crm/invoice/excelExport', ['method' => 'POST']],
// 【发票-开户行】列表 // 【发票-开户行】列表
'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']], 'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']],
@ -380,6 +382,8 @@ return [
'crm/index/queryDataInfo' => ['crm/index/queryDataInfo', ['method' => 'POST']], 'crm/index/queryDataInfo' => ['crm/index/queryDataInfo', ['method' => 'POST']],
// 【获取自动编号开启状态】 // 【获取自动编号开启状态】
'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']], 'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']],
// 【商机阶段列表】
'crm/index/businessList' => ['crm/index/businessList', ['method' => 'POST']],
// 【获取仪表盘布局】 // 【获取仪表盘布局】
'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']], 'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']],
@ -477,7 +481,7 @@ return [
'crm/printing/down' => ['crm/printing/down', ['method' => 'POST']], 'crm/printing/down' => ['crm/printing/down', ['method' => 'POST']],
//跟进记录导入模板 //跟进记录导入模板
'crm/activity/excelDownload' => ['crm/activity/excelDownload', ['method' => 'GET']], 'crm/activity/excelDownload' => ['crm/activity/excelDownload', ['method' => 'POST']],
//跟进记录导入 //跟进记录导入
'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']], 'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']],
//跟进记录导出 //跟进记录导出
@ -495,10 +499,27 @@ return [
'crm/market/enables' => ['crm/market/enables', ['method' => 'POST']], 'crm/market/enables' => ['crm/market/enables', ['method' => 'POST']],
//市场活动状态删除 //市场活动状态删除
'crm/market/delete' => ['crm/market/delete', ['method' => 'POST']], 'crm/market/delete' => ['crm/market/delete', ['method' => 'POST']],
//市场活动对象列表
'crm/market/marketList' => ['crm/market/marketList', ['method' => 'POST']],
//市场活动手机页面信息
'crm/market/marketId' => ['crm/market/marketId', ['method' => 'POST']],
//市场活动表单列表
'crm/market/marketFormList' => ['crm/market/marketFormList', ['method' => 'POST']],
//市场活动表单添加
'crm/market/marketFormSave' => ['crm/market/marketFormSave', ['method' => 'POST']],
//市场活动表单同步数据
'crm/market/marketFormUpdate' => ['crm/market/marketFormUpdate', ['method' => 'POST']],
//市场活动表单下载
'crm/market/importDown' => ['crm/market/importDown', ['method' => 'POST']],
//市场活动表单字段
'crm/market/marketGetField' => ['crm/market/marketGetField', ['method' => 'POST']],
//【通用】快捷编辑 //【通用】快捷编辑
'crm/common/quickEdit' => ['crm/common/quickEdit', ['method' => 'POST']], 'crm/common/quickEdit' => ['crm/common/quickEdit', ['method' => 'POST']],
//手机导航列表
'crm/setting/appMenuConfig' => ['crm/setting/appMenuConfig', ['method' => 'POST']],
//办公数量
'crm/setting/oaNumber' => ['crm/setting/oaNumber', ['method' => 'POST']],
// MISS路由 // MISS路由
'__miss__' => 'admin/base/miss', '__miss__' => 'admin/base/miss',
]; ];

@ -162,6 +162,8 @@ return [
'oa/log/queryLog' => ['oa/log/queryLog', ['method' => 'POST']], 'oa/log/queryLog' => ['oa/log/queryLog', ['method' => 'POST']],
//日志销售简报 //日志销售简报
'oa/log/oneBulletin' => ['oa/log/oneBulletin', ['method' => 'POST']], 'oa/log/oneBulletin' => ['oa/log/oneBulletin', ['method' => 'POST']],
//日志销售简报
'oa/log/favourUpdate' => ['oa/log/favourUpdate', ['method' => 'POST']],
// 【审批】类型列表 // 【审批】类型列表
'oa/examine/category'=>['oa/examine/category', ['method' => 'POST']], 'oa/examine/category'=>['oa/examine/category', ['method' => 'POST']],
@ -204,7 +206,8 @@ return [
// 【代办事项】办公 // 【代办事项】办公
'oa/message/num'=>['oa/message/num', ['method' => 'POST']], 'oa/message/num'=>['oa/message/num', ['method' => 'POST']],
//手机导航
'admin/setting/appMenuConfig' => ['admin/setting/appMenuConfig', ['method' => 'POST']],
// MISS路由 // MISS路由
'__miss__' => 'admin/base/miss', '__miss__' => 'admin/base/miss',
]; ];

@ -1,5 +1,5 @@
<?php <?php
return array( return array(
'VERSION'=>'11.0.3', 'VERSION'=>'11.1.0',
'RELEASE'=>'202105014', 'RELEASE'=>'20210625',
); );

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

File diff suppressed because one or more lines are too long

@ -0,0 +1,4 @@
if ( !-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
break;
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save