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);
} }
@ -375,8 +375,12 @@ INFO;
'php' => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'], 'php' => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'],
'gd' => ['gd', '开启', '开启', 'ok'], 'gd' => ['gd', '开启', '开启', 'ok'],
'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]);
}
}
} }

@ -19,7 +19,7 @@ class Setting extends ApiCommon
* @permission 无限制 * @permission 无限制
* @allow 登录用户可访问 * @allow 登录用户可访问
* @other 其他根据系统设置 * @other 其他根据系统设置
**/ **/
public function _initialize() public function _initialize()
{ {
$action = [ $action = [
@ -28,7 +28,7 @@ class Setting extends ApiCommon
]; ];
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'])) {
parent::_initialize(); parent::_initialize();
} }
@ -39,7 +39,7 @@ class Setting extends ApiCommon
if (!in_array(2,$adminTypes) && !in_array(1,$adminTypes) && !in_array($a, $unAction)) { if (!in_array(2,$adminTypes) && !in_array(1,$adminTypes) && !in_array($a, $unAction)) {
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'=>'无权操作']));
} }
} }
/** /**
@ -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,47 +16,50 @@ 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'])) {
parent::_initialize(); parent::_initialize();
} }
} }
//信息列表 //信息列表
public function index() public function index()
{ {
$systemModel = model('System'); $systemModel = model('System');
$data = $systemModel->getDataList(); $data = $systemModel->getDataList();
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
//编辑保存 //编辑保存
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='企业名称'; }
$dataInfo = db('admin_system')->where('id', $system_id)->column('name,value'); if (isset($param['name'])) {
$system_id = 1;
$field_name = '企业名称';
$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,8 +98,71 @@ 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' => '没有可用更新!'];
}
/** /**
* 员工创建 * 员工创建
@ -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);
@ -468,11 +489,13 @@ class PoolConfigLogic
foreach ($fields AS $key => $value) { foreach ($fields AS $key => $value) {
$result[] = [ $result[] = [
'pool_id' => $poolId, 'pool_id' => $poolId,
'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;

@ -10,333 +10,337 @@ namespace app\admin\model;
use think\Model; use think\Model;
use think\Request; use think\Request;
class Common extends Model class Common extends Model
{ {
/** /**
* [Request 请求参数] * [Request 请求参数]
* @Michael_xu * @Michael_xu
* @return [array] * @return [array]
*/ */
protected function requestData() protected function requestData()
{ {
$m = strtolower(request()->module()); $m = strtolower(request()->module());
$c = strtolower(request()->controller()); $c = strtolower(request()->controller());
$a = strtolower(request()->action()); $a = strtolower(request()->action());
$ret = [ $ret = [
'm' => $m, 'm' => $m,
'c' => $c, 'c' => $c,
'a' => $a 'a' => $a
]; ];
return $ret; return $ret;
} }
/** /**
* [fmtRequest 格式化请求参数] * [fmtRequest 格式化请求参数]
* @Michael_xu * @Michael_xu
* @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']);
} }
$offset = $length = null; $offset = $length = null;
if ($pageType == 'all') { if ($pageType == 'all') {
$page = 1; $page = 1;
$limit = 0; $limit = 0;
unset($request['pageType']); unset($request['pageType']);
} else { } else {
// 大数据处理-滚动加载-子分页 // 大数据处理-滚动加载-子分页
if ($request['sub_page'] && $request['sub_limit']) { if ($request['sub_page'] && $request['sub_limit']) {
$sub_page = $request['sub_page']; $sub_page = $request['sub_page'];
$sub_limit = $request['sub_limit']; $sub_limit = $request['sub_limit'];
unset($request['sub_page']); unset($request['sub_page']);
unset($request['sub_limit']); unset($request['sub_limit']);
$offset = ($page - 1) * $limit + ($sub_page - 1) * $sub_limit; $offset = ($page - 1) * $limit + ($sub_page - 1) * $sub_limit;
if ($sub_limit * $sub_page > $limit) { if ($sub_limit * $sub_page > $limit) {
$length = ($page - 1) * $limit + $limit - $offset; $length = ($page - 1) * $limit + $limit - $offset;
} else { } else {
$length = $sub_limit; $length = $sub_limit;
} }
if ($length < 0) { if ($length < 0) {
$offset = $length = 0; $offset = $length = 0;
} }
} }
} }
if (!isset($offset) || !isset($length)) { if (!isset($offset) || !isset($length)) {
$offset = ($page - 1) * $limit; $offset = ($page - 1) * $limit;
$length = $limit; $length = $limit;
} }
$ret = [ $ret = [
'page' => $page, 'page' => $page,
'limit' => $limit, 'limit' => $limit,
'map' => $request, 'map' => $request,
'offset' => $offset, 'offset' => $offset,
'length' => $length, 'length' => $length,
]; ];
return $ret; return $ret;
} }
/** /**
* [getDataById 根据主键获取详情] * [getDataById 根据主键获取详情]
* @param string $id [主键] * @param string $id [主键]
* @return [array] * @return [array]
*/ */
public function getDataById($id = '') public function getDataById($id = '')
{ {
$data = $this->get($id); $data = $this->get($id);
if (!$data) { if (!$data) {
$this->error = '暂无此数据'; $this->error = '暂无此数据';
return false; return false;
} }
return $data; return $data;
} }
/** /**
* [createData 新建] * [createData 新建]
* @param array $param [description] * @param array $param [description]
* @return [array] [description] * @return [array] [description]
*/ */
public function createData($param) public function createData($param)
{ {
// 验证 // 验证
$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; return false;
} }
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;
} }
} }
/** /**
* [updateDataById 编辑] * [updateDataById 编辑]
* @param [type] $param [description] * @param [type] $param [description]
* @param [type] $id [description] * @param [type] $id [description]
* @return [type] [description] * @return [type] [description]
*/ */
public function updateDataById($param, $id) public function updateDataById($param, $id)
{ {
$checkData = $this->get($id); $checkData = $this->get($id);
if (!$checkData) { if (!$checkData) {
$this->error = '暂无此数据'; $this->error = '暂无此数据';
return false; return false;
} }
// 验证 // 验证
$validate = validate($this->name); $validate = validate($this->name);
if (!$validate->scene('edit')->check($param)) { if (!$validate->scene('edit')->check($param)) {
$this->error = $validate->getError(); $this->error = $validate->getError();
return false; return false;
} }
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;
} }
} }
/** /**
* [delDataById 根据id删除数据] * [delDataById 根据id删除数据]
* @param string $id [主键] * @param string $id [主键]
* @param boolean $delSon [是否删除子孙数据] * @param boolean $delSon [是否删除子孙数据]
* @return [type] [description] * @return [type] [description]
*/ */
public function delDataById($id = '', $delSon = false) public function delDataById($id = '', $delSon = false)
{ {
if (!$id) { if (!$id) {
$this->error = '删除失败'; $this->error = '删除失败';
return false; return false;
} }
$this->startTrans(); $this->startTrans();
try { try {
$this->where($this->getPk(), $id)->delete(); $this->where($this->getPk(), $id)->delete();
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;
} }
} }
/** /**
* [delDatas 批量删除数据] * [delDatas 批量删除数据]
* @param array $ids [主键数组] * @param array $ids [主键数组]
* @param boolean $delSon [是否删除子孙数据] * @param boolean $delSon [是否删除子孙数据]
* @return [type] [description] * @return [type] [description]
*/ */
public function delDatas($ids = [], $delSon = false) public function delDatas($ids = [], $delSon = false)
{ {
if (empty($ids)) { if (empty($ids)) {
$this->error = '删除失败'; $this->error = '删除失败';
return false; return false;
} }
// 查找所有子元素 // 查找所有子元素
if ($delSon) { if ($delSon) {
foreach ($ids as $k => $v) { foreach ($ids as $k => $v) {
if (!is_numeric($v)) continue; if (!is_numeric($v)) continue;
$childIds = $this->getAllChild($v); $childIds = $this->getAllChild($v);
$ids = array_merge($ids, $childIds); $ids = array_merge($ids, $childIds);
} }
$ids = array_unique($ids); $ids = array_unique($ids);
} }
try { try {
$this->where($this->getPk(), 'in', $ids)->delete(); $this->where($this->getPk(), 'in', $ids)->delete();
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error = '操作失败'; $this->error = '操作失败';
return false; return false;
} }
} }
/** /**
* [enableDatas 批量启用、禁用] * [enableDatas 批量启用、禁用]
* @param string $ids [主键数组] * @param string $ids [主键数组]
* @param integer $status [状态1启用0禁用] * @param integer $status [状态1启用0禁用]
* @param [boolean] $delSon [是否删除子孙数组] * @param [boolean] $delSon [是否删除子孙数组]
* @return [type] [description] * @return [type] [description]
*/ */
public function enableDatas($ids = [], $status = 1, $delSon = false) public function enableDatas($ids = [], $status = 1, $delSon = false)
{ {
if (empty($ids)) { if (empty($ids)) {
$this->error = '参数错误'; $this->error = '参数错误';
return false; return false;
} }
// 查找所有子元素 // 查找所有子元素
if ($delSon && $status === '0') { if ($delSon && $status === '0') {
foreach ($ids as $k => $v) { foreach ($ids as $k => $v) {
$childIds = $this->getAllChild($v); $childIds = $this->getAllChild($v);
$ids = array_merge($ids, $childIds); $ids = array_merge($ids, $childIds);
} }
$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 = '操作失败';
return false; return false;
} }
} }
/** /**
* 获取所有子孙 * 获取所有子孙
*/ */
public function getAllChild($id, &$data = []) public function getAllChild($id, &$data = [])
{ {
$map['pid'] = $id; $map['pid'] = $id;
$childIds = $this->where($map)->column($this->getPk()); $childIds = $this->where($map)->column($this->getPk());
if (!empty($childIds)) { if (!empty($childIds)) {
foreach ($childIds as $v) { foreach ($childIds as $v) {
$data[] = $v; $data[] = $v;
$this->getAllChild($v, $data); $this->getAllChild($v, $data);
} }
} }
return $data; return $data;
} }
/** /**
* 逻辑删除,将数据标记为删除状态 * 逻辑删除,将数据标记为删除状态
* @author Michael_xu * @author Michael_xu
*/ */
public function signDelById($id) public function signDelById($id)
{ {
if (!$id) { if (!$id) {
$this->error = '删除失败'; $this->error = '删除失败';
return false; return false;
} }
$this->startTrans(); $this->startTrans();
try { try {
$data['is_deleted'] = 1; $data['is_deleted'] = 1;
$data['delete_time'] = time(); $data['delete_time'] = time();
$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;
} }
} }
/** /**
* 导出数据处理 * 导出数据处理
*/ */
public function exportHandle($list, $field_list, $type = '') public function exportHandle($list, $field_list, $type = '')
{ {
foreach ($list as &$val) { foreach ($list as &$val) {
foreach ($field_list as $field) { foreach ($field_list as $field) {
switch ($field['form_type']) { switch ($field['form_type']) {
case 'user': case 'user':
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']);
// $val[$field['field']] = implode(',', array_column($temp, 'name')); // $val[$field['field']] = implode(',', array_column($temp, 'name'));
// $val[$field['field']] = implode(',', array_column($temp, 'name')); // $val[$field['field']] = implode(',', array_column($temp, 'name'));
break; break;
case 'datetime': case 'datetime':
$val[$field['field']] = strtotime($val[$field['field']]) ? $val[$field['field']] : ''; $val[$field['field']] = strtotime($val[$field['field']]) ? $val[$field['field']] : '';
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;
} }
return $list; }
} }
}
return $list;
}
} }

