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();
$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
$cache = Cache::get('Auth_'.$authKey.$platform);
// $cache = cache('Auth_'.$authKey.$platform);
// dump($request->action());die;
// 校验sessionid和authKey
if (empty($sessionId) || empty($authKey) || empty($cache)) {
header('Content-Type:application/json; charset=utf-8');

@ -32,52 +32,9 @@ class Base extends Common
return resultArray(['error' => $userModel->getError()]);
}
# 数据库更新 todo 在线升级正常使用后删除
$updateStatus = $this->executeUpdateSql();
if (empty($updateStatus['status'])) return resultArray(['error' => $updateStatus['message']]);
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()
{

@ -259,7 +259,6 @@ class ExamineFlow extends ApiCommon
$content='启用了:';
}
$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']);
return resultArray(['data' => '操作成功']);
}

@ -59,11 +59,13 @@ class Field extends ApiCommon
['types' => 'crm_leads', 'name' => '线索管理'],
['types' => 'crm_customer', 'name' => '客户管理'],
['types' => 'crm_contacts', 'name' => '联系人管理'],
['types' => 'crm_product','name' => '产品管理'],
['types' => 'crm_business', 'name' => '商机管理'],
['types' => 'crm_contract', 'name' => '合同管理'],
['types' => 'crm_receivables', 'name' => '回款管理'],
['types' => 'crm_visit','name' => '客户回访管理'],
['types' => 'crm_receivables_plan', 'name' => '回款计划管理'],
['types' => 'crm_invoice', 'name' => '发票管理'],
['types' => 'crm_visit', 'name' => '回访管理'],
['types' => 'crm_product', 'name' => '产品管理'],
];
$examine_types_arr = [];
switch ($param['type']) {
@ -99,11 +101,6 @@ class Field extends ApiCommon
*/
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) {
return resultArray(['error' => '系统审批类型暂不支持编辑']);
@ -114,7 +111,6 @@ class Field extends ApiCommon
$param = $this->param;
$types = $param['types'];
$types_id = $param['types_id'] ? : 0;
// $data['types'] = $param['types'];
$data = $param['data'];
$saveParam = []; # 新增数据
@ -132,6 +128,24 @@ class Field extends ApiCommon
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 (isset($v['is_deleted']) && $v['is_deleted'] == '1') {
# 删除
@ -160,26 +174,14 @@ class Field extends ApiCommon
foreach ($deleteIds AS $key => $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 (!$data = $fieldModel->createData($types, $saveParam)) {
$errorMessage[] = $fieldModel->getError();
}
}
# 编辑
if (!empty($updateParam)) {
if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
@ -242,6 +244,7 @@ class Field extends ApiCommon
$controller = trim($param['controller']);
$action = trim($param['action']);
$system = !empty($param['system']) ? $param['system'] : 0;
$format = !empty($param['format']) ? $param['format'] : 1; // 设置返回数据的格式类型1 还是之前的二维数组格式,兼容移动端、 2 三维数组,新版自定义字段的分组排序。
unset($param['system']);
if (!$module || !$controller || !$action) {
@ -260,11 +263,6 @@ class Field extends ApiCommon
case 'crm_customer' :
$customerModel = new \app\crm\model\Customer();
$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']);
//读写权限
@ -327,6 +325,13 @@ class Field extends ApiCommon
case 'crm_product' :
$productModel = new \app\crm\model\Product();
$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;
case 'crm_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');
$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');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
@ -380,6 +401,11 @@ class Field extends ApiCommon
$action_id = $param['action_id'] ? : '';
$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') {
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') {
@ -490,10 +528,10 @@ class Field extends ApiCommon
case 'crm_customer' :
$customerModel = new Customer();
$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) {
if (empty($customerArray[$key])) continue;
if (empty($customerArray[$key]) || (!empty($param['pool_id']) && in_array($key, ['obtain_time', 'owner_user_id']))) continue;
$data[] = [
'field' => $key,
@ -606,11 +644,23 @@ class Field extends ApiCommon
];
}
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);
# 处理自定义字段分组排序
if (in_array($param['action'], ['save', 'update', 'relative']) && $format == 2) $data = getFieldGroupOrderData($data);
return resultArray(['data' => array_values($data)]);
}
@ -623,11 +673,7 @@ class Field extends ApiCommon
{
$param = $this->param;
$fieldModel = model('Field');
if (is_array($param['val'])) {
//多选类型暂不验证
return resultArray(['data' => '验证通过']);
}
$res = $fieldModel->getValidate(trim($param['field']), trim($param['val']), intval($param['id']), trim($param['types']));
$res = $fieldModel->getValidate(trim($param['field']), $param['val'], intval($param['id']), trim($param['types']));
if (!$res) {
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');
}
/**
* 处理公海详情数据
*
* @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');
$param = $this->param;
$userInfo=$this->userInfo;
$param['user_id']=$userInfo['id'];
$dataInfo = $groupModel->getDataById($param['id']);
if (!$dataInfo) {
return resultArray(['error' => '参数错误']);
@ -130,6 +132,7 @@ class Groups extends ApiCommon
{
$groupModel = model('Group');
$param = $this->param;
$userInfo=$this->userInfo;
$dataInfo = $groupModel->getDataById($param['id']);
if (!$dataInfo) {
return resultArray(['error' => '参数错误']);
@ -137,7 +140,7 @@ class Groups extends ApiCommon
if ($dataInfo['types']) {
return resultArray(['error' => '系统角色,不能删除']);
}
$data = $groupModel->delGroupById($param['id']);
$data = $groupModel->delGroupById($param['id'],$userInfo['id']);
if (!$data) {
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 ($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]);
}

@ -47,7 +47,7 @@ class Install extends Controller
*/
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) {
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
@ -70,7 +70,7 @@ class Install extends Controller
public function step1()
{
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();
header("Location:" . $url);
}
@ -97,7 +97,7 @@ class Install extends Controller
die();
}
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();
header("Location:" . $url);
}
@ -377,6 +377,10 @@ INFO;
'openssl' => ['openssl', '开启', '开启', 'ok'],
'pdo' => ['pdo', '开启', '开启', 'ok'],
];
// linux系统下需要posix扩展
if (in_array(PHP_OS, ['Linux', 'centos', 'Centos', 'ubuntu', 'Ubuntu'])) {
$items['posix'] = ['posix', '开启', '开启', 'ok'];
}
session('install_error','');
if (substr($items['php'][1],0,3) < '7.0') {
$items['php'][3] = 'error';
@ -388,6 +392,7 @@ INFO;
$items['gd'][3] = 'error';
session('install_error', true);
}
if (!extension_loaded('openssl')) {
$items['openssl'][1] = '未开启';
$items['openssl'][3] = 'error';
@ -398,7 +403,12 @@ INFO;
$items['pdo'][3] = 'error';
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;
}

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

@ -176,4 +176,20 @@ class Setting extends ApiCommon
return resultArray(['data' => $data]);
}
/**
* 设置顶部导航信息
*
* @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');
$param = $this->param;
$data = $structureModel->delStrById($param['id']);
$userInfo=$this->userInfo;
$data = $structureModel->delStrById($param['id'],$userInfo['id']);
if (!$data) {
return resultArray(['error' => $structureModel->getError()]);
}

@ -48,14 +48,17 @@ class System extends ApiCommon
$logo = !empty($param['logo']) ? './public/uploads/' . $param['logo'] : '';
$dataInfo = db('admin_system')->where('id', $system_id)->column('name,value');
db('admin_system')->where('name', 'logo')->update(['value' => $logo]);
}elseif (isset($param['name'])) {
# 修改记录
SystemActionLog($userInfo['id'], 'admin_system', 'company', 1, 'update', '企业基本信息设置', '', '', '编辑了:' . $field_name);
}
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']]);
}
# 修改记录
SystemActionLog($userInfo['id'], 'admin_system', 'company', 1, 'update', '企业基本信息设置', '', '', '编辑了:' . $field_name);
}
return resultArray(['data' => '操作成功!']);
}
}

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

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

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

@ -46,7 +46,10 @@ class FieldGrantLogic
'visit' => [
'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
'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)
{
# 防止重复,先删除一下
$this->deleteCrmFieldGrant($roleId);
# 添加线索字段授权数据
$this->createLeadsFieldGrant($roleId);
# 添加客户字段授权数据
@ -106,6 +111,8 @@ class FieldGrantLogic
$this->createProductFieldGrant($roleId);
# 添加回访字段授权信息
$this->createVisitFieldGrant($roleId);
# 添加发票字段授权信息
$this->createInvoiceFieldGrant($roleId);
}
/**
@ -678,4 +685,51 @@ class FieldGrantLogic
'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 ------ #
# ------ 重置扩展数据 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 ------ #
$phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大'];
$phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id');
@ -515,44 +534,6 @@ class InitializeLogic
# 启动事务
Db::startTrans();
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 ------ #
# 获取审批下关联的附件ID
@ -595,6 +576,11 @@ class InitializeLogic
# ------ 清除审批数据 END ------ #
# ------ 重置扩展数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."oa_examine_data");
# ------ 重置扩展数据 END ------ #
# ------ 清除活动中有关审批的数据 START ------ #
# 获取有关审批的活动ID

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

@ -245,7 +245,7 @@ class MessageLogic
$where['is_delete'] = ['eq', 1];
$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);
$taskCount = db('admin_message')->where($where)->count();
$where['type'] = $this->label(2);
@ -255,7 +255,7 @@ class MessageLogic
$where['type'] = 9;
$announceCount = db('admin_message')->where($where)->count();
$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);
$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_record')->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)
{
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 {
$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 = [
'field' => 'address',
'name' => '省、市、区/县',
'form_type' => 'customer_address',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$detailAddress = [
'field' => 'detail_address',
'name' => '详细地址',
'form_type' => 'text',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$lastRecord = [
'field' => 'last_record',
'name' => '最后跟进记录',
'form_type' => 'text',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$lastTime = [
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$beforeOwnerUser = [
'field' => 'before_owner_user_id',
'name' => '前负责人',
'form_type' => 'user',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$intoPoolTime = [
'field' => 'into_pool_time',
'name' => '进入公海时间',
'form_type' => 'datetime',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$createTime = [
'field' => 'create_time',
'name' => '创建时间',
'form_type' => 'datetime',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$updateTime = [
'field' => 'update_time',
'name' => '更新时间',
'form_type' => 'datetime',
'is_hidden' => 0
'is_hidden' => 0,
'is_null' => 0,
'is_unique' => 0,
];
$createUser = [
'field' => 'create_user_id',
'name' => '创建人',
'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);
@ -472,7 +493,9 @@ class PoolConfigLogic
'name' => $value['name'],
'field_name' => $value['field'],
'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)
{
$res=Db::name('admin_group')->where('id',$param['id'])->find();
$userInd=$param['user_id'];
unset($param['user_id']);
if(!$res){
return false;
}else{
$data=Db::name('admin_group')->update($param);
# 添加系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
SystemActionLog($userInd, 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
return $data;
}
@ -113,7 +113,7 @@ class WorkLogic
* @throws \think\Exception
* @throws \think\exception\PDOException
*/
public function deleteRole($id)
public function deleteRole($id,$userId)
{
$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]); # 处理私有项目的权限
}
# 添加系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
SystemActionLog($userId, 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
return ['status' => true];
}
}

@ -43,7 +43,7 @@ class ActionRecord extends Common
}
$userModel = model('User');
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']);
}
return $dataList;

@ -303,9 +303,9 @@ class Common extends Model
if (isset($val[$field['field'] . 'name'])) {
$val[$field['field']] = $val[$field['field'] . 'name'];
}
// else {
// $val[$field['field']] = implode(',', array_column($val[$field['field'] . '_info'], 'realname'));
// }
if ($field['field'] == 'order_user_id') {
$val[$field['field']] = $val[$field['field'] . '_name'];
}
break;
case 'structure':
// $temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']);
@ -317,7 +317,7 @@ class Common extends Model
break;
case 'customer':break;
case 'business':break;
case 'contacts':break;
case 'contacts':
$val[$field['field']] = $val[$field['field'] . '_info']['name'];
break;
default :
@ -328,11 +328,15 @@ class Common extends Model
$val[$field['field']] = $val['is_end'];
}
break;
case 'type_id':break;
case 'type_id':
break;
// $val[$field['field']] = $val[$field['field'] . '_info'];
case 'check_status' :
$val[$field['field']] = $val[$field['field'] . '_info'];
break;
case 'plan_id' :
$val[$field['field']] = $val[$field['field'] . '_info'];
break;
}
}
}