@ -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'
]; ];
@ -72,7 +75,7 @@ class Excel extends Common
public function excelImportDownload($field_list, $types, $save_path = '') public function excelImportDownload($field_list, $types, $save_path = '')
{ {
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
//实例化主文件 //实例化主文件
$objPHPExcel = new Spreadsheet(); $objPHPExcel = new Spreadsheet();
$objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性 $objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性
@ -86,7 +89,7 @@ class Excel extends Common
$objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
$objActSheet = $objPHPExcel->getActiveSheet(); $objActSheet = $objPHPExcel->getActiveSheet();
$objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题 $objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
//存储Excel数据源到其他工作薄 //存储Excel数据源到其他工作薄
$objPHPExcel->createSheet(); $objPHPExcel->createSheet();
$subObject = $objPHPExcel->getSheet(1); $subObject = $objPHPExcel->getSheet(1);
@ -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')->getAlignment()->setWrapText(true);
$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:' . $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;
} }
$user_id = $param['owner_user_id']; if (!empty($param['pool_id'])) {
$user_id = $param['create_user_id'];
} else {
$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,16 +590,16 @@ 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");
vendor("phpexcel.PHPExcel.Writer.Excel5"); vendor("phpexcel.PHPExcel.Writer.Excel5");
@ -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';
$field_list = $fieldModel->field($fieldParam); if (!empty($param['pool_id'])) {
if(!empty($param['pool_id'])){ $list = [];
$pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select(); $field_list = db('crm_customer_pool_field_setting')->where(['pool_id' => $param['pool_id'], 'is_hidden' => 0,
$merge_list = $fieldModel->field($fieldParam); 'field_name' => ['not in', ['deal_status', 'create_user_id']]])->field('field_name as field,form_type,name')->select();
$field_list=array_intersect($merge_list,$pool_list); 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);
}
if ($types != 'admin_user' && empty($param['pool_id'])) {
$field = [1 => [
'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,21 +932,32 @@ 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 == '无权操作') {
$temp_error = '当前导入人员对该数据无写入权限'; $temp_error = '当前导入人员对该数据无写入权限';
}
$error_data_func($val, $temp_error);
$dataModel->rollback();
break;
} }
$error_data_func($val, $temp_error);
$dataModel->rollback();
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 {
}else{ $data = array_merge($data, $default_data);
$data['excel'] = 1;
if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError());
}
}
} 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();
@ -1024,7 +1070,7 @@ class Excel extends Common
'user_id' => $user_id, '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::rm('item'); Cache::rm('item');
Cache::rm('excel_item'); Cache::rm('excel_item');
Cache::set('item', 1, config('import_cache_time')); Cache::set('item', 1, config('import_cache_time'));
@ -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,16 +2441,18 @@ 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;
} elseif ($param == 1) { } elseif ($param == 1) {
$data = ''; $data = '';
} }
return $data; return $data;
} }
@ -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,11 +2529,11 @@ 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');
// 队列任务ID // 队列任务ID
if (!$import_queue_index) { if (!$import_queue_index) {
if (!$import_queue_index = $queue->makeTaskId()) { if (!$import_queue_index = $queue->makeTaskId()) {
@ -2501,27 +2550,28 @@ class Excel extends Common
} }
// 取消导入 // 取消导入
if ($param['page'] == -1) { if ($param['page'] == -1) {
@unlink(UPLOAD_PATH . $param['temp_file']); @unlink(UPLOAD_PATH . $param['temp_file']);
$this->error = [ $this->error = [
'msg' => '导入已取消', 'msg' => '导入已取消',
'page' => -1 'page' => -1
]; ];
if ($param['error']) { if ($param['error']) {
$this->error['error_file_path'] = 'temp/' . $param['error_file']; $this->error['error_file_path'] = 'temp/' . $param['error_file'];
} else { } else {
@unlink(TEMP_DIR . $param['error_file']); @unlink(TEMP_DIR . $param['error_file']);
} }
$temp = $queue->cache('last_import_cache'); $temp = $queue->cache('last_import_cache');
(new ImportRecord())->createData([ (new ImportRecord())->createData([
'type' => $types, 'type' => $types,
'total' => $temp['total'], 'total' => $temp['total'],
'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();
@ -2559,7 +2609,7 @@ class Excel extends Common
vendor("phpexcel.PHPExcel.Writer.Excel5"); vendor("phpexcel.PHPExcel.Writer.Excel5");
vendor("phpexcel.PHPExcel.Writer.Excel2007"); vendor("phpexcel.PHPExcel.Writer.Excel2007");
vendor("phpexcel.PHPExcel.IOFactory"); vendor("phpexcel.PHPExcel.IOFactory");
// 错误数据临时文件路径 错误数据开始行数 // 错误数据临时文件路径 错误数据开始行数
if ($param['error_file']) { if ($param['error_file']) {
$error_path = TEMP_DIR . $param['error_file']; $error_path = TEMP_DIR . $param['error_file'];
@ -2578,7 +2628,7 @@ class Excel extends Common
// 加载错误数据文件 // 加载错误数据文件
$err_PHPExcel = \PHPExcel_IOFactory::load($error_path); $err_PHPExcel = \PHPExcel_IOFactory::load($error_path);
$error_sheet = $err_PHPExcel->setActiveSheetIndex(0); $error_sheet = $err_PHPExcel->setActiveSheetIndex(0);
/** /**
* 添加错误数据到临时文件 * 添加错误数据到临时文件
@ -2605,7 +2655,7 @@ class Excel extends Common
$objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls'); $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
$objRender->setReadDataOnly(true); $objRender->setReadDataOnly(true);
$ExcelObj = $objRender->load($save_path); $ExcelObj = $objRender->load($save_path);
// 指定工作表 // 指定工作表
$sheet = $ExcelObj->getSheet(0); $sheet = $ExcelObj->getSheet(0);
// 总行数 // 总行数
@ -2642,42 +2692,44 @@ 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;
} }
// 开始导入数据 // 开始导入数据
foreach ($dataList as $val) { foreach ($dataList as $val) {
$fk = 0; $fk = 0;
@ -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);
$data['contacts_ids']=arrayToString($contactsData);
} }
if ($classData[0]['activity_id'] != '') { // if ($classData && $classData[0]['activity_id'] != '') {
// $data['activity_id'] = $classData[0]['activity_id'];
$data['activity_id'] = $classData[0]['activity_id']; // $data['activity_type_id'] = $customerData;
$data = array_merge($data, $default_data); // $data['activity_type'] = $activity_type;
$data['create_user_id'] = $userData; // $data['create_user_id'] = $user_id;
$data['activity_type_id'] = $customerData; // if (!$resData = $activityLogic->update($data)) {
$data['activity_type'] = $activity_type; // $error_data_func($val, $dataModel->getError());
if (!$resData = $activityLogic->update($data)) { // }
$error_data_func($val, $dataModel->getError()); // } else { }
} $data['user_id'] = $userData;
}else{
$data = array_merge($data, $default_data);
$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);
@ -2755,7 +2809,7 @@ class Excel extends Common
// 错误数据文件保存 // 错误数据文件保存
$objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5'); $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
$objWriter->save($error_path); $objWriter->save($error_path);
$this->error = [ $this->error = [
// 数据导入文件临时路径 // 数据导入文件临时路径
'temp_file' => $save_name, 'temp_file' => $save_name,
@ -2774,7 +2828,7 @@ class Excel extends Common
// 导入任务ID // 导入任务ID
'import_queue_index' => $import_queue_index 'import_queue_index' => $import_queue_index
]; ];
$queue->cache('last_import_cache', [ $queue->cache('last_import_cache', [
'total' => $total, 'total' => $total,
'done' => $done, 'done' => $done,
@ -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();
@ -417,7 +416,7 @@ class Scene extends Common
} else { } else {
//处理data //处理data
$data = $resData ? json_decode($resData,true) : []; $data = $resData ? json_decode($resData,true) : [];
} }
return $data; return $data;
} }
@ -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;
} }
} }

File diff suppressed because it is too large Load Diff

@ -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,
]; ];

File diff suppressed because it is too large Load Diff

@ -23,20 +23,20 @@ class PoolCommand extends Command
{ {
protected $timer; protected $timer;
protected $interval = 10; protected $interval = 10;
protected function configure() protected function configure()
{ {
$this->setName('pool') $this->setName('pool')
->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections') ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
->addOption('d', null, Option::VALUE_NONE, 'daemon守护进程方式启动') ->addOption('d', null, Option::VALUE_NONE, 'daemon守护进程方式启动')
->setDescription('公海回收定时器'); ->setDescription('公海回收定时器');
// 读取数据库配置文件 // 读取数据库配置文件
$filename = ROOT_PATH . 'config'.DS.'database.php'; $filename = ROOT_PATH . 'config' . DS . 'database.php';
// 重新加载数据库配置文件 // 重新加载数据库配置文件
Config::load($filename, 'database'); Config::load($filename, 'database');
} }
/** /**
* 初始化 * 初始化
* *
@ -46,16 +46,16 @@ class PoolCommand extends Command
protected function init(Input $input, Output $output) protected function init(Input $input, Output $output)
{ {
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';
} else { } else {
unset($argv[2]); unset($argv[2]);
} }
} }
/** /**
* 停止定时器 * 停止定时器
*/ */
@ -63,7 +63,7 @@ class PoolCommand extends Command
{ {
Timer::del($this->timer); Timer::del($this->timer);
} }
/** /**
* 启动定时器 * 启动定时器
*/ */
@ -75,22 +75,22 @@ class PoolCommand extends Command
# 公海规则 # 公海规则
$ruleList = db('crm_customer_pool_rule')->alias('rule')->field('rule.*') $ruleList = db('crm_customer_pool_rule')->alias('rule')->field('rule.*')
->join('__CRM_CUSTOMER_POOL__ pool', 'pool.pool_id = rule.pool_id', 'LEFT')->where('pool.status', 1)->select(); ->join('__CRM_CUSTOMER_POOL__ pool', 'pool.pool_id = rule.pool_id', 'LEFT')->where('pool.status', 1)->select();
if (!empty($ruleList)) { if (!empty($ruleList)) {
# 符合公海条件的客户IDS # 符合公海条件的客户IDS
$customerIds = $this->getQueryCondition($ruleList); $customerIds = $this->getQueryCondition($ruleList);
# 整理客户公海关联数据 # 整理客户公海关联数据
$poolRelationData = $this->getCustomerPoolRelationData($customerIds); $poolRelationData = $this->getCustomerPoolRelationData($customerIds);
# 整理修改客户数据的条件(进入公海时间,前负责人... # 整理修改客户数据的条件(进入公海时间,前负责人...
$customerWhere = $this->getCustomerQueryCondition($customerIds); $customerWhere = $this->getCustomerQueryCondition($customerIds);
Db::startTrans(); Db::startTrans();
try { try {
# 将客户退回公海 # 将客户退回公海
if (!empty($poolRelationData)) Db::name('crm_customer_pool_relation')->insertAll($poolRelationData); if (!empty($poolRelationData)) Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
# 修改客户数据 # 修改客户数据
if (!empty($customerWhere)) { if (!empty($customerWhere)) {
Db::name('crm_customer')->whereIn('customer_id', $customerWhere)->exp('before_owner_user_id', 'owner_user_id')->update([ Db::name('crm_customer')->whereIn('customer_id', $customerWhere)->exp('before_owner_user_id', 'owner_user_id')->update([
@ -100,10 +100,10 @@ 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' => '']);
Db::commit(); Db::commit();
} catch (\Exception $e) { } catch (\Exception $e) {
Db::rollback(); Db::rollback();
@ -112,15 +112,17 @@ class PoolCommand extends Command
} }
}); });
} }
protected function execute(Input $input, Output $output) protected function execute(Input $input, Output $output)
{ {
# 动态修改运行时参数 # 动态修改运行时参数
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '512M'); ini_set('memory_limit', '512M');
$this->init($input, $output); $this->init($input, $output);
# 创建定时器任务 # 创建定时器任务
$task = new Worker(); $task = new Worker();
$task->name = 'pool'; $task->name = 'pool';
@ -128,83 +130,83 @@ class PoolCommand extends Command
$task->onWorkerStart = [$this, 'start']; $task->onWorkerStart = [$this, 'start'];
$task->runAll(); $task->runAll();
} }
/** /**
* 整理修改客户数据的条件 * 整理修改客户数据的条件
* *
* @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;
} }
} }
return array_unique($result); return array_unique($result);
} }
/** /**
* 客户公海关联数据 * 客户公海关联数据
* *
* @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)
{ {
$result = []; $result = [];
# 用于排重 # 用于排重
$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[] = [
'pool_id' => $k1, 'pool_id' => $k1,
'customer_id' => $v2 'customer_id' => $v2
]; ];
$repeat[$k1][$v2] = $v2; $repeat[$k1][$v2] = $v2;
} }
} }
return $result; return $result;
} }
/** /**
* 获取符合公海条件的客户 * 获取符合公海条件的客户
* *
* @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']));
} }
return $result; return $result;
} }
/** /**
* N天内无新建跟进记录的客户 * N天内无新建跟进记录的客户
* *
@ -212,200 +214,200 @@ 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)
{ {
# 转换格式 # 转换格式
$levels = json_decode($levels, true); $levels = json_decode($levels, true);
# 默认条件 # 默认条件
$where = "`customer`.`owner_user_id` > 0"; $where = "`customer`.`owner_user_id` > 0";
# 所有用户,不区分级别 # 所有用户,不区分级别
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`)))";
} }
} }
} }
# 获取最小天数,对于没有设置级别的客户数据使用 # 获取最小天数,对于没有设置级别的客户数据使用
$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`))) )";
} }
# 选择不进入公海的客户(已成交客户) # 选择不进入公海的客户(已成交客户)
if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))"; if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
# 选择不进入公海的客户(有商机客户) # 选择不进入公海的客户(有商机客户)
if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)"; if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
# 锁定的客户不提醒 # 锁定的客户不提醒
$where .= " AND `customer`.`is_lock` = 0"; $where .= " AND `customer`.`is_lock` = 0";
# 查询符合条件的客户 # 查询符合条件的客户
return db('crm_customer') return db('crm_customer')
->alias('customer')->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT') ->alias('customer')->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
->where($where)->column('customer.customer_id'); ->where($where)->column('customer.customer_id');
} }
/** /**
* N天内无新建商机的客户 * N天内无新建商机的客户
* *
* @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)
{ {
# 转换格式 # 转换格式
$levels = json_decode($levels, true); $levels = json_decode($levels, true);
# 默认条件 # 默认条件
$where = "`customer`.`owner_user_id` > 0"; $where = "`customer`.`owner_user_id` > 0";
# 所有用户,不区分级别 # 所有用户,不区分级别
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'] . "'))";
} }
} }
} }
# 获取最小天数,对于没有设置级别的客户数据使用 # 获取最小天数,对于没有设置级别的客户数据使用
$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`)) )";
} }
# 选择不进入公海的客户(已成交客户) # 选择不进入公海的客户(已成交客户)
if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))"; if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
# 锁定的客户不提醒 # 锁定的客户不提醒
$where .= " AND `customer`.`is_lock` = 0"; $where .= " AND `customer`.`is_lock` = 0";
# 查询匹配条件的客户 # 查询匹配条件的客户
return db('crm_customer')->alias('customer') return db('crm_customer')->alias('customer')
->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT') ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
->where($where)->column('customer.customer_id'); ->where($where)->column('customer.customer_id');
} }
/** /**
* N天内没有成交的客户 * N天内没有成交的客户
* *
* @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)
{ {
# 转换格式 # 转换格式
$levels = json_decode($levels, true); $levels = json_decode($levels, true);
# 默认条件 # 默认条件
$where = "`customer`.`owner_user_id` > 0"; $where = "`customer`.`owner_user_id` > 0";
# 所有用户,不区分级别 # 所有用户,不区分级别
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'] . "'))";
} }
} }
} }
# 获取最小天数,对于没有设置级别的客户数据使用 # 获取最小天数,对于没有设置级别的客户数据使用
$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`)) )";
} }
# 选择不进入公海的客户(有商机客户) # 选择不进入公海的客户(有商机客户)
if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)"; if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
# 锁定的客户不提醒 # 锁定的客户不提醒
$where .= " AND `customer`.`is_lock` = 0"; $where .= " AND `customer`.`is_lock` = 0";
# 查询符合条件的客户 # 查询符合条件的客户
return db('crm_customer')->alias('customer') return db('crm_customer')->alias('customer')
->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT') ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract', 'contract.customer_id = customer.customer_id', 'LEFT') ->join('__CRM_CONTRACT__ contract', 'contract.customer_id = customer.customer_id', 'LEFT')
->where($where)->column('customer.customer_id'); ->where($where)->column('customer.customer_id');
} }
/** /**
* 获取公海规则最小数字(最快进入公海天数) * 获取公海规则最小数字(最快进入公海天数)
* *
* @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'];
} }
return $number; return $number;
} }
} }

@ -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,53 +13,63 @@ 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 = [];
switch ($types) { switch ($types) {
case 'crm_leads' : case 'crm_leads' :
$data_name = 'leads_id'; $data_name = 'leads_id';
$authIds = $userModel->getUserByPer('crm', 'leads', 'teamsave'); $authIds = $userModel->getUserByPer('crm', 'leads', 'teamsave');
break; break;
case 'crm_customer' : case 'crm_customer' :
$data_name = 'customer_id'; $data_name = 'customer_id';
$authIds = $userModel->getUserByPer('crm', 'customer', 'teamsave'); $authIds = $userModel->getUserByPer('crm', 'customer', 'teamsave');
break; break;
case 'crm_contacts' : case 'crm_contacts' :
$data_name = 'contacts_id'; $data_name = 'contacts_id';
$authIds = $userModel->getUserByPer('crm', 'contacts', 'teamsave'); $authIds = $userModel->getUserByPer('crm', 'contacts', 'teamsave');
break; break;
case 'crm_business' : case 'crm_business' :
$data_name = 'business_id'; $data_name = 'business_id';
$authIds = $userModel->getUserByPer('crm', 'business', 'teamsave'); $authIds = $userModel->getUserByPer('crm', 'business', 'teamsave');
break; break;
case 'crm_contract' : case 'crm_contract' :
$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) {
$resData = db($types)->where([$data_name => $v])->field('name,owner_user_id,rw_user_id,ro_user_id')->find(); if ($types == 'crm_receivables') {
if (!in_array($resData['owner_user_id'],$authIds) && $resData['owner_user_id'] && $is_module !== 1) { $resData = db($types)->where([$data_name => $v])->field('number as name,owner_user_id,rw_user_id,ro_user_id')->find();
$errorMessage[] = $resData['name'].'处理团队操作失败,错误原因:无权限'; } else {
$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'] . '处理团队操作失败,错误原因:无权限';
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) : ''; //去空
$all_ro_user_id = $old_ro_user_id ? array_diff($old_ro_user_id, $user_id) : ''; // 差集 $all_ro_user_id = $old_ro_user_id ? array_diff($old_ro_user_id, $user_id) : ''; // 差集
$data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空 $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空
} elseif ($is_del == 2) { } elseif ($is_del == 2) {
@ -76,13 +85,13 @@ 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;
} }
if (in_array($val, $old_rw_user_id) && !in_array($val, $old_ro_user_id) && $type == 1) { if (in_array($val, $old_rw_user_id) && !in_array($val, $old_ro_user_id) && $type == 1) {
$del_rw_user_id[] = $val; $del_rw_user_id[] = $val;
} }
} }
if ($type == 2) { if ($type == 2) {
$all_rw_user_id = $old_rw_user_id ? array_diff(array_merge($old_rw_user_id, $user_id), $del_rw_user_id) : $user_id; // 合并 $all_rw_user_id = $old_rw_user_id ? array_diff(array_merge($old_rw_user_id, $user_id), $del_rw_user_id) : $user_id; // 合并
@ -90,22 +99,40 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_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) : ''; //去空
if ($del_ro_user_id) { if ($del_ro_user_id) {
$data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空 $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空
} }
} else { } else {
$all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $del_rw_user_id) : $user_id; // 合并 $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $del_rw_user_id) : $user_id; // 合并
$all_ro_user_id = $old_ro_user_id ? array_diff(array_merge($old_ro_user_id, $user_id), $del_ro_user_id) : $user_id; // 合并 $all_ro_user_id = $old_ro_user_id ? array_diff(array_merge($old_ro_user_id, $user_id), $del_ro_user_id) : $user_id; // 合并
$data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空 $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空
if ($del_rw_user_id) { if ($del_rw_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) : ''; //去空
} }
} }
} }
$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,17 +24,17 @@ 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'])) {
parent::_initialize(); parent::_initialize();
} }
} }
/** /**
* 活动列表 * 活动列表
* *
@ -47,12 +48,12 @@ class Activity extends ApiCommon
{ {
$param = $this->param; $param = $this->param;
$param['user_id'] = $this->userInfo['id']; $param['user_id'] = $this->userInfo['id'];
$data = $activityLogic->index($param); $data = $activityLogic->index($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 创建活动【跟进记录】 * 创建活动【跟进记录】
* *
@ -66,20 +67,20 @@ class Activity extends ApiCommon
if (!checkPerByAction('crm', 'activity', 'save')) { if (!checkPerByAction('crm', 'activity', 'save')) {
return resultArray(['error' => '你没有创建跟进记录的权限!']); return resultArray(['error' => '你没有创建跟进记录的权限!']);
} }
if (empty($this->param['activity_type'])) return resultArray(['error' => '缺少模块类型!']); if (empty($this->param['activity_type'])) return resultArray(['error' => '缺少模块类型!']);
if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID']); if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID']);
if (empty($this->param['content'])) return resultArray(['error' => '请填写跟进内容!']); if (empty($this->param['content'])) return resultArray(['error' => '请填写跟进内容!']);
if (!empty($this->param['next_time']) && strtotime($this->param['next_time']) < time()) { if (!empty($this->param['next_time']) && strtotime($this->param['next_time']) < time()) {
return resultArray(['error' => '下次联系时间不能在当前时间之前!']); return resultArray(['error' => '下次联系时间不能在当前时间之前!']);
} }
$param = $this->param; $param = $this->param;
$param['user_id'] = $this->userInfo['id']; $param['user_id'] = $this->userInfo['id'];
if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']); if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/** /**
* 活动详情 * 活动详情
* *
@ -95,12 +96,12 @@ class Activity extends ApiCommon
return resultArray(['error' => '你没有查看跟进记录的权限!']); return resultArray(['error' => '你没有查看跟进记录的权限!']);
} }
if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']); if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
$data = $activityLogic->read($this->param['activity_id']); $data = $activityLogic->read($this->param['activity_id']);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 编辑活动【跟进记录】 * 编辑活动【跟进记录】
* *
@ -114,21 +115,21 @@ class Activity extends ApiCommon
if (!checkPerByAction('crm', 'activity', 'update')) { if (!checkPerByAction('crm', 'activity', 'update')) {
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 (empty($this->param['activity_type'])) return resultArray(['error' => '缺少活动类型!']); if (empty($this->param['activity_type'])) return resultArray(['error' => '缺少活动类型!']);
if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID']); if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID']);
if (empty($this->param['content'])) return resultArray(['error' => '请填写跟进内容!']); if (empty($this->param['content'])) return resultArray(['error' => '请填写跟进内容!']);
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
if (!$activityLogic->update($param)) return resultArray(['error' => '操作失败!']); if (!$activityLogic->update($param)) return resultArray(['error' => '操作失败!']);
$data = $activityLogic->getFollowData($param['activity_id'], $userId); $data = $activityLogic->getFollowData($param['activity_id'], $userId);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 删除活动【跟进记录】 * 删除活动【跟进记录】
* *
@ -137,15 +138,16 @@ 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' => '操作成功!']);
} }
/** /**
* 获取常用语 * 获取常用语
* *
@ -155,10 +157,10 @@ class Activity extends ApiCommon
public function getPhrase(ActivityLogic $activityLogic) public function getPhrase(ActivityLogic $activityLogic)
{ {
$data = $activityLogic->getPhrase(); $data = $activityLogic->getPhrase();
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 设置常用语 * 设置常用语
* *
@ -169,14 +171,14 @@ class Activity extends ApiCommon
*/ */
public function setPhrase(ActivityLogic $activityLogic) public function setPhrase(ActivityLogic $activityLogic)
{ {
if (empty($this->param['phrase'])) return resultArray(['error' => '缺少常用语数据!']); if (empty($this->param['phrase'])) return resultArray(['error' => '缺少常用语数据!']);
if (!is_array($this->param['phrase'])) return resultArray(['error' => '参数格式错误!']); if (!is_array($this->param['phrase'])) return resultArray(['error' => '参数格式错误!']);
if (!$activityLogic->setPhrase($this->param['phrase'])) return resultArray(['error' => '操作失败!']); if (!$activityLogic->setPhrase($this->param['phrase'])) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/** /**
* 跟进记录权限 * 跟进记录权限
* *
@ -185,27 +187,29 @@ class Activity extends ApiCommon
public function getRecordAuth() public function getRecordAuth()
{ {
$data = [ $data = [
'index' => checkPerByAction('crm', 'activity', 'index'), 'index' => checkPerByAction('crm', 'activity', 'index'),
'read' => checkPerByAction('crm', 'activity', 'read'), 'read' => checkPerByAction('crm', 'activity', 'read'),
'save' => checkPerByAction('crm', 'activity', 'save'), 'save' => checkPerByAction('crm', 'activity', 'save'),
'update' => checkPerByAction('crm', 'activity', 'update'), 'update' => checkPerByAction('crm', 'activity', 'update'),
'delete' => checkPerByAction('crm', 'activity', 'delete'), 'delete' => checkPerByAction('crm', 'activity', 'delete'),
]; ];
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']
'6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
'7' => ['name' => '相关商机', 'field' => 'business_ids'],
]; ];
}else{ if ($param['crmType'] == 2) {
if(empty($field_list)){ $fields = [
$field_list=array_merge($fields,$field); '6' => ['name' => '相关联系人', 'field' => 'contacts_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',
]
];
$field_list = array_merge($field_list, $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();
$indexLogic=new \app\crm\logic\IndexLogic(); $activityLogic = new ActivityLogic();
$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,44 +273,32 @@ 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();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$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');
@ -533,7 +524,14 @@ class Contacts extends ApiCommon
$contactsId = $this->param['contacts_id']; $contactsId = $this->param['contacts_id'];
$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]);
@ -482,16 +488,16 @@ class Customer extends ApiCommon
'owner_user_id' => 0, 'owner_user_id' => 0,
'into_pool_time' => time() 'into_pool_time' => time()
]); ]);
# 删除联系人的负责人 # 删除联系人的负责人
Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]); Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]);
# 将客户放入公海 # 将客户放入公海
Db::name('crm_customer_pool_relation')->insertAll($poolRelationData); Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
# 公海操作记录 # 公海操作记录
Db::name('crm_customer_pool_record')->insertAll($poolRecordData); Db::name('crm_customer_pool_record')->insertAll($poolRecordData);
# 字段操作记录 # 字段操作记录
Db::name('admin_action_record')->insertAll($fieldRecordData); Db::name('admin_action_record')->insertAll($fieldRecordData);
@ -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,213 +44,200 @@ 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'])) {
parent::_initialize(); parent::_initialize();
} }
} }
/** /**
* 公海列表 * 公海列表
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function index() public function index()
{ {
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']); if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
$data = (new CustomerPoolLogic())->getPoolList($this->param); $data = (new CustomerPoolLogic())->getPoolList($this->param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 详情 * 详情
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function read() public function read()
{ {
if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']); if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param = $this->param; $param = $this->param;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = (new CustomerPoolLogic())->getPoolData($param); $data = (new CustomerPoolLogic())->getPoolData($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 删除公海客户 * 删除公海客户
* *
* @author fanqi
* @since 2021-04-15
* @return Json * @return Json
* @since 2021-04-15
* @author fanqi
*/ */
public function delete() public function delete()
{ {
if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']); if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']);
$this->param['user_id'] = $this->userInfo['id']; $this->param['user_id'] = $this->userInfo['id'];
$result = (new CustomerPoolLogic())->deletePoolCustomer($this->param); $result = (new CustomerPoolLogic())->deletePoolCustomer($this->param);
if (!empty($result)) return resultArray(['error' => $result]); if (!empty($result)) return resultArray(['error' => $result]);
return resultArray(['data' => '删除成功!']); return resultArray(['data' => '删除成功!']);
} }
/** /**
* 公海池列表 * 公海池列表
* *
* @author fanqi
* @since 2021-04-13
* @return Json * @return Json
* @since 2021-04-13
* @author fanqi
*/ */
public function pondList() public function pondList()
{ {
$data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]); $data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 公海字段 * 公海字段
* *
* @author fanqi
* @since 2021-04-13
* @return Json * @return Json
* @since 2021-04-13
* @author fanqi
*/ */
public function field() public function field()
{ {
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']); if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param = $this->param; $param = $this->param;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = (new CustomerPoolLogic())->getFieldList($param); $data = (new CustomerPoolLogic())->getFieldList($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 高级筛选字段列表 * 高级筛选字段列表
* *
* @author fanqi
* @since 2021-04-14
* @return Json * @return Json
* @since 2021-04-14
* @author fanqi
*/ */
public function advanced() public function advanced()
{ {
if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']); if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']);
$data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param); $data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 领取公海池客户 * 领取公海池客户
* *
* @author fanqi
* @since 2021-04-15
* @return Json * @return Json
* @since 2021-04-15
* @author fanqi
*/ */
public function receive() public function receive()
{ {
if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']); if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']);
$param = $this->param; $param = $this->param;
$param['user_id'] = $this->userInfo['id']; $param['user_id'] = $this->userInfo['id'];
$result = (new CustomerPoolLogic())->receiveCustomers($param); $result = (new CustomerPoolLogic())->receiveCustomers($param);
if (!empty($result)) return resultArray(['error' => $result]); if (!empty($result)) return resultArray(['error' => $result]);
return resultArray(['data' => '领取成功!']); return resultArray(['data' => '领取成功!']);
} }
/** /**
* 分配公海客户 * 分配公海客户
* *
* @author fanqi
* @since 2021-04-15
* @return Json * @return Json
* @since 2021-04-15
* @author fanqi
*/ */
public function distribute() public function distribute()
{ {
if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']); if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']);
if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']); if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']);
$result = (new CustomerPoolLogic())->distributeCustomer($this->param); $result = (new CustomerPoolLogic())->distributeCustomer($this->param);
if (!empty($result)) return resultArray(['error' => $result]); if (!empty($result)) return resultArray(['error' => $result]);
return resultArray(['data' => '分配成功!']); return resultArray(['data' => '分配成功!']);
} }
// 公海客户导入模板下载 // 公海客户导入模板下载
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()]);
} }
// 导出 // 导出
public function export() public function export()
{ {
$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,98 +254,146 @@ 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()
{ {
$param = $this->param; $param = $this->param;
$param['user_id'] = $this->userInfo['id']; $param['user_id'] = $this->userInfo['id'];
$param['structure_id'] = $this->userInfo['structure_id']; $param['structure_id'] = $this->userInfo['structure_id'];
$data = (new CustomerPoolLogic())->getAuthorityData($param); $data = (new CustomerPoolLogic())->getAuthorityData($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 公海字段样式 * 公海字段样式
* *
* @author fanqi
* @since 2021-04-22
* @return Json * @return Json
* @since 2021-04-22
* @author fanqi
*/ */
public function fieldConfig() public function fieldConfig()
{ {
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']); if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = (new CustomerPoolLogic())->getFieldConfigIndex($param); $data = (new CustomerPoolLogic())->getFieldConfigIndex($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 设置公海字段宽度 * 设置公海字段宽度
* *
* @author fanqi
* @since 2021-04-22
* @return Json * @return Json
* @since 2021-04-22
* @author fanqi
*/ */
public function setFieldWidth() public function setFieldWidth()
{ {
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']); if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']); if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']);
if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']); if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']);
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
(new CustomerPoolLogic())->setFieldWidth($param); (new CustomerPoolLogic())->setFieldWidth($param);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/** /**
* 设置公海字段样式 * 设置公海字段样式
* *
* @author fanqi
* @since 2021-04-22
* @return Json * @return Json
* @since 2021-04-22
* @author fanqi
*/ */
public function setFieldConfig() public function setFieldConfig()
{ {
if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID']); if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID']);
if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']); if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']);
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
(new CustomerPoolLogic())->setFieldConfig($param); (new CustomerPoolLogic())->setFieldConfig($param);
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,9 +316,13 @@ 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='';
foreach ($achievement as $val){ if($achievement){
$num+=(int)$val[$this->monthName[$data_time]]; foreach ($achievement as $val){
$num+=(int)$val[$this->monthName[$data_time]];
$item['achievement']=$num; $item['achievement']=$num;
}
}else{
$item['achievement']=0;
} }
$list[] = $item; $list[] = $item;
} }
@ -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,8 +21,8 @@ use think\Request;
class Invoice extends ApiCommon class Invoice extends ApiCommon
{ {
use AutoNumberTrait; use AutoNumberTrait, FieldVerificationTrait;
/** /**
* 用于判断权限 * 用于判断权限
* @permission 无限制 * @permission 无限制
@ -32,16 +33,16 @@ class Invoice extends ApiCommon
{ {
$action = [ $action = [
'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'])) {
parent::_initialize(); parent::_initialize();
} }
} }
/** /**
* 列表 * 列表
* *
@ -53,12 +54,12 @@ 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]);
} }
/** /**
* 创建 * 创建
* *
@ -70,14 +71,14 @@ class Invoice extends ApiCommon
*/ */
public function save(InvoiceLogic $invoiceLogic) public function save(InvoiceLogic $invoiceLogic)
{ {
if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择客户!']); if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择客户!']);
if (empty($this->param['contract_id'])) return resultArray(['error' => '请选择合同!']); if (empty($this->param['contract_id'])) return resultArray(['error' => '请选择合同!']);
if (empty($this->param['invoice_money'])) return resultArray(['error' => '请填写开票金额!']); if (empty($this->param['invoice_money'])) return resultArray(['error' => '请填写开票金额!']);
if (empty($this->param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']); if (empty($this->param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']);
if (empty($this->param['title_type'])) return resultArray(['error' => '请选择抬头类型!']); if (empty($this->param['title_type'])) return resultArray(['error' => '请选择抬头类型!']);
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
# 审批是否停用 # 审批是否停用
$examineStatus = $param['examineStatus']; $examineStatus = $param['examineStatus'];
# 删除无用参数 # 删除无用参数
@ -87,11 +88,11 @@ class Invoice extends ApiCommon
unset($param['contract_number']); unset($param['contract_number']);
# 设置创建人负责人ID # 设置创建人负责人ID
$param['create_user_id'] = $userId; $param['create_user_id'] = $userId;
$param['owner_user_id'] = $userId; $param['owner_user_id'] = $userId;
# 创建更新日期 # 创建更新日期
$param['create_time'] = time(); $param['create_time'] = time();
$param['update_time'] = time(); $param['update_time'] = time();
# 自动设置发票编号 # 自动设置发票编号
$numberInfo = []; $numberInfo = [];
if (empty($param['invoice_apple_number'])) { if (empty($param['invoice_apple_number'])) {
@ -103,7 +104,7 @@ class Invoice extends ApiCommon
if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) { if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) {
return resultArray(['error' => '发票编号重复!']); return resultArray(['error' => '发票编号重复!']);
} }
if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) { if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
$examineStepModel = new \app\admin\model\ExamineStep(); $examineStepModel = new \app\admin\model\ExamineStep();
# 审核判断(是否有符合条件的审批流) # 审核判断(是否有符合条件的审批流)
@ -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' => '创建失败!']);
} }
@ -144,7 +243,7 @@ class Invoice extends ApiCommon
(new Message())->send( (new Message())->send(
Message::INVOICE_TO_DO, Message::INVOICE_TO_DO,
[ [
'title' => $param['invoice_apple_number'], 'title' => $param['invoice_apple_number'],
'action_id' => $invoice_id 'action_id' => $invoice_id
], ],
$send_user_id $send_user_id
@ -152,24 +251,30 @@ 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,
'user_id' => $vv 'user_id' => $vv
]; ];
} }
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' => '创建成功!']);
} }
/** /**
* 详情 * 详情
* *
@ -183,33 +288,33 @@ class Invoice extends ApiCommon
public function read(InvoiceLogic $invoiceLogic) public function read(InvoiceLogic $invoiceLogic)
{ {
$invoiceId = $this->param['id']; $invoiceId = $this->param['id'];
$isUpdate = !empty($this->param['is_update']) ? $this->param['is_update'] : 0; $isUpdate = !empty($this->param['is_update']) ? $this->param['is_update'] : 0;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$data = $invoiceLogic->read($invoiceId, $isUpdate); $data = $invoiceLogic->read($invoiceId, $isUpdate);
$readStatus = false; $readStatus = false;
# 角色权限 # 角色权限
$authArray = db('admin_access')->alias('access') $authArray = db('admin_access')->alias('access')
->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'left') ->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'left')
->where('access.user_id', $userInfo['id'])->column('group.rules'); ->where('access.user_id', $userInfo['id'])->column('group.rules');
# 详情权限ID # 详情权限ID
$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;
} }
if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) { if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) {
$authData['dataAuth'] = (int)0; $authData['dataAuth'] = (int)0;
return resultArray(['data' => $authData]); return resultArray(['data' => $authData]);
} }
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 编辑 * 编辑
* *
@ -222,11 +327,11 @@ class Invoice extends ApiCommon
public function update(InvoiceLogic $invoiceLogic) public function update(InvoiceLogic $invoiceLogic)
{ {
$param = $this->param; $param = $this->param;
if (empty($param['invoice_id'])) return resultArray(['error' => '缺少发票ID']); if (empty($param['invoice_id'])) return resultArray(['error' => '缺少发票ID']);
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'];
# 删除无用参数 # 删除无用参数
@ -236,17 +341,17 @@ class Invoice extends ApiCommon
unset($param['contract_number']); unset($param['contract_number']);
# 设置负责人ID # 设置负责人ID
$param['update_time'] = time(); $param['update_time'] = time();
# 已进行审批,不能编辑 # 已进行审批,不能编辑
// $dataInfo = $invoiceLogic->read($param['invoice_id'], ''); // $dataInfo = $invoiceLogic->read($param['invoice_id'], '');
// if (!$dataInfo) { // if (!$dataInfo) {
// $this->error = '数据不存在或已删除'; // $this->error = '数据不存在或已删除';
// return false; // return false;
// } // }
$checkStatus = $invoiceLogic->getExamineStatus($param['invoice_id']); $checkStatus = $invoiceLogic->getExamineStatus($param['invoice_id']);
if (!in_array($checkStatus, ['3', '4', '5', '6'])) return resultArray(['error' => '当前状态为审批中或已审批通过,不可编辑']); if (!in_array($checkStatus, ['3', '4', '5', '6'])) return resultArray(['error' => '当前状态为审批中或已审批通过,不可编辑']);
# 自动设置发票编号 # 自动设置发票编号
$numberInfo = []; $numberInfo = [];
if (empty($param['invoice_apple_number'])) { if (empty($param['invoice_apple_number'])) {
@ -254,16 +359,16 @@ class Invoice extends ApiCommon
if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']); if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']);
$param['invoice_apple_number'] = $numberInfo['number']; $param['invoice_apple_number'] = $numberInfo['number'];
} }
# 检查发票编号是否重复 # 检查发票编号是否重复
$invoiceWhere['invoice_apple_number'] = $param['invoice_apple_number']; $invoiceWhere['invoice_apple_number'] = $param['invoice_apple_number'];
$invoiceWhere['invoice_id'] = ['neq', $this->param['invoice_id']]; $invoiceWhere['invoice_id'] = ['neq', $this->param['invoice_id']];
if ($invoiceLogic->getInvoiceId($invoiceWhere)) return resultArray(['error' => '发票编号重复!']); if ($invoiceLogic->getInvoiceId($invoiceWhere)) return resultArray(['error' => '发票编号重复!']);
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,59 +388,164 @@ 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'],
'user_id' => $vv 'user_id' => $vv
]; ];
} }
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' => '编辑成功!']);
} }
/** /**
* 删除 * 删除
* *
@ -349,39 +559,39 @@ class Invoice extends ApiCommon
{ {
$actionRecordModel = new \app\admin\model\ActionRecord(); $actionRecordModel = new \app\admin\model\ActionRecord();
$fileModel = new \app\admin\model\File(); $fileModel = new \app\admin\model\File();
$idArray = $this->param['id']; $idArray = $this->param['id'];
$userinfo = $this->userInfo['id']; $userinfo = $this->userInfo['id'];
if (!is_array($idArray)) return resultArray(['error' => '发票ID类型错误']); if (!is_array($idArray)) return resultArray(['error' => '发票ID类型错误']);
$idString = implode(',', $idArray); $idString = implode(',', $idArray);
$status = true; $status = true;
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;
} }
} }
} }
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']);
} }
return resultArray(['data' => '删除成功!']); return resultArray(['data' => '删除成功!']);
} }
/** /**
* 转移(变更负责人) * 转移(变更负责人)
* *
@ -391,23 +601,23 @@ class Invoice extends ApiCommon
public function transfer(InvoiceLogic $invoiceLogic) public function transfer(InvoiceLogic $invoiceLogic)
{ {
$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' => '操作成功!']);
} }
/** /**
* 设置开票 * 设置开票
* *
@ -416,22 +626,22 @@ class Invoice extends ApiCommon
*/ */
public function setInvoice(InvoiceLogic $invoiceLogic) public function setInvoice(InvoiceLogic $invoiceLogic)
{ {
if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']); if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']);
// if (empty($this->param['invoice_number'])) return resultArray(['error' => '请填写发票号码!']); // if (empty($this->param['invoice_number'])) return resultArray(['error' => '请填写发票号码!']);
// if (empty($this->param['logistics_number'])) return resultArray(['error' => '请填写物流单号!']); // if (empty($this->param['logistics_number'])) return resultArray(['error' => '请填写物流单号!']);
// if (empty($this->param['real_invoice_date'])) return resultArray(['error' => '请选择开票日期!']); // if (empty($this->param['real_invoice_date'])) return resultArray(['error' => '请选择开票日期!']);
$this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d'); $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
# 开票状态 # 开票状态
$this->param['invoice_status'] = 1; $this->param['invoice_status'] = 1;
# 设置开票信息 # 设置开票信息
if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']); if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/** /**
* 审核 * 审核
* *
@ -443,54 +653,54 @@ class Invoice extends ApiCommon
*/ */
public function check(InvoiceLogic $invoiceLogic) public function check(InvoiceLogic $invoiceLogic)
{ {
$param = $this->param; $param = $this->param;
$user_id = $this->userInfo['id']; $user_id = $this->userInfo['id'];
$examineStepModel = new \app\admin\model\ExamineStep(); $examineStepModel = new \app\admin\model\ExamineStep();
$examineRecordModel = new \app\admin\model\ExamineRecord(); $examineRecordModel = new \app\admin\model\ExamineRecord();
$examineFlowModel = new \app\admin\model\ExamineFlow(); $examineFlowModel = new \app\admin\model\ExamineFlow();
$invoiceData = []; $invoiceData = [];
$invoiceData['invoice_id'] = $param['id']; $invoiceData['invoice_id'] = $param['id'];
$invoiceData['update_time'] = time(); $invoiceData['update_time'] = time();
$invoiceData['check_status'] = 1; $invoiceData['check_status'] = 1;
# 权限判断 # 权限判断
if (!$examineStepModel->checkExamine($user_id, 'crm_invoice', $param['id'])) { if (!$examineStepModel->checkExamine($user_id, 'crm_invoice', $param['id'])) {
return resultArray(['error' => $examineStepModel->getError()]); return resultArray(['error' => $examineStepModel->getError()]);
} }
# 审批主体详情 # 审批主体详情
$dataInfo = $invoiceLogic->getExamineInfo($param['id']); $dataInfo = $invoiceLogic->getExamineInfo($param['id']);
$flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']); $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
# 1审批结束 # 1审批结束
$is_end = 0; $is_end = 0;
# 1通过0驳回 # 1通过0驳回
$status = !empty($param['status']) && $param['status'] == 1 ? 1 : 0; $status = !empty($param['status']) && $param['status'] == 1 ? 1 : 0;
# 审批记录 # 审批记录
$checkData = []; $checkData = [];
$checkData['check_user_id'] = $user_id; $checkData['check_user_id'] = $user_id;
$checkData['types'] = 'crm_invoice'; $checkData['types'] = 'crm_invoice';
$checkData['types_id'] = $param['id']; $checkData['types_id'] = $param['id'];
$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) {
if ($flowInfo['config'] == 1) { if ($flowInfo['config'] == 1) {
# 固定流程 # 固定流程
# 获取下一审批信息 # 获取下一审批信息
$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;
# 审批结束 # 审批结束
$checkData['check_status'] = !empty($status) ? 2 : 3; $checkData['check_status'] = !empty($status) ? 2 : 3;
$invoiceData['check_user_id'] = ''; $invoiceData['check_user_id'] = '';
} else { } else {
# 修改主体相关审批信息 # 修改主体相关审批信息
@ -498,17 +708,17 @@ 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' => '请选择下一审批人']);
} }
$invoiceData['check_user_id'] = arrayToString($param['check_user_id']); $invoiceData['check_user_id'] = arrayToString($param['check_user_id']);
} }
if ($is_end == 1) { if ($is_end == 1) {
$checkData['check_status'] = !empty($status) ? 2 : 3; $checkData['check_status'] = !empty($status) ? 2 : 3;
$invoiceData['check_user_id'] = ''; $invoiceData['check_user_id'] = '';
$invoiceData['check_status'] = 2; $invoiceData['check_status'] = 2;
} }
} else { } else {
# 审批驳回 # 审批驳回
@ -516,19 +726,19 @@ 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) {
# 审批记录 # 审批记录
$examineRecordModel->createData($checkData); $examineRecordModel->createData($checkData);
# 发送站内信 # 发送站内信
if ($is_end == 1 && !empty($status)) { if ($is_end == 1 && !empty($status)) {
# 审批流程结束,将审批通过消息告知负责人 # 审批流程结束,将审批通过消息告知负责人
(new Message())->send( (new Message())->send(
Message::INVOICE_PASS, Message::INVOICE_PASS,
[ [
'title' => $dataInfo['invoice_apple_number'], 'title' => $dataInfo['invoice_apple_number'],
'action_id' => $param['id'] 'action_id' => $param['id']
], ],
stringToArray($dataInfo['owner_user_id']) stringToArray($dataInfo['owner_user_id'])
@ -540,7 +750,7 @@ class Invoice extends ApiCommon
Message::INVOICE_TO_DO, Message::INVOICE_TO_DO,
[ [
'from_user' => User::where(['id' => $dataInfo['owner_user_id']])->value('realname'), 'from_user' => User::where(['id' => $dataInfo['owner_user_id']])->value('realname'),
'title' => $dataInfo['invoice_apple_number'], 'title' => $dataInfo['invoice_apple_number'],
'action_id' => $param['id'] 'action_id' => $param['id']
], ],
stringToArray($invoiceData['check_user_id']) stringToArray($invoiceData['check_user_id'])
@ -550,20 +760,20 @@ class Invoice extends ApiCommon
(new Message())->send( (new Message())->send(
Message::INVOICE_REJECT, Message::INVOICE_REJECT,
[ [
'title' => $dataInfo['invoice_apple_number'], 'title' => $dataInfo['invoice_apple_number'],
'action_id' => $param['id'] 'action_id' => $param['id']
], ],
stringToArray($dataInfo['owner_user_id']) stringToArray($dataInfo['owner_user_id'])
); );
} }
} }
return resultArray(['data' => '审批成功']); return resultArray(['data' => '审批成功']);
} else { } else {
return resultArray(['error' => '审批失败,请重试!']); return resultArray(['error' => '审批失败,请重试!']);
} }
} }
/** /**
* 撤销审核 * 撤销审核
* *
@ -576,15 +786,15 @@ class Invoice extends ApiCommon
public function revokeCheck(InvoiceLogic $invoiceLogic) public function revokeCheck(InvoiceLogic $invoiceLogic)
{ {
$invoiceId = $this->param['id']; $invoiceId = $this->param['id'];
$content = $this->param['content']; $content = $this->param['content'];
$realname = $this->userInfo['realname']; $realname = $this->userInfo['realname'];
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$user_id = $userInfo['id']; $user_id = $userInfo['id'];
if (empty($invoiceId)) return resultArray(['error' => '请选择要撤回审核的发票!']); if (empty($invoiceId)) return resultArray(['error' => '请选择要撤回审核的发票!']);
$examineInfo = $invoiceLogic->getExamineInfo($invoiceId); $examineInfo = $invoiceLogic->getExamineInfo($invoiceId);
if ($examineInfo['check_status'] == 2) { if ($examineInfo['check_status'] == 2) {
return resultArray(['error' => '已审批结束,不能撤销']); return resultArray(['error' => '已审批结束,不能撤销']);
} }
@ -596,18 +806,18 @@ class Invoice extends ApiCommon
if ($examineInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) { if ($examineInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
return resultArray(['error' => '没有权限']); return resultArray(['error' => '没有权限']);
} }
# 修改发票审核状态 # 修改发票审核状态
if (!$invoiceLogic->update(['invoice_id' => $invoiceId, 'check_status' => 4, 'check_user_id' => '', 'flow_user_id' => ''])) { if (!$invoiceLogic->update(['invoice_id' => $invoiceId, 'check_status' => 4, 'check_user_id' => '', 'flow_user_id' => ''])) {
return resultArray(['error' => '操作失败!']); return resultArray(['error' => '操作失败!']);
} }
# 添加撤销审核的记录 # 添加撤销审核的记录
$invoiceLogic->createExamineRecord($invoiceId, $examineInfo, $realname, $content, $user_id); $invoiceLogic->createExamineRecord($invoiceId, $examineInfo, $realname, $content, $user_id);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/** /**
* table栏数量统计 * table栏数量统计
* *
@ -617,13 +827,13 @@ class Invoice extends ApiCommon
public function count() public function count()
{ {
if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']); if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']);
# 附件 # 附件
$fileCount = Db::name('crm_invoice_file')->alias('invoice')->join('__ADMIN_FILE__ file', 'file.file_id = invoice.file_id', 'LEFT')->where('invoice_id', $this->param['invoice_id'])->count(); $fileCount = Db::name('crm_invoice_file')->alias('invoice')->join('__ADMIN_FILE__ file', 'file.file_id = invoice.file_id', 'LEFT')->where('invoice_id', $this->param['invoice_id'])->count();
return resultArray(['data' => ['fileCount' => $fileCount]]); return resultArray(['data' => ['fileCount' => $fileCount]]);
} }
/** /**
* 重置开票信息 * 重置开票信息
* *
@ -635,13 +845,86 @@ class Invoice extends ApiCommon
if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']); if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']);
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d'); $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
# 开票状态 # 开票状态
$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;
@ -16,12 +18,12 @@ use think\Request;
class Message extends ApiCommon class Message extends ApiCommon
{ {
/** /**
* 用于判断权限 * 用于判断权限
* @permission 无限制 * @permission 无限制
* @allow 登录用户可访问 * @allow 登录用户可访问
* @other 其他根据系统设置 * @other 其他根据系统设置
**/ **/
public function _initialize() public function _initialize()
{ {
$action = [ $action = [
@ -45,29 +47,29 @@ class Message extends ApiCommon
]; ];
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'])) {
parent::_initialize(); parent::_initialize();
} }
} }
/** /**
* 系统通知 * 系统通知
* *
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function index() public function index()
{ {
$messageModel = model('Message'); $messageModel = model('Message');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$param['module_name'] = 'crm'; $param['module_name'] = 'crm';
$data = $messageModel->getDataList($param); $data = $messageModel->getDataList($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 消息数 * 消息数
* *
@ -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);
} }
@ -220,10 +223,10 @@ class Message extends ApiCommon
cache('remindCustomerTime'.$userInfo['id'], time() + 180); cache('remindCustomerTime'.$userInfo['id'], time() + 180);
} }
} }
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 今日需联系线索 * 今日需联系线索
* *
@ -232,46 +235,21 @@ class Message extends ApiCommon
*/ */
public function todayLeads($getCount = false) public function todayLeads($getCount = false)
{ {
$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;
$leadsModel = new \app\crm\model\Leads();
# 负责人
$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 = $leadsModel->getDataList($param); if ($getCount == true) $param['getCount'] = 1;
$messageLogic= new MessageLogic();
$data = $messageLogic->todayLeads($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
return $data; return $data;
} }
/** /**
* 今日需联系客户 * 今日需联系客户
* *
@ -281,42 +259,21 @@ 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]);
} }
return $data; return $data;
} }
/** /**
* 今日需联系商机 * 今日需联系商机
* *
@ -331,121 +288,61 @@ 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]);
return $data; return $data;
} }
/** /**
* 分配给我的线索 * 分配给我的线索
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function followLeads($getCount = false) public function followLeads($getCount = false)
{ {
$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]);
} }
return $data; return $data;
} }
/** /**
* 分配给我的客户 * 分配给我的客户
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function followCustomer($getCount = false) public function followCustomer($getCount = false)
{ {
$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['type']);
unset($param['isSub']);
$customerModel = model('Customer');
$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); unset($param['types']);
$messageLogic=new MessageLogic();
$param['user_id'] = $userInfo['id'];
$data = $messageLogic->followCustomer($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
return $data; return $data;
} }
/** /**
* 待审核合同 * 待审核合同
* *
@ -457,77 +354,40 @@ 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]);
} }
return $data; return $data;
} }
/** /**
* 待审核回款 * 待审核回款
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function checkReceivables($getCount = false) public function checkReceivables($getCount = false)
{ {
$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]);
} }
return $data; return $data;
} }
/** /**
* 待审核发票 * 待审核发票
* *
@ -540,43 +400,22 @@ 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]);
return $data; return $data;
} }
/** /**
* 待回款提醒 * 待回款提醒
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function remindReceivablesPlan($getCount = false) public function remindReceivablesPlan($getCount = false)
{ {
@ -586,22 +425,22 @@ class Message extends ApiCommon
$type = $param['type'] ? : 1; $type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : ''; $isSub = $param['isSub'] ? : '';
unset($param['types']); unset($param['types']);
unset($param['type']); unset($param['type']);
unset($param['isSub']); unset($param['isSub']);
$receivablesPlanModel = model('ReceivablesPlan'); $receivablesPlanModel = model('ReceivablesPlan');
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$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);
@ -621,11 +460,11 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 即将到期合同 * 即将到期合同
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function endContract($getCount = false) public function endContract($getCount = false)
{ {
@ -636,17 +475,18 @@ class Message extends ApiCommon
$isSub = $param['isSub'] ? : ''; $isSub = $param['isSub'] ? : '';
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
unset($param['types']); unset($param['types']);
unset($param['type']); unset($param['type']);
unset($param['isSub']); unset($param['isSub']);
$contractModel = model('Contract'); $contractModel = model('Contract');
$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));
} }
switch ($type) { switch ($type) {
case '1' : case '1' :
$param['end_time'] = array('between',array(date('Y-m-d',time()),date('Y-m-d',time()+86400*$expireDay))); $param['end_time'] = array('between',array(date('Y-m-d',time()),date('Y-m-d',time()+86400*$expireDay)));
@ -659,17 +499,17 @@ class Message extends ApiCommon
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
return $data; return $data;
} }
/** /**
* 待进入客户池 * 待进入客户池
* @author Michael_xu * @author Michael_xu
* @return * @return
*/ */
public function remindCustomer($getCount = false) public function remindCustomer($getCount = false)
{ {
$customerModel = model('Customer'); $customerModel = model('Customer');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
@ -680,10 +520,10 @@ class Message extends ApiCommon
unset($param['isSub']); unset($param['isSub']);
unset($param['deal_status']); unset($param['deal_status']);
unset($param['owner_user_id']); unset($param['owner_user_id']);
# 负责人 # 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id']; $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
# 是否提醒 # 是否提醒
$data = []; $data = [];
$remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count(); $remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
@ -703,7 +543,7 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 待回访合同 * 待回访合同
* *
@ -722,23 +562,23 @@ class Message extends ApiCommon
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
unset($param['isSub']); unset($param['isSub']);
unset($param['types']); unset($param['types']);
$param['is_visit'] = 0; # 未回访 $param['is_visit'] = 0; # 未回访
$param['check_status'] = 2; # 审核通过 $param['check_status'] = 2; # 审核通过
$contractModel = new \app\crm\model\Contract(); $contractModel = new \app\crm\model\Contract();
# 负责人 # 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId;
$param['user_id'] = $userId; $param['user_id'] = $userId;
$data = $contractModel->getDataList($param); $data = $contractModel->getDataList($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
return $data; return $data;
} }
/** /**
* 全部标记已处理 * 全部标记已处理
* *
@ -752,12 +592,12 @@ class Message extends ApiCommon
$typeId = !empty($this->param['type_id']) ? $this->param['type_id'] : ''; $typeId = !empty($this->param['type_id']) ? $this->param['type_id'] : '';
$isSub = !empty($this->param['isSub']) ? $this->param['isSub'] : 0; $isSub = !empty($this->param['isSub']) ? $this->param['isSub'] : 0;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
if (empty($type)) return resultArray(['error' => '缺少模块类型参数']); if (empty($type)) return resultArray(['error' => '缺少模块类型参数']);
# 获得今日开始和结束时间戳 # 获得今日开始和结束时间戳
$todayTime = getTimeByType('today'); $todayTime = getTimeByType('today');
# 处理今日需联系线索、客户、商机 # 处理今日需联系线索、客户、商机
if (in_array($type, ['todayLeads', 'todayCustomer', 'todayBusiness'])) { if (in_array($type, ['todayLeads', 'todayCustomer', 'todayBusiness'])) {
# 负责人 # 负责人
@ -766,7 +606,7 @@ class Message extends ApiCommon
$where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]]; $where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
# 是否已处理(联系) # 是否已处理(联系)
$where['is_dealt'] = 0; $where['is_dealt'] = 0;
# 线索 # 线索
if ($type == 'todayLeads') { if ($type == 'todayLeads') {
$leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id'); $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
@ -794,13 +634,13 @@ class Message extends ApiCommon
]); ]);
} }
} }
# 处理分配给我的线索、客户 # 处理分配给我的线索、客户
if (in_array($type, ['followLeads', 'followCustomer'])) { if (in_array($type, ['followLeads', 'followCustomer'])) {
$where['owner_user_id'] = $userId; $where['owner_user_id'] = $userId;
$where['follow'] = [['neq','已跟进'], null, 'or']; $where['follow'] = [['neq','已跟进'], null, 'or'];
$where['is_allocation'] = 1; $where['is_allocation'] = 1;
# 线索 # 线索
if ($type == 'followLeads') { if ($type == 'followLeads') {
$leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id'); $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
@ -812,12 +652,12 @@ class Message extends ApiCommon
Db::name('crm_customer')->whereIn('customer_id', $customerId)->update(['follow' => '已跟进']); Db::name('crm_customer')->whereIn('customer_id', $customerId)->update(['follow' => '已跟进']);
} }
} }
# 处理待审核合同、回款、发票 # 处理待审核合同、回款、发票
if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) { if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) {
$where['check_status'] = ['lt','2']; $where['check_status'] = ['lt','2'];
$where['check_user_id'] = ['like',',%' . $userId . '%,']; $where['check_user_id'] = ['like',',%' . $userId . '%,'];
# 合同 # 合同
if ($type == 'checkContract') { if ($type == 'checkContract') {
$contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id'); $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
@ -833,33 +673,33 @@ class Message extends ApiCommon
$invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id'); $invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id');
db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete(); db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete();
} }
} }
# 处理到期合同 # 处理到期合同
if ($type == 'endContract') { if ($type == 'endContract') {
$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';
$where['owner_user_id'] = $userId; $where['owner_user_id'] = $userId;
$where['end_time'] = ['between', [date('Y-m-d',time()), date('Y-m-d',time()+86400*$expireDay)]]; $where['end_time'] = ['between', [date('Y-m-d',time()), date('Y-m-d',time()+86400*$expireDay)]];
$where['expire_remind'] = 1; $where['expire_remind'] = 1;
$contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id'); $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['expire_remind' => 0]); Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['expire_remind' => 0]);
} }
# 处理待回访合同 # 处理待回访合同
if ($type == 'returnVisitRemind') { if ($type == 'returnVisitRemind') {
$where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; # 负责人 $where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; # 负责人
$where['is_visit'] = 0; # 未回访 $where['is_visit'] = 0; # 未回访
$where['check_status'] = 2; # 审核通过 $where['check_status'] = 2; # 审核通过
$contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id'); $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['is_visit' => 1]); Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['is_visit' => 1]);
} }
# 处理待进入公海 # 处理待进入公海
if ($type == 'putInPoolRemind') { if ($type == 'putInPoolRemind') {
if (!empty($typeId)) { if (!empty($typeId)) {
@ -883,7 +723,7 @@ class Message extends ApiCommon
} }
} }
} }
# 带回款提醒 # 带回款提醒
if ($type == 'remindReceivablesPlan') { if ($type == 'remindReceivablesPlan') {
$planId = []; $planId = [];
@ -906,8 +746,32 @@ 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,43 +187,31 @@ 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();
// 导出的字段列表 // 导出的字段列表
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
$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);
# 删除附件 # 删除附件
@ -642,10 +644,18 @@ class Receivables extends ApiCommon
public function count() public function count()
{ {
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'=>'参数错误']);

@ -38,7 +38,7 @@ class Setting extends ApiCommon
parent::_initialize(); parent::_initialize();
} }
} }
/** /**
* 客户相关配置 * 客户相关配置
* *
@ -63,7 +63,7 @@ class Setting extends ApiCommon
return resultArray(['error' => $configModel->getError()]); return resultArray(['error' => $configModel->getError()]);
} }
} }
/** /**
* 客户相关配置(详情) * 客户相关配置(详情)
* *
@ -75,7 +75,7 @@ class Setting extends ApiCommon
$data = $configModel->getData(); $data = $configModel->getData();
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 相关团队列表 * 相关团队列表
* *
@ -107,15 +107,18 @@ 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'])) : []; //只读权限
$rw_user_ids = $resData['rw_user_id'] ? array_filter(explode(',', $resData['rw_user_id'])) : []; //读写权限 $rw_user_ids = $resData['rw_user_id'] ? array_filter(explode(',', $resData['rw_user_id'])) : []; //读写权限
$ro_user_arr = []; $ro_user_arr = [];
$rw_user_arr = []; $rw_user_arr = [];
$owner_user_arr = ['1' => ['user_id' => $resData['owner_user_id'], 'type' => 0, 'group_name' => '负责人', 'authority' => '负责人权限']]; //负责人 $owner_user_arr = ['1' => ['user_id' => $resData['owner_user_id'], 'type' => 0, 'group_name' => '负责人', 'authority' => '负责人权限']]; //负责人
//转换为二维数组 //转换为二维数组
foreach ($ro_user_ids as $k => $v) { foreach ($ro_user_ids as $k => $v) {
$ro_user_arr[$k]['user_id'] = $v; $ro_user_arr[$k]['user_id'] = $v;
@ -123,16 +126,17 @@ class Setting extends ApiCommon
$ro_user_arr[$k]['group_name'] = '普通成员'; $ro_user_arr[$k]['group_name'] = '普通成员';
$ro_user_arr[$k]['authority'] = '只读'; $ro_user_arr[$k]['authority'] = '只读';
} }
foreach ($rw_user_ids as $k => $v) { foreach ($rw_user_ids as $k => $v) {
$rw_user_arr[$k]['user_id'] = $v; $rw_user_arr[$k]['user_id'] = $v;
$rw_user_arr[$k]['type'] = 2; $rw_user_arr[$k]['type'] = 2;
$rw_user_arr[$k]['group_name'] = '普通成员'; $rw_user_arr[$k]['group_name'] = '普通成员';
$rw_user_arr[$k]['authority'] = '读写'; $rw_user_arr[$k]['authority'] = '读写';
} }
$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,12 +144,13 @@ 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;
} }
} }
return resultArray(['data' => $new_user_list]); return resultArray(['data' => $new_user_list]);
} }
/** /**
* 退出团队 * 退出团队
* *
@ -162,21 +167,21 @@ class Setting extends ApiCommon
if (!in_array($this->param['types'], ['crm_customer', 'crm_contacts', 'crm_business', 'crm_contract'])) { if (!in_array($this->param['types'], ['crm_customer', 'crm_contacts', 'crm_business', 'crm_contract'])) {
return resultArray(['error' => '参数错误']); return resultArray(['error' => '参数错误']);
} }
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$primaryKey = ['crm_customer' => 'customer_id', 'crm_contacts' => 'contacts_id', 'crm_business' => 'business_id', 'crm_contract' => 'contract_id']; $primaryKey = ['crm_customer' => 'customer_id', 'crm_contacts' => 'contacts_id', 'crm_business' => 'business_id', 'crm_contract' => 'contract_id'];
$data = Db::name($this->param['types'])->field([$primaryKey[$this->param['types']], 'ro_user_id', 'rw_user_id', 'owner_user_id,name']) $data = Db::name($this->param['types'])->field([$primaryKey[$this->param['types']], 'ro_user_id', 'rw_user_id', 'owner_user_id,name'])
->where($primaryKey[$this->param['types']], $this->param['types_id'])->find(); ->where($primaryKey[$this->param['types']], $this->param['types_id'])->find();
if ($data['owner_user_id'] == $userId) return resultArray(['error' => '负责人不能退出团队!']); if ($data['owner_user_id'] == $userId) return resultArray(['error' => '负责人不能退出团队!']);
$data[$primaryKey[$this->param['types']]] = $this->param['types_id']; $data[$primaryKey[$this->param['types']]] = $this->param['types_id'];
$data['ro_user_id'] = str_replace(',' . $userId, '', $data['ro_user_id']); $data['ro_user_id'] = str_replace(',' . $userId, '', $data['ro_user_id']);
$data['rw_user_id'] = str_replace(',' . $userId, '', $data['rw_user_id']); $data['rw_user_id'] = str_replace(',' . $userId, '', $data['rw_user_id']);
if (!Db::name($this->param['types'])->update($data)) { if (!Db::name($this->param['types'])->update($data)) {
return resultArray(['error' => '操作失败!']); return resultArray(['error' => '操作失败!']);
} }
@ -191,7 +196,7 @@ class Setting extends ApiCommon
case 'crm_contract': case 'crm_contract':
$type = Message::CONTRACT_END; $type = Message::CONTRACT_END;
break; break;
} }
//站内信 //站内信
$send_user_id = stringToArray($userId); $send_user_id = stringToArray($userId);
@ -207,7 +212,7 @@ class Setting extends ApiCommon
} }
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
/** /**
* 相关团队创建 * 相关团队创建
* *
@ -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) {
@ -334,7 +389,7 @@ class Setting extends ApiCommon
return resultArray(['data' => '保存成功']); return resultArray(['data' => '保存成功']);
} }
} }
/** /**
* 合同到期提醒天数 * 合同到期提醒天数
* *
@ -350,17 +405,17 @@ 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' => '设置失败,请重试!']);
@ -407,7 +462,7 @@ class Setting extends ApiCommon
return resultArray(['data' => $record_type]); return resultArray(['data' => $record_type]);
} }
} }
/** /**
* 跟进记录 记录方式展示 * 跟进记录 记录方式展示
* *
@ -426,7 +481,7 @@ class Setting extends ApiCommon
return resultArray(['data' => array()]); return resultArray(['data' => array()]);
} }
} }
/** /**
* 拥有、锁定客户数限制列表 * 拥有、锁定客户数限制列表
* *
@ -444,7 +499,7 @@ class Setting extends ApiCommon
$data = $customerConfigModel->getDataList($param); $data = $customerConfigModel->getDataList($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 拥有、锁定客户数限制 创建/编辑 todo 创建和编辑走一个接口,前端非要这么搞 * 拥有、锁定客户数限制 创建/编辑 todo 创建和编辑走一个接口,前端非要这么搞
* *
@ -460,15 +515,16 @@ 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()]);
} }
return resultArray(['data' => empty($param['id']) ? '创建成功!' : '编辑成功!']); return resultArray(['data' => empty($param['id']) ? '创建成功!' : '编辑成功!']);
} }
/** /**
* 拥有、锁定客户数限制 编辑 todo 编辑不走这个接口,前端非要走创建接口 * 拥有、锁定客户数限制 编辑 todo 编辑不走这个接口,前端非要走创建接口
* *
@ -481,7 +537,7 @@ 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' => '无权操作']));
} }
$param = $this->param; $param = $this->param;
$customerConfigModel = new \app\crm\model\CustomerConfig(); $customerConfigModel = new \app\crm\model\CustomerConfig();
$res = $customerConfigModel->updateDataById($param, $param['id']); $res = $customerConfigModel->updateDataById($param, $param['id']);
@ -490,7 +546,7 @@ class Setting extends ApiCommon
} }
return resultArray(['data' => '编辑成功']); return resultArray(['data' => '编辑成功']);
} }
/** /**
* 拥有、锁定客户数限制 删除 * 拥有、锁定客户数限制 删除
* *
@ -511,7 +567,7 @@ class Setting extends ApiCommon
} }
return resultArray(['data' => '删除成功']); return resultArray(['data' => '删除成功']);
} }
/** /**
* 编号列表 * 编号列表
* *
@ -527,7 +583,7 @@ class Setting extends ApiCommon
$data = $numberSequenceModel->getDataList($param); $data = $numberSequenceModel->getDataList($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 编号修改 * 编号修改
* *
@ -548,7 +604,7 @@ class Setting extends ApiCommon
} }
return resultArray(['data' => '编辑成功']); return resultArray(['data' => '编辑成功']);
} }
/** /**
* 编号删除 * 编号删除
* *
@ -569,7 +625,7 @@ class Setting extends ApiCommon
} }
return resultArray(['data' => '删除成功']); return resultArray(['data' => '删除成功']);
} }
/** /**
* 设置回访提醒 * 设置回访提醒
* *
@ -580,12 +636,12 @@ class Setting extends ApiCommon
public function setVisitDay() public function setVisitDay()
{ {
$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(); $settingModel = new \app\crm\model\Setting();
if ($settingModel->setNumber($this->param, $userInfo['id']) === false) return resultArray(['error' => '操作失败!']);
if ($settingModel->setNumber($this->param) === false) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']); 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();
$data=$settingModel->appMenuConfig($param);
return resultArray(['data' => $data]);
}
/**
* 手机端办公数量
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 13:44
*/
public function oaNumber(){
$userInfo=$this->userInfo;
# 日志
$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['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ','; if(empty($param['excel'])){
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;
} }

@ -38,11 +38,11 @@ class CustomerPoolLogic extends Common
$poolId = $param['pool_id']; $poolId = $param['pool_id'];
$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'];
@ -52,38 +52,39 @@ class CustomerPoolLogic extends Common
->whereOr('customer.telephone',array('like','%'.$search.'%')); ->whereOr('customer.telephone',array('like','%'.$search.'%'));
}; };
} }
# 处理排序参数 // 处理排序参数
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()
]; ];
@ -537,22 +573,22 @@ class CustomerPoolLogic extends Common
try { try {
# 领取客户 # 领取客户
Db::name('crm_customer')->whereIn('customer_id', $addCustomerId)->update($addCustomerData); Db::name('crm_customer')->whereIn('customer_id', $addCustomerId)->update($addCustomerData);
# 设置客户的联系人数据 # 设置客户的联系人数据
Db::name('crm_contacts')->whereIn('customer_id', $addCustomerId)->update(['owner_user_id' => $userId]); Db::name('crm_contacts')->whereIn('customer_id', $addCustomerId)->update(['owner_user_id' => $userId]);
# 删除公海与客户关联数据 # 删除公海与客户关联数据
Db::name('crm_customer_pool_relation')->whereIn('customer_id', $addCustomerId)->delete(); Db::name('crm_customer_pool_relation')->whereIn('customer_id', $addCustomerId)->delete();
# 字段操作日志 # 字段操作日志
Db::name('admin_action_record')->insertAll($addActionRecordData); Db::name('admin_action_record')->insertAll($addActionRecordData);
# 数据操作日志 # 数据操作日志
Db::name('admin_operation_log')->insertAll($addOperationLogData); Db::name('admin_operation_log')->insertAll($addOperationLogData);
# 记录领取的客户 # 记录领取的客户
Db::name('crm_customer_pool_record')->insertAll($addReceiveData); Db::name('crm_customer_pool_record')->insertAll($addReceiveData);
Db::commit(); Db::commit();
} catch (\Exception $e) { } catch (\Exception $e) {
Db::rollback(); Db::rollback();
@ -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,17 +37,16 @@ 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; //上期对比
$contactsNum = 0; //新增联系人 $contactsNum = 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,7 +857,8 @@ 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) {
$activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find(); $activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
@ -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,7 +16,8 @@ use think\Db;
class InvoiceLogic class InvoiceLogic
{ {
private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据']; private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据'];
private $check_status = ['待审核', '审核中', '审核通过', '审核未通过', '撤回'];
/** /**
* 列表 * 列表
* *
@ -25,103 +26,209 @@ 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']);
unset($param['order_field']);
unset($param['order_type']);
unset($param['is_excel']);
unset($param['scene_id']);
unset($param['isMessage']);
$request = $common->fmtRequest($param);
$where = []; $where = [];
# 高级搜索
$requestMap = !empty($request['map']) ? $request['map'] : [];
unset($requestMap['search']);
# 场景
$sceneMap = [];
$sceneModel = new \app\admin\model\Scene();
if ($scene_id) {
//自定义场景
$sceneMap = $sceneModel->getDataById($scene_id, $userId, 'invoice') ?: [];
} else {
//默认场景
$sceneMap = $sceneModel->getDefaultData('crm_invoice', $userId) ?: [];
}
//普通筛选
if ($search) { if ($search) {
# 处理基本参数 # 处理基本参数
$searchWhere = function ($query) use ($search) {
$scene_id = $param['scene_id']; $query->where(function ($query) use ($search) {
unset($param['scene_id']); $query->whereLike('customer.name', '%' . $search . '%');
})->whereOr(function ($query) use ($search) {
$common = new Common(); $query->whereLike('contract.num', '%' . $search . '%');
})->whereOr(function ($query) use ($search) {
# 高级搜索 $query->whereLike('invoice.invoice_apple_number', '%' . $search . '%');
$request = $common->fmtRequest($param); });
$requestMap = !empty($request['map']) ? $request['map'] : []; };
unset($requestMap['search']); }
# 合并高级搜索和场景的查询条件
# 场景 $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
$sceneMap = []; $map = where_arr($map, 'crm', 'invoice', 'index');
if (!empty($scene_id) && $scene_id == 1) { # 替换掉字段前缀,不修改公共函数
# 我负责的 foreach ($map as $key => $value) {
$sceneMap['owner_user_id'] = $userId; $k = str_replace('invoice.', '', $key);
}
if (!empty($scene_id) && $scene_id == 2) { $where[$k] = $value;
# 我下属负责的
$subordinate = getSubUserId(false, 0, $userId);
$sceneMap['owner_user_id'] = !empty($subordinate) ? ['in', $subordinate] : 0;
}
# 合并高级搜索和场景的查询条件
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
$map = where_arr($map, 'crm', 'invoice', 'index');
# 替换掉字段前缀,不修改公共函数
foreach ($map AS $key => $value) {
$k = str_replace('invoice.', '', $key);
$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 = [];
$userModel = new \app\admin\model\User();
$a = 'index';
if ($is_excel) $a = 'excelExport';
$auth_user_ids = $userModel->getUserByPer('crm', 'invoice', $a);
if (empty($dealt)) { if (empty($dealt)) {
$userModel = new \app\admin\model\User(); //过滤权限
$authUserIds = $userModel->getUserByPer('crm', 'invoice', 'index'); if (isset($map['invoice.owner_user_id']) && $map['invoice.owner_user_id'][0] != 'like') {
$auth['owner_user_id'] = ['in', $authUserIds]; 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;
} }
/** /**
* 创建 * 创建
* *
@ -132,7 +239,7 @@ class InvoiceLogic
{ {
return db('crm_invoice')->insert($param, false, true); return db('crm_invoice')->insert($param, false, true);
} }
/** /**
* 详情 * 详情
* *
@ -146,71 +253,71 @@ class InvoiceLogic
public function read($invoiceId, $isUpdate) public function read($invoiceId, $isUpdate)
{ {
$apiCommon = new ApiCommon(); $apiCommon = new ApiCommon();
$userId = $apiCommon->userInfo['id']; $userId = $apiCommon->userInfo['id'];
$result = []; $result = [];
$dataObject = Invoice::with(['toCustomer', 'toContract'])->where('invoice_id', $invoiceId)->find(); $dataObject = Invoice::with(['toCustomer', 'toContract'])->where('invoice_id', $invoiceId)->find();
if (empty($dataObject)) return $result; if (empty($dataObject)) return $result;
$dataArray = $dataObject->toArray(); $dataArray = $dataObject->toArray();
if (!empty($isUpdate)) return $dataArray; if (!empty($isUpdate)) return $dataArray;
# 主键ID # 主键ID
$result['invoice_id'] = $dataArray['invoice_id']; $result['invoice_id'] = $dataArray['invoice_id'];
# 是否显示撤回按钮 # 是否显示撤回按钮
$result['isShowRecall'] = 0; $result['isShowRecall'] = 0;
if ($userId == $dataArray['owner_user_id'] && $dataArray['check_status'] == 0) $result['isShowRecall'] = 1; if ($userId == $dataArray['owner_user_id'] && $dataArray['check_status'] == 0) $result['isShowRecall'] = 1;
$result['customer_name'] = $dataArray['customer_name']; # 客户名称 $result['customer_name'] = $dataArray['customer_name']; # 客户名称
$result['invoice_money'] = $dataArray['invoice_money']; # 开票金额 $result['invoice_money'] = $dataArray['invoice_money']; # 开票金额
$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'],
'invoice_type' => $dataArray['invoice_type'], 'invoice_type' => $dataArray['invoice_type'],
'remark' => $dataArray['remark'], 'remark' => $dataArray['remark'],
'create_user_name' => db('admin_user')->where('id', $dataArray['create_user_id'])->value('realname'), 'create_user_name' => db('admin_user')->where('id', $dataArray['create_user_id'])->value('realname'),
'owner_user_name' => db('admin_user')->where('id', $dataArray['owner_user_id'])->value('realname'), 'owner_user_name' => db('admin_user')->where('id', $dataArray['owner_user_id'])->value('realname'),
'create_time' => $dataArray['create_time'], 'create_time' => $dataArray['create_time'],
'update_time' => $dataArray['update_time'], 'update_time' => $dataArray['update_time'],
'invoice_number' => $dataArray['invoice_number'], 'invoice_number' => $dataArray['invoice_number'],
'real_invoice_date' => $dataArray['real_invoice_date'], 'real_invoice_date' => $dataArray['real_invoice_date'],
'customer_id' => $dataArray['customer_id'], 'customer_id' => $dataArray['customer_id'],
'check_status' => $check[$dataArray['check_status']] 'check_status' => $check[$dataArray['check_status']]
]; ];
# 发票信息 # 发票信息
$result['invoice'] = [ $result['invoice'] = [
'title_type' => $dataArray['title_type'], 'title_type' => $dataArray['title_type'],
'deposit_bank' => $dataArray['deposit_bank'], 'deposit_bank' => $dataArray['deposit_bank'],
'invoice_title' => $dataArray['invoice_title'], 'invoice_title' => $dataArray['invoice_title'],
'tax_number' => $dataArray['tax_number'], 'tax_number' => $dataArray['tax_number'],
'deposit_account' => $dataArray['deposit_account'], 'deposit_account' => $dataArray['deposit_account'],
'deposit_address' => $dataArray['deposit_address'], 'deposit_address' => $dataArray['deposit_address'],
'phone' => $dataArray['phone'] 'phone' => $dataArray['phone']
]; ];
# 邮寄信息 # 邮寄信息
$result['posting'] = [ $result['posting'] = [
'contacts_name' => $dataArray['contacts_name'], 'contacts_name' => $dataArray['contacts_name'],
'contacts_mobile' => $dataArray['contacts_mobile'], 'contacts_mobile' => $dataArray['contacts_mobile'],
'contacts_address' => $dataArray['contacts_address'] 'contacts_address' => $dataArray['contacts_address']
]; ];
return $result; return $result;
} }
/** /**
* 编辑 * 编辑
* *
@ -221,7 +328,7 @@ class InvoiceLogic
{ {
return Invoice::update($param); return Invoice::update($param);
} }
/** /**
* 删除 * 删除
* *
@ -232,7 +339,7 @@ class InvoiceLogic
{ {
return Invoice::destroy($where); return Invoice::destroy($where);
} }
/** /**
* 获取审批状态 * 获取审批状态
* *
@ -249,11 +356,11 @@ class InvoiceLogic
if ($isDelete) { if ($isDelete) {
return Invoice::field(['check_status'])->whereIn('invoice_id', $invoiceId)->select(); return Invoice::field(['check_status'])->whereIn('invoice_id', $invoiceId)->select();
} }
# 编辑 # 编辑
return Invoice::where('invoice_id', $invoiceId)->value('check_status'); return Invoice::where('invoice_id', $invoiceId)->value('check_status');
} }
/** /**
* 转移(变更负责人) * 转移(变更负责人)
* *
@ -265,10 +372,10 @@ class InvoiceLogic
{ {
return Invoice::whereIn('invoice_id', $invoiceIds)->update(['owner_user_id' => $ownerUserId]); return Invoice::whereIn('invoice_id', $invoiceIds)->update(['owner_user_id' => $ownerUserId]);
} }
/** /**
* 设置开票 * 设置开票
* *
* @param $param * @param $param
* @return Invoice * @return Invoice
*/ */
@ -276,7 +383,7 @@ class InvoiceLogic
{ {
return Invoice::update($param); return Invoice::update($param);
} }
/** /**
* 获取发票审核信息 * 获取发票审核信息
* *
@ -289,10 +396,10 @@ class InvoiceLogic
public function getExamineInfo($invoiceId) public function getExamineInfo($invoiceId)
{ {
$field = ['check_status', 'flow_id', 'order_id', 'check_user_id', 'flow_user_id', 'invoice_apple_number', 'owner_user_id', 'create_user_id']; $field = ['check_status', 'flow_id', 'order_id', 'check_user_id', 'flow_user_id', 'invoice_apple_number', 'owner_user_id', 'create_user_id'];
return Invoice::field($field)->where('invoice_id', $invoiceId)->find(); return Invoice::field($field)->where('invoice_id', $invoiceId)->find();
} }
/** /**
* 设置审批信息 * 设置审批信息
* *
@ -303,7 +410,7 @@ class InvoiceLogic
{ {
return Invoice::update($data); return Invoice::update($data);
} }
/** /**
* 添加撤销审核记录 * 添加撤销审核记录
* *
@ -316,19 +423,19 @@ class InvoiceLogic
public function createExamineRecord($invoiceId, $examineInfo, $realname, $content, $userId) public function createExamineRecord($invoiceId, $examineInfo, $realname, $content, $userId)
{ {
$data = [ $data = [
'types' => 'crm_invoice', 'types' => 'crm_invoice',
'types_id' => $invoiceId, 'types_id' => $invoiceId,
'flow_id' => $examineInfo['flow_id'], 'flow_id' => $examineInfo['flow_id'],
'order_id' => $examineInfo['order_id'], 'order_id' => $examineInfo['order_id'],
'check_user_id' => $userId, 'check_user_id' => $userId,
'check_time' => time(), 'check_time' => time(),
'status' => 2, 'status' => 2,
'content' => !empty($content) ? $content : $realname . ' 撤销了审核', 'content' => !empty($content) ? $content : $realname . ' 撤销了审核',
]; ];
Db::name('admin_examine_record')->insert($data); Db::name('admin_examine_record')->insert($data);
} }
/** /**
* 检查发票编号是否重复 * 检查发票编号是否重复
* *

@ -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,181 +6,236 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
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作为数据表前缀
*/ */
protected $name = 'crm_contacts'; protected $name = 'crm_contacts';
protected $createTime = 'create_time'; protected $createTime = 'create_time';
protected $updateTime = 'update_time'; protected $updateTime = 'update_time';
protected $autoWriteTimestamp = true; protected $autoWriteTimestamp = true;
/** /**
* [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)
$userModel = new \app\admin\model\User(); {
$structureModel = new \app\admin\model\Structure(); $userModel = new \app\admin\model\User();
$fieldModel = new \app\admin\model\Field(); $structureModel = new \app\admin\model\Structure();
$customerModel = new \app\crm\model\Customer(); $fieldModel = new \app\admin\model\Field();
$search = $request['search']; $customerModel = new \app\crm\model\Customer();
$user_id = $request['user_id']; $search = $request['search'];
$scene_id = (int)$request['scene_id']; $user_id = $request['user_id'];
$is_excel = $request['is_excel']; //导出 $scene_id = (int)$request['scene_id'];
$business_id = $request['business_id']; $is_excel = $request['is_excel']; //导出
$order_field = $request['order_field']; $business_id = $request['business_id'];
$order_type = $request['order_type']; $order_field = $request['order_field'];
$pageType = $request['pageType']; $order_type = $request['order_type'];
$getCount = $request['getCount']; $pageType = $request['pageType'];
//需要过滤的参数 $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']; //需要过滤的参数
foreach ($unsetRequest as $v) { $unsetRequest = ['scene_id', 'search', 'user_id', 'is_excel', 'action', 'order_field', 'order_type', 'is_remind', 'getCount', 'type', 'otherMap', 'business_id', 'check_status'];
unset($request[$v]); foreach ($unsetRequest as $v) {
} unset($request[$v]);
}
$request = $this->fmtRequest( $request );
$requestMap = $request['map'] ? : []; $request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: [];
$sceneModel = new \app\admin\model\Scene();
if ($scene_id) { $sceneModel = new \app\admin\model\Scene();
//自定义场景 if ($scene_id) {
$sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ? : []; //自定义场景
} else { $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ?: [];
//默认场景 } else {
$sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ? : []; //默认场景
} $sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ?: [];
$searchMap = []; }
if ($search || $search == '0') { $searchMap = [];
//普通筛选 if ($search || $search == '0') {
$searchMap = function($query) use ($search){ //普通筛选
$query->where('contacts.name',array('like','%'.$search.'%')) $searchMap = function ($query) use ($search) {
->whereOr('contacts.mobile',array('like','%'.$search.'%')) $query->where('contacts.name', array('like', '%' . $search . '%'))
->whereOr('contacts.telephone',array('like','%'.$search.'%')); ->whereOr('contacts.mobile', array('like', '%' . $search . '%'))
}; ->whereOr('contacts.telephone', array('like', '%' . $search . '%'));
// $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '联系人姓名']; };
} }
//优先级:普通筛选>高级筛选>场景 $partMap = [];
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; //优先级:普通筛选>高级筛选>场景
//高级筛选 if ($requestMap['team_id']) {
$map = where_arr($map, 'crm', 'contacts', 'index'); //相关团队查询
//权限 $map = $requestMap;
$a = 'index'; $partMap= advancedQueryFormatForTeam($requestMap,'crm_contacts','contacts_id');
if ($is_excel) $a = 'excelExport'; unset($map['team_id']);
$authMap = []; } else {
$auth_user_ids = $userModel->getUserByPer('crm', 'contacts', $a); $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
if (isset($map['contacts.owner_user_id']) && $map['contacts.owner_user_id'][0] != 'like') { }
if (!is_array($map['contacts.owner_user_id'][1])) { //高级筛选
$map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]]; $map = advancedQuery($map, 'crm', 'contacts', 'index');
} //权限
if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) { if (!$partMap) {
$auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ? : []; //取差集 $a = 'index';
} else { if ($is_excel) $a = 'excelExport';
$auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ? : []; //取交集 $authMap = [];
} $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', $a);
unset($map['contacts.owner_user_id']); if (isset($map['contacts.owner_user_id']) && $map['contacts.owner_user_id'][0] != 'like') {
} if (!is_array($map['contacts.owner_user_id'][1])) {
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1']; $map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]];
//负责人、相关团队 }
$authMap['contacts.owner_user_id'] = ['in',$auth_user_ids]; 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]) ?: []; //取差集
if ($business_id) { } else {
$contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id'); $auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
if ($contacts_id) { }
$map['contacts.contacts_id'] = array('in',$contacts_id); unset($map['contacts.owner_user_id']);
}else{ $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
$map['contacts.contacts_id'] = array('eq',-1); //负责人、相关团队
} $authMap['contacts.owner_user_id'] = ['in', $auth_user_ids];
} } else {
//列表展示字段 $authMapData = [];
$indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ? : array('name'); $authMapData['auth_user_ids'] = $auth_user_ids;
$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型 $authMapData['user_id'] = $user_id;
$structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure'); //部门类型 $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) {
$contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
if ($contacts_id) {
$map['contacts.contacts_id'] = array('in', $contacts_id);
} else {
$map['contacts.contacts_id'] = array('eq', -1);
}
}
//列表展示字段
$indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ?: array('name');
$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
$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)) {
$order_field = $temporaryField; $order_field = $temporaryField;
} }
//排序 //排序
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';
} }
$readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read'); $readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read');
$updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update'); $updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete'); $deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete');
$customerWhere = []; $customerWhere = [];
if ($pageType == !'all') { if ($pageType == !'all') {
//非客户池条件 //非客户池条件
$customerWhere = $customerModel->getWhereByCustomer(); $customerWhere = $customerModel->getWhereByCustomer();
} }
$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($customerWhere) ->where($partMap)
->count('contacts_id'); ->where($customerWhere)
if ($getCount == 1) { ->count('contacts_id');
$data['dataCount'] = $dataCount ? : 0; if ($getCount == 1) {
return $data; $data['dataCount'] = $dataCount ?: 0;
} return $data;
$list = db('crm_contacts') }
->alias('contacts') $list = db('crm_contacts')
->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT') ->alias('contacts')
->where($map) ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
->where($searchMap) ->where($map)
->where($authMap) ->where($searchMap)
->where($customerWhere) ->where($partMap)
->limit($request['offset'], $request['length']) ->where($authMap)
->field('contacts.*,customer.name as customer_name') ->where($customerWhere)
->orderRaw($order) ->limit($request['offset'], $request['length'])
->select(); ->field('contacts.*,customer.name as customer_name')
foreach ($list as $k=>$v) { ->orderRaw($order)
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : []; ->select();
$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'] ? : ''; $extraData = [];
$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : ''; $contacts_id_list = !empty($list) ? array_column($list, 'contacts_id') : [];
foreach ($userField as $key => $val) { $extraList = db('crm_contacts_data')->whereIn('contacts_id', $contacts_id_list)->select();
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : []; foreach ($extraList as $key => $value) {
$list[$k][$val.'_name'] = implode($usernameField, ','); $extraData[$value['contacts_id']][$value['field']] = $value['content'];
} }
foreach ($structureField as $key => $val) { foreach ($list as $k => $v) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : []; $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k][$val.'_name'] = implode($structureNameField, ','); $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']['name'] = $v['customer_name'] ?: '';
foreach ($userField as $key => $val) {
$usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
$list[$k][$val] = implode($usernameField, ',');
}
foreach ($structureField as $key => $val) {
$structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
$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';
$permission = []; }
$is_read = 0; // 处理日期区间类型字段的格式
$is_update = 0; foreach ($dateIntervalField as $key => $val) {
$is_delete = 0; $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
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'],$deleteAuthIds)) $is_delete = 1; foreach ($positionField as $key => $val) {
$permission['is_read'] = $is_read; $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
$permission['is_update'] = $is_update; }
$permission['is_delete'] = $is_delete; // 手写签名类型字段
$list[$k]['permission'] = $permission; 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 = [];
$is_read = 0;
$is_update = 0;
$is_delete = 0;
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'], $deleteAuthIds)) $is_delete = 1;
$permission['is_read'] = $is_read;
$permission['is_update'] = $is_update;
$permission['is_delete'] = $is_delete;
$list[$k]['permission'] = $permission;
# 关注 # 关注
$starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts']; $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
$star = Db::name('crm_star')->where($starWhere)->value('star_id'); $star = Db::name('crm_star')->where($starWhere)->value('star_id');
@ -188,7 +243,7 @@ class Contacts extends Common
# 日期 # 日期
$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;
# 创建人 # 创建人
$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'] : '';
# 负责人 # 负责人
@ -196,95 +251,174 @@ 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)
{ {
$businessId = $param['business_id']; unset($param['excel']);
unset($param['business_id']);
// 联系人扩展表数据
$fieldModel = new \app\admin\model\Field(); $contactsData = [];
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则 $businessId = $param['business_id'];
$validate = new Validate($validateArr['rule'], $validateArr['message']); unset($param['business_id']);
$result = $validate->check($param); $fieldModel = new \app\admin\model\Field();
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;
}
# 处理客户首要联系人
$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)) {
# 设置首要联系人,去除其他首要联系人状态 # 设置首要联系人,去除其他首要联系人状态
Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]); Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
} }
if (!empty($param['customer_id']) && empty($primaryStatus)) { if (!empty($param['customer_id']) && empty($primaryStatus)) {
# 为客户添加第一个联系人默认设置成首要联系人 # 为客户添加第一个联系人默认设置成首要联系人
$param['primary'] = 1; $param['primary'] = 1;
} }
// 处理部门、员工、附件、多选类型字段 // 处理部门、员工、附件、多选类型字段
$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;
} }
} }
// 处理手写签名类型
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) { $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人'); if (!empty($handwritingField)) {
RecordActionLog($param['create_user_id'],'crm_contacts','save',$param['name'],'','','新增了联系人'.$param['name']); foreach ($param as $key => $value) {
$data = []; if (in_array($key, $handwritingField)) {
$data['contacts_id'] = $this->contacts_id; $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()) {
updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
RecordActionLog($param['create_user_id'], 'crm_contacts', 'save', $param['name'], '', '', '新增了联系人' . $param['name']);
$data = [];
$data['contacts_id'] = $this->contacts_id;
# 添加活动记录 # 添加活动记录
Db::name('crm_activity')->insert([ Db::name('crm_activity')->insert([
'type' => 2, 'type' => 2,
'activity_type' => 3, 'activity_type' => 3,
'activity_type_id' => $data['contacts_id'], 'activity_type_id' => $data['contacts_id'],
'content' => $param['name'], 'content' => $param['name'],
'create_user_id' => $param['create_user_id'], 'create_user_id' => $param['create_user_id'],
'update_time' => time(), 'update_time' => time(),
'create_time' => time(), 'create_time' => time(),
'customer_ids' => ',' . $param['customer_id'] . ',' 'customer_ids' => ',' . $param['customer_id'] . ','
]); ]);
# 处理商机首要联系人 # 处理商机首要联系人
if (!empty($businessId)) { if (!empty($businessId)) {
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']]);
} }
return $data; // 添加联系人扩展数据
} else { array_walk($contactsData, function (&$val) use ($data) {
$this->error = '添加失败'; $val['contacts_id'] = $data['contacts_id'];
return false; });
} db('crm_contacts_data')->insertAll($contactsData);
}
return $data;
//根据IDs获取数组 } else {
public function getDataByStr($idstr) $this->error = '添加失败';
{ return false;
$idArr = stringToArray($idstr); }
if (!$idArr) { }
return [];
} //根据IDs获取数组
$list = Db::name('CrmContacts')->where(['contacts_id' => ['in',$idArr]])->select(); public function getDataByStr($idstr)
return $list; {
} $idArr = stringToArray($idstr);
if (!$idArr) {
return [];
}
$list = Db::name('CrmContacts')->where(['contacts_id' => ['in', $idArr]])->select();
return $list;
}
/** /**
* 编辑联系人主表信息 * 编辑联系人主表信息
* *
@ -297,52 +431,121 @@ class Contacts extends Common
* @throws \think\exception\DbException * @throws \think\exception\DbException
* @throws \think\exception\PDOException * @throws \think\exception\PDOException
*/ */
public function updateDataById($param, $contacts_id = '') public function updateDataById($param, $contacts_id = '')
{ {
$userModel = new \app\admin\model\User(); // 联系人扩展表数据
$dataInfo = $this->getDataById($contacts_id); $contactsData = [];
if (!$dataInfo) {
$this->error = '数据不存在或已删除'; $userModel = new \app\admin\model\User();
return false; $dataInfo = $this->getDataById($contacts_id);
} if (!$dataInfo) {
//判断权限 $this->error = '数据不存在或已删除';
return false;
}
//判断权限
$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); return false;
if (!$result) { }
$this->error = $validate->getError();
return false; // 处理部门、员工、附件、多选类型字段
} $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
foreach ($arrFieldAtt as $k => $v) {
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
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');
if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) { if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
@ -353,20 +556,26 @@ class Contacts extends Common
# 为客户添加第一个联系人默认设置成首要联系人 # 为客户添加第一个联系人默认设置成首要联系人
$param['primary'] = 1; $param['primary'] = 1;
} }
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); //修改记录
RecordActionLog($param['user_id'], 'crm_contacts', 'update',$dataInfo['name'], $dataInfo, $param); updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
$data = []; RecordActionLog($param['user_id'], 'crm_contacts', 'update', $dataInfo['name'], $dataInfo, $param);
$data['contacts_id'] = $contacts_id; // 添加联系人扩展数据
return $data; db('crm_contacts_data')->where('contacts_id', $contacts_id)->delete();
} else { array_walk($contactsData, function (&$val) use ($contacts_id) {
$this->error = '编辑失败'; $val['contacts_id'] = $contacts_id;
return false; });
} db('crm_contacts_data')->insertAll($contactsData);
}
return $data;
} else {
$this->error = '编辑失败';
return false;
}
}
/** /**
* 联系人数据 * 联系人数据
* *
@ -377,18 +586,18 @@ class Contacts extends Common
* @throws \think\db\exception\ModelNotFoundException * @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException * @throws \think\exception\DbException
*/ */
public function getDataById($id = '', $userId = 0) public function getDataById($id = '', $userId = 0)
{ {
$map['contacts_id'] = $id; $map['contacts_id'] = $id;
$dataInfo = db('crm_contacts')->where($map)->find(); $dataInfo = db('crm_contacts')->where($map)->find();
if (!$dataInfo) { if (!$dataInfo) {
$this->error = '暂无此数据'; $this->error = '暂无此数据';
return false; return false;
} }
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : []; $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
$dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : []; $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
$dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find(); $dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
$dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : ''; $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
$dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : ''; $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
$dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : ''; $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
@ -405,43 +614,43 @@ class Contacts extends Common
} }
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null; $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null; $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
$dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null; $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
// 字段授权 // 字段授权
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']);
# 查看权限 # 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]); if ($status['read'] == 0) unset($dataInfo[$key]);
} }
} }
} }
return $dataInfo; return $dataInfo;
} }
/** /**
* [联系人转移] * [联系人转移]
* @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)
{ {
$settingModel = new \app\crm\model\Setting(); $settingModel = new \app\crm\model\Setting();
foreach ($ids as $id) { foreach ($ids as $id) {
$data = []; $data = [];
$data['owner_user_id'] = $owner_user_id; $data['owner_user_id'] = $owner_user_id;
$data['update_time'] = time(); $data['update_time'] = time();
db('crm_contacts')->where(['contacts_id' => $id])->update($data); db('crm_contacts')->where(['contacts_id' => $id])->update($data);
} }
return true; return true;
} }
/** /**
* 设置首要联系人 * 设置首要联系人
* *
@ -455,10 +664,10 @@ class Contacts extends Common
{ {
Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]); Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]); Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
return true; return true;
} }
/** /**
* 获取跟进记录联系人 * 获取跟进记录联系人
* *
@ -472,7 +681,7 @@ class Contacts extends Common
{ {
return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select(); return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
} }
/** /**
* 获取系统信息 * 获取系统信息
* *
@ -488,7 +697,7 @@ class Contacts extends Common
$contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find(); $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
# 创建人 # 创建人
$realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname'); $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
return [ return [
'create_user_id' => $realname, 'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $contacts['create_time']), 'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),

@ -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 {
}; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
} else { }
$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,14 +120,17 @@ 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 {
$authMapData = []; // 待办事项的待审核合同不一定是自己创建的
$authMapData['auth_user_ids'] = $auth_user_ids; if (!$isMessage) {
$authMapData['user_id'] = $user_id; $authMapData = [];
$authMap = function($query) use ($authMapData){ $authMapData['auth_user_ids'] = $auth_user_ids;
$query->where('contract.owner_user_id',array('in',$authMapData['auth_user_ids'])) $authMapData['user_id'] = $user_id;
->whereOr('contract.ro_user_id',array('like','%,'.$authMapData['user_id'].',%')) $authMap = function($query) use ($authMapData){
->whereOr('contract.rw_user_id',array('like','%,'.$authMapData['user_id'].',%')); $query->where('contract.owner_user_id',array('in',$authMapData['auth_user_ids']))
}; ->whereOr('contract.ro_user_id',array('like','%,'.$authMapData['user_id'].',%'))
->whereOr('contract.rw_user_id',array('like','%,'.$authMapData['user_id'].',%'));
};
}
} }
} }
//合同签约人 | 与高级筛选冲突加一个is_array判断 //合同签约人 | 与高级筛选冲突加一个is_array判断
@ -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,21 +225,42 @@ 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'];
$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]['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,18 +396,19 @@ 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)) {
return false; $this->error = $validateResult;
} return false;
}
# 处理下次联系时间 # 处理下次联系时间
if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']); if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
@ -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,16 +593,13 @@ 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); return false;
if (!$result) { }
$this->error = $validate->getError();
return false;
}
# 处理下次联系时间 # 处理下次联系时间
if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']); if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
@ -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作为数据表前缀
@ -48,30 +47,33 @@ 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)') $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
->whereOr('FIND_IN_SET('.$sceneMap['rw_user_id'].', customer.rw_user_id)'); }
}; # 高级筛选
} else { $map = advancedQuery($map, 'crm', 'customer', 'index');
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
} # 工作台仪表盘
//高级筛选
$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,29 +187,35 @@ 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 {
$order = 'customer.update_time desc'; $order = 'customer.update_time desc';
} }
$list = db('crm_customer')->alias('customer') $list = db('crm_customer')->alias('customer')
->where($map) ->where($map)
->where($dashboardWhere) ->where($dashboardWhere)
@ -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'];
@ -327,15 +381,17 @@ class Customer extends Common
$leadsData['detail_address'] = $param['detail_address'] ? : ''; $leadsData['detail_address'] = $param['detail_address'] ? : '';
$param = $leadsData; $param = $leadsData;
}
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
return false;
} }
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_customer', $userId);
if (!empty($validateResult)) {
$this->error = $validateResult;
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
} }
} }
// 处理手写签名类型
$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;
$pool_id = !empty($param['pool_id']) ? $param['pool_id'] : 0;
unset($param['pool_id']);
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) { if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
if(!empty($param['pool_id'])){ $data['customer_id'] = $this->customer_id;
db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$param['pool_id'],'customer_id'=>$this->customer_id]); $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'])){ if (empty($param['leads_id'])) {
updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户'); updateActionLog($param['create_user_id'], 'crm_customer', $data['customer_id'], '', '', '创建了客户');
RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']); RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']);
} }
$data = []; // 添加活动记录
$data['customer_id'] = $this->customer_id;
$data['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;
} }
@ -671,94 +896,28 @@ class Customer extends Common
return $count; return $count;
} }
/** /**
* [客户默认条件] * 客户默认条件
* @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) {

File diff suppressed because it is too large Load Diff

@ -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')
@ -147,7 +145,9 @@ class ReceivablesPlan extends Common
* @return * @return
*/ */
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,21 +166,115 @@ 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; // return false;
} // }
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_receivables_plan', $userId);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件 if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
//期数规则1,2,3.. //期数规则1,2,3..
$maxNum = db('crm_receivables_plan')->where(['contract_id' => $param['contract_id']])->max('num'); $maxNum = db('crm_receivables_plan')->where(['contract_id' => $param['contract_id']])->max('num');
$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; // return false;
} // }
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_receivables_plan', $userId, $plan_id);
if (!empty($validateResult)) {
$this->error = $validateResult;
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; if ($param['page'] != 1 && ($param['page'] * $param['limit']) >= $dataCount) {
$data['page']['lastPage'] = true; $data['firstPage'] = false;
} else if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) < (int)$dataCount) { $data['lastPage'] = true;
$data['page']['firstPage'] = false; } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['page']['lastPage'] = false; $data['firstPage'] = false;
} else if ($request['page'] == 1) { $data['lastPage'] = false;
$data['page']['firstPage'] = true; } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['page']['lastPage'] = false; $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'])){ RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
$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']);
}
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,7 +298,9 @@ 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,7 +382,9 @@ 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']],
@ -203,8 +205,9 @@ return [
'oa/addresslist/userStar'=>['oa/addresslist/userStar', ['method' => 'POST']], 'oa/addresslist/userStar'=>['oa/addresslist/userStar', ['method' => 'POST']],
// 【代办事项】办公 // 【代办事项】办公
'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