@ -14,6 +14,7 @@ use com\PseudoQueue as Queue;
use think\Cache;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\cache\driver\Redis;
class Excel extends Common
{
/**
@ -26,6 +27,8 @@ class Excel extends Common
'crm_customer',
'crm_contacts',
'crm_product',
'crm_contract',
'crm_business',
'admin_user',
'task'
];
@ -111,6 +114,7 @@ class Excel extends Common
} else {
$k = 0;
}
$objActSheet->getColumnDimension('A1')->setWidth(70);
foreach ($field_list as $field) {
if ($field['form_type'] == 'map_address' && $types == 'crm_customer') {
for ($a = 0; $a <= 3; $a++) {
@ -125,7 +129,7 @@ class Excel extends Common
//产品类别
if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
$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');
} else {
$setting = $field['setting'] ?: [];
@ -146,6 +150,7 @@ class Excel extends Common
$endcell = $c;
}
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);//设置单元格格式 (文本)
//数据有效性 start
$objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
@ -164,6 +169,7 @@ class Excel extends Common
} else {
if ($select_value) {
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);//设置单元格格式 (文本)
//数据有效性 start
$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);//设置单元格格式 (文本)
//检查该字段若必填,加上"*"
$field['name'] = sign_required($field['is_null'], $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++;
}
}
@ -193,19 +203,17 @@ class Excel extends Common
$mark_row = $this->stringFromColumnIndex($k);
$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')->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) {
case 'crm_leads' :
$types_name = '线索信息';
@ -243,13 +251,34 @@ class Excel extends Common
$types_name = '任务信息';
$type_name = 'task';
break;
case 'crm_pool' :
$types_name = '公海信息';
$type_name = 'pool';
break;
case 'crm_activity' :
$types_name = '跟进记录';
$type_name = 'activity';
break;
default :
$types_name = '悟空软件';
$type_name = 'WuKong';
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);
//设置A1单元格内容为
$objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
ob_end_clean();
if ($save_path) {
@ -432,11 +461,13 @@ class Excel extends Common
foreach ($field_list as $rule) {
if ($rule['form_type'] == 'customer_address') {
$address_arr = explode(chr(10), $val['address']);
$rows[] = $address_arr[0] ?: '';
$rows[] = $address_arr[1] ?: '';
$rows[] = $address_arr[2] ?: '';
} 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']);
}
}
@ -488,8 +519,11 @@ class Excel extends Common
$queue->dequeue();
return false;
}
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);
$import_queue_index = input('import_queue_index');
@ -556,15 +590,15 @@ class Excel extends Common
$save_path = UPLOAD_PATH . $save_name;
// 队列-判断是否需要排队
// if (!$queue->canExec()) {
// $this->error = [
// 'temp_file' => $save_name,
// 'page' => -2,
// 'import_queue_index' => $import_queue_index,
// 'info' => $queue->error
// ];
// return true;
// }
if (!$queue->canExec()) {
$this->error = [
'temp_file' => $save_name,
'page' => -2,
'import_queue_index' => $import_queue_index,
'info' => $queue->error
];
return true;
}
// 加载类库
vendor("phpexcel.PHPExcel");
@ -649,15 +683,43 @@ class Excel extends Common
break;
}
// 字段
# 下次升级
$fieldModel = new \app\admin\model\Field();
$fieldParam['types'] = $types;
$fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam);
if (!empty($param['pool_id'])) {
$pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
$merge_list = $fieldModel->field($fieldParam);
$field_list=array_intersect($merge_list,$pool_list);
$list = [];
$field_list = db('crm_customer_pool_field_setting')->where(['pool_id' => $param['pool_id'], 'is_hidden' => 0,
'field_name' => ['not in', ['deal_status', 'create_user_id']]])->field('field_name as field,form_type,name')->select();
foreach ($field_list as $k => &$v) {
if ($v['field'] == 'address') {
$v['field'] = 'customer_address';
$v['form_type'] = 'map_address';
$list[] = $v;
unset($field_list[$k]);
} elseif ($v['field'] == 'detail_address') {
unset($field_list[$k]);
}
}
$field_list = array_merge($field_list, $list);
} else {
$field_list = $fieldModel->field($fieldParam);
}
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) {
if (method_exists($val, 'toArray')) {
@ -667,40 +729,6 @@ class Excel extends Common
}
}, $field_list);
$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->setReadDataOnly(true);
@ -717,12 +745,12 @@ class Excel extends Common
// 检测导入文件是否使用最新模板
$header = $sheet->rangeToArray("A2:{$max_col}2")[0];
$temp = 0;
for ($i = 0; $i < count($field_list); $i++) {
if (
$header[$i] == $field_list[$i]['name']
|| $header[$i] == '*' . $field_list[$i]['name']
) {
$res[] = $header[$i];
$temp++;
// 字段为地址时,占四列
} 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 + 3] == $this->map_address[3]
) {
$ress[] = $header[$i];
$temp++;
}
}
}
// 每次导入条数
$page_size = 100;
@ -775,24 +802,21 @@ class Excel extends Common
'create_time' => time(),
'update_time' => time(),
'owner_user_id' => 0,
'before_owner_user_id'=>$param['create_user_id'],
'into_pool_time' => time(),
'pool_id' => $param['pool_id'],
];
} else {
$default_data = [
'create_user_id' => $param['create_user_id'],
'owner_user_id' => $param['owner_user_id'],
'create_time' => time(),
'update_time' => time(),
];
}
if ($temp !== count($field_list)) {
// $this->error = '请使用最新导入模板';
@unlink($save_path);
$queue->dequeue();
foreach ($dataList as $val) {
$error_data_func($val, '请使用最新导入模板1');
$error_data_func($val, '请使用最新导入模板');
}
$objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
$objWriter->save($error_path);
@ -871,7 +895,7 @@ class Excel extends Common
}
$fk++;
}
if (!empty($not_null_field)) {
if (!empty($not_null_field) && empty($param['pool_id'])) {
$error_data_func($val, implode(', ', $not_null_field) . '不能为空');
continue;
}
@ -887,15 +911,19 @@ class Excel extends Common
$old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
}
}
$userId = '';
#下次升级
// if(empty($param['pool_id'])){
// $user_id=db('admin_user')->where('realname',$val[2])->value('id');
// $data['owner_user_id']=$user_id?:0;
// }
if ($param['pool_id']) {
$userId = db('admin_user')->where('realname', $val[2])->value('id');
$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');
$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) {
$data = array_merge($data, $default_data);
$data['create_user_id'] = $param['create_user_id'];
@ -904,13 +932,23 @@ class Excel extends Common
try {
$up_success_count = 0;
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) {
$temp_error = '当前导入人员对该公海数据,无导入权限';
$error_data_func($val, $temp_error);
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)) {
$temp_error = $dataModel->getError();
if ($temp_error == '无权操作') {
@ -920,6 +958,7 @@ class Excel extends Common
$dataModel->rollback();
break;
}
}
$up_success_count++;
}
// 全部更新完成
@ -944,16 +983,23 @@ class Excel extends Common
$unique_field = array_unique($unique_field);
$error_data_func($val, implode(', ', $unique_field) . ' 根据查重规则,该条数据重复');
}
}elseif(!empty($old_data_id_list) && !empty($param['pool_id'])){
$error_data_func($val, ' 重复数据不在当前公海,无权覆盖');
} 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) {
$temp_error = '当前导入人员对该公海数据,无导入权限';
$error_data_func($val, $temp_error);
} else {
$data = array_merge($data, $default_data);
$data['excel'] = 1;
if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError());
}
}
} else {
$data = array_merge($data, $default_data);
if ($types != 'admin_user') {
$data['excel'] = 1;
}
if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError());
}
@ -2154,8 +2200,8 @@ class Excel extends Common
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$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()->setVertical(\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_CENTER);
$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');
@ -2168,7 +2214,7 @@ class Excel extends Common
$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('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表示需要设置宽度
{
$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')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
$callCount = count($callback) + 2;
$style_array = array(
'borders' => array(
'allborders' => array(
'style' => \PHPExcel_Style_Border::BORDER_THIN
)
));
$objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array);
//边框
// $callCount = count($callback) + 2;
// $style_array = array(
// 'borders' => array(
// 'allborders' => array(
// 'style' => \PHPExcel_Style_Border::BORDER_THIN
// )
// ));
// $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array);
foreach ($callback as $k => $item) {
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()->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($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);
if ($v[3] > 0)//大于0表示需要设置宽度
@ -2396,6 +2443,8 @@ class Excel extends Common
if ($param == 0) {
if ($base == 'batchTaskImportData') {
$this->batchTaskImportData('', $excelData);
} elseif ($base == 'ActivityImport') {
$this->ActivityImport('', $excelData);
} else {
$this->batchImportData('', $excelData);
}
@ -2454,7 +2503,7 @@ class Excel extends Common
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false;
$data['lastPage'] = false;
} else if ($param['page'] == 1) {
} else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = true;
$data['lastPage'] = false;
}
@ -2480,7 +2529,7 @@ class Excel extends Common
$queue->dequeue();
return false;
}
$user_id = $param['user_id'];
// 采用伪队列 允许三人同时导入数据
$queue = new Queue(self::IMPORT_QUEUE, 30000);
$import_queue_index = input('import_queue_index');
@ -2522,6 +2571,7 @@ class Excel extends Common
'done' => $temp['done'],
'cover' => $temp['cover'],
'error' => $temp['error'],
'user_id' => $user_id,
'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
]);
$queue->dequeue();
@ -2642,26 +2692,26 @@ class Excel extends Common
}
// 读取数据
$dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
// 默认数据
$default_data = [
];
switch ($types) {
case 'crm_business':
$dataModel = new \app\crm\model\Business();
$db = db('crm_business');
$db_id = 'business_id';
$activity_type = 5;
$activity_name='所属商机';
break;
case 'crm_contract':
$db = db('crm_contract');
$db_id = 'contract_id';
$activity_type = 6;
$activity_name='所属合同';
break;
case 'crm_leads' :
$dataModel = new \app\crm\model\Leads();
$db = db('crm_leads');
$db_id = 'leads_id';
$activity_type = 1;
$activity_name='所属线索';
break;
case 'crm_customer' :
$dataModel = new \app\crm\model\Customer();
@ -2669,12 +2719,14 @@ class Excel extends Common
$db_id = 'customer_id';
$fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
$activity_type = 2;
$activity_name='所属客户';
break;
case 'crm_contacts' :
$dataModel = new \app\crm\model\Contacts();
$db = db('crm_contacts');
$db_id = 'contacts_id';
$activity_type = 3;
$activity_name='所属联系人';
break;
}
@ -2707,8 +2759,9 @@ class Excel extends Common
$userData = db('admin_user')->where(['realname' => $val[1], 'status' => ['neq', 0]])->value('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();
if (empty($customerData)) {
$error_data_func($val, '所属客户'.$val[2].'不存在');
$error_data_func($val, $activity_name . $val[2] . '不存在');
continue;
}
if (empty($userData)) {
@ -2716,33 +2769,34 @@ class Excel extends Common
continue;
}
if ($types == 'crm_customer' && (!empty($val[5]) || !empty($val[6]))) {
$contactsData=db('crm_contacts')->where('name',$val[5])->value($db_id);
$businessData=$db->where('crm_business',$val[6])->value($db_id);
if (empty($contactsData)&&eempty($businessData)) {
$error_data_func($val, '联系人'.$val[5].'不存在或商机'.$val[6].'不存在');
continue;
}
}
if ($classData[0]['activity_id'] != '') {
$data['activity_id'] = $classData[0]['activity_id'];
$data = array_merge($data, $default_data);
$data['create_user_id'] = $userData;
$data['activity_type_id'] = $customerData;
$data['activity_type'] = $activity_type;
if (!$resData = $activityLogic->update($data)) {
$error_data_func($val, $dataModel->getError());
}
}else{
$data = array_merge($data, $default_data);
if(strstr($val[5], '/')||strstr($val[6], '/')){
$val[5]= explode ( '/' , $val[5]);
$val[6]= explode ( '/' , $val[6]);
}
$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 && $classData[0]['activity_id'] != '') {
// $data['activity_id'] = $classData[0]['activity_id'];
// $data['activity_type_id'] = $customerData;
// $data['activity_type'] = $activity_type;
// $data['create_user_id'] = $user_id;
// if (!$resData = $activityLogic->update($data)) {
// $error_data_func($val, $dataModel->getError());
// }
// } else { }
$data['user_id'] = $userData;
$data['activity_type_id'] = $customerData;
$data['activity_type'] = $activity_type;
$data['excel'] = 1;
$data['create_user_id'] = $user_id;
unset($data['create_user_id']);
if (!$resData = $activityLogic->save($data)) {
$error_data_func($val, $dataModel->getError());
}
}
}
// 完成数(已导入数)
$done = ($page - 1) * $page_size + count($dataList);
@ -2800,6 +2854,7 @@ class Excel extends Common
'done' => $done,
'cover' => $cover,
'error' => $error,
'user_id' => $user_id,
'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
]);
Cache::set('item', 1, config('import_cache_time'));
@ -2826,101 +2881,4 @@ class Excel extends Common
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');
}
}
}

@ -29,8 +29,47 @@ class Field extends Model
private $queryStr = ''; //sql语句
private $__db_prefix; //数据库表前缀
private $types_arr = ['crm_leads', 'crm_customer', 'crm_contacts', 'crm_product', 'crm_business', 'crm_contract', 'oa_examine', 'hrm_parroll', 'admin_user', 'crm_receivables', 'crm_receivables_plan', 'crm_invoice', 'crm_visit']; //支持自定义字段的表,不包含表前缀
private $formtype_arr = ['text', 'textarea', 'mobile', 'email', 'number', 'floatnumber', 'radio', 'select', 'checkbox', 'date', 'datetime', 'address', 'user', 'file', 'structure'];
private $types_arr = [
'crm_leads',
'crm_customer',
'crm_contacts',
'crm_product',
'crm_business',
'crm_contract',
'oa_examine',
'hrm_parroll',
'admin_user',
'crm_receivables',
'crm_receivables_plan',
'crm_invoice',
'crm_visit',
]; //支持自定义字段的表,不包含表前缀
private $formtype_arr = [
'text',
'textarea',
'mobile',
'email',
'number',
'floatnumber',
'radio',
'select',
'checkbox',
'date',
'datetime',
'address',
'user',
'file',
'structure',
'boolean_value', # 布尔值
'percent', # 百分数
'website', # 网址
'position', # 地址
'location', # 地址
'handwriting_sign', # 手写签名
'date_interval', # 日期区间
'desc_text', # 描述类型
'detail_table', # 明细表格
];
protected $type = [
'form_value' => 'array',
];
@ -199,14 +238,39 @@ class Field extends Model
if ($param['types'] == 'crm_customer') {
$map['field'] = array('not in', ['deal_status']);
}
$list = Db::name('AdminField')->where($map)->order('order_id')->select();
$list = Db::name('AdminField')->where($map)->order('form_position', 'asc')->select();
$detailTableList = db('admin_field_extend')->field(['field', 'content'])->where('types', $types)->select();
$detailTableData = [];
foreach ($detailTableList as $key => $value) {
$detailTableData[$value['field']] = !empty($value['content']) ? json_decode($value['content']) : [];
}
foreach ($list as $k => $v) {
$list[$k]['setting'] = $v['setting'] ? explode(chr(10), $v['setting']) : [];
if ($v['form_type'] == 'checkbox') {
$list[$k]['default_value'] = $v['default_value'] ? explode(',', $v['default_value']) : array();
}
if (in_array($v['form_type'], ['position', 'date_interval'])) {
$list[$k]['default_value'] = !empty($v['default_value']) ? json_decode($v['default_value'], true) : [];
}
if ($v['form_type'] == 'detail_table') {
$list[$k]['fieldExtendList'] = !empty($detailTableData[$v['field']]) ? $detailTableData[$v['field']] : [];
}
if (!empty($v['form_position'])) {
$coordinate = explode(',', $v['form_position']);
$list[$k]['xaxis'] = (int)$coordinate[0];
$list[$k]['yaxis'] = (int)$coordinate[1];
}
if (!empty($v['options'])) {
$list[$k]['optionsData'] = json_decode($v['options'], true);
} else {
$list[$k]['options'] = $v['setting'];
}
// 处理数值范围字段
$list[$k]['minNumRestrict'] = $v['min_num_restrict'];
$list[$k]['maxNumRestrict'] = $v['max_num_restrict'];
}
return $list ?: [];
return getFieldGroupOrderData((array)$list);
}
/**
@ -238,9 +302,25 @@ class Field extends Model
# 用户自定义字段
$userFields = db('admin_user_field')->field(['id', 'datas'])->where('types', $types)->select();
# 获取最大formAssistId
$formAssistId = db('admin_field')->where('types', $types)->order('formAssistId', 'desc')->value('formAssistId');
$formAssistId = !empty($formAssistId) ? $formAssistId : 1000;
$error_message = [];
$i = 0;
foreach ($param as $k => $data) {
// 设置$formAssistId值
$formAssistId += 1;
$data['formAssistId'] = $formAssistId;
// 清除坐标
unset($data['xaxis']);
unset($data['yaxis']);
unset($data['maxNumRestrict']);
unset($data['minNumRestrict']);
// 设置明细表格类型的默认值为空防止为null的报错。
if ($data['form_type'] == 'detail_table') {
$data['default_value'] = '';
}
$i++;
$data['types'] = $types;
if ($types == 'oa_examine' && !$data['types_id']) {
@ -251,17 +331,17 @@ class Field extends Model
$error_message[] = $data['name'] . ',字段类型错误';
}
//生成字段名
if (!$data['field']) $data['field'] = $this->createField($types);
if (!$data['field']) $data['field'] = $this->createField($types, $types == 'oa_examine' ? 'oa_' : 'crm_');
$rule = [
'field' => ['regex' => '/^[a-z]([a-z]|_)+[a-z]$/i'],
'name' => 'require',
// 'name' => 'require',
'types' => 'require',
'form_type' => 'require',
];
$msg = [
'field.regex' => '字段名称格式不正确!',
'name.require' => '字段标识必须填写',
// 'name.require' => '字段标识必须填写',
'types.require' => '分类必须填写',
'form_type.require' => '字段类型必须填写',
];
@ -290,6 +370,30 @@ class Field extends Model
$data['form_value'] = $new_form_value;
}
# 处理日期区间、地址类型的默认数据
if (in_array($data['form_type'], ['position', 'date_interval']) && !empty($data['default_value'])) {
$data['default_value'] = json_encode($data['default_value'], JSON_NUMERIC_CHECK);
}
# 处理明细表格中的字段数据
if ($data['form_type'] == 'detail_table' && !empty($data['fieldExtendList']) && $this->setDetailTableData($types, $data['field'], $data['fieldExtendList']) === false) {
$error_message[] = '创建明细表单失败!';
}
# 处理选项中的逻辑表单数据
// if (in_array($data['form_type'], ['select', 'checkbox'])) {
// $data['options'] = !empty($data['options']) ? json_encode($data['options']) : '';
// }
# 设置描述文字类型的字段名称
if (empty($data['name']) && $data['form_type'] == 'desc_text') {
$data['name'] = '描述文字';
}
// 数值范围
if (!empty($data['minNumRestrict'])) $data['min_num_restrict'] = $data['minNumRestrict'];
if (!empty($data['maxNumRestrict'])) $data['max_num_restrict'] = $data['maxNumRestrict'];
unset($data['field_id']);
if ($i > 1) {
@ -299,12 +403,14 @@ class Field extends Model
}
# 处理公海字段数据
if ($types == 'crm_customer') {
foreach ($poolList AS $k1 => $poolId) {
foreach ($poolList as $k1 => $poolId) {
$poolData[] = [
'pool_id' => $poolId,
'name' => $data['name'],
'field_name' => $data['field'],
'form_type' => $data['form_type'],
'is_null' => $data['is_null'],
'is_unique' => $data['is_unique'],
'is_hidden' => 1
];
}
@ -331,9 +437,7 @@ class Field extends Model
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` TEXT COMMENT '" . $data['name'] . "'";
break;
case 'number' :
$defaultvalue = abs(intval($data['default_value'])) > 2147483647 ? 2147483647 : intval($data['default_value']);
$maxlength = 11;
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` int ( " . $maxlength . " ) DEFAULT '" . $defaultvalue . "' COMMENT '" . $data['name'] . "'";
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(255) NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'floatnumber' :
$defaultvalue = abs(intval($data['default_value'])) > 9999999999999999.99 ? 9999999999999999.99 : intval($data['default_value']);
@ -353,19 +457,63 @@ class Field extends Model
case 'form' :
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '" . $data['name'] . "'";
break;
case 'boolean_value' :
# 布尔值类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` TINYINT(1) unsigned NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'percent' :
# 百分数类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(255) NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'position' :
# 地址类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$addressValue = [];
if (!empty($data['default_value'])) {
$data['default_value'] = json_decode($data['default_value'], true);
foreach ($data['default_value'] as $kk => $vv) {
if (!empty($vv['name'])) $addressValue[] = $vv['name'];
}
}
$defaultValue = !empty($addressValue) ? "DEFAULT '" . implode(',', $addressValue) . "'" : "DEFAULT NULL";
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultValue . " COMMENT '" . $data['name'] . "'";
break;
case 'location' :
# 定位类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'handwriting_sign' :
# 手写签名类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` INT(10) unsigned NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'date_interval' :
# 日期区间类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$defaultValue = !empty($data['default_value']) ? "DEFAULT '" . implode('_', json_decode($data['default_value'], true)) . "'" : "DEFAULT NULL";
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultValue . " COMMENT '" . $data['name'] . "'";
break;
case 'desc_text' :
# 描述文字类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(1000) NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'detail_table' :
# 明细表格类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
default :
$maxlength = 255;
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` ADD `" . $data['field'] . "` VARCHAR( " . $maxlength . " ) CHARACTER SET utf8 COLLATE utf8_general_ci " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
}
if (!empty($this->queryStr)) {
$resData = Db::execute($this->queryStr);
if ($resData === false) {
$this->where(['field_id' => $this->field_id])->delete();
$error_message[] = $data['name'] . ',添加失败';
}
}
# 处理用户自定义字段数据
if ($resData !== false && !empty($userFields)) {
foreach ($userFields AS $key => $value) {
if (!empty($userFields)) {
foreach ($userFields as $key => $value) {
if (in_array($data['form_type'], ['handwriting_sign', 'desc_text', 'detail_table'])) continue;
$userFields[$key]['datas'] = json_decode($value['datas'], true);
$userFields[$key]['datas'][$data['field']] = ['width' => '', 'is_hide' => 0];
$userFields[$key]['datas'] = json_encode($userFields[$key]['datas']);
@ -379,7 +527,7 @@ class Field extends Model
}
# 更新用户自定义字段
if (!empty($userFields)) {
foreach ($userFields AS $key => $value) {
foreach ($userFields as $key => $value) {
db('admin_user_field')->where('id', $value['id'])->update(['datas' => $value['datas']]);
}
}
@ -438,16 +586,34 @@ class Field extends Model
$this->error = '参数错误';
return false;
}
# 查询老数据
// 查询老数据
$oldData = [];
if (!empty($types) && $types == 'crm_customer') {
$oldList = db('admin_field')->field(['field', 'name'])->where('types', $types)->select();
foreach ($oldList AS $key => $value) {
foreach ($oldList as $key => $value) {
$oldData[$value['field']] = $value['name'];
}
}
// 获取最大formAssistId
$formAssistId = db('admin_field')->where('types', $types)->order('formAssistId', 'desc')->value('formAssistId');
$formAssistId = !empty($formAssistId) ? $formAssistId : 1000;
$i = 0;
foreach ($param as $data) {
// 设置formAssistId
if (empty($data['formAssistId'])) {
$formAssistId += 1;
$data['formAssistId'] = $formAssistId;
}
// 清除坐标
unset($data['xaxis']);
unset($data['yaxis']);
unset($data['maxNumRestrict']);
unset($data['minNumRestrict']);
// 设置明细表格类型的默认值为空防止为null的报错。
if ($data['form_type'] == 'detail_table') {
$data['default_value'] = '';
}
$i++;
$field_id = intval($data['field_id']);
if (!$field_id) {
@ -472,10 +638,33 @@ class Field extends Model
// unset($data['field']);
$data['field'] = $dataInfo['field'];
unset($data['operating']);
$box_form_type = array('checkbox', 'select', 'radio');
if ((in_array($dataInfo['form_type'], $box_form_type) && !in_array($data['form_type'], $box_form_type)) || !in_array($dataInfo['form_type'], $box_form_type)) {
unset($data['form_type']);
// $box_form_type = array('checkbox', 'select', 'radio');
// if ((in_array($dataInfo['form_type'], $box_form_type) && !in_array($data['form_type'], $box_form_type)) || !in_array($dataInfo['form_type'], $box_form_type)) {
// unset($data['form_type']);
// }
# 处理日期区间、地址类型的默认数据
if (in_array($data['form_type'], ['position', 'date_interval']) && !empty($data['default_value'])) {
$data['default_value'] = json_encode($data['default_value'], JSON_NUMERIC_CHECK);
}
# 处理明细表格中的字段数据
if ($data['form_type'] == 'detail_table' && !empty($data['fieldExtendList']) && $this->setDetailTableData($data['types'], $data['field'], $data['fieldExtendList']) === false) {
$error_message[] = '创建明细表单失败!';
}
unset($data['fieldExtendList']);
# 处理选项中的逻辑表单数据
// if (in_array($data['form_type'], ['select', 'checkbox'])) {
// $data['options'] = json_encode($data['options'], JSON_NUMERIC_CHECK);
// }
// 数值范围
if (!empty($data['minNumRestrict'])) $data['min_num_restrict'] = $data['minNumRestrict'];
if (!empty($data['maxNumRestrict'])) $data['max_num_restrict'] = $data['maxNumRestrict'];
if (isset($data['minNumRestrict'])) unset($data['minNumRestrict']);
if (isset($data['maxNumRestrict'])) unset($data['maxNumRestrict']);
// $resField = $this->allowField(true)->save($data, ['field_id' => $field_id]);
unset($data['showSetting']);
unset($data['componentName']);
@ -486,7 +675,7 @@ class Field extends Model
if ($resField) {
# 更新公海字段
if (!empty($oldData[$data['field']]) && $data['name'] != $oldData[$data['field']]['name']) {
db('crm_customer_pool_field_setting')->where('field_name', $data['field'])->update(['name' => $data['name']]);
db('crm_customer_pool_field_setting')->where('field_name', $data['field'])->update(['name' => $data['name'], 'is_null' => $data['is_null'], 'is_unique' => $data['is_unique']]);
}
//actionLog($field_id); //操作日志
$this->tableName = $dataInfo['types'];
@ -508,9 +697,7 @@ class Field extends Model
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` CHANGE `" . $dataInfo['field'] . "` `" . $data['field'] . "` TEXT COMMENT '" . $data['name'] . "'";
break;
case 'number' :
$defaultvalue = abs(intval($data['default_value'])) > 2147483647 ? 2147483647 : intval($data['default_value']);
$maxlength = 11;
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` CHANGE `" . $dataInfo['field'] . "` `" . $data['field'] . "` int ( " . $maxlength . " ) DEFAULT '" . $defaultvalue . "' COMMENT '" . $data['name'] . "'";
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` CHANGE `" . $dataInfo['field'] . "` `" . $data['field'] . "` VARCHAR(255) NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'floatnumber' :
$defaultvalue = abs(intval($data['default_value'])) > 9999999999999999.99 ? 9999999999999999.99 : intval($data['default_value']);
@ -527,15 +714,58 @@ class Field extends Model
case 'file' :
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` CHANGE `" . $dataInfo['field'] . "` `" . $data['field'] . "` VARCHAR ( " . $maxlength . " ) CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '" . $data['name'] . "' ";
break;
case 'boolean_value' :
# 布尔值类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` TINYINT(1) unsigned NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'percent' :
# 百分数类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` VARCHAR(255) NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'position' :
# 地址类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$addressValue = [];
if (!empty($data['default_value'])) {
$data['default_value'] = json_decode($data['default_value'], true);
foreach ($data['default_value'] as $kk => $vv) {
if (!empty($vv['name'])) $addressValue[] = $vv['name'];
}
}
$defaultValue = !empty($addressValue) ? "DEFAULT '" . implode(',', $addressValue) . "'" : "DEFAULT NULL";
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultValue . " COMMENT '" . $data['name'] . "'";
break;
case 'location' :
# 定位类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'handwriting_sign' :
# 手写签名类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` INT(10) unsigned NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'date_interval' :
# 日期区间类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$defaultValue = !empty($data['default_value']) ? "DEFAULT '" . implode('_', json_decode($data['default_value'], true)) . "'" : "DEFAULT NULL";
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultValue . " COMMENT '" . $data['name'] . "'";
break;
case 'desc_text' :
# 描述文字类型字段
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` VARCHAR(1000) NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
case 'detail_table' :
# 明细表格类型字段存放在相应的数据扩展表中比如crm_customer_extra_data
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` MODIFY COLUMN `" . $data['field'] . "` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
default :
$maxlength = 255;
$this->queryStr = "ALTER TABLE `" . $this->__db_prefix . $this->tableName . "` CHANGE `" . $dataInfo['field'] . "` `" . $data['field'] . "` VARCHAR( " . $maxlength . " ) CHARACTER SET utf8 COLLATE utf8_general_ci " . $defaultvalue . " COMMENT '" . $data['name'] . "'";
break;
}
if (!empty($this->queryStr)) {
$resData = Db::execute($this->queryStr);
if ($resData === false) {
$error_message[] = $data['name'] . ',修改失败';
}
}
} else {
$error_message[] = $data['name'] . ',修改失败';
}
@ -573,6 +803,7 @@ class Field extends Model
$delMessage[] = $dataInfo['name'] . ',系统字段,不能删除';
} else {
$resDel = $this->where(['field_id' => $id])->delete(); //删除自定义字段信息
// 客户模块下的栏目,成功删除自定义字段后做相应的处理
if ($resDel && $dataInfo['types'] !== 'oa_examine') {
$this->tableName = $dataInfo['types'];
if ($dataInfo['form_type'] == 'img') {
@ -589,7 +820,6 @@ class Field extends Model
//删除列表字段配置数据
$userFieldList = db('admin_user_field')->where(['types' => $dataInfo['types']])->select();
foreach ($userFieldList as $key => $val) {
$datas = [];
$datas = json_decode($val['datas'], true);
if ($datas) {
foreach ($datas as $k => $v) {
@ -605,7 +835,6 @@ class Field extends Model
//删除场景字段数据
$sceneFieldList = db('admin_scene')->where(['types' => $dataInfo['types']])->select();
foreach ($sceneFieldList as $key => $val) {
$data = [];
$data = json_decode($val['data'], true);
if ($data) {
foreach ($data as $k => $v) {
@ -613,12 +842,26 @@ class Field extends Model
}
$data = $data ?: [];
$sceneModel = new \app\admin\model\Scene();
$resScene = $sceneModel->updateData($data, $val['scene_id']);
$sceneModel->updateData($data, $val['scene_id']);
}
}
# 处理删除公海字段的条件
// 处理删除公海字段的条件
if (!empty($types) && $types == 'crm_customer' && !empty($dataInfo['field'])) $poolWhere[] = $dataInfo['field'];
} else {
}
// 删除字段成功后做相应处理
if ($resDel) {
// 删除明细表格字段数据
if (!empty($dataInfo['form_type']) && $dataInfo['form_type'] == 'detail_table') {
db('admin_field_extend')->where(['types' => $dataInfo['types'], 'field' => $dataInfo['field']])->delete();
}
// 删除相应模块扩展数据crm_leads_data、crm_customer_data、oa_examine ...
if (!empty($types)) db($types . '_data')->where('field', $dataInfo['field'])->delete();
}
// 删除失败
if (!$resDel) {
$delMessage[] = $dataInfo['name'] . ',删除失败';
}
}
@ -701,7 +944,7 @@ class Field extends Model
$types = 'crm_customer_pool';
}
if ($param['action'] == 'excel') {
$map['form_type'] = array('not in', ['file', 'form','deal_status']);//删除了过滤structure user字段类型数据 添加deal_status
$map['form_type'] = array('not in', ['file', 'form','user','structure', 'checkbox' ,'deal_status','position','location','handwriting_sign','date_interval','detail_table','desc_text','boolean_value']);//删除了过滤structure user字段类型数据 添加deal_status
} elseif ($param['action'] == 'index') {
$map['form_type'] = array('not in', ['file', 'form']);
}
@ -725,55 +968,45 @@ class Field extends Model
$field_list[$k]['writeStatus'] = $status['write'];
}
}
# 客户模块增加锁定状态、距进入公海天数字段
if (!$userLevel && $param['types'] == 'crm_customer' && !empty($grantData[$param['types']])) {
$poolDayStatus = getFieldGrantStatus('pool_day', $grantData[$param['types']]);
if (!empty($poolDayStatus['read'])) {
if ($param['types'] == 'crm_invoice') {
$field_list[] = [
'field' => 'pool_day',
'name' => '距进入公海天数',
'field' => 'check_status',
'name' => '审核状态',
'form_type' => 'text',
'writeStatus' => 0,
'fieldName' => 'pool_day'
'fieldName' => 'check_status'
];
}
$isLockStatus = getFieldGrantStatus('is_lock', $grantData[$param['types']]);
if (!empty($isLockStatus['read'])) {
$field_list[] = [
'field' => "is_lock",
'fieldName' => "is_lock",
'form_type' => "text",
'name' => "锁定状态",
'writeStatus' => 0
'field' => 'invoice_number',
'name' => '发票号码',
'form_type' => 'text',
'writeStatus' => 0,
'fieldName' => 'invoice_number'
];
}
}
if ($userLevel) {
$field_list[] = [
'field' => 'pool_day',
'name' => '距进入公海天数',
'form_type' => 'text',
'field' => 'real_invoice_date',
'name' => '实际开票日期',
'form_type' => 'date',
'writeStatus' => 0,
'fieldName' => 'pool_day'
'fieldName' => 'real_invoice_date'
];
$field_list[] = [
'field' => "is_lock",
'fieldName' => "is_lock",
'form_type' => "text",
'name' => "锁定状态",
'writeStatus' => 0
'field' => 'logistics_number',
'name' => '物流单号',
'form_type' => 'text',
'writeStatus' => 0,
'fieldName' => 'logistics_number'
];
}
} else {
$field_list = db('admin_field')->where($map)->where( 'is_hidden',0)->field('field,types,name,form_type,default_value,is_unique,is_null,input_tips,setting,is_hidden')->order($order)->select();
$fields = 'field_id,field,types,name,form_type,default_value,is_unique,is_null,input_tips,setting,is_hidden,form_position,precisions,options,style_percent,formAssistId';
$field_list = db('admin_field')->field($fields)->where($map)->where('is_hidden', 0)->order($order)->select();
// 获取X坐标值
$x = $this->getFormPositionXValue($types, $types_id);
# 详情页面增加负责人字段
if ($param['action'] == 'read' && !in_array($param['types'], ['crm_visit', 'crm_product','oa_examine'])) {
if ($param['action'] == 'read' && !in_array($param['types'], ['crm_visit', 'crm_product', 'oa_examine', 'crm_invoice'])) {
$field_list[] = [
'field' => 'owner_user_id',
'name' => '负责人',
@ -795,11 +1028,33 @@ class Field extends Model
'is_null' => 0,
'input_tips' => '',
'setting' => [],
'value' => []
'value' => [],
'style_percent' => 100,
'xaxis' => $x,
'yaxis' => 0,
'form_position' => $x . ',0'
];
}
// 商机下产品
if (in_array($param['types'], ['crm_business'])) {
$new_field_list[] = [
'field' => 'product',
'name' => '产品',
'form_type' => 'product',
'default_value' => '',
'is_unique' => 0,
'is_null' => 0,
'input_tips' => '',
'setting' => [],
'value' => [],
'style_percent' => 100,
'xaxis' => $x,
'yaxis' => 0,
'form_position' => $x . ',0'
];
}
//商机、合同下产品
if (in_array($param['types'], ['crm_business', 'crm_contract'])) {
// 合同下产品
if (in_array($param['types'], ['crm_contract'])) {
$new_field_list[] = [
'field' => 'product',
'name' => '产品',
@ -809,7 +1064,11 @@ class Field extends Model
'is_null' => 0,
'input_tips' => '',
'setting' => [],
'value' => []
'value' => [],
'style_percent' => 100,
'xaxis' => $x,
'yaxis' => 0,
'form_position' => $x . ',0'
];
}
# 产品基本信息增加负责人信息
@ -838,6 +1097,11 @@ class Field extends Model
$field_list[$k]['writeStatus'] = 0;
}
// 删除描述文字的name名称
if ($v['form_type'] == 'desc_text') {
$field_list[$k]['name'] = '';
}
//处理setting内容
$setting = [];
$default_value = $v['default_value'];
@ -918,6 +1182,11 @@ class Field extends Model
$value = $dataInfo[$v['field']] ? db('crm_contacts')->where(['contacts_id' => $dataInfo[$v['field']]])->field('contacts_id,name')->select() : [];
} elseif ($v['form_type'] == 'contract') {
$value = $dataInfo[$v['field']] ? db('crm_contract')->where(['contract_id' => $dataInfo[$v['field']]])->field('contract_id,num')->select() : [];
} elseif ($v['form_type'] == 'floatnumber' && $v['field'] == 'contract_money' && $types == 'crm_invoice') {
$contractMoney = db('crm_invoice')->alias('invoice')
->join('__CRM_CONTRACT__ contract', 'invoice.contract_id = contract.contract_id', 'LEFT')
->where('invoice.invoice_id', $param['action_id'])->value('contract.money');
$value = $contractMoney;
} elseif ($v['form_type'] == 'category') {
//产品类别
if ($param['action'] == 'read') {
@ -998,17 +1267,68 @@ class Field extends Model
$value = isset($dataInfo[$v['field']]) ? stringToArray($dataInfo[$v['field']]) : [];
} elseif ($v['form_type'] == 'date') {
$value = ($dataInfo[$v['field']] && $dataInfo[$v['field']] !== '0000-00-00') ? $dataInfo[$v['field']] : '';
} elseif ($v['form_type'] == 'boolean_value') {
// 布尔类型
$value = !empty($dataInfo[$v['field']]) ? (string)$dataInfo[$v['field']] : '0';
} elseif ($v['form_type'] == 'percent') {
// 百分数
$value = !empty($dataInfo[$v['field']]) ? $dataInfo[$v['field']] : '';
} elseif ($v['form_type'] == 'website') {
// 网址
$value = !empty($dataInfo[$v['field']]) ? $dataInfo[$v['field']] : '';
} elseif ($v['form_type'] == 'handwriting_sign') {
// 手写签名
$fileData = !empty($dataInfo[$v['field']]) ? db('admin_file')->where('file_id', $dataInfo[$v['field']])->find() : '';
if (!empty($fileData['file_path'])) $fileData['file_path'] = getFullPath($fileData['file_path']);
if (!empty($fileData['file_path_thumb'])) $fileData['file_path_thumb'] = getFullPath($fileData['file_path_thumb']);
$value = !empty($fileData) ? ['file_id' => $fileData['file_id'], 'url' => $fileData['file_path']] : "";
} elseif ($v['form_type'] == 'desc_text') {
// 描述文字
$value = !empty($dataInfo[$v['field']]) ? $dataInfo[$v['field']] : $v['default_value'];
} elseif (in_array($v['form_type'], ['position', 'location', 'date_interval', 'detail_table'])) {
// 地址、定位、日期区间、明细表格
$primaryKey = getPrimaryKeyName($param['types']);
$positionJson = !empty($dataInfo[$primaryKey]) ? db($param['types'] . '_data')->where([$primaryKey => $dataInfo[$primaryKey], 'field' => $v['field']])->value($param['types'] == 'oa_examine' ? 'value' : 'content') : '';
$positionData = !empty($positionJson) ? json_decode($positionJson, true) : '';
$value = $positionData;
if ($v['form_type'] == 'detail_table') {
$content = db('admin_field_extend')->where(['types' => $types, 'field' => $v['field']])->value('content');
$field_list[$k]['fieldExtendList'] = json_decode($content, true);
}
} else {
$value = isset($dataInfo[$v['field']]) ? $dataInfo[$v['field']] : '';
}
$field_list[$k]['setting'] = $setting;
$field_list[$k]['default_value'] = $default_value;
$field_list[$k]['value'] = $value;
$field_list[$k]['options'] = !empty($field_list[$k]['options']) ? $field_list[$k]['options'] : '';
$field_list[$k]['optionsData'] = !empty($field_list[$k]['options']) ? json_decode($field_list[$k]['options'], true) : '';
}
}
return array_values($field_list) ?: [];
}
private function getFormPositionXValue($types, $typesId)
{
$positionArray = db('admin_field')->where(['types' => $types, 'types_id' => $typesId, 'form_position' => [['neq', ''], ['not null'], 'AND']])->column('form_position');
if (!empty($positionArray)) {
$positionString = implode('-', $positionArray);
$positionString = str_replace(',0', '', $positionString);
$positionString = str_replace(',1', '', $positionString);
$positionString = str_replace(',2', '', $positionString);
$positionString = str_replace(',3', '', $positionString);
$positionArray = explode('-', $positionString);
return max($positionArray) + 1;
}
return 0;
}
/**
* [fieldSearch 获取自定义字段高级筛选信息]
* @param $types 分类
@ -1027,7 +1347,7 @@ class Field extends Model
$userModel = new \app\admin\model\User();
$user_id = $param['user_id'];
$map['types'] = ['in', ['', $types]];
$map['form_type'] = ['not in', ['file', 'form', 'business_status']];
$map['form_type'] = ['not in', ['file', 'form', 'business_status', 'detail_table', 'desc_text', 'handwriting_sign', 'date_interval']];
$map['is_hidden'] = 0;
$field_list = db('admin_field')
->where($map)
@ -1063,6 +1383,14 @@ class Field extends Model
'setting' => []
];
}
if (in_array($param['types'], ['crm_customer', 'crm_leads', 'crm_contacts', 'crm_business', 'crm_contract'])) {
$field_arr[] = [
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'setting' => []
];
}
if ($field_arr) $field_list = array_merge($field_list, $field_arr);
foreach ($field_list as $k => $v) {
//处理setting内容
@ -1183,9 +1511,10 @@ class Field extends Model
/**
* [getIndexField 列表展示字段]
* @param types 分类
* @param excel 导出使用
* @author Michael_xu
*/
public function getIndexFieldConfig($types, $user_id, $types_id = '')
public function getIndexFieldConfig($types, $user_id, $types_id = '',$excel='')
{
$userFieldModel = new \app\admin\model\UserField();
$userFieldData = $userFieldModel->getConfig($types, $user_id);
@ -1193,7 +1522,7 @@ class Field extends Model
$grantData = getFieldGrantData($user_id);
$userLevel = isSuperAdministrators($user_id);
$fieldList = $this->getFieldList($types, $types_id);
$fieldList = $this->getFieldList($types, $types_id,$excel);
$where = [];
if ($userFieldData) {
$fieldArr = [];
@ -1238,7 +1567,7 @@ class Field extends Model
* @author Ymob
* @datetime 2019-10-23 17:32:57
*/
public function getFieldList($types, $types_id = '')
public function getFieldList($types, $types_id = '', $excel = '')
{
$newTypes = $types;
$unField = ['-1'];
@ -1246,17 +1575,27 @@ class Field extends Model
$newTypes = 'crm_customer';
$unField = ['owner_user_id'];
}
$fieldArr = $this
->where([
if($excel=='excel'){
$where=[
'types' => ['IN', ['', $newTypes]],
'form_type' => ['not in', ['file', 'form']],
'form_type' => ['not in', ['file', 'form', 'deal_status','position','location','handwriting_sign','date_interval','detail_table','desc_text','boolean_value']],
'field' => ['not in', $unField],
'types_id' => ['eq', $types_id],
'is_hidden' => 0
])
->field(['field', 'name', 'form_type,is_hidden'])
->order('order_id asc')
];
}else{
$where=[
'types' => ['IN', ['', $newTypes]],
'form_type' => ['not in', ['file', 'form', 'desc_text', 'detail_table']],
'field' => ['not in', $unField],
'types_id' => ['eq', $types_id],
'is_hidden' => 0
];
}
$fieldArr = $this
->where($where)
->field(['field', 'name', 'form_type', 'is_hidden'])
->order('field_id', 'asc')
->select();
$res = [];
@ -1274,6 +1613,21 @@ class Field extends Model
}
}
if ($types == 'crm_customer') {
$res[] = [
'field' => 'pool_day',
'name' => '距进入公海天数',
'form_type' => 'text',
'is_hidden' => 0
];
$res[] = [
'field' => 'is_lock',
'name' => '锁定状态',
'form_type' => 'text',
'is_hidden' => 0
];
}
return array_column($res, null, 'field');
}
@ -1360,6 +1714,16 @@ class Field extends Model
}
$sysField = ['visit.visit_id', 'visit.owner_user_id', 'visit.status', 'visit.customer_id', 'visit.contract_id', 'visit.create_time', 'visit.update_time', 'visit.create_user_id', 'visit.visit_time', 'visit.contacts_id'];
break;
case 'crm_invoice' :
$newList = [];
foreach ($dataList as $k => $v) {
$newList[] = 'invoice.' . $v;
if ($v == 'contract_money') {
unset($newList[$k]);
}
}
$sysField = ['invoice.invoice_id', 'invoice.owner_user_id', 'invoice.invoice_status', 'invoice.invoice_number', 'invoice.invoice_type', 'invoice.check_status', 'invoice.customer_id', 'invoice.contract_id', 'invoice.create_user_id', 'invoice.flow_id', 'invoice.real_invoice_date', 'invoice.logistics_number'];
break;
}
$listArr = $sysField ? array_unique(array_merge($newList, $sysField)) : $dataList;
} else {
@ -1418,10 +1782,6 @@ class Field extends Model
case 'admin_user' :
$field_arr = \app\hrm\model\Userdet::getField();
break;
case 'crm_invoice':
$field_arr = $this->getInvoiceSearch();
break;
default :
$data = [];
$data['types'] = $types;
@ -1430,22 +1790,28 @@ class Field extends Model
$field_arr = $this->fieldSearch($data);
}
if ($types == 'crm_visit') {
foreach ($field_arr AS $key => $value) {
foreach ($field_arr as $key => $value) {
if ($value['name'] == '负责人') unset($field_arr[(int)$key]);
}
}
if ($types == 'crm_invoice') {
$field_arr = array_merge($field_arr, $this->getInvoiceSearch());
}
return $field_arr;
}
/**
* 自定义字段验重
* @param $field 字段名, $val 值, $id 排除当前数据验重, $types 需要查询的模块名
* @return
* @author
*
* @param $field string 字段名称
* @param $val array|string 字段值
* @param $id int 数据id
* @param $types string 模块类型
* @return bool
*/
public function getValidate($field, $val, $id, $types)
{
$val = trim($val);
$val = is_array($val) ? $val : trim($val);
if (!$val) {
$this->error = '验证内容不能为空';
return false;
@ -1465,6 +1831,23 @@ class Field extends Model
return false;
}
// 人员、部门、文件、手写签名、描述文字、多选、明细表格跳过验证唯一性
if (in_array($field_info['form_type'], ['user', 'structure', 'file', 'handwriting_sign', 'desc_text', 'checkbox', 'detail_table'])) return true;
// 前端传来的定位数据有问题,在提交数据时做验证
if ($field_info['form_type'] == 'location') return true;
// 处理日期区间类型数据
if ($field_info['form_type'] == 'date_interval') {
$val = implode('_', $val);
}
// 处理地址类型数据
if ($field_info['form_type'] == 'position') {
$positionNames = array_column($val, 'name');
$val = implode(',', $positionNames);
}
$dataModel = '';
switch ($types) {
case 'crm_leads' :
@ -1488,14 +1871,19 @@ class Field extends Model
case 'crm_receivables' :
$dataModel = new \app\crm\model\Receivables();
break;
case 'crm_invoice' :
$dataModel = new \app\crm\model\Invoice();
break;
case 'oa_examine' :
$dataModel = db('oa_examine');
break;
}
$where = [];
$where[$field] = ['eq', $val];
if ($id) {
//为编辑时的验重
$where[$dataModel->getpk()] = ['neq', $id];
}
// 编辑时的验重
if ($id) $where[$dataModel->getpk()] = ['neq', $id];
if ($types == 'crm_product') {
$where['delete_user_id'] = 0;
}
@ -1566,7 +1954,7 @@ class Field extends Model
$val = db('crm_customer')->where(['customer_id' => $val])->value('name');
break;
case 'contract' :
$val = db('crm_contract')->where(['customer_id' => $val])->value('num');
$val = db('crm_contract')->where(['contract_id' => $val])->value('num');
break;
case 'business' :
$val = db('crm_business')->where(['business_id' => $val])->value('name');
@ -1683,16 +2071,16 @@ class Field extends Model
* @param string $types 模块类型
* @param string $action 行为
* @param array $data 字段数据
* @author fanqi
* @since 2021-04-06
* @return array
* @since 2021-04-06
* @author fanqi
*/
public function resetField($userId, $types, $action, $data)
{
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($data AS $key => $value) {
foreach ($data as $key => $value) {
# 处理字段授权
if (!$userLevel && !empty($grantData[$types])) {
$status = getFieldGrantStatus($value['field'], $grantData[$types]);
@ -1742,10 +2130,6 @@ class Field extends Model
$data[$key]['fieldName'] = $value['field'];
}
if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field'], ['create_user_id', 'owner_user_id'])) {
$data[$key]['fieldName'] = $value['field'] . '_name';
}
# 详情中不显示产品类别、回款期数
if ($action == 'read' && in_array($value['field'], ['category_id'])) {
unset($data[(int)$key]);
@ -1766,7 +2150,7 @@ class Field extends Model
{
$poolFields = db('crm_customer_pool_field_setting')->field(['field_name AS field', 'form_type', 'name'])->where(['pool_id' => $poolId, 'is_hidden' => 0])->select();
foreach ($poolFields AS $key => $value) {
foreach ($poolFields as $key => $value) {
# 字段值
$poolFields[$key]['value'] = !empty($dataInfo[$value['field']]) ? $dataInfo[$value['field']] : '';
@ -1806,12 +2190,11 @@ class Field extends Model
private function getInvoiceSearch()
{
return [
['field' => 'invoice_number', 'form_type' => 'text', 'setting' => [], 'name' => '发票号码'],
// ['field' => 'invoice_number', 'form_type' => 'text', 'setting' => [], 'name' => '发票号码'],
['field' => 'real_invoice_date', 'form_type' => 'datetime', 'setting' => [], 'name' => '实际开票日期'],
['field' => 'logistics_number', 'form_type' => 'text', 'setting' => [], 'name' => '物流单号'],
['field' => 'invoice_status', 'form_type' => 'select', 'setting' => ['未开票', '已开票'], 'name' => '开票状态'],
['field' => 'check_status', 'form_type' => 'select', 'setting' => ['待审核', '审核中', '审核通过', '审核未通过', '撤回'], 'name' => '审核状态'],
['field' => 'owner_user_id', 'form_type' => 'user', 'setting' => [], 'name' => '负责人']
];
}
@ -1840,4 +2223,34 @@ class Field extends Model
return $parentIds;
}
/**
* 设置明细表格数据
*
* @param string $types 模块类型crm_leads crm_customer ...
* @param string $field 字段名称
* @param array $data 明细表单中的字段数据
* @return bool
* @since 2021-04-27
* @author fanqi
*/
private function setDetailTableData($types, $field, $data)
{
$id = db('admin_field_extend')->where(['field' => $field, 'types' => $types])->value('id');
foreach ($data as $k1 => $v1) {
if (empty($v1['field'])) $data[$k1]['field'] = $this->createField($types, $types == 'oa_examine' ? 'oa_' : 'crm_');
$data[$k1]['default_value'] = !empty($v1['default_value']) ? $v1['default_value'] : '';
}
if (!empty($id)) {
return db('admin_field_extend')->where('id', $id)->update(['content' => json_encode($data, JSON_NUMERIC_CHECK)]);
}
if (empty($id)) {
return db('admin_field_extend')->insert(['types' => $types, 'field' => $field, 'content' => json_encode($data, JSON_NUMERIC_CHECK), 'create_time' => time()]);
}
return false;
}
}

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

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

@ -150,7 +150,6 @@ class Scene extends Common
{
$where = [];
$where['scene_id'] = $id;
// $where['user_id'] = [['=',$user_id],['=',0],'or'];
$data = db('admin_scene')->where($where)->find();
if (!$types) {
$types = $data['types'] ? : '';
@ -407,7 +406,7 @@ class Scene extends Common
$where['types'] = $types;
$where['user_id'] = $user_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';
} else {
$resData = db('admin_scene')->where(['scene_id' => $scene_id])->find();
@ -429,10 +428,6 @@ class Scene extends Common
*/
public function getByData($types, $bydata, $user_id)
{
// print_r($types . '--');
// print_r($bydata . '--');
// print_r($user_id);
// exit;
$map = [];
$auth_user_ids = [];
$part_user_ids = [];
@ -448,7 +443,7 @@ class Scene extends Common
break;
case 'sub' :
# 下属负责的
$auth_user_ids = getSubUserId(false) ? : ['-1'];
$auth_user_ids = getSubUserId(false, 0, $user_id) ? : ['-1'];
break;
case 'all' :
# 全部
@ -456,7 +451,7 @@ class Scene extends Common
break;
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;
case 'pool' :
# 今日进入公海的客户
@ -465,16 +460,28 @@ class Scene extends Common
break;
case 'win_business' :
# 赢单的商机
$map['is_end'] = ['condition' => 'eq', 'value' => 1];
$map['is_end'] = ['condition' => 'is', 'value' => [1], 'form_type' => 'text'];
break;
case 'fail_business' :
# 输单的商机
$map['is_end'] = ['condition' => 'eq', 'value' => 2];
$map['is_end'] = ['condition' => 'is', 'value' => [2], 'form_type' => 'text'];
break;
case 'star' :
$where = $this->getStarParam($types, $user_id);
if (!empty($where)) $map = $where;
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 :
# 全部
$auth_user_ids = '';
@ -483,12 +490,12 @@ class Scene extends Common
$auth_user_ids = $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) {
$map['ro_user_id'] = $part_user_ids ? : '';
$map['rw_user_id'] = $part_user_ids ? : '';
$map['ro_user_id'] = $part_user_ids;
$map['rw_user_id'] = $part_user_ids;
}
return $map;
@ -505,17 +512,11 @@ class Scene extends Common
*/
public function getStarParam($types, $user_id)
{
$where = [];
$result = [];
$data = Db::name('crm_star')->field(['target_id'])->where(['user_id' => $user_id, 'type' => 'crm_' . $types])->select();
$primaryKey = getPrimaryKeyName('crm_' . $types);
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;
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;
$where[$primaryKey] = ['condition' => 'in', 'value' => !empty($targetIds) ? $targetIds : [-1], 'form_type' => 'user'];
return $where;
}

@ -64,7 +64,7 @@ class Structure extends Common
return $det;
}
public function delStrById($id)
public function delStrById($id,$userId)
{
if (!$id) {
$this->error = '删除失败';
@ -90,11 +90,9 @@ class Structure extends Common
$this->error = '删除失败';
return false;
} else {
$apiCommon = new ApiCommon();
$userInfo = $apiCommon->userInfo;
$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;
}
}

@ -48,7 +48,7 @@ class User extends Common
'name' => '手机号(登录名)',
'form_type' => 'mobile',
'is_null' => 1,
// 'is_unique' => 1 //guogaobo 导入此字段会进行验重查询调用修改用户方法
'is_unique' => 1
],
[
'field' => 'password',
@ -279,30 +279,32 @@ class User extends Common
$this->error = '手机号已存在';
return false;
}
if(db('admin_user')->where('realname',$param['realname'])->find()){
$this->error = '姓名已存在';
return false;
}
} else {
if (empty($param['group_id']) || !is_array($param['group_id'])) {
$this->error = '请至少勾选一个用户组';
return false;
}
}
$nameData = db('admin_user')->where('realname', 'like', '%' . $param['realname'] . '%')->column('realname');
if (in_array($param['realname'], $nameData)) {
for ($j = 1; $j < 100; $j++) {
$name=$param['realname'].$j;
$name = $param['realname'] . '-' . $j;
if (in_array($name, $nameData)) {
continue;
} else {
$name= $param['realname'].$j;
$name = $param['realname'] . '-' . $j;
break;
}
}
$param['realname'] = $name;
}
// if(db('admin_user')->where('realname',$param['realname'])->find()){
// $this->error = '姓名已存在';
// return false;
// }
} else {
$param['realname']= $param['realname'];
if (empty($param['group_id']) || !is_array($param['group_id'])) {
$this->error = '请至少勾选一个用户组';
return false;
}
}
$userId=$param['userId'];
unset($param['userId']);
// 验证
$validate = validate($this->name);
if (!$validate->check($param)) {
@ -322,6 +324,7 @@ class User extends Common
$param['password'] = user_md5($password, $salt, $param['username']);
$param['type'] = 1;
$param['mobile'] = $param['username'];
$this->data($param)->allowField(true)->isUpdate(false)->save();
$user_id = (int)$this->getLastInsId();
//员工档案
@ -343,14 +346,13 @@ class User extends Common
if ($userGroups) {
Db::name('admin_access')->insertAll($userGroups);
}
$this->commit();
$param['user_id'] = $data['user_id'];
$resSync = $syncModel->syncData($param);
# 添加记录
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'admin_user','employee', $user_id, 'save', $param['realname'], '', '','新增用户:'.$param['realname']);
if (request()->action() != 'import') {
SystemActionLog($userId, 'admin_user', 'employee', $user_id, 'save', $param['realname'], '', '', '新增用户:' . $param['realname']);
}
return true;
} catch (\Exception $e) {
$this->rollback();
@ -394,8 +396,6 @@ class User extends Common
*/
public function updateDataById($param, $id)
{
$user=new ApiCommon();
$user_id=$user->userInfo;
if ($param['user_id']) {
//修改个人信息
$data['email'] = $param['email'];
@ -406,12 +406,25 @@ class User extends Common
$this->error = '手机号已存在';
return false;
}
$nameData = db('admin_user')->where(['realname' => ['like', '%' . $param['realname'] . '%']])->column('realname');
if (in_array($param['realname'], $nameData)) {
for ($j = 1; $j < 100; $j++) {
$name = $param['realname'] . '-' . $j;
if (in_array($name, $nameData)) {
continue;
} else {
$name = $param['realname'] . '-' . $j;
break;
}
}
$param['realname'] = $name;
}
Db::name('HrmUserDet')->where(['user_id' => $param['user_id']])->update($data);
$data['realname'] = $param['realname'];
$data['post'] = $param['post'];
$flag = $this->where(['id' => $param['user_id']])->update($data);
if ($flag == 0 || $flag == 1) {
SystemActionLog($user_id['id'],'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '','编辑了:'.$param['realname']);
SystemActionLog($param['user_id'], 'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '', '编辑了:' . $param['realname']);
return true;
} else {
$this->error = '保存失败';
@ -429,6 +442,25 @@ class User extends Common
$this->error = '暂无此数据';
return false;
}
if(request()->action() == 'import'){
// $param['realname'] = $checkData['realname'];
$nameData = db('admin_user')->where('realname', 'like', '%' . $param['realname'] . '%')->column('realname');
if (in_array($param['realname'], $nameData)) {
for ($j = 1; $j < 100; $j++) {
$name = $param['realname'] . '-' . $j;
if (in_array($name, $nameData)) {
continue;
} else {
$name = $param['realname'] . '-' . $j;
break;
}
}
$param['realname'] = $name;
}
$param['userId']=!empty($param['create_user_id'])?:$param['owner_user_id'];
unset($param['owner_user_id']);
unset($param['create_user_id']);
}
if (request()->action() != 'import') {
if (empty($param['group_id'])) {
$this->error = '请至少勾选一个用户组';
@ -448,7 +480,6 @@ class User extends Common
$this->error = '手机号已存在';
return false;
}
$this->startTrans();
try {
$accessModel = model('Access');
@ -460,10 +491,11 @@ class User extends Common
$salt = $userInfo['salt'];
$param['password'] = user_md5($param['password'], $salt, $param['username']);
}
$this->allowField(true)->save($param, ['id' => $id]);
$this->commit();
Cache::rm('user_info' . $id);
SystemActionLog($user_id['id'], 'admin_user','employee', $id, 'update', $userInfo['realname'], '', '','编辑了:'.$userInfo['realname']);
SystemActionLog($param['userId'], 'admin_user', 'employee', $id, 'update', $userInfo['realname'], '', '', '编辑了:' . $userInfo['realname']);
// $data['mobile'] = $param['username'];
$data['email'] = $param['email'];
$data['sex'] = $param['sex'];
@ -600,7 +632,7 @@ class User extends Common
* 修改密码
* @param array $param [description]
*/
public function updatePaw($userInfo, $old_pwd, $new_pwd)
public function updatePaw($userInfo, $old_pwd, $new_pwd,$userId)
{
if (!$old_pwd) {
$this->error = '请输入旧密码';
@ -638,9 +670,7 @@ class User extends Common
$userInfo = $this->where('id', $userInfo['id'])->find();
# 添加记录
$user=new ApiCommon();
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_user','employee', $userInfo['id'], 'update', $userInfo['realname'], '', '','重置了密码:'.$userInfo['realname']);
SystemActionLog($userId, 'admin_user', 'employee', $userInfo['id'], 'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
// 重新设置缓存
session_start();
$cache['userInfo'] = $userInfo;
@ -659,8 +689,6 @@ class User extends Common
{
$syncModel = new \app\admin\model\Sync();
$flag = true;
$userInfo = new ApiCommon();
$user_id=$userInfo->userInfo;
foreach ($param['id'] as $value) {
$password = '';
$userInfo = db('admin_user')->where(['id' => $value])->find();
@ -678,9 +706,7 @@ class User extends Common
foreach ($param['id'] as $v) {
$userInfo = db('admin_user')->where(['id' => $v])->find();
# 添加记录
$user=new ApiCommon();
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_user','employee', $v, 'update',$userInfo['realname'],'', '', '重置了密码:'.$userInfo['realname']);
SystemActionLog($param['user_id'], 'admin_user', 'employee', $v, 'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
}
return $flag;
} else {
@ -725,6 +751,10 @@ class User extends Common
foreach ($rules as $k => $v) {
$newRuleIds[] = $v['id'];
$rules[$k]['name'] = strtolower($v['name']);
if ($v['name'] == 'market') {
$rules[$k]['name'] = 'activityForm';
}
}
//菜单管理(弃用)
// $menuMap['status'] = 1;
@ -770,7 +800,7 @@ class User extends Common
}
# 任务审批
if (in_array('taskExamine', $adminConfig)) {
$authList['oa']['taskExamine'] = (Object)[];
$authList['oa']['taskExamine'] = (object)[];
}
# 项目
if (in_array('work', $adminConfig)) {
@ -781,18 +811,19 @@ class User extends Common
}
# 日志
if (in_array('log', $adminConfig)) {
$authList['oa']['log'] = (Object)[];
$authList['oa']['log'] = (object)[];
}
# 日历
if (in_array('calendar', $adminConfig)) {
$authList['oa']['calendar'] = (Object)[];
$authList['oa']['calendar'] = (object)[];
}
# 公海权限
$structureId = db('admin_user')->where('id', $u_id)->value('structure_id');
$poolStatus = db('crm_customer_pool')->whereLike('admin_user_ids', '%,' . $u_id . ',%')
->whereOr('user_ids', 'like', '%,' . $u_id . ',%')
->whereOr('department_ids', 'like', '%,' . $structureId . ',%')
->value('pool_id');
$poolStatus = db('crm_customer_pool')->where('status', 1)->where(function ($requery) use ($u_id, $structureId, $adminTypes) {
if (!in_array(1, $adminTypes)) $requery->whereLike('admin_user_ids', '%,' . $u_id . ',%');
if (!in_array(1, $adminTypes)) $requery->whereOr('user_ids', 'like', '%,' . $u_id . ',%');
if (!in_array(1, $adminTypes)) $requery->whereOr('department_ids', 'like', '%,' . $structureId . ',%');
})->value('pool_id');
if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true];
$ret['authList'] = $this->resetAuthorityFiled($authList);
@ -828,6 +859,13 @@ class User extends Common
# 发票
if (isset($authList['crm']['invoice']['setinvoice'])) {
$authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice'];
$authList['crm']['invoice']['resetInvoiceStatus'] = $authList['crm']['invoice']['resetinvoicestatus'];
unset($authList['crm']['invoice']['resetinvoicestatus']);
}
# 市场活动
if (isset($authList['crm']['marketing']['updatestatus'])) {
$authList['crm']['marketing']['updateStatus'] = $authList['crm']['marketing']['updatestatus'];
unset($authList['crm']['marketing']['updatestatus']);
}
# 发票抬头权限
if (!empty($authList['crm']['invoice']['index'])) {
@ -930,8 +968,8 @@ class User extends Common
'work.update', 'permission.update'
];
foreach ($authList['manage'] AS $key1 => $value1) {
foreach ($value1 AS $key2 => $value2) {
foreach ($authList['manage'] as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
if (in_array($key1 . '.' . $key2, $adminAuth)) {
$authList['manage']['other_rule'] = [
'setwelcome' => true,
@ -948,10 +986,10 @@ class User extends Common
# 通讯录
$authList['email'] = (Object)[];
$authList['hrm'] = (Object)[];
$authList['jxc'] = (Object)[];
$authList['knowledge'] = (Object)[];
$authList['email'] = (object)[];
$authList['hrm'] = (object)[];
$authList['jxc'] = (object)[];
$authList['knowledge'] = (object)[];
return $authList;
}
@ -1147,7 +1185,8 @@ class User extends Common
* @param
* @return
*/
public function getUserByPer($m = '', $c = '', $a = ''){
public function getUserByPer($m = '', $c = '', $a = '')
{
$request = Request::instance();
$header = $request->header();
$authKey = $header['authkey'];
@ -1240,8 +1279,8 @@ class User extends Common
/**
* [getUserThree 员工第三方扩展信息]
* @param key 分类
* @author Michael_xu
* @return [array]
* @author Michael_xu
*/
public function getUserThree($key, $user_id)
{
@ -1299,7 +1338,8 @@ class User extends Common
* @param $param
* @return array
*/
public function sortList($param){
public function sortList($param)
{
$list = Db::name('admin_sort')->where('user_id', $param['user_id'])->field('value')->find();
$list = unserialize($list['value']);
return $list ?: [];
@ -1309,7 +1349,8 @@ class User extends Common
* 修改顶部菜单显示
* @param $param
*/
public function updateSort($param){
public function updateSort($param)
{
$list = Db::name('admin_sort')->where('user_id', $param['user_id'])->field('value')->select();
if ($list) {
$data = Db::name('admin_sort')->where('user_id', $param['user_id'])->update(['value' => serialize($param['value'])]);
@ -1346,11 +1387,11 @@ class User extends Common
Db::name('admin_access')->whereIn('user_id', $userIds)->delete();
# 重新设置员工角色
foreach ($userIds AS $key => $value) {
foreach ($userIds as $key => $value) {
# 默认跳过超级管理员
if ($value == 1) continue;
foreach ($groupIds AS $k => $v) {
foreach ($groupIds as $k => $v) {
$userGroup[] = [
'user_id' => $value,
'group_id' => $v
@ -1361,11 +1402,9 @@ class User extends Common
if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);
Db::commit();
$user= new ApiCommon();
$user_id=$user->userInfo;
foreach ($userIds AS $key => $value) {
foreach ($userIds as $key => $value) {
$userInfo = Db::name('admin_user')->where('id', $value)->find();
SystemActionLog($user_id['id'], 'admin_user','employee', $value, 'update', $userInfo['realname'], '', '','编辑员工角色:'.$userInfo['realname']);
SystemActionLog($param['userId'], 'admin_user', 'employee', $value, 'update', $userInfo['realname'], '', '', '编辑员工角色:' . $userInfo['realname']);
}
return true;
} catch (\Exception $e) {
@ -1410,7 +1449,8 @@ class User extends Common
* @version 1.0 版本号
* @since 2021/4/24 0024 14:42
*/
public function countNumOfUser(){
public function countNumOfUser()
{
//全部
// $data['allUserCount']=$this->count();
// //未激活

@ -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>
<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>2、在config目录下创建database.php文件</p>
<p>3、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>
<p>2、修改config目录下database_template.php文件的数据库连接信息</p>
<p>3、最后将database_template.php重名为database.php</p>
</div>
</div>
</div>

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

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

@ -100,7 +100,7 @@ class PoolCommand extends Command
'into_pool_time' => time()
]);
}
$this->updateInfo($ruleList,$customerWhere);
# 删除联系人的负责人
Db::name('crm_contacts')->whereIn('customer_id', $customerWhere)->update(['owner_user_id' => '']);
@ -113,6 +113,8 @@ class PoolCommand extends Command
});
}
protected function execute(Input $input, Output $output)
{
# 动态修改运行时参数
@ -133,16 +135,16 @@ class PoolCommand extends Command
* 整理修改客户数据的条件
*
* @param array $customerIds 客户ID
* @author fanqi
* @since 2021-04-01
* @return array
* @since 2021-04-01
* @author fanqi
*/
private function getCustomerQueryCondition($customerIds)
{
$result = [];
foreach ($customerIds AS $k1 => $v1) {
foreach ($v1 AS $k2 => $v2) {
foreach ($customerIds as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
$result[] = $v2;
}
}
@ -154,9 +156,9 @@ class PoolCommand extends Command
* 客户公海关联数据
*
* @param array $customerIds 客户ID
* @author fanqi
* @since 2021-04-01
* @return array
* @since 2021-04-01
* @author fanqi
*/
private function getCustomerPoolRelationData($customerIds)
{
@ -165,9 +167,9 @@ class PoolCommand extends Command
# 用于排重
$repeat = [];
foreach ($customerIds AS $k1 => $v1) {
foreach ($customerIds as $k1 => $v1) {
$customerArray = array_unique($v1);
foreach ($customerArray AS $k2 => $v2) {
foreach ($customerArray as $k2 => $v2) {
if (!empty($repeat[$k1][$v2])) continue;
$result[] = [
@ -186,17 +188,17 @@ class PoolCommand extends Command
* 获取符合公海条件的客户
*
* @param array $rules 公海规则数据
* @author fanqi
* @since 2021-04-01
* @return array
* @since 2021-04-01
* @author fanqi
*/
private function getQueryCondition($rules)
{
$result = [];
foreach ($rules AS $k => $v) {
if (!isset($result[$v['pool_id']])) $result[$v['pool_id']] = [];
foreach ($rules as $k => $v) {
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'] == 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']));
@ -212,9 +214,9 @@ class PoolCommand extends Command
* @param Json $levels 级别数据
* @param int $dealStatus 是否排除成交用户1 排除0 不排除
* @param int $businessStatus 是否排除有商机用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array
* @since 2021-04-01
* @author fanqi
*/
private function getFollowUpQueryResult($type, $levels, $dealStatus, $businessStatus)
{
@ -226,7 +228,7 @@ class PoolCommand extends Command
# 所有用户,不区分级别
if ($type == 1) {
foreach ($levels AS $k1 => $v1) {
foreach ($levels as $k1 => $v1) {
if (!empty($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`)))";
@ -236,7 +238,7 @@ class PoolCommand extends Command
# 根据用户级别设置条件
if ($type == 2) {
foreach ($levels AS $k1 => $v1) {
foreach ($levels as $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = (time() - 24 * 60 * 60 * $v1['limit_day']);
if ($k1 == 0) {
@ -275,9 +277,9 @@ class PoolCommand extends Command
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据
* @param int $dealStatus 是否排除成交用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array|false|string
* @since 2021-04-01
* @author fanqi
*/
private function getBusinessQueryResult($type, $levels, $dealStatus)
{
@ -289,7 +291,7 @@ class PoolCommand extends Command
# 所有用户,不区分级别
if ($type == 1) {
foreach ($levels AS $k1 => $v1) {
foreach ($levels as $k1 => $v1) {
if (!empty($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`) )";
@ -299,7 +301,7 @@ class PoolCommand extends Command
# 根据用户级别设置条件
if ($type == 2) {
foreach ($levels AS $k1 => $v1) {
foreach ($levels as $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day'];
if ($k1 == 0) {
@ -335,9 +337,9 @@ class PoolCommand extends Command
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据
* @param int $businessStatus 是否排除有商机用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array|false|string
* @since 2021-04-01
* @author fanqi
*/
private function getDealQueryResult($type, $levels, $businessStatus)
{
@ -349,7 +351,7 @@ class PoolCommand extends Command
# 所有用户,不区分级别
if ($type == 1) {
foreach ($levels AS $k1 => $v1) {
foreach ($levels as $k1 => $v1) {
if (!empty($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`) )";
@ -359,7 +361,7 @@ class PoolCommand extends Command
# 根据用户级别设置条件
if ($type == 2) {
foreach ($levels AS $k1 => $v1) {
foreach ($levels as $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day'];
if ($k1 == 0) {
@ -394,15 +396,15 @@ class PoolCommand extends Command
* 获取公海规则最小数字(最快进入公海天数)
*
* @param $data
* @author fanqi
* @since 2021-04-19
* @return int
* @since 2021-04-19
* @author fanqi
*/
private function getMinDay($data)
{
$number = 1;
foreach ($data AS $k1 => $v1) {
foreach ($data as $k1 => $v1) {
if (empty($number) || $v1['limit_day'] < $number) $number = $v1['limit_day'];
}

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

@ -6,7 +6,6 @@ use think\Db;
/**
* 处理相关团队
* @author
* @param types 类型
* @param types 类型ID
* @param type 权限 1只读2读写
@ -14,8 +13,9 @@ use think\Db;
* @param is_del 1 移除操作, 2编辑操作, 3添加操作
* @param owner_user_id 操作人
* @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();
$authIds = [];
@ -40,13 +40,22 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
$data_name = 'contract_id';
$authIds = $userModel->getUserByPer('crm', 'contract', 'teamsave');
break;
case 'crm_receivables' :
$data_name = 'receivables_id';
$authIds = $userModel->getUserByPer('crm', 'receivables', 'teamsave');
break;
}
if (!is_array($types_id) && $types_id) {
$types_id = [$types_id];
}
$errorMessage = [];
foreach ($types_id as $k => $v) {
if ($types == 'crm_receivables') {
$resData = db($types)->where([$data_name => $v])->field('number as name,owner_user_id,rw_user_id,ro_user_id')->find();
} else {
$resData = db($types)->where([$data_name => $v])->field('name,owner_user_id,rw_user_id,ro_user_id')->find();
}
if (!in_array($resData['owner_user_id'], $authIds) && $resData['owner_user_id'] && $is_module !== 1) {
$errorMessage[] = $resData['name'] . '处理团队操作失败,错误原因:无权限';
continue;
@ -100,8 +109,26 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
}
}
}
$res = !empty($param['user_id']) ?$param['user_id'] :[];
$types_data = ['crm_leads' => 6, 'crm_customer' => 1, 'crm_contacts' => 2, 'crm_business' => 3, 'crm_contract' => 4, 'crm_receivables' => 5];
$target_time = $param['target_time'];
$request = [];
foreach ($res as $val) {
$request['team_user_id'] = $val;
$request['target_time'] = $target_time;
$request['auth'] = $type;
$request['target_id'] = $v;
$dataInfo = db('crm_team')->where(['target_id' => $v, 'types' => $types_data[$types],'team_user_id'=>$val])->find();
if ($dataInfo) {
$res = db('crm_team')->where(['target_id' => $v, 'types' => $types_data[$types],'team_user_id'=>$val])->update($request);
} else {
$request['types'] = $types_data[$types];
$res = db('crm_team')->insert($request);
}
}
$upData = db($types)->where([$data_name => $v])->update($data);
if (!$upData) {
if (!$upData && !$res) {
$errorMessage[] = $resData['name'] . '处理团队操作失败';
}
}
@ -129,3 +156,56 @@ function getmonthByTime($start_time, $end_time)
}
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
* @date 2020-12-09
*/
namespace app\crm\controller;
use app\admin\controller\ApiCommon;
@ -137,12 +138,13 @@ class Activity extends ApiCommon
*/
public function delete(ActivityLogic $activityLogic)
{
$userInfo = $this->userInfo;
if (!checkPerByAction('crm', 'activity', 'delete')) {
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' => '操作成功!']);
}
@ -194,18 +196,20 @@ class Activity extends ApiCommon
return resultArray(['data' => $data]);
}
/**
* 导入模板下载
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/10 0010 16:01
*/
public function excelDownload($save_path = ''){
public function excelDownload($save_path = '')
{
$param = $this->param;
$excelModel = new \app\admin\model\Excel();
$field_list = $this->importData($param);
$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 版本号
* @since 2021/4/13 0013 11:15
*/
public function importData($param){
switch ($param['label']){
public function importData($param)
{
$field_list = [];
switch ($param['crmType']) {
case 1 :
$field = [
'2' => [
'name' => '所属线索',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'datetime',
'form_type' => 'leads_id',
'is_null' => 1,
]
];
$name = '所属线索';
break;
case 3:
$field = [
'2' => [
'name' => '所属联系人',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'datetime',
'form_type' => 'contacts_id',
'is_null' => 1,
],
];
$name = '所属联系人';
break;
case 5:
$field = [
'2' => [
'name' => '所属商机',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'form_type' => 'business_id',
'is_null' => 1,
]
],
];
$name = '所属商机';
break;
case 6:
$field = [
'2' => [
'name' => '所属合同',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'form_type' => 'contract_id',
'is_null' => 1,
],
];
$name = '所属合同';
break;
case 2:
$field_list = [
'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,
],
$field = [
'2' => [
'name' => '所属客户',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'form_type' => 'customer_id',
'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;
}
$fields = [
'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' => [
'name' => '所属111',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'is_null' => 1,
],
'3' => [
'name' => '跟进时间-例:2020-2-1',
'field' => 'next_time',
'types' => 'log',
'form_type' => 'datetime',
],
'4' => [
'3' => [
'name' => '跟进方式',
'field' => 'category',
'types' => 'log',
'form_type' => 'text',
'form_type' => 'select',
'setting' =>
array
(
0 => "见面拜访",
1 => "电话",
2 => "短信",
3 => "邮件",
4 => "微信"
)
],
];
// 导入的字段列表
if(!empty($param['down'])){
$field_list = [
'0' => ['name' => '所属客户', 'field' => 'activity_type_name'],
if ($param['is_excel']) {
$field_lists = [
'0' => ['name' => $name, 'field' => 'activity_type_name'],
'1' => ['name' => '跟进内容', 'field' => 'content'],
'2' => ['name' => '创建人', 'field' => 'create_user_name'],
'3' => ['name' => '跟进时间', 'field' => 'create_time'],
'4' => ['name' => '跟进方式', 'field' => 'category'],
'5' => ['name' => '下次联系时间', 'field' => 'next_time'],
'6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
'7' => ['name' => '相关商机', 'field' => 'business_ids'],
'5' => ['name' => '下次联系时间', 'field' => 'next_time']
];
if ($param['crmType'] == 2) {
$fields = [
'6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
'7' => ['name' => '相关商机', 'field' => 'business_ids'],];
$field_list = array_merge($field_lists, $fields);
} else {
if(empty($field_list)){
$field_list=array_merge($fields,$field);
$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;
}
/**
* 导入数据
*
@ -374,12 +360,15 @@ class Activity extends ApiCommon
* @version 1.0 版本号
* @since 2021/4/10 0010 16:27
*/
public function excelImport(){
public function excelImport()
{
$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();
$file = request()->file('file');
switch ($param['label']){
switch ($param['crmType']) {
case 1 :
$param['types'] = 'crm_leads';
$param['activity_type'] = 1;
@ -417,14 +406,17 @@ class Activity extends ApiCommon
* @version 1.0 版本号
* @since 2021/4/13 0013 11:32
*/
public function excelExport(){
public function excelExport()
{
$activityLogic = new ActivityLogic();
$indexLogic = new \app\crm\logic\IndexLogic();
$userInfo = $this->userInfo;
$param = $this->param;
$param['action'] = 'crm_activity';
$param['is_excel'] = 1;
$param['id'] = $userInfo['id'];
$list = $indexLogic->activityList($param);
// $param['down']=1;
$field_list = $this->importData($param);
$data = $activityLogic->excelExport($field_list, $list);
return $data;

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

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

@ -175,11 +175,14 @@ class Contacts extends ApiCommon
$delIds[] = $v;
}
}
$dataInfo = $contactsModel->getDataById($v);
if ($delIds) {
$data = $contactsModel->delDatas($delIds);
if (!$data) {
return resultArray(['error' => $contactsModel->getError()]);
}
// 删除联系人扩展数据
db('crm_contacts_data')->whereIn('contacts_id', $delIds)->delete();
//删除跟进记录
$recordModel->delDataByTypes(3,$delIds);
//删除关联附件
@ -188,8 +191,8 @@ class Contacts extends ApiCommon
$actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
$userInfo = $this->userInfo;
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) {
@ -270,6 +273,7 @@ class Contacts extends ApiCommon
*/
public function excelDownload($save_path = '')
{
# 下次升级
$param = $this->param;
$userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel();
@ -279,35 +283,22 @@ class Contacts extends ApiCommon
$fieldParam['types'] = 'crm_contacts';
$fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam);
$res = $excelModel->excelImportDownload($field_list, 'crm_contacts', $save_path);
# 下次升级
// $param = $this->param;
// $userInfo = $this->userInfo;
// $excelModel = new \app\admin\model\Excel();
//
// // 导出的字段列表
// $fieldModel = new \app\admin\model\Field();
// $fieldParam['types'] = 'crm_contacts';
// $fieldParam['action'] = 'excel';
// $field_list = $fieldModel->field($fieldParam);
// $array=[];
// $field=[1=>[
// 'field'=>'owner_user_id',
// 'types'=>'crm_contacts',
// '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);
// $res = $excelModel->excelImportDownload($array, 'crm_contacts', $save_path);
$array=[];
$field=[1=>[
'field'=>'owner_user_id',
'types'=>'crm_contacts',
'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_contacts', $save_path);
}
/**
@ -331,7 +322,7 @@ class Contacts extends ApiCommon
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$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');
@ -534,6 +525,13 @@ class Contacts extends ApiCommon
$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');
@ -548,7 +546,8 @@ class Contacts extends ApiCommon
$data = [
'businessCount' => $businessCount,
'fileCount' => $fileCount
'fileCount' => $fileCount,
'memberCount' => count($teamCount),
];
return resultArray(['data' => $data]);

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

@ -82,6 +82,7 @@ class Customer extends ApiCommon
$customerModel = model('Customer');
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $userInfo['id'];
if ($res = $customerModel->createData($param)) {
@ -235,6 +236,8 @@ class Customer extends ApiCommon
if (!$delRes) {
return resultArray(['error' => $customerModel->getError()]);
}
// 删除客户扩展数据
db('crm_customer_data')->whereIn('customer_id', $delIds)->delete();
// 删除跟进记录
$recordModel->delDataByTypes(2, $delIds);
// 删除关联附件
@ -404,7 +407,7 @@ class Customer extends ApiCommon
$userId = $userInfo['id'];
$customerIds = $this->param['customer_id'];
$poolId = $this->param['pool_id'];
$customerModel=new \app\crm\model\Customer();
# 消息数据
$message = [];
@ -429,7 +432,10 @@ class Customer extends ApiCommon
continue;
}
if (!$customerModel->checkData($value)) {
$message[] = '"' . $customerData[$value]['name'] . '"放入公海失败,错误原因:无权限';
continue;
}
if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
$message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
unset($customerIds[(int)$key]);
@ -767,7 +773,7 @@ class Customer extends ApiCommon
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$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');
@ -796,43 +802,30 @@ class Customer extends ApiCommon
*/
public function excelDownload($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_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);
# 下次升级
// $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);
}

@ -55,9 +55,9 @@ class CustomerPool extends ApiCommon
/**
* 公海列表
*
* @author fanqi
* @since 2021-04-14
* @return Json
* @since 2021-04-14
* @author fanqi
*/
public function index()
{
@ -71,9 +71,9 @@ class CustomerPool extends ApiCommon
/**
* 详情
*
* @author fanqi
* @since 2021-04-14
* @return Json
* @since 2021-04-14
* @author fanqi
*/
public function read()
{
@ -91,9 +91,9 @@ class CustomerPool extends ApiCommon
/**
* 删除公海客户
*
* @author fanqi
* @since 2021-04-15
* @return Json
* @since 2021-04-15
* @author fanqi
*/
public function delete()
{
@ -111,9 +111,9 @@ class CustomerPool extends ApiCommon
/**
* 公海池列表
*
* @author fanqi
* @since 2021-04-13
* @return Json
* @since 2021-04-13
* @author fanqi
*/
public function pondList()
{
@ -125,9 +125,9 @@ class CustomerPool extends ApiCommon
/**
* 公海字段
*
* @author fanqi
* @since 2021-04-13
* @return Json
* @since 2021-04-13
* @author fanqi
*/
public function field()
{
@ -145,9 +145,9 @@ class CustomerPool extends ApiCommon
/**
* 高级筛选字段列表
*
* @author fanqi
* @since 2021-04-14
* @return Json
* @since 2021-04-14
* @author fanqi
*/
public function advanced()
{
@ -161,9 +161,9 @@ class CustomerPool extends ApiCommon
/**
* 领取公海池客户
*
* @author fanqi
* @since 2021-04-15
* @return Json
* @since 2021-04-15
* @author fanqi
*/
public function receive()
{
@ -182,9 +182,9 @@ class CustomerPool extends ApiCommon
/**
* 分配公海客户
*
* @author fanqi
* @since 2021-04-15
* @return Json
* @since 2021-04-15
* @author fanqi
*/
public function distribute()
{
@ -204,19 +204,20 @@ class CustomerPool extends ApiCommon
$excelModel = new \app\admin\model\Excel();
$param = $this->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()
{
$param = $this->param;
$userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel();
$param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $userInfo['id'];
$param['deal_time'] = time();
$param['types'] = 'crm_customer';
$param['deal_status'] = '未成交';
$file = request()->file('file');
// $res = $excelModel->importExcel($file, $param, $this);
$res = $excelModel->batchImportData($file, $param, $this);
@ -236,21 +237,7 @@ class CustomerPool extends ApiCommon
$param['is_excel'] = 1;
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$fieldModel = new \app\admin\model\Field();
$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');
$model = model('Customer');
@ -259,7 +246,7 @@ class CustomerPool extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
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) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -274,9 +261,9 @@ class CustomerPool extends ApiCommon
/**
* 公海权限
*
* @author fanqi
* @since 2021-04-14
* @return Json
* @since 2021-04-14
* @author fanqi
*/
public function authority()
{
@ -292,9 +279,9 @@ class CustomerPool extends ApiCommon
/**
* 公海字段样式
*
* @author fanqi
* @since 2021-04-22
* @return Json
* @since 2021-04-22
* @author fanqi
*/
public function fieldConfig()
{
@ -312,9 +299,9 @@ class CustomerPool extends ApiCommon
/**
* 设置公海字段宽度
*
* @author fanqi
* @since 2021-04-22
* @return Json
* @since 2021-04-22
* @author fanqi
*/
public function setFieldWidth()
{
@ -334,9 +321,9 @@ class CustomerPool extends ApiCommon
/**
* 设置公海字段样式
*
* @author fanqi
* @since 2021-04-22
* @return Json
* @since 2021-04-22
* @author fanqi
*/
public function setFieldConfig()
{
@ -351,14 +338,62 @@ class CustomerPool extends ApiCommon
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['action'] = 'excel';
$merge_list = $fieldModel->field($fieldParam);
$field_list=array_intersect($merge_list,$pool_list);
return $field_list;
$setting = [];
$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',
'dashboard',
'updatedashboard',
'activitylist'
'activitylist',
]
];
Hook::listen('check_auth', $action);
@ -316,10 +316,14 @@ class Index extends ApiCommon
$achievement=Db::name('crm_achievement')->where($userWhere)->select();
$data_time=date('m',strtotime($val['type']));
$num='';
if($achievement){
foreach ($achievement as $val){
$num+=(int)$val[$this->monthName[$data_time]];
$item['achievement']=$num;
}
}else{
$item['achievement']=0;
}
$list[] = $item;
}
$data['list'] = $list;
@ -667,7 +671,6 @@ class Index extends ApiCommon
*/
public function ranking()
{
// Db::query('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;');
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $param['user_id']?:$userInfo['id'];
@ -691,7 +694,7 @@ class Index extends ApiCommon
}
/**
* 销售漏斗点击查看赢单输单
* 销售漏斗点击查看
*/
public function businessList()
{

@ -11,6 +11,7 @@ namespace app\crm\controller;
use app\admin\controller\ApiCommon;
use app\admin\model\Message;
use app\admin\model\User;
use app\admin\traits\FieldVerificationTrait;
use app\crm\logic\InvoiceLogic;
use app\crm\model\NumberSequence;
use app\crm\traits\AutoNumberTrait;
@ -20,7 +21,7 @@ use think\Request;
class Invoice extends ApiCommon
{
use AutoNumberTrait;
use AutoNumberTrait, FieldVerificationTrait;
/**
* 用于判断权限
@ -54,7 +55,7 @@ class Invoice extends ApiCommon
$param = $this->param;
$param['user_id'] = $this->userInfo['id'];
$data = $invoiceLogic->index($param, true);
$data = $invoiceLogic->index($param);
return resultArray(['data' => $data]);
}
@ -137,6 +138,104 @@ class Invoice extends ApiCommon
$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)) {
return resultArray(['error' => '创建失败!']);
}
@ -158,7 +257,7 @@ class Invoice extends ApiCommon
$checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds);
$dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) {
foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [
'types' => 'crm_invoice',
'types_id' => $invoice_id,
@ -167,6 +266,12 @@ class Invoice extends ApiCommon
}
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' => '创建成功!']);
}
@ -198,7 +303,7 @@ class Invoice extends ApiCommon
$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');
foreach ($authArray AS $key => $value) {
foreach ($authArray as $key => $value) {
if (!empty($value) && in_array($invoiceReadAuthId, stringToArray($value))) $readStatus = true;
}
@ -226,7 +331,7 @@ class Invoice extends ApiCommon
if (empty($param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']);
if (empty($param['title_type'])) return resultArray(['error' => '请选择抬头类型!']);
$userId = $this->userInfo['id'];
$dataInfo = $this->get($param['invoice_id']);
$dataInfo = db('crm_invoice')->where('invoice_id',$param['invoice_id'])->find();
# 审批是否停用
$examineStatus = $param['examineStatus'];
# 删除无用参数
@ -305,6 +410,103 @@ class Invoice extends ApiCommon
}
}
// 数据验证
// $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)) {
return resultArray(['error' => '编辑失败!']);
}
@ -324,7 +526,7 @@ class Invoice extends ApiCommon
$checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds);
$dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) {
foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [
'types' => 'crm_invoice',
'types_id' => $param['invoice_id'],
@ -333,6 +535,14 @@ class Invoice extends ApiCommon
}
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' => '编辑成功!']);
}
@ -359,7 +569,7 @@ class Invoice extends ApiCommon
if (!isSuperAdministrators($userinfo['id'])) {
$list = $invoiceLogic->getExamineStatus($idString, true);
foreach ($list AS $key => $value) {
foreach ($list as $key => $value) {
if (!in_array($value['check_status'], [4, 5])) {
$status = false;
break;
@ -644,4 +854,77 @@ class Invoice extends ApiCommon
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) {
return resultArray(['error' => $leadsModel->getError()]);
}
// 删除线索扩展数据
db('crm_leads_data')->whereIn('leads_id', $delIds)->delete();
//删除跟进记录
$recordModel->delDataByTypes(1, $delIds);
//删除关联附件
@ -346,7 +348,7 @@ class Leads extends ApiCommon
*/
public function excelDownload($save_path = '')
{
# 下次升级使用
$param = $this->param;
$userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel();
@ -355,37 +357,21 @@ class Leads extends ApiCommon
$fieldParam['types'] = 'crm_leads';
$fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam);
// $field_list = $fieldModel->getIndexFieldList('crm_leads', $userInfo['id']);
$data = $excelModel->excelImportDownload($field_list, 'crm_leads', $save_path);
# 下次升级使用
// $param = $this->param;
// $userInfo = $this->userInfo;
// $excelModel = new \app\admin\model\Excel();
// // 导出的字段列表
// $fieldModel = new \app\admin\model\Field();
// $fieldParam['types'] = 'crm_leads';
// $fieldParam['action'] = 'excel';
// $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);
// $array = array_merge($first_array, $field, $field_list);
// $data = $excelModel->excelImportDownload($array, 'crm_leads', $save_path);
return resultArray(['data' => $data]);
$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);
$excelModel->excelImportDownload($field_list, 'crm_leads', $save_path);
}
/**
@ -409,7 +395,7 @@ class Leads extends ApiCommon
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$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');

@ -9,6 +9,8 @@ namespace app\crm\controller;
use app\admin\controller\ApiCommon;
use app\crm\logic\InvoiceLogic;
use app\crm\logic\MessageLogic;
use think\Cache;
use think\cache\driver\Redis;
use think\Db;
use think\Hook;
@ -80,7 +82,6 @@ class Message extends ApiCommon
$configDataModel = model('ConfigData');
$configData = $configDataModel->getData();
$data = [];
# 今日需联系线索
$todayLeadsTime = cache('todayLeadsTime'.$userInfo['id']);
$todayLeadsCount = cache('todayLeadsCount'.$userInfo['id']);
@ -106,7 +107,7 @@ class Message extends ApiCommon
# 今日需联系商机
$todayBusinessTime = cache('todayBusinessTime'.$userInfo['id']);
$todayBusinessCount = cache('todayBusinessCount'.$userInfo['id']);
if ($todayBusinessTime <= time()) {
if (time() <= $todayBusinessTime) {
$data['todayBusiness'] = (int)$todayBusinessCount;
} else {
$todayBusiness = $this->todayBusiness(true);
@ -163,9 +164,11 @@ class Message extends ApiCommon
$checkInvoiceCount = cache('checkInvoiceCount'.$userInfo['id']);
if (time() <= $checkInvoiceTime) {
$data['checkInvoice'] = (int)$checkInvoiceCount;
} else {
$checkInvoice = $this->checkInvoice(true);
$data['checkInvoice'] = $checkInvoice['dataCount'] ? : 0;
cache('checkInvoiceCount'.$userInfo['id'], $data['checkInvoice']);
cache('checkInvoiceTime'.$userInfo['id'], time() + 180);
}
@ -235,37 +238,12 @@ class Message extends ApiCommon
$param = $this->param;
$userId = $this->userInfo['id'];
$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['type']);
unset($param['isSub']);
$param['user_id'] = $userId;
if ($getCount == true) $param['getCount'] = 1;
$messageLogic= new MessageLogic();
$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;
$data = $leadsModel->getDataList($param);
$data = $messageLogic->todayLeads($param);
if ($types == 'list') return resultArray(['data' => $data]);
@ -281,36 +259,15 @@ class Message extends ApiCommon
public function todayCustomer($getCount = false)
{
$param = $this->param;
$userInfo = $this->userInfo;
$userId = $this->userInfo['id'];
$types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
if ($getCount == true) {
$param['getCount'] = 1;
}
unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$customerModel = model('Customer');
$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);
$param['user_id'] = $userId;
$messageLogic= new MessageLogic();
$data = $messageLogic->remindCustomer($param);
if ($types == 'list') {
return resultArray(['data' => $data]);
}
@ -331,37 +288,11 @@ class Message extends ApiCommon
$param = $this->param;
$userId = $this->userInfo['id'];
$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['type']);
unset($param['isSub']);
if ($getCount == true) $param['getCount'] = 1;
$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;
}
$messageLogic= new MessageLogic();
$param['user_id'] = $userId;
$data = $businessModel->getDataList($param);
$data = $messageLogic->todayBusiness($param);
if ($types == 'list') return resultArray(['data' => $data]);
@ -378,29 +309,11 @@ class Message extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$leadsModel = model('Leads');
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'];
$data = $leadsModel->getDataList($param);
$messageLogic=new MessageLogic();
$data = $messageLogic->followLeads($param);
if ($types == 'list') {
return resultArray(['data' => $data]);
}
@ -417,29 +330,13 @@ class Message extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
if ($getCount == true) {
$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);
$messageLogic=new MessageLogic();
$param['user_id'] = $userInfo['id'];
$data = $messageLogic->followCustomer($param);
if ($types == 'list') {
return resultArray(['data' => $data]);
}
@ -457,31 +354,13 @@ class Message extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$contractModel = model('Contract');
if ($getCount == true) {
$param['getCount'] = 1;
}
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;
}
$messageLogic=new MessageLogic();
$param['user_id'] = $userInfo['id'];
$data = $contractModel->getDataList($param);
$data = $messageLogic->checkContract($param);
if ($types == 'list') {
return resultArray(['data' => $data]);
}
@ -498,30 +377,11 @@ class Message extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$types = $param['types'];
$type = $param['type'] ? : 1;
$isSub = $param['isSub'] ? : '';
unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$receivablesModel = model('Receivables');
if ($getCount == true) $param['getCount'] = 1;
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;
}
$messageLogic=new MessageLogic();
$param['user_id'] = $userInfo['id'];
$data = $receivablesModel->getDataList($param);
$data = $messageLogic->checkReceivables($param);
if ($types == 'list') {
return resultArray(['data' => $data]);
}
@ -540,33 +400,12 @@ class Message extends ApiCommon
$param = $this->param;
$userId = $this->userInfo['id'];
$types = $param['types'];
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
if ($getCount == true) $param['getCount'] = 1;
# 清除与模型无关的数据
unset($param['types']);
unset($param['type']);
unset($param['isSub']);
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);
$param['user_id'] = $userId;
$messageLogic=new MessageLogic();
$data = $messageLogic->checkInvoice($param);
if ($types == 'list') return resultArray(['data' => $data]);
@ -594,14 +433,14 @@ class Message extends ApiCommon
$param['owner_user_id'] = $userInfo['id'];
if ($isSub) {
$param['owner_user_id'] = array('in',getSubUserId(false));
$param['owner_user_id'] = ['in', getSubUserId(false)];
}
switch ($type) {
case '1' :
$param['receivables_id'] = 0;
$param['check_status'] = array('lt',2);
$param['remind_date'] = array('elt',date('Y-m-d',time()));
$param['return_date'] = array('egt',date('Y-m-d',time()));
$param['check_status'] = ['lt', 2];
$param['remind_date'] = ['elt', date('Y-m-d', time())];
$param['return_date'] = ['egt', date('Y-m-d', time())];
$param['types'] = 1;
$param['is_dealt'] = 0;
break;
@ -612,7 +451,7 @@ class Message extends ApiCommon
break;
case '3' :
$param['receivables_id'] = 0;
$param['remind_date'] = array('lt',date('Y-m-d',time()));
$param['return_date'] = ['lt', date('Y-m-d', time())];
break;
}
$data = $receivablesPlanModel->getDataList($param);
@ -642,7 +481,8 @@ class Message extends ApiCommon
$configModel = new \app\crm\model\ConfigData();
$configInfo = $configModel->getData();
$expireDay = $configInfo['contract_day'] ? : '7';
// 合同到期不提醒
if (empty($configInfo['contract_config'])) return resultArray(['data' => []]);
$param['owner_user_id'] = $userInfo['id'];
if ($isSub) {
$param['owner_user_id'] = array('in',getSubUserId(false));
@ -907,7 +747,31 @@ class Message extends ApiCommon
if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]);
}
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' => '操作成功!']);
}
}

@ -187,6 +187,7 @@ class Product extends ApiCommon
*/
public function excelDownload($save_path = '')
{
# 下次升级
$param = $this->param;
$userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel();
@ -196,34 +197,21 @@ class Product extends ApiCommon
$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_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);
# 下次升级
// $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();
// 导出的字段列表
$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');
@ -337,6 +325,8 @@ class Product extends ApiCommon
if ($res == count($delIds)) {
// 事务提交
ProductModel::commit();
// 删除客户扩展数据
db('crm_product_data')->whereIn('product_id', $delIds)->delete();
// 删除关联附件
(new FileModel)->delRFileByModule('crm_product', $delIds);
// 操作记录

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

@ -348,6 +348,8 @@ class Receivables extends ApiCommon
if (!$data) {
return resultArray(['error' => $receivablesModel->getError()]);
}
// 删除回款扩展数据
db('crm_receivables_data')->whereIn('receivables_id', $delIds)->delete();
//删除跟进记录
$recordModel->delDataByTypes(7,$delIds);
# 删除附件
@ -643,9 +645,17 @@ class Receivables extends ApiCommon
{
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();
return resultArray(['data' => ['fileCount' => $fileCount]]);
return resultArray(['data' => ['fileCount' => $fileCount,'memberCount' => count($teamCount)]]);
}
}

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

@ -107,6 +107,9 @@ class Setting extends ApiCommon
case 'crm_contract' :
$dataModel = new \app\crm\model\Contract();
break;
case 'crm_receivables' :
$dataModel = new \app\crm\model\Receivables();
break;
}
$resData = $dataModel->getDataById($param['types_id']);
$ro_user_ids = $resData['ro_user_id'] ? array_filter(explode(',', $resData['ro_user_id'])) : []; //只读权限
@ -133,6 +136,7 @@ class Setting extends ApiCommon
$user_list = array_merge($owner_user_arr, $rw_user_arr, $ro_user_arr);
$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) {
if ($v['user_id']) {
$userInfo = [];
@ -140,6 +144,7 @@ class Setting extends ApiCommon
$userInfo['group_name'] = $v['group_name'];
$userInfo['authority'] = $v['authority'];
$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;
}
}
@ -286,13 +291,62 @@ class Setting extends ApiCommon
}
$message_type = Message::TEAM_CONTRACT;
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) {
$param['type_id'] = $v;
$param['type'] = $param['type'] ?: 1;
$param['is_del'] = $param['is_del'] ?: 3;
$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);
if (!$res) {
$errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
@ -306,7 +360,8 @@ class Setting extends ApiCommon
$param['user_id']
);
$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 {
$res = $settingModel->createTeamData($param);
@ -323,9 +378,9 @@ class Setting extends ApiCommon
);
}
$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) {
@ -460,7 +515,8 @@ class Setting extends ApiCommon
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$userInfo = $this->userInfo;
$this->param['user_id'] = $userInfo['id'];
$customerConfigModel = new \app\crm\model\CustomerConfig();
if (!$customerConfigModel->createData($this->param)) {
return resultArray(['error' => $customerConfigModel->getError()]);
@ -581,10 +637,10 @@ class Setting extends ApiCommon
{
$status = !empty($this->param['status']) ? $this->param['status'] : 0;
$day = !empty($this->param['day']) ? $this->param['day'] : 0;
$userInfo = $this->userInfo;
$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' => '操作成功!']);
}
@ -602,6 +658,7 @@ class Setting extends ApiCommon
return resultArray(['data' => $data]);
}
/**
* 设置自动编号
*
@ -610,11 +667,50 @@ class Setting extends ApiCommon
public function setNumber()
{
if (empty($this->param) || !is_array($this->param)) return resultArray(['error' => '参数错误!']);
$userInfo = $this->userInfo;
$settingModel = new \app\crm\model\Setting();
if ($settingModel->setNumber($this->param, $userInfo['id']) === false) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
}
/**
* 手机端导航栏显示
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 11:27
*/
public function appMenuConfig(){
$param=$this->userInfo['id'];
$settingModel = new \app\crm\model\Setting();
$data=$settingModel->appMenuConfig($param);
return resultArray(['data' => $data]);
}
if ($settingModel->setNumber($this->param) === false) return resultArray(['error' => '操作失败!']);
/**
* 手机端办公数量
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/6/22 0022 13:44
*/
public function oaNumber(){
$userInfo=$this->userInfo;
return resultArray(['data' => '操作成功!']);
# 日志
$logNum=db('oa_log')->where('create_user_id',$userInfo['id'])->count();
#审批
$examineNum=db('oa_examine')->where('create_user_id',$userInfo['id'])->count();
#任务
$taskNum=db('task')->where('create_user_id',$userInfo['id'])->count();
#跟进
$activityNum=db('crm_activity')->where(['create_user_id'=>$userInfo['id'],'type'=>1])->count();
$data=[];
$data['logNum']=$logNum;
$data['examineNum']=$examineNum;
$data['taskNum']=$taskNum;
$data['activityNu']=$activityNum;
return $data;
}
}

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

@ -10,16 +10,19 @@ namespace app\crm\logic;
use app\admin\controller\ApiCommon;
use app\admin\model\User;
use app\admin\traits\FieldVerificationTrait;
use app\crm\model\Customer;
use think\Db;
use think\Validate;
class CommonLogic
{
use FieldVerificationTrait;
public $error = '操作失败!';
/**
* 快捷编辑【线索、客户、联系人、商机、合同、回款、回访、产品】
* 快捷编辑【线索、客户、联系人、商机、合同、回款、发票、回访、产品】
*
* @param $param
* @return false|int|string
@ -48,51 +51,46 @@ class CommonLogic
$model = db($types);
# 主键
$primaryKey = '';
// author guogaobo $item模块
$primaryKey = getPrimaryKeyName($types);
$info='';
switch ($types) {
case 'crm_leads' :
$primaryKey = 'leads_id';
$dataModel=new \app\crm\model\Leads();
$info=$dataModel->getDataById($actionId);
break;
case 'crm_customer' :
$primaryKey = 'customer_id';
$info=db('crm_customer')->where('customer_id',$actionId)->find();
break;
case 'crm_contacts' :
$primaryKey = 'contacts_id';
$dataModel=new \app\crm\model\Contacts();
$info=$dataModel->getDataById($actionId);
break;
case 'crm_business' :
$primaryKey = 'business_id';
$dataModel=new \app\crm\model\Business();
$info=$dataModel->getDataById($actionId);
break;
case 'crm_contract' :
$primaryKey = 'contract_id';
$info=db('crm_contract')->where('customer_id',$actionId)->find();
break;
case 'crm_receivables' :
$primaryKey = 'receivables_id';
$info=db('crm_receivables')->where('customer_id',$actionId)->find();
break;
case 'crm_invoice' :
$info = $model->where($primaryKey, $actionId)->find();
break;
case 'crm_visit' :
$primaryKey = 'visit_id';
$dataModel=new \app\crm\logic\VisitLogic();
$info=$dataModel->getDataById($actionId);
break;
case 'crm_product' :
$primaryKey = 'product_id';
$dataModel=new \app\crm\model\Product();
$info=$dataModel->getDataById($actionId);
break;
}
$apiCommon = new ApiCommon();
$userModel = new User();
$userInfo = $apiCommon->userInfo;
if (in_array($types, ['crm_contract', 'crm_receivables'])) {
$checkStatus = $model->where($primaryKey, $actionId)->value('check_status');
@ -101,6 +99,22 @@ class CommonLogic
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'){
foreach ($param['list'] as $val){
@ -164,41 +178,27 @@ class CommonLogic
$userField = $fieldModel->getFieldByFormType($types, 'user');
# 部门类型
$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) {
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 常规数据 extraData 扩展数据(地址、定位、日期区间、详细表格)
$data = [];
$extraData = [];
$deleteExtraWhere = [];
if (!empty($param['list'])) {
foreach ($param['list'] as $key => $value) {
foreach ($value as $k => $v) {
if ($k == 'next_time' || in_array($k, $datetimeField)) {
# 处理下次联系时间格式、datetime类型数据
$data[$k] = !empty($v) ? strtotime($v) : '';
$data[$k] = !empty($v) && $v == strtotime($v) ? strtotime($v) : $v;
} elseif ($types == 'crm_product' && $k == 'category_id') {
# 处理产品类别
$categorys = explode(',', $v);
@ -209,25 +209,84 @@ class CommonLogic
} elseif ($types == 'crm_visit' && $k == '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 {
$data[$k] = $v;
}
$item[$k]=$v;
}
}
$data[$primaryKey] = $actionId;
$data['update_time'] = time();
}
$res = $model->update($data);
unset($data[$primaryKey]);
unset($data['update_time']);
//详细信息修改新增操作记录
// 详细信息修改新增操作记录、处理扩展数据
if ($res) {
// 删除扩展数据
if (!empty($deleteExtraWhere)) db($types . '_data')->where([$primaryKey => $actionId, 'field' => ['in', $deleteExtraWhere]])->delete();
// 添加扩展数据
if (!empty($extraData)) db($types . '_data')->insertAll($extraData);
// 修改记录
$user_id = $apiCommon->userInfo;
updateActionLog($user_id['id'], $types, $actionId, $info, $data);
RecordActionLog($user_id['id'], $types, 'update',$info['name'], $info, $data);
updateActionLog($userInfo['id'], $types, $actionId, $info, $data);
RecordActionLog($userInfo['id'], $types, 'update',$info['name'], $info, $data);
}
return $res;
}

@ -39,10 +39,10 @@ class CustomerPoolLogic extends Common
$orderField = $param['order_field'];
$orderType = $param['order_type'];
# 基础条件
// 基础条件
$where['relation.pool_id'] = $poolId;
# 普通搜索
// 普通搜索
$searchMap = [];
if ($param['search'] == '0' || !empty($param['search'])) {
$search = $param['search'];
@ -53,37 +53,38 @@ class CustomerPoolLogic extends Common
};
}
# 处理排序参数
// 处理排序参数
if (!empty($orderField)) {
if ($orderField == 'create_user_id_name') $orderField = 'create_user_id';
if ($orderField == 'before_owner_user_name') $orderField = 'before_owner_user_id';
}
# 公海条件
// 公海条件
if ($param['is_excel'] == 1 && !empty($param['customer_id'])) {
$authMap['customer.customer_id'] = ['in', trim(arrayToString($param['customer_id']),',')];
}
# 排序
// 排序
if (!empty($orderField) && !empty($orderType)) {
$order = $fieldModel->getOrderByFormtype('crm_customer','customer', $orderField, $orderType);
} else {
$order = 'customer.update_time desc';
}
# 删除参数
// 删除参数
unset($param['pool_id']);
unset($param['search']);
unset($param['order_field']);
unset($param['order_type']);
unset($param['is_excel']);
unset($param['customer_id']);
# 格式化参数
// 格式化参数
$request = $this->fmtRequest( $param );
$requestMap = !empty($request['map']) ? $request['map'] : [];
# 高级搜索
$map = where_arr($requestMap, 'crm', 'customer', 'index');
# 公海字段
// 高级搜索
$map = advancedQuery($requestMap, 'crm', 'customer', 'index');
// 公海字段
$customerFieldString = $this->getPoolQueryField($poolId);
# 公海数据
// 公海数据
$customerPoolCount = db('crm_customer_pool_relation')->alias('relation')
->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
->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')
->limit($request['offset'], $request['length'])->where($where)->where($searchMap)->where($map)->where($authMap)->orderRaw($order)->select();
# 员工列表
// 员工列表
$userData = $this->getUserList();
# 部门列表
// 部门列表
$structureData = $this->getStructureList();
# 特殊字段
// 特殊字段
$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); # 人员类型
$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); # 部门类型
$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) {
$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']] : '';
@ -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]['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) {
if (isset($datetimeField[$key][$v])) {
$datetimeField[$key][$v] = !empty($value[$v]) ? date('Y-m-d H:i:s', $value[$v]) : null;
if (!empty($value[$v])) $customerPoolList[$key][$v] = date('Y-m-d H:i:s', $value[$v]);
}
}
# 处理人员类型的自定义字段
// 处理人员类型的自定义字段
foreach ($userField AS $k => $v) {
if (isset($datetimeField[$key][$v]) && !empty($value[$v])) {
$datetimeField[$key][$v] = $this->fieldTransformToText($value[$v], $userData);
if (!empty($value[$v])) {
$customerPoolList[$key][$v] = $this->fieldTransformToText($value[$v], $userData);
}
}
# 处理部门类型的自定义字段
// 处理部门类型的自定义字段
foreach ($structureField AS $k => $v) {
if (isset($datetimeField[$key][$v]) && !empty($value[$v])) {
$datetimeField[$key][$v] = $this->fieldTransformToText($value[$v], $structureData);
if (!empty($value[$v])) $customerPoolList[$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)
{
$adminTypes = adminGroupTypes($param['user_id']);
return db('crm_customer_pool')->field(['pool_id', 'pool_name'])
->where('status', 1)
->where(function ($query) use ($param) {
$query->where('admin_user_ids', 'like', '%,' . $param['user_id'] . ',%');
$query->whereOr('user_ids', 'like', '%,' . $param['user_id'] . ',%');
$query->whereOr('department_ids', '%,' . $param['structure_id'] . ',%');
->where(function ($query) use ($param, $adminTypes) {
if (!in_array(1, $adminTypes)) $query->where('admin_user_ids', 'like', '%,' . $param['user_id'] . ',%');
if (!in_array(1, $adminTypes)) $query->whereOr('user_ids', 'like', '%,' . $param['user_id'] . ',%');
if (!in_array(1, $adminTypes)) $query->whereOr('department_ids', '%,' . $param['structure_id'] . ',%');
})->select();
}
@ -329,7 +362,12 @@ class CustomerPoolLogic extends Common
$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) {
@ -346,9 +384,6 @@ class CustomerPoolLogic extends Common
default :
$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'])) {
$list[$key]['system'] = 1;
@ -395,7 +430,7 @@ class CustomerPoolLogic extends Common
['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);
# 整理数据
@ -416,6 +451,7 @@ class CustomerPoolLogic extends Common
*/
public function receiveCustomers($param)
{
if (empty($param['user_id'])) return ['缺少员工ID'];
# 查询参数
@ -453,15 +489,15 @@ class CustomerPoolLogic extends Common
$message[] = '客户《' . $customerData[$value]['name'] . '》领取失败,失败原因:持有客户数达到上限!';
}
}
# 可以领取的客户ID取差集
$addCustomerId = count($customerId) == 1 ? $customerId : array_diff($customerId, $failCustomer);
# 检查是否还有要领取的客户
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天内不能领取客户
if (!empty($poolConfig['before_owner_conf'])) {
@ -483,7 +519,7 @@ class CustomerPoolLogic extends Common
# 检查每天领取的个数限制
$countWhere['type'] = 1;
$countWhere['pool_id'] = $param['pool_id'];
$countWhere['pool_id'] = $poolId;
$countWhere['user_id'] = $userId;
$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();
@ -527,7 +563,7 @@ class CustomerPoolLogic extends Common
$addReceiveData[] = [
'customer_id' => $value,
'user_id' => $userId,
'pool_id' => $param['pool_id'],
'pool_id' => $poolId,
'type' => 1,
'create_time' => time()
];
@ -615,7 +651,8 @@ class CustomerPoolLogic extends Common
# 检查是否还有要领取的客户
if (empty($addCustomerId)) return $message;
# 查询分配客户的公海id
$poolId=db('crm_customer_pool_relation')->whereIn('customer_id',$customerId)->value('pool_id');
# 整理客户更新数据
$addCustomerData = [
'owner_user_id' => $userId,
@ -653,7 +690,7 @@ class CustomerPoolLogic extends Common
$addReceiveData[] = [
'customer_id' => $value,
'user_id' => $userId,
'pool_id' => $param['pool_id'],
'pool_id' => $poolId,
'type' => 3,
'create_time' => time()
];
@ -755,7 +792,11 @@ class CustomerPoolLogic extends Common
$data = !empty($data) ? json_decode($data, true) :[];
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) {
if (in_array($value['field'], $exceptFields)) continue;
if (!empty($value['is_hidden'])) {
$hideList[] = $value;
} else {
@ -764,7 +805,12 @@ class CustomerPoolLogic extends Common
}
} 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) {
if (empty($value['is_hidden'])) {
$showList[] = [

@ -37,16 +37,15 @@ class IndexLogic extends Common
$contractModel = new \app\crm\model\Contract();
$receivablesModel = new \app\crm\model\Receivables();
$activityModel = new \app\crm\model\Activity();
$last_between_time = ByDateTime($param['type']);
if($param['start_time'] && $param['end_time']){
$param['start_time']=$param['start_time'].' 00:00:00';
$param['end_time']=$param['end_time'].' 23:59:59';
}
$whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
$lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
// $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
$userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time'];
$last_between_time = $lastArr['between_time'];
$customerNum = 0; //新增客户
$customerLastNum = 0; //上期对比
@ -89,11 +88,10 @@ class IndexLogic extends Common
'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1],
])
);
$resLastCount = queryCache(
$this->getCountSql([
'start_time' => $last_between_time[0],
'end_time' => $last_between_time[1],
'start_time' => $last_between_time['last_time'][0],
'end_time' => $last_between_time['last_time'][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],
'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;
$receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0;
$recordLastNum = (int)$resLastCount[5]['count'] ?: 0;
$data = [];
$data['data']['customerNum'] = $customerNum;
$data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum);
@ -145,19 +142,12 @@ class IndexLogic extends Common
$data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
$data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
return $data;
}
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
count(1) count1,
0 count2
@ -210,15 +200,14 @@ class IndexLogic extends Common
///计算涨幅
public function getProportion($now, $last)
{
$res = 0;
if ($last && $last != 0.00) {
if ($now && $now != 0.00) {
$res = round(($now / $last), 2);
}
if($now-$last>0){
$res = round(($now-$last) / $last,2);
}else{
if ($now && $now != 0.00) {
$res = 1;
$res =round(($now-$last) / $last,2);
}
} else {
$res = 0;
}
return $res;
}
@ -363,10 +352,6 @@ class IndexLogic extends Common
->field([
'SUM(CASE WHEN check_status = 2 THEN money ELSE 0 END) as money',
'contract.owner_user_id as owner_user_id',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name'
])
->where([
'contract.owner_user_id' => ['in', $auth_user_ids],
@ -388,10 +373,6 @@ class IndexLogic extends Common
->field([
'SUM(CASE WHEN receivables.check_status = 2 THEN receivables.money ELSE 0 END) as money',
'receivables.owner_user_id as owner_user_id',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name'
])
->where([
'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')
->field([
'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'])
->where([
'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')
->field([
'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'])
->where(
'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')
->field([
'count(contacts.contacts_id) as count',
'user.realname as realname',
'user.id',
'user.thumb_img',
'structure.name',
'contacts.contacts_id',
'contacts.owner_user_id as owner_user_id'])
->where([
@ -484,9 +453,6 @@ class IndexLogic extends Common
->join('__ADMIN_USER__ user', 'activity.create_user_id=user.id')
->field([
'count(activity.activity_id) as count',
'user.realname as realname',
'user.id',
'user.thumb_img',
'activity.create_user_id as create_user_id'])
->where([
'activity.create_user_id' => ['in', $auth_user_ids],
@ -500,7 +466,15 @@ class IndexLogic extends Common
->select();
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']);
$start_time = $between_time[0];
@ -587,10 +561,10 @@ class IndexLogic extends Common
$business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
$contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', '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');
$resDataArr = [];
for ($i = 1; $i <= 5; $i++) {
for ($i = 1; $i <= 6; $i++) {
$resData = queryCache(
$this->getQueryDataSql([
'type' => $i,
@ -602,6 +576,7 @@ class IndexLogic extends Common
'contract_auth_user_ids' => array_intersect($userIds, $contract_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],
'$receivablesPlan_auth_user_ids' => array_intersect($userIds, $receivablesPlan_auth_user_ids) ? : [-1],
])
);
$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
FROM 5kcrm_crm_contract
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;
case 5 :
$start_time=date('Y-m-d',$param['start_time']);
$end_time=date('Y-m-d',$param['end_time']);
$countSql = "SELECT
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
SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney
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 " . $param['start_time'] . " AND " . $param['end_time'] . "
AND r.owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")";
WHERE r.create_time BETWEEN " . "'".$start_time."'" . " AND " ."'".$end_time."'" . "
AND r.owner_user_id IN (" . implode(',', $param['receivables_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;
}
return $countSql;
}
/**
* 赢单输单查看
* 销售漏斗查看
*/
public function businessList($param)
{
$userModel = new \app\admin\model\User();
$adminModel = new \app\admin\model\Admin();
if($param['start_time'] && $param['end_time']){
$param['start_time']=$param['start_time'].'00:00:00';
$param['end_time']=$param['end_time'].'23:59:59';
$between_time[0]=$param['start_time'].'00:00:00';
$between_time[1]=$param['end_time'].'23:59:59';
}
$whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
$user_id = $param['user_id'] ?: [-1];
$userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time'];
//权限控制
$where_customer['create_time'] = array('between', $between_time);
$auth_customer_user_ids = $userModel->getUserByPer('bi', 'ranking', 'read');
$auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
$where_customer['owner_user_id'] = array('in', $auth_customer_user_ids);
$businessList = db('crm_business')
->where([
'owner_user_id' => $where_customer['owner_user_id'],
'create_time' => $where_customer['create_time'],
'status_id' => $param['status_id']
])
->select();
$data = [];
$data['businesslist'] = $businessList;
$start_time = $between_time[0];
$end_time = $between_time[1];
//场景默认全部
$scene_id = db('admin_scene')->where(['types' => 'crm_business', 'bydata' => 'all'])->value('scene_id');
$param['scene_id'] = $scene_id ?: '';
$param['create_time']['start'] = $start_time;
$param['create_time']['end'] = $end_time;
$param['owner_user_id']['value'] = $userIds;
unset($param['type']);
unset($param['dataType']);
unset($param['label']);
unset($param['log_type']);
unset($param['types']);
$businessModel = new \app\crm\model\Business();
$data=$businessModel->getDataList($param);
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) : []; //取交集
$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.status'] = 1;
if ($param['label'] == 2) {
if ($param['label'] != 1) {
if ($param['search']) {
$type['t.content'] = array('like', '%' . $param['search'] . '%');
}
@ -822,14 +805,15 @@ class IndexLogic extends Common
$type['t.type'] = $param['queryType'];
}
if ($param['user_id'] == '') {
if ($param['subUser'] == '0') {
if ($param['subUser'] === "0" || $param['subUser']===0) {
$type['t.create_user_id'] = $param['id'];
//下属创建
} elseif ($param['subUser'] == '1') {
$subList = getSubUserId(false, 0, $param['id']);
$subStr = $subList ? implode(',', $subList) : '-1';
$type['t.create_user_id'] = array('in', $subStr);
} elseif ($param['subUser'] == '') {
} else {
$userIds = getSubUserId(true, 0, $param['id']);
$subStr = $userIds ? implode(',', $userIds) : '-1';
$type['t.create_user_id'] = array('in', $subStr);
@ -846,6 +830,15 @@ class IndexLogic extends Common
->page($param['page'], $param['limit'])
->order('t.create_time desc')
->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')
->alias('t')
->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
@ -864,6 +857,7 @@ class IndexLogic extends Common
$activity_contacts = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->select();
$list[$k]['business_list'] = $activity_business ?: [];
$list[$k]['contacts_list'] = $activity_contacts ?: [];
}
if ($v['activity_type'] == 3) {
@ -901,21 +895,18 @@ class IndexLogic extends Common
$imgList[] = $val;
}
}
}
};
$list[$k]['fileList'] = $fileList ?: [];
$list[$k]['imgList'] = $imgList ?: [];
$dataInfo['customerList'] = $relation_list['customer_list'] ?: [];
$dataInfo['contactsList'] = $relation_list['contacts_list'] ?: [];
$dataInfo['businessList'] = $relation_list['business_list'] ?: [];
$dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
$dataInfo['customerList'] = $relation_list['customerList'] ?: [];
$dataInfo['contactsList'] = $relation_list['contactsList'] ?: [];
$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]['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 {
$list = db('crm_activity')
@ -981,14 +972,12 @@ class IndexLogic extends Common
}
$list[$k]['fileList'] = $fileList ?: [];
$list[$k]['imgList'] = $imgList ?: [];
$dataInfo['customerList'] = $relation_list['customer_list'] ?: [];
$dataInfo['contactsList'] = $relation_list['contacts_list'] ?: [];
$dataInfo['businessList'] = $relation_list['business_list'] ?: [];
$dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
$dataInfo['customerList'] = $relation_list['customerList'] ?: [];
$dataInfo['contactsList'] = $relation_list['contactsList'] ?: [];
$dataInfo['businessList'] = $relation_list['businessList'] ?: [];
$dataInfo['contractList'] = $relation_list['contractList'] ?: [];
$list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
$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) {
$data['firstPage'] = false;
$data['lastPage'] = false;
} else if ($param['page'] == 1) {
} else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = true;
$data['lastPage'] = false;
}

@ -16,6 +16,7 @@ use think\Db;
class InvoiceLogic
{
private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据'];
private $check_status = ['待审核', '审核中', '审核通过', '审核未通过', '撤回'];
/**
* 列表
@ -25,101 +26,207 @@ class InvoiceLogic
* @return array
* @throws \think\exception\DbException
*/
public function index($param, $search = false)
public function index($param)
{
$field = [
'invoice_id',
'invoice_apple_number',
'invoice_money',
'invoice_date',
'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'];
$fieldModel = new \app\admin\model\Field();
//列表展示字段
$field = $fieldModel->getIndexField('crm_invoice', $param['user_id'], 1) ?: array('name');
if (!empty($param['is_excel']) && !empty($param['invoice_id'])) {
$param['invoice_id'] = ['in', arrayToString($param['invoice_id'])];
}
$getCount = $param['getCount'];
$userId = $param['user_id'];
$invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数
$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['limit']);
unset($param['page']);
// unset($param['limit']); 导出使用 暂未发现为何去掉分页参数
// unset($param['page']);
unset($param['user_id']);
unset($param['invoiceIdArray']);
unset($param['dealt']);
$where = [];
if ($search) {
# 处理基本参数
$scene_id = $param['scene_id'];
unset($param['search']);
unset($param['order_field']);
unset($param['order_type']);
unset($param['is_excel']);
unset($param['scene_id']);
$common = new Common();
unset($param['isMessage']);
$request = $common->fmtRequest($param);
$where = [];
# 高级搜索
$request = $common->fmtRequest($param);
$requestMap = !empty($request['map']) ? $request['map'] : [];
unset($requestMap['search']);
# 场景
$sceneMap = [];
if (!empty($scene_id) && $scene_id == 1) {
# 我负责的
$sceneMap['owner_user_id'] = $userId;
$sceneModel = new \app\admin\model\Scene();
if ($scene_id) {
//自定义场景
$sceneMap = $sceneModel->getDataById($scene_id, $userId, 'invoice') ?: [];
} else {
//默认场景
$sceneMap = $sceneModel->getDefaultData('crm_invoice', $userId) ?: [];
}
if (!empty($scene_id) && $scene_id == 2) {
# 我下属负责的
$subordinate = getSubUserId(false, 0, $userId);
$sceneMap['owner_user_id'] = !empty($subordinate) ? ['in', $subordinate] : 0;
//普通筛选
if ($search) {
# 处理基本参数
$searchWhere = function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query->whereLike('customer.name', '%' . $search . '%');
})->whereOr(function ($query) use ($search) {
$query->whereLike('contract.num', '%' . $search . '%');
})->whereOr(function ($query) use ($search) {
$query->whereLike('invoice.invoice_apple_number', '%' . $search . '%');
});
};
}
# 合并高级搜索和场景的查询条件
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
$map = where_arr($map, 'crm', 'invoice', 'index');
# 替换掉字段前缀,不修改公共函数
foreach ($map AS $key => $value) {
foreach ($map as $key => $value) {
$k = str_replace('invoice.', '', $key);
$where[$k] = $value;
}
# 重置查询条件
if ($where) $param = $where;
}
# 待办事项查询参数
$dealtWhere = [];
if (!empty($invoiceIdArray)) $dealtWhere['invoice_id'] = ['in', $invoiceIdArray];
if (!empty($invoiceIdArray)) $dealtWhere['invoice.invoice_id'] = ['in', $invoiceIdArray];
# 权限,不是待办事项,则加上列表权限
$auth = [];
if (empty($dealt)) {
$userModel = new \app\admin\model\User();
$authUserIds = $userModel->getUserByPer('crm', 'invoice', 'index');
$auth['owner_user_id'] = ['in', $authUserIds];
$a = 'index';
if ($is_excel) $a = 'excelExport';
$auth_user_ids = $userModel->getUserByPer('crm', 'invoice', $a);
if (empty($dealt)) {
//过滤权限
if (isset($map['invoice.owner_user_id']) && $map['invoice.owner_user_id'][0] != 'like') {
if (!is_array($map['invoice.owner_user_id'][1])) {
$map['invoice.owner_user_id'][1] = [$map['invoice.owner_user_id'][1]];
}
if (in_array($map['invoice.owner_user_id'][0], ['neq', 'notin'])) {
$auth_user_ids = array_diff($auth_user_ids, $map['invoice.owner_user_id'][1]) ?: []; //取差集
} else {
$auth_user_ids = array_intersect($map['invoice.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
}
unset($map['invoice.owner_user_id']);
}
}
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
// 待办事项的待审核发票不一定是自己创建的
if (!$isMessage) {
$auth['invoice.owner_user_id'] = ['in', $auth_user_ids];
}
if ($order_type && $order_field) {
$order = $fieldModel->getOrderByFormtype('crm_invoice', 'invoice', $order_field, $order_type);
} else {
$order = 'invoice.update_time desc';
}
$join = [
['__CRM_CUSTOMER__ customer', 'customer.customer_id=invoice.customer_id', 'LEFT'],
['__CRM_CONTRACT__ contract', 'contract.contract_id=invoice.contract_id', 'LEFT'],
['__ADMIN_USER__ user', 'user.id=invoice.owner_user_id', 'LEFT'],
['__ADMIN_USER__ u', 'u.id=invoice.create_user_id', 'LEFT'],
];
# 查询数据
$list = Invoice::with(['toCustomer', 'toContract', 'toAdminUser'])->field($field)->where($auth)
->where($param)->where($dealtWhere)->limit($limit)->order('update_time', 'desc')->paginate($limit)->toArray();
$list = 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)
->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) {
// $list['data'][$key]['invoice_type'] = $this->invoiceType[$value['invoice_type']];
// }
return ['list' => $list['data'], 'dataCount' => $list['total']];
foreach ($list as $key => $value) {
$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;
$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;
}
/**
@ -174,7 +281,7 @@ class InvoiceLogic
$result['essential'] = [
'invoice_apple_number' => $dataArray['invoice_apple_number'],
'customer_name' => $dataArray['customer_name'],
'contract_number' => $dataArray['contract_number'],
'contract_num' => $dataArray['contract_number'],
'contract_money' => $dataArray['contract_money'],
'invoice_money' => $dataArray['invoice_money'],
'invoice_date' => $dataArray['invoice_date'],

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

@ -328,6 +328,9 @@ class PrintingLogic
$contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find();
# 查询产品数据
$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 = [];
foreach ($businessProduct AS $key => $value) {
$productIdArray[] = $value['product_id'];
@ -525,8 +528,8 @@ class PrintingLogic
}
# 替换整单折扣
$content = str_replace('{整单折扣}', $businessData['discount_rate'], $content);
$content = str_replace('{产品总金额}', $businessData['money'], $content);
$content = str_replace('{整单折扣}', !empty($businessData['discount_rate']) ? $businessData['discount_rate'] : $contractData['discount_rate'], $content);
$content = str_replace('{产品总金额}', !empty($businessData['money']) ? $businessData['money'] : $contractData['money'], $content);
return $content;
}

@ -4,12 +4,14 @@ namespace app\crm\logic;
use app\admin\controller\ApiCommon;
use app\admin\model\Common;
use app\admin\traits\FieldVerificationTrait;
use app\crm\model\Visit;
use think\Db;
use think\Validate;
class VisitLogic extends Common
{
use FieldVerificationTrait;
/**
* 获取回访列表
* @param $param
@ -54,7 +56,7 @@ class VisitLogic extends Common
}
//高级筛选
$map = where_arr($map, 'crm', 'visit', 'index');
$map = advancedQuery($map, 'crm', 'visit', 'index');
$authMap = [];
if (!$partMap) {
@ -93,6 +95,11 @@ class VisitLogic extends Common
$userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure'); //部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
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_CONTACTS__ contacts', 'visit.contacts_id=contacts.contacts_id', 'LEFT')
->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) {
$list[$k]['contract_num'] = $v['contract_number'];
$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) {
$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']['name'] = $v['contract_name'];
$list[$k]['customer_id_info']['customer_id'] = $v['create_user_id'];
@ -232,16 +265,18 @@ class VisitLogic extends Common
*/
public function createData($param)
{
// 回访扩展表数据
$visitData = [];
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_visit', $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
if (!$param['customer_id']) {
$this->error = '请选择相关客户';
return false;
@ -263,14 +298,88 @@ class VisitLogic extends Common
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();
if ($visitModel->data($param)->allowField(true)->save()) {
$visit_id = $visitModel->visit_id;
$data['visit_id'] = $visit_id;
updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
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;
} else {
$this->error = '添加失败';
@ -283,6 +392,9 @@ class VisitLogic extends Common
*/
public function updateDataById($param, $visit_id = '')
{
// 回访扩展表数据
$visitData = [];
$Visit = model('Visit');
$productModel = new \app\crm\model\Product();
$dataInfo = $this->getDataById($visit_id);
@ -298,15 +410,14 @@ class VisitLogic extends Common
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_visit', $param['user_id'], $param['visit_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_visit');
foreach ($arrFieldAtt as $k => $v) {
@ -320,13 +431,88 @@ class VisitLogic extends Common
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)) {
$data['visit_id'] = $visit_id;
//修改记录
updateActionLog($param['user_id'], 'crm_visit', $visit_id, $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;
} else {
$this->rollback();
@ -371,6 +557,8 @@ class VisitLogic extends Common
if (!$data) {
return resultArray(['error' => $this->getError()]);
}
// 删除回访扩展数据
db('crm_visit_data')->whereIn('visit_id', $delIds)->delete();
//删除关联附件
$fileModel->delRFileByModule('crm_visit', $delIds);
//删除关联操作记录

@ -6,14 +6,15 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;
use app\crm\model\Business as CrmBusinessModel;
class Business extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -47,6 +48,7 @@ class Business extends Common
$getCount = $request['getCount'];
$businessTypeId = $request['typesId']; // 针对mobile
$businessStatusId = $request['statusId']; // 针对mobile
$overdue = $request['overdue']; // 待办事项下需联系商机(逾期)
unset($request['scene_id']);
unset($request['search']);
unset($request['user_id']);
@ -57,7 +59,7 @@ class Business extends Common
unset($request['getCount']);
unset($request['typesId']);
unset($request['statusId']);
unset($request['overdue']);
$request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: [];
$sceneModel = new \app\admin\model\Scene();
@ -97,18 +99,16 @@ class Business extends Common
}
$partMap = [];
//优先级:普通筛选>高级筛选>场景
if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
if ($requestMap['team_id']) {
//相关团队查询
$map = $requestMap;
$partMap = function ($query) use ($sceneMap) {
$query->where('business.ro_user_id', array('like', '%,' . $sceneMap['ro_user_id'] . ',%'))
->whereOr('business.rw_user_id', array('like', '%,' . $sceneMap['rw_user_id'] . ',%'));
};
$partMap= advancedQueryFormatForTeam($requestMap,'crm_business','business_id');
unset($map['team_id']);
} else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
//高级筛选
$map = where_arr($map, 'crm', 'business', 'index');
$map = advancedQuery($map, 'crm', 'business', 'index');
$authMap = [];
if (!$partMap) {
$a = 'index';
@ -156,6 +156,11 @@ class Business extends Common
$userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_business', 'structure'); //部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -178,13 +183,20 @@ class Business extends Common
$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');
$updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
$dataCount = db('crm_business')
->alias('business')
->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) {
$data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
# 商机总金额
@ -199,11 +211,19 @@ class Business extends Common
->where($map)
->where($partMap)
->where($authMap)
->where($overdueWhere)
->limit($request['offset'], $request['length'])
->field('business.*,customer.name as customer_name')
->orderRaw($order)
->select();
$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) {
$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
$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'] : '';
foreach ($userField as $key => $val) {
$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) {
$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) {
$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 = [];
$status_count = 0;
if (!$v['is_end']) {
@ -281,14 +321,15 @@ class Business extends Common
*/
public function createData($param)
{
// 商机扩展表数据
$businessData = [];
$fieldModel = new \app\admin\model\Field();
$productModel = new \app\crm\model\Product();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
if (!$param['customer_id']) {
@ -308,6 +349,75 @@ class Business extends Common
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;
@ -318,6 +428,7 @@ class Business extends Common
updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']);
$business_id = $this->business_id;
$data['business_id'] = $business_id;
if ($param['product']) {
//产品数据处理
$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['remark'] = '新建商机';
Db::name('CrmBusinessLog')->insert($data_log);
$data = [];
$data['business_id'] = $business_id;
# 添加活动记录
Db::name('crm_activity')->insert([
'type' => 2,
@ -350,6 +456,11 @@ class Business extends Common
'create_time' => time(),
'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;
} else {
@ -366,6 +477,9 @@ class Business extends Common
*/
public function updateDataById($param, $business_id = '')
{
// 商机扩展表数据
$businessData = [];
$productModel = new \app\crm\model\Product();
$dataInfo = $this->getDataById($business_id);
if (!$dataInfo) {
@ -380,14 +494,11 @@ class Business extends Common
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['business_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -408,6 +519,75 @@ class Business extends Common
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;
@ -422,13 +602,19 @@ class Business extends Common
$param['is_end'] = $param['status_id'];
}
if ($this->update($param, ['business_id' => $business_id], true)) {
$data['business_id'] = $business_id;
//产品数据处理
$resProduct = $productModel->createObject('crm_business', $param, $business_id);
//修改记录
updateActionLog($param['user_id'], 'crm_business', $business_id, $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;
} else {
$this->rollback();

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

@ -6,13 +6,15 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;
class Contacts extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -24,11 +26,11 @@ class Contacts extends Common
/**
* [getDataList 联系人list]
* @author Michael_xu
* @param [string] $map [查询条件]
* @param [number] $page [当前页数]
* @param [number] $limit [每页数量]
* @return [array] [description]
* @author Michael_xu
*/
public function getDataList($request)
{
@ -70,13 +72,21 @@ class Contacts extends Common
->whereOr('contacts.mobile', array('like', '%' . $search . '%'))
->whereOr('contacts.telephone', array('like', '%' . $search . '%'));
};
// $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '联系人姓名'];
}
$partMap = [];
//优先级:普通筛选>高级筛选>场景
if ($requestMap['team_id']) {
//相关团队查询
$map = $requestMap;
$partMap= advancedQueryFormatForTeam($requestMap,'crm_contacts','contacts_id');
unset($map['team_id']);
} else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
//高级筛选
$map = where_arr($map, 'crm', 'contacts', 'index');
$map = advancedQuery($map, 'crm', 'contacts', 'index');
//权限
if (!$partMap) {
$a = 'index';
if ($is_excel) $a = 'excelExport';
$authMap = [];
@ -91,10 +101,22 @@ class Contacts extends Common
$auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
}
unset($map['contacts.owner_user_id']);
}
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
//负责人、相关团队
$authMap['contacts.owner_user_id'] = ['in', $auth_user_ids];
} else {
$authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id;
$authMap = function ($query) use ($authMapData) {
$query->where('contacts.owner_user_id', array('in', $authMapData['auth_user_ids']))
->whereOr('contacts.ro_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'))
->whereOr('contacts.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
};
}
}
//联系人商机
if ($business_id) {
$contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
@ -109,6 +131,11 @@ class Contacts extends Common
$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure'); //部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -134,6 +161,7 @@ class Contacts extends Common
->where($map)
->where($searchMap)
->where($authMap)
->where($partMap)
->where($customerWhere)
->count('contacts_id');
if ($getCount == 1) {
@ -145,12 +173,20 @@ class Contacts extends Common
->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
->where($map)
->where($searchMap)
->where($partMap)
->where($authMap)
->where($customerWhere)
->limit($request['offset'], $request['length'])
->field('contacts.*,customer.name as customer_name')
->orderRaw($order)
->select();
# 扩展数据
$extraData = [];
$contacts_id_list = !empty($list) ? array_column($list, 'contacts_id') : [];
$extraList = db('crm_contacts_data')->whereIn('contacts_id', $contacts_id_list)->select();
foreach ($extraList as $key => $value) {
$extraData[$value['contacts_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@ -158,16 +194,35 @@ class Contacts extends Common
$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.'_name'] = implode($usernameField, ',');
$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.'_name'] = implode($structureNameField, ',');
$list[$k][$val] = implode($structureNameField, ',');
}
foreach ($datetimeField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
}
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField as $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
}
//权限
$permission = [];
$is_read = 0;
@ -202,24 +257,28 @@ class Contacts extends Common
/**
* 创建联系人主表信息
* @author Michael_xu
* @param
* @return
* @author Michael_xu
*/
public function createData($param)
{
unset($param['excel']);
// 联系人扩展表数据
$contactsData = [];
$businessId = $param['business_id'];
unset($param['business_id']);
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$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');
if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
@ -239,10 +298,79 @@ class Contacts extends Common
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$contactsData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
@ -267,6 +395,12 @@ class Contacts extends Common
Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
}
// 添加联系人扩展数据
array_walk($contactsData, function (&$val) use ($data) {
$val['contacts_id'] = $data['contacts_id'];
});
db('crm_contacts_data')->insertAll($contactsData);
return $data;
} else {
$this->error = '添加失败';
@ -299,6 +433,9 @@ class Contacts extends Common
*/
public function updateDataById($param, $contacts_id = '')
{
// 联系人扩展表数据
$contactsData = [];
$userModel = new \app\admin\model\User();
$dataInfo = $this->getDataById($contacts_id);
if (!$dataInfo) {
@ -319,14 +456,11 @@ class Contacts extends Common
unset($param[$v]);
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contacts_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -338,10 +472,79 @@ class Contacts extends Common
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
foreach ($param as $key => $value) {
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');
@ -355,11 +558,17 @@ class Contacts extends Common
}
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);
$data = [];
$data['contacts_id'] = $contacts_id;
// 添加联系人扩展数据
db('crm_contacts_data')->where('contacts_id', $contacts_id)->delete();
array_walk($contactsData, function (&$val) use ($contacts_id) {
$val['contacts_id'] = $contacts_id;
});
db('crm_contacts_data')->insertAll($contactsData);
return $data;
} else {
$this->error = '编辑失败';
@ -410,7 +619,7 @@ class Contacts extends Common
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
foreach ($dataInfo as $key => $value) {
if (!$userLevel && !empty($grantData['crm_contacts'])) {
$status = getFieldGrantStatus($key, $grantData['crm_contacts']);
@ -424,11 +633,11 @@ class Contacts extends Common
/**
* [联系人转移]
* @author Michael_xu
* @param ids 联系人ID数组
* @param owner_user_id 变更负责人
* @param is_remove 1移出2转为团队成员
* @return
* @author Michael_xu
*/
public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
{

@ -6,14 +6,15 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\admin\model\Common;
use app\admin\model\Message;
use think\Request;
use think\Validate;
class Contract extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -48,6 +49,7 @@ class Contract extends Common
$is_excel = $request['is_excel']; //导出
$getCount = $request['getCount'];
$contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
$isMessage = !empty($request['isMessage']);
unset($request['scene_id']);
unset($request['search']);
@ -57,6 +59,7 @@ class Contract extends Common
unset($request['is_excel']);
unset($request['getCount']);
unset($request['contractIdArray']);
unset($request['isMessage']);
$request = $this->fmtRequest( $request );
@ -85,28 +88,19 @@ class Contract extends Common
$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 = [];
//优先级:普通筛选>高级筛选>场景
if ($sceneMap['contract.ro_user_id'] && $sceneMap['contract.rw_user_id']) {
if ($requestMap['team_id']) {
//相关团队查询
$map = $requestMap;
$partMap = function($query) use ($sceneMap){
$query->where('contract.ro_user_id',array('like','%,'.$sceneMap['ro_user_id'].',%'))
->whereOr('contract.rw_user_id',array('like','%,'.$sceneMap['rw_user_id'].',%'));
};
$partMap= advancedQueryFormatForTeam($requestMap,'crm_contract','contract_id');
unset($map['team_id']);
} 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'];
$authMap = [];
if (!$partMap) {
@ -126,6 +120,8 @@ class Contract extends Common
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
$authMap['contract.owner_user_id'] = array('in',$auth_user_ids);
} else {
// 待办事项的待审核合同不一定是自己创建的
if (!$isMessage) {
$authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id;
@ -136,6 +132,7 @@ class Contract extends Common
};
}
}
}
//合同签约人 | 与高级筛选冲突加一个is_array判断
if ($map['contract.order_user_id'] && !is_array($map['contract.order_user_id'][1])) {
$map['contract.order_user_id'] = ['like','%,'.$map['contract.order_user_id'][1].',%'];
@ -146,6 +143,11 @@ class Contract extends Common
$userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -209,6 +211,13 @@ class Contract extends Common
->orderRaw($order)
->group('contract.contract_id')
->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) {
$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']) : [];
@ -216,14 +225,34 @@ class Contract extends Common
$list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
foreach ($userField as $key => $val) {
$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) {
$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) {
$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']['name'] = $v['business_name'];
@ -231,6 +260,7 @@ class Contract extends Common
$list[$k]['customer_id_info']['name'] = $v['customer_name'];
$list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
$list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
$list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
$moneyInfo = [];
$moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
$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');
$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['list'] = $list;
@ -364,16 +396,17 @@ class Contract extends Common
*/
public function createData($param)
{
// 合同扩展表数据
$contractData = [];
$fieldModel = new \app\admin\model\Field();
$userModel = new \app\admin\model\User();
$productModel = new \app\crm\model\Product();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -392,6 +425,75 @@ class Contract extends Common
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());
@ -456,6 +558,12 @@ class Contract extends Common
}
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;
} else {
$this->error = '添加失败';
@ -472,6 +580,9 @@ class Contract extends Common
*/
public function updateDataById($param, $contract_id = '')
{
// 合同扩展表数据
$contractData = [];
$productModel = new \app\crm\model\Product();
$userModel = new \app\admin\model\User();
$dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
@ -482,14 +593,11 @@ class Contract extends Common
}
$param['contract_id'] = $contract_id;
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contract_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -512,6 +620,75 @@ class Contract extends Common
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)) {
//产品数据处理
@ -549,6 +726,13 @@ class Contract extends Common
}
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;
} else {
$this->error = '编辑失败';

@ -8,16 +8,15 @@ namespace app\crm\model;
use app\admin\controller\ApiCommon;
use app\admin\model\User;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
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\Validate;
class Customer extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -49,29 +48,32 @@ class Customer extends Common
public function getDataList($request)
{
$userModel = new \app\admin\model\User();
$structureModel = new \app\admin\model\Structure();
$fieldModel = new \app\admin\model\Field();
$search = $request['search'];
$user_id = $request['user_id'];
$scene_id = (int)$request['scene_id'];
$is_excel = $request['is_excel']; //导出
$action = $request['action'];
$order_field = $request['order_field'];
$order_type = $request['order_type'];
$is_remind = $request['is_remind'];
$getCount = $request['getCount'];
$otherMap = $request['otherMap'];
unset($request['poolId']);
//需要过滤的参数
$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap'];
$overdue = $request['overdue']; // 待办事项下需联系客户(逾期)
# 需要过滤的参数
$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap','poolId','overdue'];
foreach ($unsetRequest as $v) {
unset($request[$v]);
}
# 格式化参数
$request = $this->fmtRequest( $request );
$requestMap = $request['map'] ? : [];
$sceneModel = new \app\admin\model\Scene();
# 默认条件
# 客户默认条件
$customerMap = $this->getWhereByCustomer();
# getCount是代办事项传来的参数代办事项不需要使用场景
$sceneMap = [];
if (empty($getCount)) {
@ -83,33 +85,32 @@ class Customer extends Common
$sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
}
}
# 普通筛选
$searchMap = [];
if ($search || $search == '0') {
//普通筛选
$searchMap = function($query) use ($search){
$query->where('customer.name',array('like','%'.$search.'%'))
->whereOr('customer.mobile',array('like','%'.$search.'%'))
->whereOr('customer.telephone',array('like','%'.$search.'%'));
};
}
//优先级:普通筛选>高级筛选>场景
# 优先级:普通筛选 > 高级筛选 > 场景
$map = [];
$partMap = [];
if (is_array($sceneMap)) {
if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
//相关团队查询
$map = $requestMap;
$partMap = function($query) use ($sceneMap){
$query->where('FIND_IN_SET('.$sceneMap['ro_user_id'].', customer.ro_user_id)')
->whereOr('FIND_IN_SET('.$sceneMap['rw_user_id'].', customer.rw_user_id)');
};
//团队成员 高级筛选
if($requestMap['team_id']){
$partMap= advancedQueryFormatForTeam($requestMap,'crm_customer','customer_id');
unset($map['team_id']);
}else{
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
}
//高级筛选
$map = where_arr($map, 'crm', 'customer', 'index');
//工作台仪表盘
# 高级筛选
$map = advancedQuery($map, 'crm', 'customer', 'index');
# 工作台仪表盘
$requestData = $this->requestData();
$dashboardWhere = [];
if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
@ -119,9 +120,9 @@ class Customer extends Common
};
unset($map['customer.create_time']);
}
//权限
# 权限
$authMap = [];
$auth_user_ids = [];
if (!$partMap) {
$a = 'index';
if ($is_excel) $a = 'excelExport';
@ -156,6 +157,7 @@ class Customer extends Common
}
}
# 代办事项 - 待进入公海
$remindWhere = [];
if ($is_remind) {
@ -163,7 +165,17 @@ class Customer extends Common
$userIds[] = $user_id;
$poolDays = $this->getPoolDay([], $userIds);
$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')
@ -175,23 +187,29 @@ class Customer extends Common
->where($partMap)
->where($otherMap)
->where($remindWhere)
->where($overdueWhere)
->count();
if ($getCount == 1) {
$data['dataCount'] = $dataCount ? : 0;
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'); // 人员类型
$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); // 部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
$order_field = $temporaryField;
}
//排序
# 排序
if ($order_type && $order_field) {
$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
} else {
@ -207,12 +225,11 @@ class Customer extends Common
->where($partMap)
->where($otherMap)
->where($remindWhere)
->where($overdueWhere)
->limit($request['offset'], $request['length'])
->field($indexField)
->orderRaw($order)
->select();
# 查询公海数据的条件
$poolWhere = [];
$readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
$updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
@ -231,29 +248,62 @@ class Customer extends Common
$business_count = array_column($business_count, null, 'customer_id');
$field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
$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]['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]['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') : [];
$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') : [];
$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;
}
//商机数
// 布尔值类型字段
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;
//权限
# 权限
$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');
$permission = [];
@ -272,22 +322,16 @@ class Customer extends Common
$starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer'];
$star = Db::name('crm_star')->where($starWhere)->value('star_id');
$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]['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;
//查询公海数据的条件
$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;
}
# 获取公海天数
$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['list'] = $list ? : [];
@ -303,20 +347,30 @@ class Customer extends Common
*/
public function createData($param)
{
unset($param['excel']);
// 客户扩展表数据
$customerData = [];
$userId = $param['user_id'];
$fieldModel = new \app\admin\model\Field();
$userModel = new \app\admin\model\User();
$customerConfigModel = new \app\crm\model\CustomerConfig();
// 添加上限检测
if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
$this->error = $customerConfigModel->getError();
return false;
}
// 获取客户时间
$param['obtain_time'] = time();
// 地址
$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
$param['deal_time'] = time(); //领取、分配时间
$param['deal_status'] = '未成交';
// 线索转客户
if ($param['leads_id']) {
$leadsData = $param;
@ -328,14 +382,16 @@ class Customer extends Common
$param = $leadsData;
}
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_customer', $userId);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
// 删除无效数据
unset($param['user_id']);
unset($param['customer_id']);
// 处理部门、员工、附件、多选类型字段
@ -343,6 +399,7 @@ class Customer extends Common
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
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;
$pool_id = !empty($param['pool_id']) ? $param['pool_id'] : 0;
unset($param['pool_id']);
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
if(!empty($param['pool_id'])){
db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$param['pool_id'],'customer_id'=>$this->customer_id]);
$data['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'])) {
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']);
}
$data = [];
$data['customer_id'] = $this->customer_id;
$data['name'] = $param['name'];
# 添加活动记录
// 添加活动记录
Db::name('crm_activity')->insert([
'type' => 2,
'activity_type' => 2,
@ -377,6 +505,11 @@ class Customer extends Common
'update_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;
} else {
@ -404,19 +537,25 @@ class Customer extends Common
*/
public function updateDataById($param, $customer_id = '')
{
// 客户扩展表数据
$customerData = [];
$user_id = $param['user_id'];
$dataInfo = $this->get($customer_id);
if (!$dataInfo) {
$this->error = '数据不存在或已删除';
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();
$auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
// 读写权限
$rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
// 判断是否客户池数据
if(empty($param['pool_id'])){
$wherePool = $this->getWhereByPool();
@ -426,7 +565,7 @@ class Customer extends Common
return false;
}
}
$param['customer_id'] = $customer_id;
// 过滤不能修改的字段
$unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
foreach ($unUpdateField as $v) {
@ -434,15 +573,14 @@ class Customer extends Common
}
$param['deal_status'] = $dataInfo['deal_status'];
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, 'crm_customer', $user_id, $id);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
// 地址
$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
@ -454,6 +592,7 @@ class Customer extends Common
foreach ($arrFieldAtt as $k=>$v) {
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
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 ($this->update($param, ['customer_id' => $customer_id], true)) {
$data['customer_id'] = $customer_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);
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;
} else {
$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;
}
@ -672,93 +897,27 @@ class Customer extends Common
}
/**
* [客户默认条件]
* @author Michael_xu
* @param
* @return
* 客户默认条件
*
* @author fanqi
* @since 2021-05-12
* @return array
*/
public function getWhereByCustomer()
{
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
* @return
* 客户公海条件
*
* @author fanqi
* @since 2021-05-12
* @return array
*/
public function getWhereByPool()
{
// $configModel = new \app\crm\model\ConfigData();
// $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 : '';
return ['customer.owner_user_id' => ['eq', 0]];
}
/**
@ -1449,31 +1608,22 @@ class Customer extends Common
*/
public function getNearbyList($param)
{
$apiCommon = new ApiCommon();
$userModel = new \app\admin\model\User();
$poolStatus = checkPerByAction('crm', 'customer', 'pool');
# 客户
$customerAuth = [];
# 客户条件
$customerWhere = [];
if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
if (!empty($param['type']) && $param['type'] == 2) {
$customerWhere = $this->getWhereByCustomer();
}
# 公海
# 公海条件
$poolWhere = [];
if (!empty($param['type']) && $param['type'] == 9 && $poolStatus) {
$poolWhere = ['customer.customer_id' => 0];
if (!empty($param['type']) && $param['type'] == 9) {
$poolWhere = ['customer.owner_user_id' => 0];
$model = '公海客户管理模块';
}
if (!empty($param['type']) && $param['type'] == 9 && !$poolStatus) {
$model = '客户管理模块';
return [];
}
# 附近
# 距离条件
$lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
$lngLatWhere = function ($query) use ($lngLatRange) {
$query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
@ -1493,14 +1643,12 @@ class Customer extends Common
->where($customerWhere)
->where($poolWhere)
->where($lngLatWhere)
->where($customerAuth)
->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time'])
->order('update_time', 'desc')
->select();
# 组装数据
foreach ($list as $key => $value) {
# todo 暂时将查询写在循环中
$ownerUserInfo = !empty($value['owner_user_id']) ? $userModel->getUserById($value['owner_user_id']) : [];
$ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
$list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
@ -1585,15 +1733,18 @@ class Customer extends Common
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();
# 创建人
$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 [
'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'] : '',
'create_user_id' => $realname,
'create_user_id' => $createUserName,
'owner_user_id' => $ownerUserName,
'create_time' => date('Y-m-d H:i:s', $customer['create_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']) : '',

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

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

@ -6,14 +6,14 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\admin\model\Common;
use app\admin\model\Record as RecordModel;
use think\Request;
use think\Validate;
class Leads extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -43,6 +43,7 @@ class Leads extends Common
$order_field = $request['order_field'];
$order_type = $request['order_type'];
$getCount = $request['getCount'];
$overdue = $request['overdue']; // 待办事项下需联系线索(逾期)
unset($request['scene_id']);
unset($request['search']);
unset($request['user_id']);
@ -50,6 +51,7 @@ class Leads extends Common
unset($request['order_field']);
unset($request['order_type']);
unset($request['getCount']);
unset($request['overdue']);
$request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: [];
@ -74,13 +76,13 @@ class Leads extends Common
->whereOr('leads.mobile', 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 = where_arr($map, 'crm', 'leads', 'index');
$map = advancedQuery($map, 'crm', 'leads', 'index');
// $map = where_arr($map, 'crm', 'leads', 'index');
//权限
$a = 'index';
if ($is_excel) $a = 'excelExport';
@ -105,6 +107,11 @@ class Leads extends Common
$userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure'); //部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -121,23 +128,39 @@ class Leads extends Common
$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');
$updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update');
$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) {
$data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
return $data;
}
$list = db('crm_leads')
->alias('leads')
->where($map)
->where($searchMap)
->where($authMap)
->where($overdueWhere)
->limit($request['offset'], $request['length'])
->field(implode(',', $indexField))
->orderRaw($order)
->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) {
$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']) : [];
@ -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'] : '';
foreach ($userField as $key => $val) {
$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) {
$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) {
$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 = [];
$is_read = 0;
@ -201,14 +244,26 @@ class Leads extends Common
*/
public function createData($param)
{
unset($param['excel']);
// 线索扩展表数据
$leadsData = [];
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// // 自动验证
// $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, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -224,11 +279,81 @@ class Leads extends Common
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 ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
$data['leads_id'] = $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']);
@ -245,8 +370,12 @@ class Leads extends Common
'contacts_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;
} else {
$this->error = '添加失败';
@ -262,6 +391,9 @@ class Leads extends Common
*/
public function updateDataById($param, $leads_id = '')
{
// 线索扩展表数据
$leadsData = [];
$userModel = new \app\admin\model\User();
$dataInfo = $this->getDataById($leads_id);
if (!$dataInfo) {
@ -284,12 +416,17 @@ class Leads extends Common
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
// $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['user_id'], $leads_id);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -305,16 +442,90 @@ class Leads extends Common
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 ($this->update($param, ['leads_id' => $leads_id], true)) {
$data['leads_id'] = $leads_id;
//修改记录
updateActionLog($param['user_id'], 'crm_leads', $leads_id, $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;
} else {
$this->error = '编辑失败';

@ -6,17 +6,15 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\admin\model\Common;
use app\admin\model\User as UserModel;
use app\admin\model\File as FileModel;
use think\Request;
use think\Validate;
use traits\model\SoftDelete;
class Product extends Common
{
use SoftDelete;
use SoftDelete, FieldVerificationTrait;
protected $deleteTime = 'delete_time';
@ -72,7 +70,7 @@ class Product extends Common
//优先级:普通筛选>高级筛选>场景
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
//高级筛选
$map = where_arr($map, 'crm', 'product', 'index');
$map = advancedQuery($map, 'crm', 'product', 'index');
if (!empty($isStatus)) {
$map['product.status'] = '上架';
}
@ -104,6 +102,11 @@ class Product extends Common
$userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
$structureField = $fieldModel->getFieldByFormType('crm_product', 'structure'); //部门类型
$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的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -132,6 +135,13 @@ class Product extends Common
$dataCount = db('crm_product')->alias('product')
->where($map)->where($authMap)
->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) {
$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']) : [];
@ -148,6 +158,26 @@ class Product extends Common
foreach ($datetimeField as $key => $val) {
$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'];
# 处理日期格式
@ -169,20 +199,28 @@ class Product extends Common
*/
public function createData($param)
{
// 产品扩展表数据
$productData = [];
$fieldModel = new \app\admin\model\Field();
$productCategoryModel = model('ProductCategory');
$dataInfo = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->find();
if (isset($dataInfo)) {
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
$productStatus = false;
if (!empty($param['excel'])) {
$productStatus = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->value('product_id');
}
// 数据验证
if (empty($param['excel']) || $productStatus) {
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
}
unset($param['excel']);
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_product');
foreach ($arrFieldAtt as $k => $v) {
@ -195,6 +233,75 @@ class Product extends Common
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'];
@ -213,10 +320,15 @@ class Product extends Common
}
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, '', '', '创建了产品');
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;
} else {
$this->error = '添加失败';
@ -232,6 +344,9 @@ class Product extends Common
*/
public function updateDataById($param, $product_id = '')
{
// 产品扩展表数据
$productData = [];
$userModel = new \app\admin\model\User();
$dataInfo = $this->getDataById($product_id);
$productCategoryModel = model('ProductCategory');
@ -254,18 +369,14 @@ class Product extends Common
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['product_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_product');
foreach ($arrFieldAtt as $k => $v) {
@ -278,6 +389,75 @@ class Product extends Common
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'];
@ -295,11 +475,17 @@ class Product extends Common
}
}
if ($this->update($param, ['product_id' => $product_id], true)) {
$data['product_id'] = $product_id;
//修改记录
updateActionLog($param['user_id'], 'crm_product', $product_id, $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;
} else {
$this->rollback();

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

@ -6,15 +6,17 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\crm\model\Contract as ContractModel;
use app\admin\model\Common;
use app\admin\model\Message;
use think\Request;
use think\Validate;
class Receivables extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -46,6 +48,7 @@ class Receivables extends Common
$order_type = $request['order_type'];
$getCount = $request['getCount'];
$receivablesIdArray = $request['receivablesIdArray']; // 待办事项提醒参数
$isMessage = !empty($request['isMessage']);
unset($request['scene_id']);
unset($request['search']);
unset($request['user_id']);
@ -53,6 +56,7 @@ class Receivables extends Common
unset($request['order_type']);
unset($request['getCount']);
unset($request['receivablesIdArray']);
unset($request['isMessage']);
$request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: [];
@ -79,19 +83,24 @@ class Receivables extends Common
$query->whereLike('receivables.number', '%' . $search . '%');
});
};
// if (db('crm_customer')->whereLike('name', '%' . $search . '%')->value('customer_id')) {
// $sceneMap['customer_name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '客户名称'];
// } else {
// $sceneMap['number'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '回款编号'];
// }
}
$partMap = [];
//优先级:普通筛选>高级筛选>场景
//优先级:普通筛选>高级筛选>场景
if ($requestMap['team_id']) {
//相关团队查询
$map = $requestMap;
$partMap= advancedQueryFormatForTeam($requestMap,'crm_receivables','receivables_id');
unset($map['team_id']);
} else {
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
}
//高级筛选
$map = where_arr($map, 'crm', 'receivables', 'index');
$map = advancedQuery($map, 'crm', 'receivables', 'index');
//权限
$authMap = [];
if (!$partMap) {
$auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
if (isset($map['receivables.owner_user_id']) && $map['receivables.owner_user_id'][0] != 'like') {
if (!is_array($map['receivables.owner_user_id'][1])) {
@ -103,16 +112,34 @@ class Receivables extends Common
$auth_user_ids = array_intersect($map['receivables.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
}
unset($map['receivables.owner_user_id']);
}
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
//负责人、相关团队
$authMap['receivables.owner_user_id'] = ['in', $auth_user_ids];
} else {
// 待办事项的待审核回款不一定是自己创建的
if (!$isMessage) {
$authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id;
$authMap = function ($query) use ($authMapData) {
$query->where('receivables.owner_user_id', array('in', $authMapData['auth_user_ids']))
->whereOr('receivables.ro_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'))
->whereOr('receivables.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
};
}
}
}
//列表展示字段
$indexField = $fieldModel->getIndexField('crm_receivables', $user_id, 1) ?: array('number');
//人员类型
$userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
$structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure'); //部门类型
$datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型
$booleanField = $fieldModel->getFieldByFormType('crm_receivables', 'boolean_value'); //布尔值
$dateIntervalField = $fieldModel->getFieldByFormType('crm_receivables', 'date_interval'); // 日期区间类型字段
$positionField = $fieldModel->getFieldByFormType('crm_receivables', 'position'); // 地址类型字段
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables', 'handwriting_sign'); // 手写签名类型字段
$locationField = $fieldModel->getFieldByFormType('crm_receivables', 'location'); // 定位类型字段
# 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
$temporaryField = str_replace('_name', '', $order_field);
if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@ -136,13 +163,13 @@ class Receivables extends Common
->alias('receivables')
->join('__CRM_CUSTOMER__ customer', 'receivables.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract', 'receivables.contract_id = contract.contract_id', 'LEFT')
->where($searchWhere)->where($map)->where($authMap)->where($dealtWhere)->count('receivables_id');
->where($searchWhere)->where($map)->where($authMap)->where($partMap)->where($dealtWhere)->count('receivables_id');
if (!empty($getCount) && $getCount == 1) {
$data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
$data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
return $data;
}
foreach ($indexField AS $kk => $vv) {
foreach ($indexField as $kk => $vv) {
if ($vv == 'receivables.contract_num') unset($indexField[(int)$kk]);
}
$list = db('crm_receivables')
@ -151,13 +178,20 @@ class Receivables extends Common
->join('__CRM_CONTRACT__ contract', 'receivables.contract_id = contract.contract_id', 'LEFT')
->where($searchWhere)
->where($map)
->where($partMap)
->where($authMap)
->where($dealtWhere)
->limit($request['offset'], $request['length'])
->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
->orderRaw($order)
->select();
# 扩展数据
$extraData = [];
$receivables_id_list = !empty($list) ? array_column($list, 'receivables_id') : [];
$extraList = db('crm_receivables_data')->whereIn('receivables_id', $receivables_id_list)->select();
foreach ($extraList as $key => $value) {
$extraData[$value['receivables_id']][$value['field']] = $value['content'];
}
foreach ($list as $k => $v) {
$list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : [];
$list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : [];
@ -171,15 +205,35 @@ class Receivables extends Common
$list[$k]['contract_money'] = $v['contract_money'] ?: '0.00';
foreach ($userField as $key => $val) {
$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) {
$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) {
$list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
}
foreach ($booleanField as $key => $val) {
$list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
}
// 处理日期区间类型字段的格式
foreach ($dateIntervalField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['receivables_id']][$val]) ? json_decode($extraData[$v['receivables_id']][$val], true) : null;
}
// 处理地址类型字段的格式
foreach ($positionField as $key => $val) {
$list[$k][$val] = !empty($extraData[$v['receivables_id']][$val]) ? json_decode($extraData[$v['receivables_id']][$val], true) : null;
}
// 手写签名类型字段
foreach ($handwritingField as $key => $val) {
$handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
$list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
}
// 定位类型字段
foreach ($locationField AS $key => $val) {
$list[$k][$val] = !empty($extraData[$v['receivables_id']][$val]) ? json_decode($extraData[$v['receivables_id']][$val], true) : null;
}
$list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
//期数
$plan_num = db('crm_receivables_plan')->where(['plan_id' => $v['plan_id']])->value('num');
@ -227,12 +281,15 @@ class Receivables extends Common
/**
* 创建回款信息
* @author Michael_xu
* @param
* @return
* @author Michael_xu
*/
public function createData($param)
{
// 回款扩展表数据
$receivablesData = [];
if (!$param['customer_id']) {
$this->error = '请先选择客户';
return false;
@ -253,13 +310,11 @@ class Receivables extends Common
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -277,10 +332,79 @@ class Receivables extends Common
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->data($param)->allowField(true)->save()) {
//站内信
@ -319,7 +443,7 @@ class Receivables extends Common
$checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds);
$dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) {
foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [
'types' => 'crm_receivables',
'types_id' => $data['receivables_id'],
@ -328,6 +452,12 @@ class Receivables extends Common
}
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加回款扩展数据
array_walk($receivablesData, function (&$val) use ($data) {
$val['receivables_id'] = $data['receivables_id'];
});
db('crm_receivables_data')->insertAll($receivablesData);
return $data;
} else {
$this->error = '添加失败';
@ -363,12 +493,15 @@ class Receivables extends Common
/**
* 编辑回款主表信息
* @author Michael_xu
* @param
* @return
* @author Michael_xu
*/
public function updateDataById($param, $receivables_id = '')
{
// 回款扩展表数据
$receivablesData = [];
$userModel = new \app\admin\model\User();
$dataInfo = db('crm_receivables')->where(['receivables_id' => $receivables_id])->find();
if (!$dataInfo) {
@ -383,14 +516,11 @@ class Receivables extends Common
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
if (!$result) {
$this->error = $validate->getError();
// 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['receivables_id']);
if (!empty($validateResult)) {
$this->error = $validateResult;
return false;
}
@ -402,10 +532,79 @@ class Receivables extends Common
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
// 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_receivables', 'handwriting_sign');
if (!empty($handwritingField)) {
foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
}
}
}
// 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param as $key => $value) {
// 处理地址类型字段数据
if (in_array($key, $positionField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$positionNames = array_column($value, 'name');
$param[$key] = implode(',', $positionNames);
} else {
$param[$key] = '';
}
}
// 处理定位类型字段数据
if (in_array($key, $locationField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $value['address'];
} else {
$param[$key] = '';
}
}
// 处理日期区间类型字段数据
if (in_array($key, $dateIntervalField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = implode('_', $value);
} else {
$param[$key] = '';
}
}
// 处理明细表格类型字段数据
if (in_array($key, $detailTableField)) {
if (!empty($value)) {
$receivablesData[] = [
'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time()
];
$param[$key] = $key;
} else {
$param[$key] = '';
}
}
}
if ($this->update($param, ['receivables_id' => $receivables_id], true)) {
//修改记录
@ -433,7 +632,7 @@ class Receivables extends Common
$checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
$checkUserIdArray = stringToArray($checkUserIds);
$dealtData = [];
foreach ($checkUserIdArray AS $kk => $vv) {
foreach ($checkUserIdArray as $kk => $vv) {
$dealtData[] = [
'types' => 'crm_receivables',
'types_id' => $data['receivables_id'],
@ -442,6 +641,13 @@ class Receivables extends Common
}
if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
// 添加回款扩展数据
db('crm_receivables_data')->where('receivables_id', $receivables_id)->delete();
array_walk($receivablesData, function (&$val) use ($receivables_id) {
$val['receivables_id'] = $receivables_id;
});
db('crm_receivables_data')->insertAll($receivablesData);
return $data;
} else {
$this->error = '编辑失败';
@ -486,7 +692,7 @@ class Receivables extends Common
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
foreach ($dataInfo as $key => $value) {
if (!$userLevel && !empty($grantData['crm_receivables'])) {
$status = getFieldGrantStatus($key, $grantData['crm_receivables']);
@ -525,7 +731,7 @@ class Receivables extends Common
$contractModel = new \app\crm\model\Contract();
$adminModel = new \app\admin\model\Admin();
$perUserIds = $userModel->getUserByPer('bi', 'receivables', 'read'); //权限范围内userIds
$whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
$whereData = $adminModel->getWhere($request, '', $perUserIds); //统计条件
$userIds = $whereData['userIds'];
if (!$request['year']) {
@ -625,10 +831,10 @@ class Receivables extends Common
/**
* [回款统计] 柱状图
* @author Michael_xu
* @param request [查询条件]
* @param
* @return [array]
* @author Michael_xu
*/
public function getStatistics($request)
{
@ -685,10 +891,10 @@ class Receivables extends Common
/**
* [合同回款金额]
* @author Michael_xu
* @param contract_id 合同ID
* @param
* @return
* @author Michael_xu
*/
public function getMoneyByContractId($contract_id)
{

@ -6,6 +6,7 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\traits\FieldVerificationTrait;
use think\Db;
use app\admin\model\Common;
use app\crm\model\Contract as ContractModel;
@ -14,6 +15,8 @@ use think\Validate;
class ReceivablesPlan extends Common
{
use FieldVerificationTrait;
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
@ -59,7 +62,8 @@ class ReceivablesPlan extends Common
$map['name'] = ['like', '%'.$map['search'].'%'];
unset($map['search']);
} else {
$map = where_arr($map, 'crm', 'receivables_plan', 'index'); //高级筛选
// 高级筛选
$map = advancedQuery($map, 'crm', 'receivables_plan', 'index');
}
if ($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')
->alias('receivables_plan')
->join('__CRM_CONTRACT__ contract','receivables_plan.contract_id = contract.contract_id','LEFT')
@ -148,6 +146,8 @@ class ReceivablesPlan extends Common
*/
public function createData($param)
{
$userId = $param['user_id'];
unset($param['user_id']);
if (!$param['contract_id']) {
$this->error = '请先选择合同';
return false;
@ -166,10 +166,16 @@ class ReceivablesPlan extends Common
$this->error = '提前提醒最大时间为 90 天';
return false;
}
// 自动验证
$validate = validate($this->name);
if (!$validate->check($param)) {
$this->error = $validate->getError();
// // 自动验证
// $validate = validate($this->name);
// if (!$validate->check($param)) {
// $this->error = $validate->getError();
// 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']); //附件
@ -178,9 +184,97 @@ class ReceivablesPlan extends Common
$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'];
$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()) {
$data = [];
$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;
} else {
$this->error = '添加失败';
@ -196,6 +290,8 @@ class ReceivablesPlan extends Common
*/
public function updateDataById($param, $plan_id = '')
{
$userId = $param['user_id'];
unset($param['user_id']);
$dataInfo = $this->getDataById($plan_id);
if (!$dataInfo) {
$this->error = '数据不存在或已删除';
@ -208,18 +304,114 @@ class ReceivablesPlan extends Common
unset($param[$v]);
}
// 自动验证
$validate = validate($this->name);
if (!$validate->check($param)) {
$this->error = $validate->getError();
// // 自动验证
// $validate = validate($this->name);
// if (!$validate->check($param)) {
// $this->error = $validate->getError();
// 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']); //附件
//提醒日期
$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])) {
$data = [];
$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;
} else {
$this->error = '编辑失败';

@ -36,7 +36,7 @@ class Setting extends Common
if (!is_array($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 (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_business' : $module_id = 'business_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) {
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\PDOException
*/
public function setVisitDay($status, $day)
public function setVisitDay($status, $day,$userId)
{
$status = intval($status);
$day = intval($day);
@ -99,9 +101,7 @@ class Setting extends Common
}
}
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
SystemActionLog($userId, 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
return true;
}
@ -124,7 +124,7 @@ class Setting extends Common
* @param $param
* @return bool
*/
public function setNumber($param)
public function setNumber($param,$userId)
{
$apiCommon = new ApiCommon();
@ -176,9 +176,7 @@ class Setting extends Common
Db::commit();
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
SystemActionLog($userId, 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
return true;
} catch (Exception $e) {
Db::rollback();
@ -186,4 +184,41 @@ class Setting extends Common
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']]) {
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' => '设置关注成功!']);
}
//通讯录列表
// 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;
$userInfo = $this->userInfo;
$param['create_user_id'] = $userInfo['id'];
$param['user_id'] = $userInfo['id'];
$dataInfo = db('oa_examine')->where(['examine_id' => $param['id']])->find();
if (!$dataInfo) {
return resultArray(['error' => '数据不存在或已删除']);
@ -249,6 +250,8 @@ class Examine extends ApiCommon
return resultArray(['error' => $examineModel->getError()]);
}
$fileModel = new \app\admin\model\File();
// 删除自定义字段数据
db('oa_examine_data')->where('examine_id', $param['id'])->delete();
//删除关联附件
$fileModel->delRFileByModule('oa_examine',$param['id']);
# 删除记录
@ -445,6 +448,9 @@ class Examine extends ApiCommon
->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%');
});
})->order($orderField,$orderSort)->select();
foreach ($list AS $key => $value) {
$list[$key]['category_name'] = $value['title'];
}
return resultArray(['data' => $list]);
}

@ -38,7 +38,8 @@ class Log extends ApiCommon
'activitycount',
'activitylist',
'querylog',
'onebulletin'
'onebulletin',
'favourupdate'
]
];
Hook::listen('check_auth', $action);
@ -331,6 +332,7 @@ class Log extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$log_id = $param['log_id'];
$param['user_id']=$userInfo['id'];
if ($log_id) {
$dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
$adminTypes = adminGroupTypes($userInfo['id']);
@ -494,4 +496,20 @@ class Log extends ApiCommon
$data = $TaskLogic->queryLog($param);
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))
->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')
->where($userMap)
->where($logMap)
->count();
$businessNum = Db::name('CrmBusiness')
@ -304,21 +308,20 @@ class LogLogic extends Common
if ($search) {
$map['name'] = array('like', '%' . $search . '%');
}
$customerModel=new \app\crm\model\Customer();
$customerMap =$customerModel->getWhereByCustomer();
$type = $param['log_type'];
switch ($type) {
case '1':
if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
$map['customer.create_time'] = array('between', $between_time);
$logMap['obtain_time'] = array('between', $between_time);
$logMap=function ($query) use ($between_time) {
$query->where('customer.create_time', array('between', $between_time))
->whereOr('customer.obtain_time', array('between', $between_time));
};
$activityData = Db::name('CrmCustomer')
->alias('customer')
->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
->where($map)
->where($map1)
->where($customerMap)
->whereOr($logMap)
->where($logMap)
->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')
->page($param['page'],$param['limit'])
@ -331,7 +334,8 @@ class LogLogic extends Common
->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
->where($map)
->where($map1)
->where($customerMap)
->where($logMap)
->where('customer.owner_user_id' , ['neq', 0])
->count();
break;
case '2':
@ -378,20 +382,19 @@ class LogLogic extends Common
$activityData = Db::name('CrmContract')
->alias('contract')
->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($map3)
->order('contract.contract_id desc')
->page($param['page'],$param['limit'])
->field(['contract.contract_id',
->field([
'contract.contract_id',
'contract.name',
'contract.create_time',
'contract.check_status',
'contract.order_date',
'contract.money',
'u.realname as order_user_name',
'ifnull(SUM(receivables.money), 0)' => 'done_money',
'(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money'])
])
->select();
foreach ($activityData as $k => $v){
if(!empty($v['contract_id'])){
@ -835,7 +838,7 @@ class LogLogic extends Common
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false;
$data['lastPage'] = false;
} else if ($param['page'] == 1) {
} else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount ) {
$data['firstPage'] = true;
$data['lastPage'] = false;
}
@ -1015,4 +1018,38 @@ class LogLogic extends Common
$data['list'] = $item;
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) {
return 'Z';
}
// return '#';
}
}

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

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

@ -249,9 +249,7 @@ class ExamineCategory extends Common
$data['delete_user_id'] = $user_id;
$this->allowField(true)->save($data, ['category_id' => $id]);
# 系统操作记录
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'],'oa_examine', 'approval', $id, 'delete',$info['title'] , '', '','删除了:'.$info['title']);
SystemActionLog($user_id,'oa_examine', 'approval', $id, 'delete',$info['title'] , '', '','删除了:'.$info['title']);
$this->commit();
return true;
} 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'];
$data = [];
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)) {
$data[$k]['examine_id'] = $examine_id;
$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) {
db('oa_examine_data')->where('examine_id', $examine_id)->delete();
// print_r($data);exit;
$resData = db('oa_examine_data')->insertAll($data);
if (!$resData) {
$this->error = '添加失败';

@ -40,10 +40,8 @@ class Log extends Common
$fileModel = new \app\admin\model\File();
$commonModel = new \app\admin\model\Comment();
$recordModel = new \app\admin\model\Record();
$user_id = $request['read_user_id'];
$by = $request['by'] ?: '';
$map = [];
$search = $request['search'];
if (isset($request['search']) && $request['search']) {
@ -130,6 +128,9 @@ class Log extends Common
$list[$k]['imgList'] = $imgList ?: [];
$list[$k]['sendUserList'] = $userModel->getDataByStr($v['send_user_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'] = 'oa_log';
$list[$k]['replyList'] = $commonModel->read($param);
@ -174,17 +175,17 @@ class Log extends Common
$data = [];
$data['page']['list'] = $list;
$data['page']['dataCount'] = $dataCount ?: 0;
if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) >= (int)$dataCount) {
$data['page']['firstPage'] = false;
$data['page']['lastPage'] = true;
} else if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) < (int)$dataCount) {
$data['page']['firstPage'] = false;
$data['page']['lastPage'] = false;
} else if ($request['page'] == 1) {
$data['page']['firstPage'] = true;
$data['page']['lastPage'] = false;
}
if ($param['page'] != 1 && ($param['page'] * $param['limit']) >= $dataCount) {
$data['firstPage'] = false;
$data['lastPage'] = true;
} else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = false;
$data['lastPage'] = false;
} else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
$data['firstPage'] = true;
$data['lastPage'] = true;
}
return $data;
}
@ -375,9 +376,7 @@ class Log extends Common
'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
]);
}
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'oa_log', 'update',$dataInfo['title'], '','','修改了日志:'.$dataInfo['title']);
RecordActionLog($param['user_id'], 'oa_log', 'update',$dataInfo['title'], '','','修改了日志:'.$dataInfo['title']);
return $data;
} else {
$this->error = '编辑失败';
@ -453,8 +452,6 @@ class Log extends Common
*/
public function delDataById($param)
{
$user=new ApiCommon();
$userInfo=$user->userInfo;
$map['log_id'] = $param['log_id'];
$dataInfo = $this->get($map['log_id']);
if (!$dataInfo) {
@ -469,7 +466,7 @@ class Log extends Common
$fileModel->delRFileByModule('oa_log', $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();
return true;
@ -478,4 +475,22 @@ class Log extends Common
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);
# 下次升级
// $userInfo=$this->userInfo;
// $rule=db('work_user')
// ->where('user_id',$userInfo['id'])
// ->value('group_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');
// if(!in_array($list,stringToArray($groupList))){
// $workInfo['is_open']=1;
// }
$userInfo=$this->userInfo;
$rule=db('work_user')
->where('user_id',$userInfo['id'])
->value('group_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');
if(!in_array($list,stringToArray($groupList))){
$workInfo['is_open']=1;
}
return resultArray(['data' => $workInfo]);
}
@ -288,6 +289,7 @@ class work extends ApiCommon
{
$param = $this->param;
$userInfo = $this->userInfo;
$userId=$userInfo['id'];
if (!$param['work_id'] || !$param['owner_user_id']) {
return resultArray(['error'=>'参数错误']);
}
@ -301,7 +303,7 @@ class work extends ApiCommon
// header('Content-Type:application/json; charset=utf-8');
// exit(json_encode(['code'=>102,'error'=>'无权操作']));
// }
$res = $workModel->delOwner($param);
$res = $workModel->delOwner($param,$userId);
if ($res) {
return resultArray(['data'=>'操作成功']);
@ -381,7 +383,7 @@ class work extends ApiCommon
// header('Content-Type:application/json; charset=utf-8');
// exit(json_encode(['code'=>102,'error'=>'无权操作']));
// }
$ret = $workModel->arRecover($param['work_id']);
$ret = $workModel->arRecover($param['work_id'],$userInfo['id']);
if ($ret) {
return resultArray(['data'=>'操作成功']);
} else {

@ -330,6 +330,11 @@ class Task extends Common
->select();
$complete = 0;
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]['stop_time'] = !empty($value['stop_time']) ? date('Y-m-d', $value['stop_time']) : null;
if ($value['status'] == 5) ++$complete;
@ -442,8 +447,6 @@ class Task extends Common
$datalog['task_id'] = $task_id;
$datalog['work_id'] = $param['work_id'] ?: '';
$ret = $taskLog->newTaskLog($datalog);
//操作日志
// actionLog($task_id, '', '', '新建了任务');
//抄送站内信
(new Message())->send(
Message::TASK_ALLOCATION,
@ -480,8 +483,6 @@ class Task extends Common
}
db('work_task_file')->insertAll($fileData);
}
$user=new ApiCommon();
$userInfo=$user->userInfo;
# 添加子任务
if (!empty($subtask)) {
$subtaskData = [];
@ -503,15 +504,10 @@ class Task extends Common
}
Db::name('task')->insertAll($subtaskData);
foreach ($subtaskData as $v){
RecordActionLog($userInfo['id'],'work_task','save',$param['name'],'','','新增了子任务'.$v['name']);
}
RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增了子任务'.$v['name']);
}
if(!empty($param['pid'])){
$dataInfo=Db::name('task')->where('task_id',$param['pid'])->find();
RecordActionLog($userInfo['id'],'work_task','save',$dataInfo['name'],'','','新增了子任务'.$param['name']);
}else{
RecordActionLog($userInfo['id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
}
RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
return $task_id;
} else {
$this->error = '添加失败';
@ -701,16 +697,13 @@ class Task extends Common
if (!$param['pid']) {
$LogModel = new LogModel();
$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($param['description'])){
$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();
if ($resRelation) {
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);
$flag = $this->where(['task_id' => $param['task_id']])->update($data);
if ($flag) {
//添加归档日志
// actionLog($param['task_id'], '', '', '归档了任务');
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work_task', 'archiveData',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
RecordActionLog($param['create_user_id'], 'work_task', 'archiveData',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
return true;
} else {
$this->error = '归档失败';
@ -872,9 +861,7 @@ class Task extends Common
$flag = $this->where(['task_id' => $param['task_id']])->setField('is_archive', 0);
if ($flag) {
//添加日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work_task', 'recover',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
RecordActionLog($param['create_user_id'], 'work_task', 'recover',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
return true;
} else {
$this->error = '操作失败';

@ -76,7 +76,8 @@ class Work extends Common
$ownerData['work_id'] = $workId;
$ownerData['create_user_id'] = $createUserId;
$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);
@ -173,9 +174,7 @@ class Work extends Common
$datalog['work_id'] = $param['work_id'];
$datalog['user_id'] = $userId;
$ret = $logmodel->workLogAdd($datalog);
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'update',$param['name'], '','','编辑了项目:'.$param['name']);
RecordActionLog($userId, 'work', 'update',$param['name'], '','','编辑了项目:'.$param['name']);
return true;
} else {
$this->error = '重命名失败';
@ -227,9 +226,7 @@ class Work extends Common
$data['status'] = 3;
$data['archive_time'] = time();
Db::name('task')->where($map)->update($data);
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'archiveData',$dataInfo['name'], '','','归档了项目:'.$dataInfo['name']);
RecordActionLog($param['create_user_id'], 'work', 'archiveData',$dataInfo['name'], '','','归档了项目:'.$dataInfo['name']);
return true;
} else {
$this->error = '归档失败';
@ -268,7 +265,7 @@ class Work extends Common
* @param
* @return
*/
public function arRecover($work_id='')
public function arRecover($work_id='',$userId)
{
if (!$work_id) {
$this->error = '参数错误';
@ -281,9 +278,7 @@ class Work extends Common
$this->where($map)->setField('status',1);
$map['status'] = 3;
Db::name('Task')->where($map)->setField('status',1);
$user=new ApiCommon();
$userInfo=$user->userInfo;
RecordActionLog($userInfo['id'], 'work', 'recover',$dataInfo['name'], '','','归档恢复项目:'.$dataInfo['name']);
RecordActionLog($userId, 'work', 'recover',$dataInfo['name'], '','','归档恢复项目:'.$dataInfo['name']);
return true;
}
@ -301,8 +296,6 @@ class Work extends Common
$this->error = '项目创建人不可以退出';
return false;
}
$user=new ApiCommon();
$userInfo=$user->userInfo;
//从项目成员中移除
db('work_user')->where(['work_id' => $work_id,'user_id' => $user_id])->delete();
$str = ','.$user_id.',';
@ -317,13 +310,13 @@ class Work extends Common
$new_own_user_id = str_replace($str,',',$value['owner_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'] = '';
}
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;
}
@ -356,7 +349,7 @@ class Work extends Common
$data['types'] = 0;
if ($v == $create_user_id) {
$data['types'] = 1;
$group_id = 1;
$group_id = $param['group_id'];
} else {
# 默认角色
$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
* @return
*/
public function delOwner($param)
public function delOwner($param,$userId)
{
$work_id = $param['work_id'];
$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 = '删除失败,请重试!';
return false;
}
$user=new ApiCommon();
$userInfo=$user->userInfo;
$user= new \app\admin\model\User();
$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;
}
@ -423,7 +414,14 @@ class Work extends Common
$workInfo = $this->get($param['work_id']);
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 {
// $exp = new \think\db\Expression('field(types,1,0,2)');
$list = db('work_user')

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

2882
composer.lock generated

File diff suppressed because it is too large Load Diff

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

@ -298,6 +298,8 @@ return [
'crm/invoice/count' => ['crm/invoice/count', ['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']],
@ -380,6 +382,8 @@ return [
'crm/index/queryDataInfo' => ['crm/index/queryDataInfo', ['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']],
@ -477,7 +481,7 @@ return [
'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']],
//跟进记录导出
@ -495,10 +499,27 @@ return [
'crm/market/enables' => ['crm/market/enables', ['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/setting/appMenuConfig' => ['crm/setting/appMenuConfig', ['method' => 'POST']],
//办公数量
'crm/setting/oaNumber' => ['crm/setting/oaNumber', ['method' => 'POST']],
// MISS路由
'__miss__' => 'admin/base/miss',
];

@ -162,6 +162,8 @@ return [
'oa/log/queryLog' => ['oa/log/queryLog', ['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']],
@ -204,7 +206,8 @@ return [
// 【代办事项】办公
'oa/message/num'=>['oa/message/num', ['method' => 'POST']],
//手机导航
'admin/setting/appMenuConfig' => ['admin/setting/appMenuConfig', ['method' => 'POST']],
// MISS路由
'__miss__' => 'admin/base/miss',
];

@ -1,5 +1,5 @@
<?php
return array(
'VERSION'=>'11.0.3',
'RELEASE'=>'202105014',
'VERSION'=>'11.1.0',
'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